purser-client 0.0.0-stage → 1.6.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.
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/dist/index.d.ts +162 -0
- package/dist/index.js +186 -0
- package/package.json +31 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Max Geurtsen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Purser TypeScript client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small, typed client for Purser Cloud's API. It lists invoices, proposes an invoice's payment for the CFO's approval
|
|
4
|
+
and reads a proposal's status. It has no dependencies (the platform's `fetch`, Node 22.13 or later) and calls only the
|
|
5
|
+
operations of [`openapi/purser.yaml`](../../openapi/purser.yaml), under their `operationId`s
|
|
6
|
+
(`test/sdk-typescript.test.ts` checks every one).
|
|
7
|
+
|
|
8
|
+
**It cannot approve.** Approving a payment is the CFO's passkey over the exact terms, in Purser Cloud. The API refuses
|
|
9
|
+
every key there, and this client has no method for it. Test money only until a company goes live.
|
|
10
|
+
|
|
11
|
+
```mermaid
|
|
12
|
+
sequenceDiagram
|
|
13
|
+
participant Y as Your code (this client)
|
|
14
|
+
participant P as Purser Cloud API
|
|
15
|
+
participant C as CFO (passkey, in Purser Cloud)
|
|
16
|
+
Y->>P: listInvoices / listPayableInvoices (read scope)
|
|
17
|
+
P-->>Y: invoices
|
|
18
|
+
Y->>P: proposePayment(id) (propose scope)
|
|
19
|
+
P-->>Y: proposal PENDING_APPROVAL, with terms_sha256
|
|
20
|
+
Note over Y,P: no method approves, and the API refuses every key there
|
|
21
|
+
C->>P: signs the SHA-256 of the exact terms
|
|
22
|
+
Y->>P: getProposal(id)
|
|
23
|
+
P-->>Y: APPROVED, then EXECUTED (or REJECTED, EXPIRED)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Status: tested locally against Purser Cloud in-process. Packaged as `purser-client` (ESM with type declarations):
|
|
27
|
+
`test/sdk-packages.test.ts` packs it with `npm pack`, installs the tarball into an empty project and imports it with
|
|
28
|
+
plain `node`. **Not yet published to npm**; publishing is the owner's step ([docs/releasing.md](../../docs/releasing.md),
|
|
29
|
+
"Packages"). Until then, install it from a clone:
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
cd sdk/typescript && npm pack # builds dist/ and writes purser-client-<version>.tgz (needs the repo's npm ci)
|
|
33
|
+
cd your-project && npm install /path/to/purser-client-<version>.tgz
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Once it is published: `npm install purser-client`. Or use it from this repository (`sdk/typescript/src/index.ts`).
|
|
37
|
+
|
|
38
|
+
## Quickstart
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
export PURSER_BASE_URL=https://purser.example.com # your Purser Cloud (PURSER_URL works too)
|
|
42
|
+
export PURSER_API_KEY=pck_... # an owner makes it: scopes read and propose; never in code
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { Purser, PurserError } from "purser-client"; // or "./sdk/typescript/src/index.js" in a clone
|
|
47
|
+
|
|
48
|
+
const purser = Purser.fromEnv();
|
|
49
|
+
|
|
50
|
+
// 1. List invoices (one page; purser.invoices() walks every page)
|
|
51
|
+
const page = await purser.listInvoices({ status: "ready", limit: 20 });
|
|
52
|
+
for (const inv of page.items) console.log(inv.id, inv.vendor, inv.currency, inv.total);
|
|
53
|
+
|
|
54
|
+
// 2. Propose a payment for the CFO's approval (a key with the propose scope)
|
|
55
|
+
const payable = (await purser.listPayableInvoices()).find((i) => i.payable && !i.proposal);
|
|
56
|
+
if (payable) {
|
|
57
|
+
try {
|
|
58
|
+
const { proposal } = await purser.proposePayment(payable.id);
|
|
59
|
+
console.log(`${proposal.id} waits for the CFO's passkey`); // nothing is paid yet
|
|
60
|
+
} catch (e) {
|
|
61
|
+
if (e instanceof PurserError && e.status === 409) console.log("Purser did not file it:", e.message);
|
|
62
|
+
else throw e;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 3. Read a proposal's status
|
|
67
|
+
const p = await purser.getProposal("P-0009");
|
|
68
|
+
console.log(p.status); // PENDING_APPROVAL, then APPROVED and EXECUTED, or REJECTED or EXPIRED
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Notes
|
|
72
|
+
|
|
73
|
+
- `baseUrl` must be https (http only for localhost). The key is sent as `Authorization: Bearer` and never logged.
|
|
74
|
+
- Errors are `PurserError` with `status` and `code`: `forbidden` for a scope the key lacks, `conflict` when Purser
|
|
75
|
+
will not file (held, waiting or paid; the message says why), and `not_found`.
|
|
76
|
+
- `invoices()` follows `next_cursor` page by page. If the server sends a cursor it already gave, or the same page
|
|
77
|
+
again, it throws `PurserError` (`repeated_cursor`, `repeated_page`) before yielding that page, instead of reading
|
|
78
|
+
the same invoices for ever.
|
|
79
|
+
- If the CFO set a pay-alone limit (off unless set), a proposal within it is paid under the CFO's own policy, and the
|
|
80
|
+
answer says so in `alone`.
|
|
81
|
+
- Pass `fetch` to use your own (a proxy, a test).
|
|
82
|
+
- Each request is given up after `timeoutMs` (30,000 by default; 0 for none), and `signal` (an `AbortSignal`) stops
|
|
83
|
+
every request of the client, and any wait before a retry, when it fires.
|
|
84
|
+
- Every POST carries an `Idempotency-Key`: a new UUID, or yours (`proposePayment(id, { idempotencyKey })`). Purser
|
|
85
|
+
Cloud answers the same key and request within 24 hours with the first answer, so the payment is filed once.
|
|
86
|
+
- A read (GET), or a POST with its `Idempotency-Key`, answered 429 or 5xx is tried again up to `retries` times (2 by
|
|
87
|
+
default; every try the same key), waiting as the answer's `Retry-After` says (at most a minute), else 0.5 s, 1 s, 2 s
|
|
88
|
+
with jitter. With `idempotencyKeys: false` a POST carries no key and is never tried again.
|
|
89
|
+
- Requests carry `User-Agent: purser-client/<version>`. A proposal's `status` is a `ProposalStatus`
|
|
90
|
+
(`PENDING_APPROVAL`, `APPROVED`, `EXECUTED`, `FAILED`, `REJECTED` or `EXPIRED`). `Purser.fromEnv()` reads
|
|
91
|
+
`PURSER_BASE_URL` (or `PURSER_URL`) and `PURSER_API_KEY` where the platform has `process.env`; elsewhere pass the values.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/** A supplier invoice as the company's records hold it (OpenAPI: Invoice). */
|
|
2
|
+
export interface Invoice {
|
|
3
|
+
id: string;
|
|
4
|
+
version: number;
|
|
5
|
+
vendor?: string;
|
|
6
|
+
invoice_no?: string;
|
|
7
|
+
due_date?: string;
|
|
8
|
+
currency?: string;
|
|
9
|
+
total?: string;
|
|
10
|
+
status?: string;
|
|
11
|
+
[field: string]: unknown;
|
|
12
|
+
}
|
|
13
|
+
export interface InvoiceDetail extends Invoice {
|
|
14
|
+
earlier_versions?: {
|
|
15
|
+
version: number;
|
|
16
|
+
replaced_at: string;
|
|
17
|
+
}[];
|
|
18
|
+
}
|
|
19
|
+
export interface InvoicePage {
|
|
20
|
+
items: Invoice[];
|
|
21
|
+
next_cursor: string | null;
|
|
22
|
+
}
|
|
23
|
+
/** Where a proposal stands (OpenAPI: Proposal.status): PENDING_APPROVAL waits for the CFO's passkey. */
|
|
24
|
+
export type ProposalStatus = "PENDING_APPROVAL" | "APPROVED" | "EXECUTED" | "FAILED" | "REJECTED" | "EXPIRED";
|
|
25
|
+
export declare const PROPOSAL_STATUSES: readonly ProposalStatus[];
|
|
26
|
+
/** A payment proposal: the exact terms the CFO's passkey signs (OpenAPI: Proposal). */
|
|
27
|
+
export interface Proposal {
|
|
28
|
+
id: string;
|
|
29
|
+
kind: string;
|
|
30
|
+
/** PENDING_APPROVAL waits for the CFO; APPROVED, EXECUTED, FAILED, REJECTED or EXPIRED after. */
|
|
31
|
+
status: ProposalStatus;
|
|
32
|
+
terms_sha256: string;
|
|
33
|
+
challenge?: string;
|
|
34
|
+
facts?: [string, string][];
|
|
35
|
+
warnings?: string[];
|
|
36
|
+
[field: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
/** What filing a proposal answers (OpenAPI: ProposeAnswer). `alone` only when a pay-alone limit the CFO set covered it. */
|
|
39
|
+
export interface ProposeAnswer {
|
|
40
|
+
proposal: Proposal;
|
|
41
|
+
alone?: Record<string, unknown>;
|
|
42
|
+
settled?: Record<string, unknown> | null;
|
|
43
|
+
[field: string]: unknown;
|
|
44
|
+
}
|
|
45
|
+
/** An invoice as the company's engine sees it (OpenAPI: EngineInvoice). */
|
|
46
|
+
export interface PayableInvoice {
|
|
47
|
+
id: string;
|
|
48
|
+
status: string;
|
|
49
|
+
status_words?: string;
|
|
50
|
+
payable: boolean;
|
|
51
|
+
vendor: string;
|
|
52
|
+
invoice_no?: string;
|
|
53
|
+
currency: string;
|
|
54
|
+
total: string;
|
|
55
|
+
due_date?: string;
|
|
56
|
+
findings?: {
|
|
57
|
+
level: string;
|
|
58
|
+
code: string;
|
|
59
|
+
message: string;
|
|
60
|
+
}[];
|
|
61
|
+
proposal: Proposal | null;
|
|
62
|
+
[field: string]: unknown;
|
|
63
|
+
}
|
|
64
|
+
export type Scope = "read" | "sync" | "admin" | "propose";
|
|
65
|
+
export interface Me {
|
|
66
|
+
tenant: {
|
|
67
|
+
id: string;
|
|
68
|
+
slug?: string;
|
|
69
|
+
name?: string;
|
|
70
|
+
language?: string;
|
|
71
|
+
};
|
|
72
|
+
kind: "key" | "session";
|
|
73
|
+
scopes: Scope[];
|
|
74
|
+
role: string | null;
|
|
75
|
+
[field: string]: unknown;
|
|
76
|
+
}
|
|
77
|
+
/** The operations this client calls, by OpenAPI operationId: [method, path]. */
|
|
78
|
+
export declare const OPERATIONS: {
|
|
79
|
+
readonly getMe: readonly ["GET", "/v1/me"];
|
|
80
|
+
readonly listInvoices: readonly ["GET", "/v1/invoices"];
|
|
81
|
+
readonly getInvoice: readonly ["GET", "/v1/invoices/{id}"];
|
|
82
|
+
readonly listPayableInvoices: readonly ["GET", "/v1/engine/invoices"];
|
|
83
|
+
readonly proposePayment: readonly ["POST", "/v1/engine/invoices/{id}/pay"];
|
|
84
|
+
readonly getProposal: readonly ["GET", "/v1/engine/proposals/{id}"];
|
|
85
|
+
};
|
|
86
|
+
export type OperationId = keyof typeof OPERATIONS;
|
|
87
|
+
/**
|
|
88
|
+
* An answer that was not 2xx (the API's sentence for a person and its stable code for a program), or a 2xx answer the
|
|
89
|
+
* client cannot use: not_json, or repeated_cursor and repeated_page while paging (invoices()).
|
|
90
|
+
*/
|
|
91
|
+
export declare class PurserError extends Error {
|
|
92
|
+
readonly status: number;
|
|
93
|
+
readonly code: string;
|
|
94
|
+
constructor(status: number, code: string, message: string);
|
|
95
|
+
}
|
|
96
|
+
/** This client's version, sent in its User-Agent (purser-client/<version>); the package's own (test/sdk-typescript.test.ts). */
|
|
97
|
+
export declare const VERSION = "1.6.0";
|
|
98
|
+
export declare const USER_AGENT = "purser-client/1.6.0";
|
|
99
|
+
export interface PurserOptions {
|
|
100
|
+
/** Your Purser Cloud, like https://purser.example.com (https; http only for localhost). */
|
|
101
|
+
baseUrl: string;
|
|
102
|
+
/** An API key (pck_…) from the environment, never from code. read to read; read and propose to file payments. */
|
|
103
|
+
apiKey: string;
|
|
104
|
+
/** Another fetch (a test's, a proxy's); the platform's by default. */
|
|
105
|
+
fetch?: (input: string, init?: RequestInit) => Promise<Response>;
|
|
106
|
+
/** Each request (each try, when a read is tried again) is given up after this many milliseconds: 30,000 by default; 0 for none. */
|
|
107
|
+
timeoutMs?: number;
|
|
108
|
+
/** Aborts every request of this client, and any wait before a retry, when it fires. */
|
|
109
|
+
signal?: AbortSignal;
|
|
110
|
+
/**
|
|
111
|
+
* How many more times a request is tried after a 429 or a 5xx answer: 2 by default, 0 for none. It waits as the
|
|
112
|
+
* answer's Retry-After says (seconds or a date, at most a minute), else 0.5 s, 1 s, 2 s... with jitter. A read (GET)
|
|
113
|
+
* always; a POST only when it carries an Idempotency-Key (the default), so the server files it once.
|
|
114
|
+
*/
|
|
115
|
+
retries?: number;
|
|
116
|
+
/**
|
|
117
|
+
* Whether each POST carries an Idempotency-Key (a new random UUID, or the one the call gives): true by default. The
|
|
118
|
+
* server answers the same key and body with the first answer for 24 hours. false: no key, and a POST is never tried again.
|
|
119
|
+
*/
|
|
120
|
+
idempotencyKeys?: boolean;
|
|
121
|
+
}
|
|
122
|
+
/** Per call: the Idempotency-Key to send (your own order or job id), instead of one the client makes. */
|
|
123
|
+
export interface PostOptions {
|
|
124
|
+
idempotencyKey?: string;
|
|
125
|
+
}
|
|
126
|
+
/** Whether an answer's status is worth asking again (a read only): too many requests, or the server's fault. */
|
|
127
|
+
export declare const RETRYABLE: (status: number) => boolean;
|
|
128
|
+
/** How long to wait before retry n (1 for the first), in milliseconds: Retry-After when usable, else backoff with jitter. */
|
|
129
|
+
export declare function retryDelay(attempt: number, retryAfter: string | null, now?: number, random?: () => number): number;
|
|
130
|
+
export interface ListInvoicesQuery {
|
|
131
|
+
status?: string;
|
|
132
|
+
dueFrom?: string;
|
|
133
|
+
dueTo?: string;
|
|
134
|
+
limit?: number;
|
|
135
|
+
cursor?: string;
|
|
136
|
+
}
|
|
137
|
+
export declare class Purser {
|
|
138
|
+
#private;
|
|
139
|
+
constructor(o: PurserOptions);
|
|
140
|
+
/** A client from PURSER_BASE_URL (or PURSER_URL) and PURSER_API_KEY (the platform's environment, where it has one). */
|
|
141
|
+
static fromEnv(env?: Record<string, string | undefined>): Purser;
|
|
142
|
+
/** Who is calling: the company and this key's scopes. */
|
|
143
|
+
me(): Promise<Me>;
|
|
144
|
+
/** One page of supplier invoices; next_cursor fetches the next. */
|
|
145
|
+
listInvoices(q?: ListInvoicesQuery): Promise<InvoicePage>;
|
|
146
|
+
/**
|
|
147
|
+
* Every invoice that matches, page by page. A server that hands back a cursor it gave before, or the same page again,
|
|
148
|
+
* would have this read the same invoices for ever: it throws a PurserError (repeated_cursor, repeated_page) before
|
|
149
|
+
* yielding that page.
|
|
150
|
+
*/
|
|
151
|
+
invoices(q?: Omit<ListInvoicesQuery, "cursor">): AsyncGenerator<Invoice>;
|
|
152
|
+
getInvoice(id: string): Promise<InvoiceDetail>;
|
|
153
|
+
/** The engine's invoices: whether each can be proposed (payable) and its proposal, if one was filed. */
|
|
154
|
+
listPayableInvoices(): Promise<PayableInvoice[]>;
|
|
155
|
+
/**
|
|
156
|
+
* File an invoice's payment for the CFO's approval (a key with the propose scope). Nothing is paid until the CFO signs
|
|
157
|
+
* these exact terms with their passkey in Purser Cloud. A 409 PurserError says why Purser would not file it.
|
|
158
|
+
*/
|
|
159
|
+
proposePayment(invoiceId: string, o?: PostOptions): Promise<ProposeAnswer>;
|
|
160
|
+
/** Where a proposal stands: PENDING_APPROVAL until the CFO's passkey, then APPROVED and EXECUTED, or REJECTED or EXPIRED. */
|
|
161
|
+
getProposal(id: string): Promise<Proposal>;
|
|
162
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// Purser's TypeScript client (sdk/typescript/README.md): read the books, propose an invoice's payment, read a proposal's
|
|
2
|
+
// status. No dependency: the platform's fetch. Its operations are those of openapi/purser.yaml (test/sdk-typescript.test.ts
|
|
3
|
+
// checks every one against the document).
|
|
4
|
+
//
|
|
5
|
+
// What it cannot do, on purpose: approve. Approving a payment is a signed-in person's passkey over the exact terms, in
|
|
6
|
+
// Purser Cloud; the API refuses every key there, and this client has no method for it.
|
|
7
|
+
export const PROPOSAL_STATUSES = ["PENDING_APPROVAL", "APPROVED", "EXECUTED", "FAILED", "REJECTED", "EXPIRED"];
|
|
8
|
+
/** The operations this client calls, by OpenAPI operationId: [method, path]. */
|
|
9
|
+
export const OPERATIONS = {
|
|
10
|
+
getMe: ["GET", "/v1/me"],
|
|
11
|
+
listInvoices: ["GET", "/v1/invoices"],
|
|
12
|
+
getInvoice: ["GET", "/v1/invoices/{id}"],
|
|
13
|
+
listPayableInvoices: ["GET", "/v1/engine/invoices"],
|
|
14
|
+
proposePayment: ["POST", "/v1/engine/invoices/{id}/pay"],
|
|
15
|
+
getProposal: ["GET", "/v1/engine/proposals/{id}"],
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* An answer that was not 2xx (the API's sentence for a person and its stable code for a program), or a 2xx answer the
|
|
19
|
+
* client cannot use: not_json, or repeated_cursor and repeated_page while paging (invoices()).
|
|
20
|
+
*/
|
|
21
|
+
export class PurserError extends Error {
|
|
22
|
+
status;
|
|
23
|
+
code;
|
|
24
|
+
constructor(status, code, message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.status = status;
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.name = "PurserError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** This client's version, sent in its User-Agent (purser-client/<version>); the package's own (test/sdk-typescript.test.ts). */
|
|
32
|
+
export const VERSION = "1.6.0";
|
|
33
|
+
export const USER_AGENT = `purser-client/${VERSION}`;
|
|
34
|
+
/** Whether an answer's status is worth asking again (a read only): too many requests, or the server's fault. */
|
|
35
|
+
export const RETRYABLE = (status) => status === 429 || (status >= 500 && status <= 599);
|
|
36
|
+
/** How long to wait before retry n (1 for the first), in milliseconds: Retry-After when usable, else backoff with jitter. */
|
|
37
|
+
export function retryDelay(attempt, retryAfter, now = Date.now(), random = Math.random) {
|
|
38
|
+
const MAX = 60_000;
|
|
39
|
+
const v = retryAfter?.trim() ?? "";
|
|
40
|
+
if (/^\d+$/.test(v))
|
|
41
|
+
return Math.min(Number(v) * 1000, MAX);
|
|
42
|
+
const at = v ? Date.parse(v) : Number.NaN;
|
|
43
|
+
if (!Number.isNaN(at))
|
|
44
|
+
return Math.min(Math.max(at - now, 0), MAX);
|
|
45
|
+
const base = Math.min(500 * 2 ** (attempt - 1), 8_000);
|
|
46
|
+
return Math.round(base / 2 + random() * (base / 2));
|
|
47
|
+
}
|
|
48
|
+
/** The environment where there is one (Node, Bun, Deno's process); none in a browser or a Worker without it. */
|
|
49
|
+
const platformEnv = () => globalThis.process?.env ?? {};
|
|
50
|
+
const LOCAL = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
51
|
+
const ID = /^[A-Za-z0-9_.:-]{1,120}$/;
|
|
52
|
+
export class Purser {
|
|
53
|
+
#base;
|
|
54
|
+
#key;
|
|
55
|
+
#fetch;
|
|
56
|
+
#timeoutMs;
|
|
57
|
+
#signal;
|
|
58
|
+
#retries;
|
|
59
|
+
#idempotencyKeys;
|
|
60
|
+
constructor(o) {
|
|
61
|
+
const url = new URL(o.baseUrl);
|
|
62
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL.has(url.hostname)))
|
|
63
|
+
throw new Error("baseUrl must be https (http only for localhost)");
|
|
64
|
+
if (!o.apiKey)
|
|
65
|
+
throw new Error("apiKey is empty: read it from the environment (PURSER_API_KEY)");
|
|
66
|
+
this.#base = url.origin;
|
|
67
|
+
this.#key = o.apiKey;
|
|
68
|
+
this.#fetch = o.fetch ?? ((i, init) => fetch(i, init));
|
|
69
|
+
const whole = (v, d, what) => {
|
|
70
|
+
if (v === undefined)
|
|
71
|
+
return d;
|
|
72
|
+
if (!Number.isInteger(v) || v < 0)
|
|
73
|
+
throw new Error(`${what} must be a whole number, 0 or more`);
|
|
74
|
+
return v;
|
|
75
|
+
};
|
|
76
|
+
this.#timeoutMs = whole(o.timeoutMs, 30_000, "timeoutMs");
|
|
77
|
+
this.#retries = whole(o.retries, 2, "retries");
|
|
78
|
+
this.#idempotencyKeys = o.idempotencyKeys ?? true;
|
|
79
|
+
this.#signal = o.signal;
|
|
80
|
+
}
|
|
81
|
+
/** A client from PURSER_BASE_URL (or PURSER_URL) and PURSER_API_KEY (the platform's environment, where it has one). */
|
|
82
|
+
static fromEnv(env = platformEnv()) {
|
|
83
|
+
return new Purser({ baseUrl: env.PURSER_BASE_URL || env.PURSER_URL || "", apiKey: env.PURSER_API_KEY ?? "" });
|
|
84
|
+
}
|
|
85
|
+
async #call(op, id, query, post = {}) {
|
|
86
|
+
const [method, path] = OPERATIONS[op];
|
|
87
|
+
if (path.includes("{id}") && !(id && ID.test(id)))
|
|
88
|
+
throw new Error(`${op} needs an id like AP-0004 or P-0009`);
|
|
89
|
+
const qs = new URLSearchParams(Object.entries(query ?? {}).filter((e) => e[1] !== undefined).map(([k, v]) => [k, String(v)]));
|
|
90
|
+
const search = qs.toString();
|
|
91
|
+
const url = `${this.#base}${path.replace("{id}", encodeURIComponent(id ?? ""))}${search ? `?${search}` : ""}`;
|
|
92
|
+
const key = method === "POST" ? (post.idempotencyKey ?? (this.#idempotencyKeys ? crypto.randomUUID() : undefined)) : undefined;
|
|
93
|
+
if (key !== undefined && !/^[\x21-\x7e]{1,255}$/.test(key))
|
|
94
|
+
throw new Error("idempotencyKey is 1 to 255 printable characters without spaces");
|
|
95
|
+
const res = await this.#send(url, method, key);
|
|
96
|
+
const text = await res.text();
|
|
97
|
+
let body = null;
|
|
98
|
+
try {
|
|
99
|
+
body = text ? JSON.parse(text) : null;
|
|
100
|
+
}
|
|
101
|
+
catch { /* not JSON: said below */ }
|
|
102
|
+
if (!res.ok) {
|
|
103
|
+
const e = (body ?? {});
|
|
104
|
+
throw new PurserError(res.status, e.code ?? "error", e.error ?? `HTTP ${res.status}`);
|
|
105
|
+
}
|
|
106
|
+
if (body === null)
|
|
107
|
+
throw new PurserError(res.status, "not_json", "the answer was not JSON");
|
|
108
|
+
return body;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* One request, with the timeout and the client's signal; tried again after a 429 or a 5xx, as `retries` says, when it
|
|
112
|
+
* is a read or carries an Idempotency-Key (every try the same key).
|
|
113
|
+
*/
|
|
114
|
+
async #send(url, method, idempotencyKey) {
|
|
115
|
+
const tries = method === "GET" || idempotencyKey !== undefined ? this.#retries + 1 : 1;
|
|
116
|
+
for (let attempt = 1;; attempt++) {
|
|
117
|
+
this.#signal?.throwIfAborted();
|
|
118
|
+
const signals = [this.#signal, this.#timeoutMs ? AbortSignal.timeout(this.#timeoutMs) : undefined].filter((x) => x !== undefined);
|
|
119
|
+
const res = await this.#fetch(url, {
|
|
120
|
+
method,
|
|
121
|
+
headers: { authorization: `Bearer ${this.#key}`, accept: "application/json", "user-agent": USER_AGENT, ...(idempotencyKey !== undefined ? { "idempotency-key": idempotencyKey } : {}) },
|
|
122
|
+
...(signals.length ? { signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals) } : {}),
|
|
123
|
+
});
|
|
124
|
+
if (attempt >= tries || !RETRYABLE(res.status))
|
|
125
|
+
return res;
|
|
126
|
+
await res.body?.cancel().catch(() => undefined);
|
|
127
|
+
await sleep(retryDelay(attempt, res.headers.get("retry-after")), this.#signal);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** Who is calling: the company and this key's scopes. */
|
|
131
|
+
me() { return this.#call("getMe"); }
|
|
132
|
+
/** One page of supplier invoices; next_cursor fetches the next. */
|
|
133
|
+
listInvoices(q = {}) {
|
|
134
|
+
return this.#call("listInvoices", undefined, { status: q.status, due_from: q.dueFrom, due_to: q.dueTo, limit: q.limit, cursor: q.cursor });
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Every invoice that matches, page by page. A server that hands back a cursor it gave before, or the same page again,
|
|
138
|
+
* would have this read the same invoices for ever: it throws a PurserError (repeated_cursor, repeated_page) before
|
|
139
|
+
* yielding that page.
|
|
140
|
+
*/
|
|
141
|
+
async *invoices(q = {}) {
|
|
142
|
+
let cursor;
|
|
143
|
+
const seen = new Set();
|
|
144
|
+
let previous;
|
|
145
|
+
do {
|
|
146
|
+
const page = await this.listInvoices({ ...q, ...(cursor ? { cursor } : {}) });
|
|
147
|
+
const next = page.next_cursor ?? undefined;
|
|
148
|
+
if (next && seen.has(next))
|
|
149
|
+
throw new PurserError(200, "repeated_cursor", `the server sent the cursor ${JSON.stringify(next)} again: stopped paging so the same invoices are not read twice`);
|
|
150
|
+
const items = JSON.stringify(page.items);
|
|
151
|
+
if (page.items.length && items === previous)
|
|
152
|
+
throw new PurserError(200, "repeated_page", "the server sent the same page of invoices again under a new cursor: stopped paging so they are not read twice");
|
|
153
|
+
if (next)
|
|
154
|
+
seen.add(next);
|
|
155
|
+
previous = items;
|
|
156
|
+
yield* page.items;
|
|
157
|
+
cursor = next;
|
|
158
|
+
} while (cursor);
|
|
159
|
+
}
|
|
160
|
+
getInvoice(id) { return this.#call("getInvoice", id); }
|
|
161
|
+
/** The engine's invoices: whether each can be proposed (payable) and its proposal, if one was filed. */
|
|
162
|
+
async listPayableInvoices() {
|
|
163
|
+
return (await this.#call("listPayableInvoices")).items;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* File an invoice's payment for the CFO's approval (a key with the propose scope). Nothing is paid until the CFO signs
|
|
167
|
+
* these exact terms with their passkey in Purser Cloud. A 409 PurserError says why Purser would not file it.
|
|
168
|
+
*/
|
|
169
|
+
proposePayment(invoiceId, o = {}) { return this.#call("proposePayment", invoiceId, undefined, o); }
|
|
170
|
+
/** Where a proposal stands: PENDING_APPROVAL until the CFO's passkey, then APPROVED and EXECUTED, or REJECTED or EXPIRED. */
|
|
171
|
+
async getProposal(id) {
|
|
172
|
+
return (await this.#call("getProposal", id)).proposal;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/** Waits, or rejects as soon as the signal fires. */
|
|
176
|
+
function sleep(ms, signal) {
|
|
177
|
+
return new Promise((resolve, reject) => {
|
|
178
|
+
if (signal?.aborted) {
|
|
179
|
+
reject(signal.reason);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const stop = () => { clearTimeout(t); reject(signal.reason); };
|
|
183
|
+
const t = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(); }, ms);
|
|
184
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
185
|
+
});
|
|
186
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "purser-client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.6.0",
|
|
4
|
+
"description": "Purser's TypeScript client: read the books, propose an invoice's payment, read a proposal's status. It cannot approve: only the CFO's passkey does.",
|
|
5
|
+
"keywords": ["purser", "accounts-payable", "payments", "x402"],
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/agamemnon-coder/x402-business-agents/tree/main/sdk/typescript#readme",
|
|
8
|
+
"bugs": "https://github.com/agamemnon-coder/x402-business-agents/issues",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/agamemnon-coder/x402-business-agents.git",
|
|
12
|
+
"directory": "sdk/typescript"
|
|
13
|
+
},
|
|
14
|
+
"private": false,
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"engines": { "node": "^22.13.0 || >=24" },
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.json",
|
|
30
|
+
"prepack": "npm run build"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": { "access": "public", "provenance": true }
|
|
33
|
+
}
|