filecheck-node 0.1.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 +142 -0
- package/dist/index.cjs +563 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +710 -0
- package/dist/index.d.ts +710 -0
- package/dist/index.js +543 -0
- package/dist/index.js.map +1 -0
- package/package.json +59 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var crypto = require('crypto');
|
|
6
|
+
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
var FilecheckError = class extends Error {
|
|
9
|
+
status;
|
|
10
|
+
requestId;
|
|
11
|
+
/** Parsed response body, when it was JSON. */
|
|
12
|
+
body;
|
|
13
|
+
constructor(message, options = {}) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = new.target.name;
|
|
16
|
+
this.status = options.status;
|
|
17
|
+
this.requestId = options.requestId;
|
|
18
|
+
this.body = options.body;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var AuthenticationError = class extends FilecheckError {
|
|
22
|
+
};
|
|
23
|
+
var InvalidRequestError = class extends FilecheckError {
|
|
24
|
+
};
|
|
25
|
+
var NotFoundError = class extends FilecheckError {
|
|
26
|
+
};
|
|
27
|
+
var RateLimitError = class extends FilecheckError {
|
|
28
|
+
};
|
|
29
|
+
var APIError = class extends FilecheckError {
|
|
30
|
+
};
|
|
31
|
+
var ConnectionError = class extends FilecheckError {
|
|
32
|
+
};
|
|
33
|
+
var WebhookSignatureError = class extends FilecheckError {
|
|
34
|
+
};
|
|
35
|
+
function parseErrorBody(text) {
|
|
36
|
+
try {
|
|
37
|
+
const body = JSON.parse(text);
|
|
38
|
+
if (body && typeof body === "object") {
|
|
39
|
+
const message = body.message;
|
|
40
|
+
return { message: typeof message === "string" ? message : null, body };
|
|
41
|
+
}
|
|
42
|
+
return { message: null, body };
|
|
43
|
+
} catch {
|
|
44
|
+
return { message: null, body: void 0 };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function errorFromResponse(status, bodyText, requestId) {
|
|
48
|
+
const { message, body } = parseErrorBody(bodyText);
|
|
49
|
+
const options = { status, requestId, body };
|
|
50
|
+
const text = message ?? `Request failed with status ${status}`;
|
|
51
|
+
if (status === 401 || status === 403) return new AuthenticationError(text, options);
|
|
52
|
+
if (status === 400) return new InvalidRequestError(text, options);
|
|
53
|
+
if (status === 404) return new NotFoundError(text, options);
|
|
54
|
+
if (status === 429) return new RateLimitError(text, options);
|
|
55
|
+
return new APIError(text, options);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/http/fetch.ts
|
|
59
|
+
var FetchTransport = class {
|
|
60
|
+
constructor(fetchImpl = fetch) {
|
|
61
|
+
this.fetchImpl = fetchImpl;
|
|
62
|
+
}
|
|
63
|
+
fetchImpl;
|
|
64
|
+
async request(req) {
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
const timer = req.timeoutMs > 0 ? setTimeout(() => controller.abort(), req.timeoutMs) : null;
|
|
67
|
+
try {
|
|
68
|
+
const response = await this.fetchImpl(req.url, {
|
|
69
|
+
method: req.method,
|
|
70
|
+
headers: req.headers,
|
|
71
|
+
body: req.body,
|
|
72
|
+
signal: controller.signal
|
|
73
|
+
});
|
|
74
|
+
const text = await response.text();
|
|
75
|
+
return { status: response.status, headers: response.headers, text };
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (controller.signal.aborted) {
|
|
78
|
+
throw new ConnectionError(`Request to ${req.url} timed out after ${req.timeoutMs}ms`);
|
|
79
|
+
}
|
|
80
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
81
|
+
throw new ConnectionError(`Request to ${req.url} failed: ${message}`);
|
|
82
|
+
} finally {
|
|
83
|
+
if (timer !== null) clearTimeout(timer);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// src/version.ts
|
|
89
|
+
var VERSION = "0.1.0";
|
|
90
|
+
|
|
91
|
+
// src/http/retry.ts
|
|
92
|
+
var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
|
|
93
|
+
var BASE_DELAY_MS = 500;
|
|
94
|
+
var MAX_DELAY_MS = 8e3;
|
|
95
|
+
function isRetryableStatus(status) {
|
|
96
|
+
return RETRYABLE_STATUSES.has(status);
|
|
97
|
+
}
|
|
98
|
+
function backoffDelayMs(attempt, response) {
|
|
99
|
+
const retryAfter = response?.headers.get("retry-after");
|
|
100
|
+
if (retryAfter) {
|
|
101
|
+
const seconds = Number(retryAfter);
|
|
102
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1e3, 3e4);
|
|
103
|
+
}
|
|
104
|
+
const cap = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
|
|
105
|
+
return Math.random() * cap;
|
|
106
|
+
}
|
|
107
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
108
|
+
async function withRetries(attempt, options) {
|
|
109
|
+
const attempts = options.idempotent ? options.maxRetries + 1 : 1;
|
|
110
|
+
let lastError;
|
|
111
|
+
for (let i = 0; i < attempts; i++) {
|
|
112
|
+
let response;
|
|
113
|
+
try {
|
|
114
|
+
response = await attempt();
|
|
115
|
+
} catch (error) {
|
|
116
|
+
lastError = error;
|
|
117
|
+
if (!(error instanceof ConnectionError) || i === attempts - 1) throw error;
|
|
118
|
+
await sleep(backoffDelayMs(i));
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (isRetryableStatus(response.status) && i < attempts - 1) {
|
|
122
|
+
await sleep(backoffDelayMs(i, response));
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
return response;
|
|
126
|
+
}
|
|
127
|
+
throw lastError instanceof Error ? lastError : new ConnectionError("Request failed");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/http/requestor.ts
|
|
131
|
+
var Requestor = class {
|
|
132
|
+
constructor(transport, baseUrl, secretKey, timeoutMs, maxRetries) {
|
|
133
|
+
this.transport = transport;
|
|
134
|
+
this.baseUrl = baseUrl;
|
|
135
|
+
this.secretKey = secretKey;
|
|
136
|
+
this.timeoutMs = timeoutMs;
|
|
137
|
+
this.maxRetries = maxRetries;
|
|
138
|
+
}
|
|
139
|
+
transport;
|
|
140
|
+
baseUrl;
|
|
141
|
+
secretKey;
|
|
142
|
+
timeoutMs;
|
|
143
|
+
maxRetries;
|
|
144
|
+
async raw(method, path, options = {}) {
|
|
145
|
+
const url = new URL(this.baseUrl + path);
|
|
146
|
+
for (const [key, value] of Object.entries(options.query ?? {})) {
|
|
147
|
+
if (value !== void 0) url.searchParams.set(key, String(value));
|
|
148
|
+
}
|
|
149
|
+
const headers = {
|
|
150
|
+
authorization: `Bearer ${this.secretKey}`,
|
|
151
|
+
accept: "application/json",
|
|
152
|
+
"user-agent": `filecheck-node/${VERSION}`
|
|
153
|
+
};
|
|
154
|
+
let body;
|
|
155
|
+
if (options.body !== void 0) {
|
|
156
|
+
headers["content-type"] = "application/json";
|
|
157
|
+
body = JSON.stringify(options.body);
|
|
158
|
+
}
|
|
159
|
+
return withRetries(
|
|
160
|
+
() => this.transport.request({
|
|
161
|
+
method,
|
|
162
|
+
url: url.toString(),
|
|
163
|
+
headers,
|
|
164
|
+
body,
|
|
165
|
+
timeoutMs: this.timeoutMs
|
|
166
|
+
}),
|
|
167
|
+
{ idempotent: options.idempotent ?? method === "GET", maxRetries: this.maxRetries }
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
/** Request + parse. Throws a typed FilecheckError on any non-2xx. */
|
|
171
|
+
async json(method, path, options = {}) {
|
|
172
|
+
const response = await this.raw(method, path, options);
|
|
173
|
+
const requestId = response.headers.get("apigw-requestid") ?? void 0;
|
|
174
|
+
if (response.status < 200 || response.status >= 300) {
|
|
175
|
+
throw errorFromResponse(response.status, response.text, requestId);
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
return { status: response.status, data: JSON.parse(response.text) };
|
|
179
|
+
} catch {
|
|
180
|
+
throw errorFromResponse(response.status, response.text, requestId);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// src/types/job.ts
|
|
186
|
+
var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
187
|
+
"done",
|
|
188
|
+
"skipped",
|
|
189
|
+
"error"
|
|
190
|
+
]);
|
|
191
|
+
function isTerminal(subject) {
|
|
192
|
+
return TERMINAL_STATUSES.has(subject.status);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/verify.ts
|
|
196
|
+
function resolveVerify(job, options = {}) {
|
|
197
|
+
if (!isTerminal(job)) {
|
|
198
|
+
return { ok: false, state: "not_terminal", job, reason: "not_terminal" };
|
|
199
|
+
}
|
|
200
|
+
const onFail = options.policy ?? job.summary?.policy?.onFail ?? "reject";
|
|
201
|
+
let hasFail = false;
|
|
202
|
+
let hasWarn = false;
|
|
203
|
+
for (const task of job.tasks ?? []) {
|
|
204
|
+
const outcome = task?.outcome;
|
|
205
|
+
if (outcome === "fail" || outcome === "mixed") hasFail = true;
|
|
206
|
+
else if (outcome === "warn") hasWarn = true;
|
|
207
|
+
}
|
|
208
|
+
let state;
|
|
209
|
+
if (hasFail) state = onFail === "reject" ? "rejected" : "partial";
|
|
210
|
+
else state = hasWarn ? "partial" : "ready";
|
|
211
|
+
if (options.workflowId !== void 0 && job.workflowId !== options.workflowId) {
|
|
212
|
+
return { ok: false, state, job, reason: "workflow_mismatch" };
|
|
213
|
+
}
|
|
214
|
+
if (options.strict && job.status === "error") {
|
|
215
|
+
return { ok: false, state, job, reason: "cannot_proceed" };
|
|
216
|
+
}
|
|
217
|
+
const ok = state === "ready" || state === "partial";
|
|
218
|
+
return ok ? { ok, state, job } : { ok, state, job, reason: "cannot_proceed" };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/resources/jobs.ts
|
|
222
|
+
var DEFAULT_WAIT_TIMEOUT_MS = 12e4;
|
|
223
|
+
var POLL_MIN_MS = 250;
|
|
224
|
+
var POLL_MAX_MS = 2e3;
|
|
225
|
+
var JobsResource = class {
|
|
226
|
+
constructor(requestor) {
|
|
227
|
+
this.requestor = requestor;
|
|
228
|
+
}
|
|
229
|
+
requestor;
|
|
230
|
+
/**
|
|
231
|
+
* Canonical `POST /jobs`. Async by default; pass `wait: true` to resolve
|
|
232
|
+
* with a terminal job. Note the API does not accept a `workflowId` here —
|
|
233
|
+
* workflow-driven jobs are created through the browser Element.
|
|
234
|
+
*/
|
|
235
|
+
create(params) {
|
|
236
|
+
return this.submit("/jobs", params, "sync-flag", false);
|
|
237
|
+
}
|
|
238
|
+
/** `POST /jobs/preflight` — async by default. */
|
|
239
|
+
preflight(params) {
|
|
240
|
+
return this.submit("/jobs/preflight", params, "sync-flag", false);
|
|
241
|
+
}
|
|
242
|
+
/** `POST /jobs/previews` — async by default. */
|
|
243
|
+
previews(params) {
|
|
244
|
+
return this.submit("/jobs/previews", params, "sync-flag", false);
|
|
245
|
+
}
|
|
246
|
+
/** `POST /jobs/fix` — async by default. */
|
|
247
|
+
fix(params) {
|
|
248
|
+
return this.submit("/jobs/fix", params, "sync-flag", false);
|
|
249
|
+
}
|
|
250
|
+
/** `POST /jobs/validate` — waits by default. */
|
|
251
|
+
validate(params) {
|
|
252
|
+
return this.submit("/jobs/validate", params, "async-flag", true);
|
|
253
|
+
}
|
|
254
|
+
/** `POST /jobs/optimize` — waits by default. */
|
|
255
|
+
optimize(params) {
|
|
256
|
+
return this.submit("/jobs/optimize", params, "async-flag", true);
|
|
257
|
+
}
|
|
258
|
+
async retrieve(id) {
|
|
259
|
+
const { data } = await this.requestor.json("GET", `/jobs/${id}`);
|
|
260
|
+
return data.job;
|
|
261
|
+
}
|
|
262
|
+
/** `?expand=runs` — flattened per-file summary with proof + download URLs. */
|
|
263
|
+
async retrieveRuns(id) {
|
|
264
|
+
const { data } = await this.requestor.json("GET", `/jobs/${id}`, {
|
|
265
|
+
query: { expand: "runs" }
|
|
266
|
+
});
|
|
267
|
+
return data;
|
|
268
|
+
}
|
|
269
|
+
async list(params = {}) {
|
|
270
|
+
const { data } = await this.requestor.json("GET", "/jobs", {
|
|
271
|
+
query: {
|
|
272
|
+
limit: params.limit,
|
|
273
|
+
nextKey: params.nextKey,
|
|
274
|
+
preview: params.preview ? "true" : void 0
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
return data;
|
|
278
|
+
}
|
|
279
|
+
/** Auto-paginates over `list()` following `nextKey`. */
|
|
280
|
+
async *iterate(params = {}) {
|
|
281
|
+
let nextKey = params.nextKey;
|
|
282
|
+
do {
|
|
283
|
+
const page = await this.list({ ...params, nextKey });
|
|
284
|
+
yield* page.jobs;
|
|
285
|
+
nextKey = page.nextKey ?? void 0;
|
|
286
|
+
} while (nextKey);
|
|
287
|
+
}
|
|
288
|
+
async del(id) {
|
|
289
|
+
const { data } = await this.requestor.json("DELETE", `/jobs/${id}`, {
|
|
290
|
+
idempotent: false
|
|
291
|
+
});
|
|
292
|
+
return data;
|
|
293
|
+
}
|
|
294
|
+
/** Poll `GET /jobs/{id}` until terminal. Throws FilecheckError on timeout. */
|
|
295
|
+
async waitUntilTerminal(id, options = {}) {
|
|
296
|
+
const { job, terminal } = await this.pollUntilTerminal(
|
|
297
|
+
id,
|
|
298
|
+
options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS,
|
|
299
|
+
options.pollIntervalMs
|
|
300
|
+
);
|
|
301
|
+
if (!terminal) {
|
|
302
|
+
throw new FilecheckError(
|
|
303
|
+
`Timed out waiting for job ${id} to reach a terminal status (last: ${job.status})`
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
return job;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* The server-side fulfillment gate: fetch the job and check that it is
|
|
310
|
+
* terminal and proceedable (the Element's `canProceed` equivalent), and —
|
|
311
|
+
* when `workflowId` is given — that it ran the expected workflow.
|
|
312
|
+
*/
|
|
313
|
+
async verify(jobId, options = {}) {
|
|
314
|
+
const job = await this.retrieve(jobId);
|
|
315
|
+
return resolveVerify(job, options);
|
|
316
|
+
}
|
|
317
|
+
async submit(path, params, flagStyle, defaultWait) {
|
|
318
|
+
const {
|
|
319
|
+
wait = defaultWait,
|
|
320
|
+
waitTimeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
|
321
|
+
...body
|
|
322
|
+
} = params;
|
|
323
|
+
if (flagStyle === "sync-flag") {
|
|
324
|
+
if (wait) body.sync = true;
|
|
325
|
+
} else if (!wait) {
|
|
326
|
+
body.async = true;
|
|
327
|
+
}
|
|
328
|
+
const { status, data } = await this.requestor.json(
|
|
329
|
+
"POST",
|
|
330
|
+
path,
|
|
331
|
+
{ body, idempotent: false }
|
|
332
|
+
);
|
|
333
|
+
let job = data.job;
|
|
334
|
+
if (status === 202 && wait && waitTimeoutMs > 0) {
|
|
335
|
+
const result = await this.pollUntilTerminal(job.id, waitTimeoutMs);
|
|
336
|
+
job = result.job;
|
|
337
|
+
}
|
|
338
|
+
return { job, pending: !isTerminal(job) };
|
|
339
|
+
}
|
|
340
|
+
async pollUntilTerminal(id, timeoutMs, fixedIntervalMs) {
|
|
341
|
+
const deadline = Date.now() + timeoutMs;
|
|
342
|
+
let delay = fixedIntervalMs ?? POLL_MIN_MS;
|
|
343
|
+
let job = await this.retrieve(id);
|
|
344
|
+
while (!isTerminal(job) && Date.now() < deadline) {
|
|
345
|
+
await sleep(Math.min(delay, Math.max(0, deadline - Date.now())));
|
|
346
|
+
if (fixedIntervalMs === void 0) delay = Math.min(delay * 2, POLL_MAX_MS);
|
|
347
|
+
job = await this.retrieve(id);
|
|
348
|
+
}
|
|
349
|
+
return { job, terminal: isTerminal(job) };
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
// src/resources/library.ts
|
|
354
|
+
var LibraryResource = class {
|
|
355
|
+
constructor(requestor, path, listKey, itemKey) {
|
|
356
|
+
this.requestor = requestor;
|
|
357
|
+
this.path = path;
|
|
358
|
+
this.listKey = listKey;
|
|
359
|
+
this.itemKey = itemKey;
|
|
360
|
+
}
|
|
361
|
+
requestor;
|
|
362
|
+
path;
|
|
363
|
+
listKey;
|
|
364
|
+
itemKey;
|
|
365
|
+
async list() {
|
|
366
|
+
const { data } = await this.requestor.json("GET", this.path);
|
|
367
|
+
return data[this.listKey] ?? [];
|
|
368
|
+
}
|
|
369
|
+
async retrieve(id) {
|
|
370
|
+
const { data } = await this.requestor.json(
|
|
371
|
+
"GET",
|
|
372
|
+
`${this.path}/${id}`
|
|
373
|
+
);
|
|
374
|
+
return data[this.itemKey];
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
// src/resources/orders.ts
|
|
379
|
+
var OrdersResource = class {
|
|
380
|
+
constructor(requestor) {
|
|
381
|
+
this.requestor = requestor;
|
|
382
|
+
}
|
|
383
|
+
requestor;
|
|
384
|
+
/** `POST /orders/{id}` — attach/refresh order data on the tenant's jobs. */
|
|
385
|
+
async create(orderId, params) {
|
|
386
|
+
const { data } = await this.requestor.json(
|
|
387
|
+
"POST",
|
|
388
|
+
`/orders/${encodeURIComponent(orderId)}`,
|
|
389
|
+
{ body: params, idempotent: false }
|
|
390
|
+
);
|
|
391
|
+
return data;
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
// src/resources/uploads.ts
|
|
396
|
+
function toBlob(input, mimeType) {
|
|
397
|
+
if (typeof Blob !== "undefined" && input instanceof Blob) return input;
|
|
398
|
+
if (ArrayBuffer.isView(input)) {
|
|
399
|
+
const bytes = new Uint8Array(
|
|
400
|
+
input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength)
|
|
401
|
+
);
|
|
402
|
+
return new Blob([bytes], mimeType ? { type: mimeType } : void 0);
|
|
403
|
+
}
|
|
404
|
+
return new Blob([input], mimeType ? { type: mimeType } : void 0);
|
|
405
|
+
}
|
|
406
|
+
var UploadsResource = class {
|
|
407
|
+
constructor(requestor, transport, timeoutMs) {
|
|
408
|
+
this.requestor = requestor;
|
|
409
|
+
this.transport = transport;
|
|
410
|
+
this.timeoutMs = timeoutMs;
|
|
411
|
+
}
|
|
412
|
+
requestor;
|
|
413
|
+
transport;
|
|
414
|
+
timeoutMs;
|
|
415
|
+
/**
|
|
416
|
+
* Upload a file for later use as a job source (`{ fileRef }`). Performs
|
|
417
|
+
* both legs: `POST /uploads` for a presigned S3 POST, then the multipart
|
|
418
|
+
* upload itself. Max 500 MB.
|
|
419
|
+
*/
|
|
420
|
+
async create(file, options = {}) {
|
|
421
|
+
const blob = toBlob(file, options.mimeType);
|
|
422
|
+
const { data: presign } = await this.requestor.json("POST", "/uploads", {
|
|
423
|
+
body: {
|
|
424
|
+
...options.mimeType !== void 0 || blob.type ? { mimeType: options.mimeType ?? blob.type } : {},
|
|
425
|
+
sizeBytes: blob.size
|
|
426
|
+
},
|
|
427
|
+
idempotent: false
|
|
428
|
+
});
|
|
429
|
+
if (blob.size > presign.maxBytes) {
|
|
430
|
+
throw new InvalidRequestError(
|
|
431
|
+
`File is ${blob.size} bytes; the upload limit is ${presign.maxBytes} bytes`
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
const form = new FormData();
|
|
435
|
+
for (const [key, value] of Object.entries(presign.upload.fields)) {
|
|
436
|
+
form.append(key, value);
|
|
437
|
+
}
|
|
438
|
+
form.append("file", blob, options.fileName ?? "file");
|
|
439
|
+
const response = await this.transport.request({
|
|
440
|
+
method: "POST",
|
|
441
|
+
url: presign.upload.url,
|
|
442
|
+
headers: {},
|
|
443
|
+
body: form,
|
|
444
|
+
timeoutMs: this.timeoutMs
|
|
445
|
+
});
|
|
446
|
+
if (![200, 201, 204].includes(response.status)) {
|
|
447
|
+
throw new APIError(`S3 upload leg failed with status ${response.status}`, {
|
|
448
|
+
status: response.status,
|
|
449
|
+
body: response.text
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
return {
|
|
453
|
+
fileRef: presign.fileRef,
|
|
454
|
+
maxBytes: presign.maxBytes,
|
|
455
|
+
expiresIn: presign.expiresIn
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
function computeSignature(secret, rawBody) {
|
|
460
|
+
return crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
|
|
461
|
+
}
|
|
462
|
+
function safeEqualHex(a, b) {
|
|
463
|
+
const bufA = Buffer.from(a, "utf8");
|
|
464
|
+
const bufB = Buffer.from(b, "utf8");
|
|
465
|
+
if (bufA.length !== bufB.length) return false;
|
|
466
|
+
return crypto.timingSafeEqual(bufA, bufB);
|
|
467
|
+
}
|
|
468
|
+
function constructEvent(rawBody, signatureHeader, secret, options = {}) {
|
|
469
|
+
const text = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
|
|
470
|
+
let verified = false;
|
|
471
|
+
if (secret && signatureHeader) {
|
|
472
|
+
const expected = computeSignature(secret, rawBody);
|
|
473
|
+
if (!safeEqualHex(expected, signatureHeader.trim())) {
|
|
474
|
+
throw new WebhookSignatureError("Webhook signature verification failed");
|
|
475
|
+
}
|
|
476
|
+
verified = true;
|
|
477
|
+
} else if (options.verify !== false) {
|
|
478
|
+
throw new WebhookSignatureError(
|
|
479
|
+
"Webhook payload has no verifiable signature. Filecheck webhooks are not yet signed \u2014 pass { verify: false } to accept unsigned payloads (temporary until the signing scheme ships)."
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
let payload;
|
|
483
|
+
try {
|
|
484
|
+
payload = JSON.parse(text);
|
|
485
|
+
} catch {
|
|
486
|
+
throw new WebhookSignatureError("Webhook body is not valid JSON");
|
|
487
|
+
}
|
|
488
|
+
if (Array.isArray(payload.taskIds) && payload.finalized && Array.isArray(payload.tasks)) {
|
|
489
|
+
return { type: "job.completed", payload, verified };
|
|
490
|
+
}
|
|
491
|
+
if (typeof payload.taskCount === "number") {
|
|
492
|
+
return { type: "job.created", payload, verified };
|
|
493
|
+
}
|
|
494
|
+
return { type: "unknown", payload, verified };
|
|
495
|
+
}
|
|
496
|
+
var webhooks = { constructEvent, computeSignature };
|
|
497
|
+
|
|
498
|
+
// src/client.ts
|
|
499
|
+
var DEFAULT_BASE_URL = "https://api.filecheck.io";
|
|
500
|
+
var DEFAULT_TIMEOUT_MS = 6e4;
|
|
501
|
+
var DEFAULT_MAX_RETRIES = 2;
|
|
502
|
+
function maskKey(key) {
|
|
503
|
+
return key.length > 8 ? `${key.slice(0, 3)}\u2026${key.slice(-4)}` : "sk_\u2026";
|
|
504
|
+
}
|
|
505
|
+
var Filecheck = class {
|
|
506
|
+
jobs;
|
|
507
|
+
uploads;
|
|
508
|
+
orders;
|
|
509
|
+
workflows;
|
|
510
|
+
connectors;
|
|
511
|
+
rules;
|
|
512
|
+
profiles;
|
|
513
|
+
optimizePresets;
|
|
514
|
+
webhooks = webhooks;
|
|
515
|
+
constructor(secretKey, options = {}) {
|
|
516
|
+
if (!secretKey || typeof secretKey !== "string") {
|
|
517
|
+
throw new AuthenticationError(
|
|
518
|
+
"A secret key is required, e.g. new Filecheck(process.env.FILECHECK_SECRET_KEY)"
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
if (secretKey.startsWith("pk_")) {
|
|
522
|
+
throw new AuthenticationError(
|
|
523
|
+
`${maskKey(secretKey)} is a publishable key. Publishable keys are browser-only (for the Element); the server SDK needs your secret key (sk_\u2026) from the Filecheck dashboard.`
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
if (!secretKey.startsWith("sk_")) {
|
|
527
|
+
throw new AuthenticationError('Invalid API key: secret keys start with "sk_"');
|
|
528
|
+
}
|
|
529
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
530
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
531
|
+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
532
|
+
const transport = options.transport ?? new FetchTransport(options.fetch);
|
|
533
|
+
const requestor = new Requestor(transport, baseUrl, secretKey, timeoutMs, maxRetries);
|
|
534
|
+
this.jobs = new JobsResource(requestor);
|
|
535
|
+
this.uploads = new UploadsResource(requestor, transport, timeoutMs);
|
|
536
|
+
this.orders = new OrdersResource(requestor);
|
|
537
|
+
this.workflows = new LibraryResource(requestor, "/workflows", "workflows", "workflow");
|
|
538
|
+
this.connectors = new LibraryResource(requestor, "/connectors", "connectors", "connector");
|
|
539
|
+
this.rules = new LibraryResource(requestor, "/rules", "rules", "rule");
|
|
540
|
+
this.profiles = new LibraryResource(requestor, "/profiles", "profiles", "profile");
|
|
541
|
+
this.optimizePresets = new LibraryResource(requestor, "/optimize-presets", "presets", "preset");
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
exports.APIError = APIError;
|
|
546
|
+
exports.AuthenticationError = AuthenticationError;
|
|
547
|
+
exports.ConnectionError = ConnectionError;
|
|
548
|
+
exports.Filecheck = Filecheck;
|
|
549
|
+
exports.FilecheckError = FilecheckError;
|
|
550
|
+
exports.InvalidRequestError = InvalidRequestError;
|
|
551
|
+
exports.NotFoundError = NotFoundError;
|
|
552
|
+
exports.RateLimitError = RateLimitError;
|
|
553
|
+
exports.TERMINAL_STATUSES = TERMINAL_STATUSES;
|
|
554
|
+
exports.WebhookSignatureError = WebhookSignatureError;
|
|
555
|
+
exports.computeSignature = computeSignature;
|
|
556
|
+
exports.constructEvent = constructEvent;
|
|
557
|
+
exports.default = Filecheck;
|
|
558
|
+
exports.isTerminal = isTerminal;
|
|
559
|
+
exports.maskKey = maskKey;
|
|
560
|
+
exports.resolveVerify = resolveVerify;
|
|
561
|
+
exports.webhooks = webhooks;
|
|
562
|
+
//# sourceMappingURL=index.cjs.map
|
|
563
|
+
//# sourceMappingURL=index.cjs.map
|