@puntjes/sdk 0.0.0-stage → 1.0.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 (63) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +152 -2
  3. package/dist/auth/token-source.d.ts +20 -0
  4. package/dist/auth/token-source.js +105 -0
  5. package/dist/auth/token-store.d.ts +21 -0
  6. package/dist/auth/token-store.js +13 -0
  7. package/dist/create-puntjes.d.ts +25 -0
  8. package/dist/create-puntjes.js +48 -0
  9. package/dist/errors.d.ts +55 -0
  10. package/dist/errors.js +60 -0
  11. package/dist/generated/client/client.gen.d.ts +2 -0
  12. package/dist/generated/client/client.gen.js +216 -0
  13. package/dist/generated/client/index.d.ts +10 -0
  14. package/dist/generated/client/index.js +6 -0
  15. package/dist/generated/client/types.gen.d.ts +120 -0
  16. package/dist/generated/client/types.gen.js +2 -0
  17. package/dist/generated/client/utils.gen.d.ts +37 -0
  18. package/dist/generated/client/utils.gen.js +228 -0
  19. package/dist/generated/client.gen.d.ts +12 -0
  20. package/dist/generated/client.gen.js +3 -0
  21. package/dist/generated/core/auth.gen.d.ts +25 -0
  22. package/dist/generated/core/auth.gen.js +14 -0
  23. package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
  24. package/dist/generated/core/bodySerializer.gen.js +57 -0
  25. package/dist/generated/core/params.gen.d.ts +43 -0
  26. package/dist/generated/core/params.gen.js +109 -0
  27. package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
  28. package/dist/generated/core/pathSerializer.gen.js +106 -0
  29. package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
  30. package/dist/generated/core/queryKeySerializer.gen.js +92 -0
  31. package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
  32. package/dist/generated/core/serverSentEvents.gen.js +132 -0
  33. package/dist/generated/core/types.gen.d.ts +83 -0
  34. package/dist/generated/core/types.gen.js +2 -0
  35. package/dist/generated/core/utils.gen.d.ts +19 -0
  36. package/dist/generated/core/utils.gen.js +87 -0
  37. package/dist/generated/error-codes.gen.d.ts +56 -0
  38. package/dist/generated/error-codes.gen.js +110 -0
  39. package/dist/generated/index.d.ts +2 -0
  40. package/dist/generated/index.js +2 -0
  41. package/dist/generated/sdk.gen.d.ts +69 -0
  42. package/dist/generated/sdk.gen.js +323 -0
  43. package/dist/generated/types.gen.d.ts +2794 -0
  44. package/dist/generated/types.gen.js +2 -0
  45. package/dist/http/auth-fetch.d.ts +8 -0
  46. package/dist/http/auth-fetch.js +24 -0
  47. package/dist/http/error-body.d.ts +18 -0
  48. package/dist/http/error-body.js +75 -0
  49. package/dist/http/error-fetch.d.ts +3 -0
  50. package/dist/http/error-fetch.js +22 -0
  51. package/dist/http/fetch.d.ts +9 -0
  52. package/dist/http/fetch.js +4 -0
  53. package/dist/http/retry-fetch.d.ts +16 -0
  54. package/dist/http/retry-fetch.js +93 -0
  55. package/dist/idempotency-key.d.ts +2 -0
  56. package/dist/idempotency-key.js +4 -0
  57. package/dist/index.d.ts +9 -0
  58. package/dist/index.js +8 -0
  59. package/dist/paginate.d.ts +10 -0
  60. package/dist/paginate.js +16 -0
  61. package/dist/wallet-pass.d.ts +5 -0
  62. package/dist/wallet-pass.js +12 -0
  63. package/package.json +45 -4
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ # The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Puntjes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
6
+ software and associated documentation files (the "Software"), to deal in the Software
7
+ without restriction, including without limitation the rights to use, copy, modify,
8
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
9
+ permit persons to whom the Software is furnished to do so, subject to the following
10
+ conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all copies
13
+ or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
16
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
17
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
18
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
19
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
20
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,153 @@
1
- # Temporary Holding Version
1
+ # @puntjes/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official TypeScript client for the [Puntjes](https://puntjes.app) loyalty API. It runs on Node 20 or later and
4
+ ships as an ES module with its own types.
5
+
6
+ ```bash
7
+ npm install @puntjes/sdk
8
+ ```
9
+
10
+ Use it on a server only. The client secret gives full access to your shop's API, so it must never reach a browser.
11
+
12
+ ## Quick start
13
+
14
+ Create your API credentials in the Puntjes admin portal. The secret is shown once.
15
+
16
+ ```ts
17
+ import { createPuntjes, idempotencyKey } from '@puntjes/sdk';
18
+
19
+ const puntjes = createPuntjes({
20
+ clientId: process.env.PUNTJES_CLIENT_ID!,
21
+ clientSecret: process.env.PUNTJES_CLIENT_SECRET!,
22
+ });
23
+
24
+ // A customer scans their card at the till.
25
+ const { data: customer } = await puntjes.lookupCustomer({ query: { identifier: scannedCard } });
26
+ console.log(customer.data.wallet_balance);
27
+
28
+ // Record the purchase. Amounts are in cents.
29
+ const { data: transaction } = await puntjes.submitTransaction({
30
+ body: { identifier: scannedCard, total_amount: 4200, idempotency_key: `order-${orderId}` },
31
+ });
32
+ console.log(transaction.data.points_earned);
33
+ ```
34
+
35
+ `createPuntjes` returns a client generated from the Puntjes OpenAPI document, so it has every call the API has, with
36
+ the types of every request and answer. Each call takes `path`, `query` and `body` as the API names them and returns
37
+ `{ data, request, response }`. The API wraps each answer in its own `data` field, so the record is `data.data`.
38
+
39
+ `examples/quick-start.ts` is a complete script:
40
+ `npm run build && node examples/quick-start.ts <card number> [amount in cents]`, with `PUNTJES_CLIENT_ID`,
41
+ `PUNTJES_CLIENT_SECRET` and, for a local app, `PUNTJES_BASE_URL` set.
42
+
43
+ ## Options
44
+
45
+ ```ts
46
+ const puntjes = createPuntjes({
47
+ clientId,
48
+ clientSecret,
49
+ baseUrl: 'https://puntjes.app', // with or without /api/v1
50
+ maxRetries: 2, // 0 turns retries off
51
+ retryBaseDelay: 500, // milliseconds before the first retry, doubled for each next one
52
+ timeout: 30_000, // milliseconds per attempt
53
+ tokenStore: myRedisStore, // a TokenStore; memory by default
54
+ fetch: myFetch, // (request, init) => Response, for a proxy or a test; pass init.signal on
55
+ });
56
+ ```
57
+
58
+ ## What the SDK does for you
59
+
60
+ - **Authentication.** It asks for a `client_credentials` token on the first call, keeps it until 30 seconds before it
61
+ expires, and asks once more when the API rejects it. Parallel calls on one client share one request for a token. A `TokenStore`
62
+ keeps each token under a key made from the host and the credentials, so one shared store (Redis, for example) can
63
+ serve the clients of many shops without mixing their tokens. The key is the same one the .NET SDK uses.
64
+ - **Retries.** A GET, PUT, PATCH or DELETE, and a POST that carries an `idempotency_key`, is sent again after a network
65
+ failure, a 5xx answer or `RATE_LIMITED`. It waits 0.5 s, then 1 s, or what `Retry-After` says. A POST without a key
66
+ is never sent twice, so a purchase is never recorded twice. `PLAN_LIMIT_EXCEEDED` is never retried. An attempt that
67
+ takes longer than `timeout` counts as a network failure. A failed token request is retried the same way.
68
+ - **Idempotency keys.** `idempotencyKey()` makes one. Send the same key again to repeat a call safely.
69
+
70
+ ## Errors
71
+
72
+ Every error is a `PuntjesError`, with a subclass per kind:
73
+
74
+ | Error | When |
75
+ |---|---|
76
+ | `AuthenticationError` | 401: wrong credentials or a rejected token |
77
+ | `ForbiddenError` | 403 |
78
+ | `NotFoundError` | 404 |
79
+ | `ConflictError` | 409 |
80
+ | `ValidationError` | 422 `VALIDATION_ERROR`; `errorsFor('field')` gives the messages |
81
+ | `RateLimitError` | Any other 429, such as `RATE_LIMITED`; `retryAfter` says how many milliseconds to wait |
82
+ | `PlanLimitExceededError` | 429 `PLAN_LIMIT_EXCEEDED`: the shop's plan is used up |
83
+ | `ServerError` | 5xx |
84
+ | `TransportError` | No answer from the API, or an answer that is not from the API |
85
+
86
+ A 422 for a business rule, such as `INSUFFICIENT_BALANCE`, is a plain `PuntjesError`.
87
+
88
+ ```ts
89
+ import { ErrorCode, PuntjesError } from '@puntjes/sdk';
90
+
91
+ try {
92
+ await puntjes.redeemReward({ body });
93
+ } catch (error) {
94
+ if (error instanceof PuntjesError && error.code === ErrorCode.InsufficientBalance) {
95
+ console.log(`Not enough points. Request ${error.requestId}`);
96
+ } else {
97
+ throw error;
98
+ }
99
+ }
100
+ ```
101
+
102
+ `code` is null for a code that is newer than your SDK. `rawCode` holds the code as the API sent it, or
103
+ `UNKNOWN_ERROR` and `NON_JSON_RESPONSE` when the answer carried none.
104
+
105
+ ## Pages
106
+
107
+ ```ts
108
+ import { paginate, type ProductData } from '@puntjes/sdk';
109
+
110
+ for await (const product of paginate<ProductData>(async (page) => (await puntjes.listProducts({ query: { page } })).data.data)) {
111
+ console.log(product.name);
112
+ }
113
+ ```
114
+
115
+ ## Apple wallet pass
116
+
117
+ ```ts
118
+ import { walletPass } from '@puntjes/sdk';
119
+
120
+ const pkpass: Uint8Array = await walletPass.apple(puntjes, customerId);
121
+ ```
122
+
123
+ ## How this package is made
124
+
125
+ The code under `src/generated` is generated by [hey-api](https://heyapi.dev) from `spec/api.json`. Never edit it by
126
+ hand: CI regenerates it and fails on any difference. A bump of `@hey-api/openapi-ts` turns that check red until the
127
+ code is regenerated in the same PR, and that is the point of the check. Dependabot titles that PR `chore`; rename it
128
+ to `fix:` when the regenerated code changes, so release-please ships it as its own release.
129
+
130
+ - `npm run generate` regenerates it: hey-api, then `tools/codegen.ts` for the `ErrorCode` list. hey-api is pinned to
131
+ an exact version, and TypeScript is pinned to 5 beside it, because hey-api fails under TypeScript 7.
132
+ - When Puntjes publishes a new API spec, `.github/workflows/regenerate.yml` opens a PR with the new code. A minor or
133
+ patch spec merges itself when CI is green; a major one waits for a person.
134
+ - `.github/workflows/release.yml` runs release-please. Its release PR merges itself when CI is green, and the tag
135
+ publishes the package to npm with provenance.
136
+
137
+ ### Releases and npm trusted publishing
138
+
139
+ The publish job has no stored npm token. npm trades the job's GitHub token for a one-time credential and adds the
140
+ provenance statement itself. npm can attach a trusted publisher only to a package that exists, so the first version
141
+ goes by hand, once, and 1.0.0 is the one version without provenance:
142
+
143
+ 1. The `1.0.0` release PR merges and release-please tags `v1.0.0`. The publish job fails and points here.
144
+ 2. An owner of the `puntjes` npm organisation checks out `v1.0.0` and runs `npm ci && npm run build &&
145
+ npm publish --access public`.
146
+ 3. Within two days, on npmjs.com, open the package's **Settings**, then **Trusted Publisher**, choose GitHub Actions,
147
+ and enter organisation `PuntjesApp`, repository `puntjes-typescript`, workflow `release.yml`, no environment.
148
+ Then set **Publishing access** to require two-factor authentication and disallow tokens.
149
+ 4. Re-run the failed publish job. It sees that `1.0.0` is on npm and passes. Every later release publishes by itself.
150
+
151
+ ## License
152
+
153
+ MIT
@@ -0,0 +1,20 @@
1
+ import type { Fetch } from '../http/fetch.js';
2
+ import type { TokenStore } from './token-store.js';
3
+ /** The store key of one shop's token. The same key as the .NET SDK, so a shared store holds one token per shop. */
4
+ export declare function tokenKey(host: string, clientId: string, clientSecret: string): string;
5
+ /** Grants client credentials tokens, one grant at a time, and keeps them in the store. */
6
+ export declare class TokenSource {
7
+ private readonly clientId;
8
+ private readonly clientSecret;
9
+ private readonly tokenUrl;
10
+ private readonly key;
11
+ private readonly store;
12
+ private readonly grants;
13
+ private queue;
14
+ constructor(clientId: string, clientSecret: string, tokenUrl: string, key: string, store: TokenStore, grants: Fetch);
15
+ get(): Promise<string>;
16
+ /** Clears the stored token, but only while it is still the one the API rejected. */
17
+ forget(rejected: string): Promise<void>;
18
+ private exclusive;
19
+ private grant;
20
+ }
@@ -0,0 +1,105 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AuthenticationError, PuntjesError, TransportError } from '../errors.js';
3
+ import { toError } from '../http/error-body.js';
4
+ const LEEWAY = 30_000;
5
+ /** The store key of one shop's token. The same key as the .NET SDK, so a shared store holds one token per shop. */
6
+ export function tokenKey(host, clientId, clientSecret) {
7
+ return 'puntjes:token:' + createHash('sha256').update(`${host}|${clientId}|${clientSecret}`).digest('hex').slice(0, 32);
8
+ }
9
+ /** Grants client credentials tokens, one grant at a time, and keeps them in the store. */
10
+ export class TokenSource {
11
+ clientId;
12
+ clientSecret;
13
+ tokenUrl;
14
+ key;
15
+ store;
16
+ grants;
17
+ queue = Promise.resolve();
18
+ constructor(clientId, clientSecret, tokenUrl, key, store, grants) {
19
+ this.clientId = clientId;
20
+ this.clientSecret = clientSecret;
21
+ this.tokenUrl = tokenUrl;
22
+ this.key = key;
23
+ this.store = store;
24
+ this.grants = grants;
25
+ }
26
+ async get() {
27
+ const stored = usable(await this.store.get(this.key));
28
+ if (stored !== null) {
29
+ return stored;
30
+ }
31
+ return this.exclusive(async () => {
32
+ const granted = usable(await this.store.get(this.key));
33
+ if (granted !== null) {
34
+ return granted;
35
+ }
36
+ const fresh = await this.grant();
37
+ await this.store.set(this.key, fresh);
38
+ return fresh.value;
39
+ });
40
+ }
41
+ /** Clears the stored token, but only while it is still the one the API rejected. */
42
+ forget(rejected) {
43
+ return this.exclusive(async () => {
44
+ if ((await this.store.get(this.key))?.value === rejected) {
45
+ await this.store.delete(this.key);
46
+ }
47
+ });
48
+ }
49
+ exclusive(work) {
50
+ const run = this.queue.then(work, work);
51
+ this.queue = run.catch(() => undefined);
52
+ return run;
53
+ }
54
+ async grant() {
55
+ const issuedAt = Date.now();
56
+ let response;
57
+ try {
58
+ response = await this.grants(new Request(this.tokenUrl, {
59
+ method: 'POST',
60
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
61
+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: this.clientId, client_secret: this.clientSecret }).toString(),
62
+ }));
63
+ }
64
+ catch (error) {
65
+ if (error instanceof PuntjesError) {
66
+ throw error;
67
+ }
68
+ throw new TransportError(`The Puntjes token endpoint could not be reached: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
69
+ }
70
+ if (response.status === 400 || response.status === 401) {
71
+ throw rejected(await response.text(), response.status);
72
+ }
73
+ if (!response.ok) {
74
+ throw await toError(response);
75
+ }
76
+ let root;
77
+ try {
78
+ root = JSON.parse(await response.text());
79
+ }
80
+ catch (error) {
81
+ throw new TransportError('The Puntjes token endpoint returned no usable token.', { cause: error });
82
+ }
83
+ if (typeof root.access_token !== 'string' || root.access_token === '') {
84
+ throw new TransportError('The Puntjes token endpoint returned no access_token.');
85
+ }
86
+ const expiresIn = typeof root.expires_in === 'number' ? root.expires_in : 3600;
87
+ return { value: root.access_token, expiresAt: issuedAt + expiresIn * 1000 };
88
+ }
89
+ }
90
+ function usable(token) {
91
+ return token !== null && token.expiresAt - LEEWAY > Date.now() ? token.value : null;
92
+ }
93
+ function rejected(text, status) {
94
+ let code = null;
95
+ let description = null;
96
+ try {
97
+ const root = JSON.parse(text);
98
+ code = typeof root.error === 'string' ? root.error : null;
99
+ description = typeof root.error_description === 'string' ? root.error_description : null;
100
+ }
101
+ catch {
102
+ code = null;
103
+ }
104
+ return new AuthenticationError(description ?? 'The Puntjes API refused the client credentials.', { status, rawCode: code });
105
+ }
@@ -0,0 +1,21 @@
1
+ /** A bearer token and the moment it stops working, in milliseconds since the epoch. */
2
+ export interface AccessToken {
3
+ value: string;
4
+ expiresAt: number;
5
+ }
6
+ /**
7
+ * Keeps access tokens between calls, for example in Redis shared by several servers. The key names the credentials a
8
+ * token belongs to, so one store can serve the clients of many shops.
9
+ */
10
+ export interface TokenStore {
11
+ get(key: string): Promise<AccessToken | null>;
12
+ set(key: string, token: AccessToken): Promise<void>;
13
+ delete(key: string): Promise<void>;
14
+ }
15
+ /** Keeps tokens in this process. The default. */
16
+ export declare class InMemoryTokenStore implements TokenStore {
17
+ private readonly tokens;
18
+ get(key: string): Promise<AccessToken | null>;
19
+ set(key: string, token: AccessToken): Promise<void>;
20
+ delete(key: string): Promise<void>;
21
+ }
@@ -0,0 +1,13 @@
1
+ /** Keeps tokens in this process. The default. */
2
+ export class InMemoryTokenStore {
3
+ tokens = new Map();
4
+ async get(key) {
5
+ return this.tokens.get(key) ?? null;
6
+ }
7
+ async set(key, token) {
8
+ this.tokens.set(key, token);
9
+ }
10
+ async delete(key) {
11
+ this.tokens.delete(key);
12
+ }
13
+ }
@@ -0,0 +1,25 @@
1
+ import { type TokenStore } from './auth/token-store.js';
2
+ import { PuntjesApi } from './generated/sdk.gen.js';
3
+ export declare const DEFAULT_BASE_URL = "https://puntjes.app";
4
+ export interface PuntjesOptions {
5
+ clientId: string;
6
+ clientSecret: string;
7
+ /** The Puntjes host, with or without `/api/v1`. Production by default. */
8
+ baseUrl?: string;
9
+ /** A fetch to send every request through, for a proxy or a test; it must honour `init.signal`. The global fetch by default. */
10
+ fetch?: (request: Request, init: {
11
+ signal?: AbortSignal;
12
+ }) => Promise<Response>;
13
+ /** How many times a failed call that is safe to repeat is sent again. 2 by default. */
14
+ maxRetries?: number;
15
+ /** The first wait before a retry, in milliseconds, doubled for each next one. 500 by default. */
16
+ retryBaseDelay?: number;
17
+ /** How long one attempt may take, in milliseconds. 30000 by default. */
18
+ timeout?: number;
19
+ /** Where tokens are kept between calls. In this process by default. */
20
+ tokenStore?: TokenStore;
21
+ /** How to wait between retries, for a test. */
22
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
23
+ }
24
+ /** Builds the generated `PuntjesApi` with authentication, retries and typed errors. */
25
+ export declare function createPuntjes(options: PuntjesOptions): PuntjesApi;
@@ -0,0 +1,48 @@
1
+ import { TokenSource, tokenKey } from './auth/token-source.js';
2
+ import { InMemoryTokenStore } from './auth/token-store.js';
3
+ import { createClient, createConfig } from './generated/client/index.js';
4
+ import { PuntjesApi } from './generated/sdk.gen.js';
5
+ import { authFetch } from './http/auth-fetch.js';
6
+ import { errorFetch } from './http/error-fetch.js';
7
+ import { asGlobalFetch } from './http/fetch.js';
8
+ import { retryFetch } from './http/retry-fetch.js';
9
+ export const DEFAULT_BASE_URL = 'https://puntjes.app';
10
+ const API_PREFIX = '/api/v1';
11
+ const TOKEN_PATH = '/oauth/token';
12
+ const UNSIGNED_TOKEN = 'pending';
13
+ /** Builds the generated `PuntjesApi` with authentication, retries and typed errors. */
14
+ export function createPuntjes(options) {
15
+ if (!options.clientId?.trim() || !options.clientSecret?.trim()) {
16
+ throw new TypeError('createPuntjes needs a clientId and a clientSecret.');
17
+ }
18
+ const host = hostOf(options.baseUrl ?? DEFAULT_BASE_URL);
19
+ const transport = (request, init = {}) => (options.fetch ?? globalThis.fetch)(request, init);
20
+ const retry = {
21
+ maxRetries: options.maxRetries ?? 2,
22
+ retryBaseDelay: options.retryBaseDelay ?? 500,
23
+ timeout: options.timeout ?? 30_000,
24
+ sleep: options.sleep ?? sleep,
25
+ };
26
+ const grants = retryFetch(transport, { ...retry, repeatEveryMethod: true });
27
+ const tokens = new TokenSource(options.clientId, options.clientSecret, host + TOKEN_PATH, tokenKey(host, options.clientId, options.clientSecret), options.tokenStore ?? new InMemoryTokenStore(), grants);
28
+ const client = createClient(createConfig({
29
+ baseUrl: host + API_PREFIX,
30
+ auth: () => UNSIGNED_TOKEN,
31
+ fetch: asGlobalFetch(errorFetch(retryFetch(authFetch(transport, tokens), retry))),
32
+ throwOnError: true,
33
+ }));
34
+ return new PuntjesApi({ client });
35
+ }
36
+ function hostOf(baseUrl) {
37
+ const trimmed = baseUrl.replace(/\/+$/, '');
38
+ return trimmed.toLowerCase().endsWith(API_PREFIX) ? trimmed.slice(0, -API_PREFIX.length) : trimmed;
39
+ }
40
+ function sleep(ms, signal) {
41
+ return new Promise((resolve, reject) => {
42
+ const timer = setTimeout(resolve, ms);
43
+ signal.addEventListener('abort', () => {
44
+ clearTimeout(timer);
45
+ reject(signal.reason);
46
+ }, { once: true });
47
+ });
48
+ }
@@ -0,0 +1,55 @@
1
+ import { type ErrorCode } from './generated/error-codes.gen.js';
2
+ export interface PuntjesErrorInit {
3
+ status?: number | null;
4
+ rawCode?: string | null;
5
+ requestId?: string | null;
6
+ details?: Record<string, unknown> | null;
7
+ cause?: unknown;
8
+ }
9
+ /**
10
+ * A call the Puntjes API refused, or one that got no usable answer. `code` is null for a code this version does not
11
+ * know yet; `rawCode` holds the code the API sent, `UNKNOWN_ERROR` or `NON_JSON_RESPONSE` when it sent none.
12
+ */
13
+ export declare class PuntjesError extends Error {
14
+ readonly status: number | null;
15
+ readonly rawCode: string | null;
16
+ readonly code: ErrorCode | null;
17
+ /** Identifies the request in the Puntjes logs. Quote it when you report a problem. */
18
+ readonly requestId: string | null;
19
+ /** Extra context; a validation error holds each rejected field and its messages here. */
20
+ readonly details: Record<string, unknown> | null;
21
+ constructor(message: string, init?: PuntjesErrorInit);
22
+ }
23
+ /** HTTP 401: the credentials or the token were refused. */
24
+ export declare class AuthenticationError extends PuntjesError {
25
+ }
26
+ /** HTTP 403. */
27
+ export declare class ForbiddenError extends PuntjesError {
28
+ }
29
+ /** HTTP 404. */
30
+ export declare class NotFoundError extends PuntjesError {
31
+ }
32
+ /** HTTP 409. */
33
+ export declare class ConflictError extends PuntjesError {
34
+ }
35
+ /** HTTP 422 with VALIDATION_ERROR; `details` holds the fields. Other 422 codes are domain refusals. */
36
+ export declare class ValidationError extends PuntjesError {
37
+ /** The messages for one rejected field, or none. */
38
+ errorsFor(field: string): string[];
39
+ }
40
+ /** HTTP 429 other than PLAN_LIMIT_EXCEEDED: wait `retryAfter` milliseconds. Only RATE_LIMITED is retried for you. */
41
+ export declare class RateLimitError extends PuntjesError {
42
+ readonly retryAfter: number | null;
43
+ constructor(message: string, init?: PuntjesErrorInit & {
44
+ retryAfter?: number | null;
45
+ });
46
+ }
47
+ /** HTTP 429 with PLAN_LIMIT_EXCEEDED: the shop's plan is used up. Waiting does not clear it. */
48
+ export declare class PlanLimitExceededError extends PuntjesError {
49
+ }
50
+ /** HTTP 5xx. */
51
+ export declare class ServerError extends PuntjesError {
52
+ }
53
+ /** No usable answer: the network failed, or something other than the Puntjes API answered. */
54
+ export declare class TransportError extends PuntjesError {
55
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,60 @@
1
+ import { isErrorCode } from './generated/error-codes.gen.js';
2
+ /**
3
+ * A call the Puntjes API refused, or one that got no usable answer. `code` is null for a code this version does not
4
+ * know yet; `rawCode` holds the code the API sent, `UNKNOWN_ERROR` or `NON_JSON_RESPONSE` when it sent none.
5
+ */
6
+ export class PuntjesError extends Error {
7
+ status;
8
+ rawCode;
9
+ code;
10
+ /** Identifies the request in the Puntjes logs. Quote it when you report a problem. */
11
+ requestId;
12
+ /** Extra context; a validation error holds each rejected field and its messages here. */
13
+ details;
14
+ constructor(message, init = {}) {
15
+ super(message, init.cause === undefined ? undefined : { cause: init.cause });
16
+ this.name = new.target.name;
17
+ this.status = init.status ?? null;
18
+ this.rawCode = init.rawCode ?? null;
19
+ this.code = this.rawCode !== null && isErrorCode(this.rawCode) ? this.rawCode : null;
20
+ this.requestId = init.requestId ?? null;
21
+ this.details = init.details ?? null;
22
+ }
23
+ }
24
+ /** HTTP 401: the credentials or the token were refused. */
25
+ export class AuthenticationError extends PuntjesError {
26
+ }
27
+ /** HTTP 403. */
28
+ export class ForbiddenError extends PuntjesError {
29
+ }
30
+ /** HTTP 404. */
31
+ export class NotFoundError extends PuntjesError {
32
+ }
33
+ /** HTTP 409. */
34
+ export class ConflictError extends PuntjesError {
35
+ }
36
+ /** HTTP 422 with VALIDATION_ERROR; `details` holds the fields. Other 422 codes are domain refusals. */
37
+ export class ValidationError extends PuntjesError {
38
+ /** The messages for one rejected field, or none. */
39
+ errorsFor(field) {
40
+ const messages = this.details?.[field];
41
+ return Array.isArray(messages) ? messages.filter((m) => typeof m === 'string') : [];
42
+ }
43
+ }
44
+ /** HTTP 429 other than PLAN_LIMIT_EXCEEDED: wait `retryAfter` milliseconds. Only RATE_LIMITED is retried for you. */
45
+ export class RateLimitError extends PuntjesError {
46
+ retryAfter;
47
+ constructor(message, init = {}) {
48
+ super(message, init);
49
+ this.retryAfter = init.retryAfter ?? null;
50
+ }
51
+ }
52
+ /** HTTP 429 with PLAN_LIMIT_EXCEEDED: the shop's plan is used up. Waiting does not clear it. */
53
+ export class PlanLimitExceededError extends PuntjesError {
54
+ }
55
+ /** HTTP 5xx. */
56
+ export class ServerError extends PuntjesError {
57
+ }
58
+ /** No usable answer: the network failed, or something other than the Puntjes API answered. */
59
+ export class TransportError extends PuntjesError {
60
+ }
@@ -0,0 +1,2 @@
1
+ import type { Client, Config } from './types.gen.js';
2
+ export declare const createClient: (config?: Config) => Client;