@proofline/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.
@@ -0,0 +1,38 @@
1
+ declare const inspect: unique symbol;
2
+ export declare class SecretToken {
3
+ #private;
4
+ constructor(value: string);
5
+ apply(headers: Headers): void;
6
+ toString(): string;
7
+ toJSON(): string;
8
+ [inspect](): string;
9
+ }
10
+ export declare class ProoflineError extends Error {
11
+ #private;
12
+ readonly status: number;
13
+ constructor(status: number, type: string, detail: string);
14
+ get type(): string;
15
+ get detail(): string;
16
+ toJSON(): {
17
+ status: number;
18
+ };
19
+ [inspect](): string;
20
+ }
21
+ export interface ClientOptions {
22
+ baseUrl: string;
23
+ token?: string | SecretToken;
24
+ requestTimeoutMs?: number;
25
+ }
26
+ export interface Parameters {
27
+ path?: object;
28
+ query?: object;
29
+ }
30
+ export type Invoke = <T>(method: string, template: string, parameters: Parameters, body?: object) => Promise<T>;
31
+ export declare function sleep(milliseconds: number): Promise<void>;
32
+ export declare class Transport {
33
+ #private;
34
+ constructor(options: ClientOptions);
35
+ reviewUrl(orgId: string, reviewId: string): string;
36
+ request<T>(method: string, template: string, parameters: Parameters, deadline?: number, body?: object): Promise<T>;
37
+ }
38
+ export {};
@@ -0,0 +1,255 @@
1
+ const VERSION = "1.0.0";
2
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
3
+ const MAX_RETRIES = 3;
4
+ const MAX_RETRY_SECONDS = 60;
5
+ const inspect = Symbol.for("nodejs.util.inspect.custom");
6
+ export class SecretToken {
7
+ #value;
8
+ constructor(value) {
9
+ if (!value ||
10
+ /\s/.test(value) ||
11
+ Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
12
+ throw new TypeError("a nonempty Proofline token without whitespace is required");
13
+ }
14
+ this.#value = value;
15
+ }
16
+ apply(headers) {
17
+ headers.set("Authorization", `Bearer ${this.#value}`);
18
+ }
19
+ toString() {
20
+ return "SecretToken([redacted])";
21
+ }
22
+ toJSON() {
23
+ return "[redacted]";
24
+ }
25
+ [inspect]() {
26
+ return this.toString();
27
+ }
28
+ }
29
+ export class ProoflineError extends Error {
30
+ status;
31
+ #problemType;
32
+ #detail;
33
+ constructor(status, type, detail) {
34
+ super(`Proofline request failed with status ${status}`);
35
+ this.status = status;
36
+ this.name = "ProoflineError";
37
+ this.#problemType = type;
38
+ this.#detail = detail;
39
+ }
40
+ get type() {
41
+ return this.#problemType;
42
+ }
43
+ get detail() {
44
+ return this.#detail;
45
+ }
46
+ toJSON() {
47
+ return { status: this.status };
48
+ }
49
+ [inspect]() {
50
+ return this.toString();
51
+ }
52
+ }
53
+ function environmentToken() {
54
+ return typeof process === "undefined"
55
+ ? undefined
56
+ : process.env.PROOFLINE_TOKEN;
57
+ }
58
+ function origin(value) {
59
+ let url;
60
+ try {
61
+ url = new URL(value);
62
+ }
63
+ catch {
64
+ throw new TypeError("baseUrl must be an absolute HTTPS URL or loopback HTTP URL");
65
+ }
66
+ const loopback = url.hostname === "localhost" ||
67
+ url.hostname === "[::1]" ||
68
+ /^127\.\d+\.\d+\.\d+$/.test(url.hostname);
69
+ if ((url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) ||
70
+ url.username ||
71
+ url.password ||
72
+ url.search ||
73
+ url.hash ||
74
+ url.pathname !== "/") {
75
+ throw new TypeError("baseUrl must be an HTTPS origin or loopback HTTP origin without credentials");
76
+ }
77
+ return url;
78
+ }
79
+ function positive(value, name) {
80
+ if (!Number.isFinite(value) || value <= 0) {
81
+ throw new TypeError(`${name} must be a finite positive number`);
82
+ }
83
+ return value;
84
+ }
85
+ async function json(response, deadline, signal, waitTimeout) {
86
+ const reader = response.body?.getReader();
87
+ if (!reader) {
88
+ throw new ProoflineError(response.status, "urn:proofline:sdk:invalid-response", "the response has no JSON body");
89
+ }
90
+ const chunks = [];
91
+ let size = 0;
92
+ try {
93
+ for (;;) {
94
+ const { value, done } = await reader.read();
95
+ if (done)
96
+ break;
97
+ size += value.byteLength;
98
+ if (size > MAX_RESPONSE_BYTES) {
99
+ await reader.cancel();
100
+ throw new ProoflineError(response.status, "urn:proofline:sdk:invalid-response", "the response exceeds 8 MiB");
101
+ }
102
+ chunks.push(value);
103
+ }
104
+ const data = new Uint8Array(size);
105
+ let offset = 0;
106
+ for (const chunk of chunks) {
107
+ data.set(chunk, offset);
108
+ offset += chunk.length;
109
+ }
110
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(data));
111
+ }
112
+ catch (error) {
113
+ if (error instanceof ProoflineError)
114
+ throw error;
115
+ if (response.ok && (signal.aborted || performance.now() >= deadline))
116
+ throw new ProoflineError(0, waitTimeout
117
+ ? "urn:proofline:sdk:timeout"
118
+ : "urn:proofline:sdk:transport", waitTimeout
119
+ ? "the review wait deadline expired"
120
+ : "the successful response body did not finish within its timeout");
121
+ throw new ProoflineError(response.status, "urn:proofline:sdk:invalid-response", "the response is not valid UTF-8 JSON");
122
+ }
123
+ finally {
124
+ reader.releaseLock();
125
+ }
126
+ }
127
+ function problem(status, value) {
128
+ const body = value !== null && typeof value === "object"
129
+ ? value
130
+ : {};
131
+ return new ProoflineError(status, typeof body.type === "string" ? body.type : "about:blank", typeof body.detail === "string"
132
+ ? body.detail
133
+ : "the server refused the request without a problem detail");
134
+ }
135
+ function retryDelay(header, attempt) {
136
+ if (header === null)
137
+ return Math.min(2 ** attempt, MAX_RETRY_SECONDS) * 1000;
138
+ const seconds = /^\d+$/.test(header.trim())
139
+ ? Number(header)
140
+ : Math.max(0, (httpDate(header.trim()) - Date.now()) / 1000);
141
+ return Number.isFinite(seconds) && seconds <= MAX_RETRY_SECONDS
142
+ ? seconds * 1000
143
+ : undefined;
144
+ }
145
+ function httpDate(value) {
146
+ let canonical = value;
147
+ if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)) {
148
+ const obsolete = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}:\d{2}:\d{2}) GMT$/.exec(value);
149
+ const asctime = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}:\d{2}:\d{2}) (\d{4})$/.exec(value);
150
+ if (obsolete) {
151
+ const futureLimit = new Date();
152
+ const currentYear = futureLimit.getUTCFullYear();
153
+ const year = Math.floor(currentYear / 100) * 100 + Number(obsolete[4]);
154
+ canonical = `${obsolete[1]?.slice(0, 3)}, ${obsolete[2]} ${obsolete[3]} ${year} ${obsolete[5]} GMT`;
155
+ futureLimit.setUTCFullYear(currentYear + 50);
156
+ if (Date.parse(canonical) > futureLimit.getTime())
157
+ canonical = `${obsolete[1]?.slice(0, 3)}, ${obsolete[2]} ${obsolete[3]} ${year - 100} ${obsolete[5]} GMT`;
158
+ }
159
+ else if (asctime) {
160
+ canonical = `${asctime[1]}, ${asctime[3]?.trim().padStart(2, "0")} ${asctime[2]} ${asctime[5]} ${asctime[4]} GMT`;
161
+ }
162
+ else {
163
+ return Number.NaN;
164
+ }
165
+ }
166
+ const timestamp = Date.parse(canonical);
167
+ return new Date(timestamp).toUTCString() === canonical
168
+ ? timestamp
169
+ : Number.NaN;
170
+ }
171
+ export function sleep(milliseconds) {
172
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
173
+ }
174
+ export class Transport {
175
+ #base;
176
+ #token;
177
+ #timeout;
178
+ constructor(options) {
179
+ this.#base = origin(options.baseUrl);
180
+ const token = options.token ?? environmentToken();
181
+ this.#token =
182
+ token instanceof SecretToken ? token : new SecretToken(token ?? "");
183
+ this.#timeout = positive(options.requestTimeoutMs ?? 30_000, "requestTimeoutMs");
184
+ }
185
+ reviewUrl(orgId, reviewId) {
186
+ return new URL(`/orgs/by-id/${coordinate(orgId)}/reviews/${coordinate(reviewId)}`, this.#base).href;
187
+ }
188
+ async request(method, template, parameters, deadline, body) {
189
+ const path = Object.entries(parameters.path ?? {}).reduce((value, [key, coordinateValue]) => value.replace(`{${key}}`, coordinate(coordinateValue)), template);
190
+ if (/[{}]/.test(path))
191
+ throw new TypeError("a required path coordinate is missing");
192
+ const url = new URL(path, this.#base);
193
+ for (const [key, value] of Object.entries(parameters.query ?? {})) {
194
+ if (value !== null && value !== undefined)
195
+ url.searchParams.set(key, String(value));
196
+ }
197
+ const requestBody = body === undefined ? undefined : JSON.stringify(body);
198
+ for (let attempt = 0;; attempt += 1) {
199
+ const headers = new Headers({
200
+ Accept: "application/json, application/problem+json",
201
+ "User-Agent": `proofline-typescript/${VERSION}`,
202
+ });
203
+ if (requestBody !== undefined)
204
+ headers.set("Content-Type", "application/json");
205
+ this.#token.apply(headers);
206
+ const now = performance.now();
207
+ const waitRemaining = deadline === undefined ? this.#timeout : deadline - now;
208
+ const remaining = Math.min(this.#timeout, waitRemaining);
209
+ const waitTimeout = deadline !== undefined && waitRemaining <= this.#timeout;
210
+ if (remaining <= 0)
211
+ throw new ProoflineError(0, "urn:proofline:sdk:timeout", "the request deadline expired");
212
+ const requestDeadline = now + remaining;
213
+ const signal = AbortSignal.timeout(Math.ceil(remaining));
214
+ let response;
215
+ try {
216
+ response = await fetch(url, {
217
+ method,
218
+ headers,
219
+ ...(requestBody === undefined ? {} : { body: requestBody }),
220
+ redirect: "manual",
221
+ credentials: "omit",
222
+ signal,
223
+ });
224
+ }
225
+ catch {
226
+ if (signal.aborted && waitTimeout)
227
+ throw new ProoflineError(0, "urn:proofline:sdk:timeout", "the review wait deadline expired");
228
+ throw new ProoflineError(0, "urn:proofline:sdk:transport", "the request did not receive a response within its timeout");
229
+ }
230
+ const value = await json(response, requestDeadline, signal, waitTimeout);
231
+ if (response.ok)
232
+ return value;
233
+ const error = problem(response.status, value);
234
+ const delay = retryDelay(response.headers.get("Retry-After"), attempt);
235
+ if (method !== "GET" ||
236
+ ![429, 503].includes(response.status) ||
237
+ attempt >= MAX_RETRIES ||
238
+ delay === undefined)
239
+ throw error;
240
+ if (deadline !== undefined && performance.now() + delay >= deadline) {
241
+ throw new ProoflineError(0, "urn:proofline:sdk:timeout", "the review timeout expires before the server permits a retry");
242
+ }
243
+ await sleep(delay);
244
+ }
245
+ }
246
+ }
247
+ function coordinate(value) {
248
+ if ((typeof value !== "string" && typeof value !== "number") ||
249
+ value === "" ||
250
+ value === "." ||
251
+ value === "..") {
252
+ throw new TypeError("path coordinates must be nonempty strings or numbers without traversal segments");
253
+ }
254
+ return encodeURIComponent(String(value));
255
+ }