@vecsnap/sdk 0.0.0-stage → 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.
Files changed (40) hide show
  1. package/README.md +23 -2
  2. package/dist/errors.d.ts +25 -0
  3. package/dist/errors.js +50 -0
  4. package/dist/generated/client/client.gen.d.ts +2 -0
  5. package/dist/generated/client/client.gen.js +216 -0
  6. package/dist/generated/client/index.d.ts +10 -0
  7. package/dist/generated/client/index.js +6 -0
  8. package/dist/generated/client/types.gen.d.ts +120 -0
  9. package/dist/generated/client/types.gen.js +2 -0
  10. package/dist/generated/client/utils.gen.d.ts +37 -0
  11. package/dist/generated/client/utils.gen.js +228 -0
  12. package/dist/generated/client.gen.d.ts +12 -0
  13. package/dist/generated/client.gen.js +3 -0
  14. package/dist/generated/core/auth.gen.d.ts +25 -0
  15. package/dist/generated/core/auth.gen.js +14 -0
  16. package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
  17. package/dist/generated/core/bodySerializer.gen.js +57 -0
  18. package/dist/generated/core/params.gen.d.ts +43 -0
  19. package/dist/generated/core/params.gen.js +109 -0
  20. package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
  21. package/dist/generated/core/pathSerializer.gen.js +106 -0
  22. package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
  23. package/dist/generated/core/queryKeySerializer.gen.js +92 -0
  24. package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
  25. package/dist/generated/core/serverSentEvents.gen.js +132 -0
  26. package/dist/generated/core/types.gen.d.ts +83 -0
  27. package/dist/generated/core/types.gen.js +2 -0
  28. package/dist/generated/core/utils.gen.d.ts +19 -0
  29. package/dist/generated/core/utils.gen.js +87 -0
  30. package/dist/generated/index.d.ts +2 -0
  31. package/dist/generated/index.js +2 -0
  32. package/dist/generated/sdk.gen.d.ts +243 -0
  33. package/dist/generated/sdk.gen.js +438 -0
  34. package/dist/generated/types.gen.d.ts +4954 -0
  35. package/dist/generated/types.gen.js +2 -0
  36. package/dist/index.d.ts +61 -0
  37. package/dist/index.js +178 -0
  38. package/dist/webhooks.d.ts +29 -0
  39. package/dist/webhooks.js +69 -0
  40. package/package.json +37 -4
@@ -0,0 +1,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};
@@ -0,0 +1,61 @@
1
+ import * as operations from "./generated/sdk.gen.ts";
2
+ import type { Conversion, Vectorized } from "./generated/types.gen.ts";
3
+ export { VecSnapError } from "./errors.ts";
4
+ export { signWebhook, verifyWebhook, WebhookVerificationError, WEBHOOK_TOLERANCE_SECONDS } from "./webhooks.ts";
5
+ export type * from "./generated/types.gen.ts";
6
+ /** Where the API answers. */
7
+ export declare const DEFAULT_BASE_URL = "https://api.vecsnap.com/v1";
8
+ export interface VecSnapOptions {
9
+ /** `vs_test_…` (free: a sample result) or `vs_live_…`. Default: the `VECSNAP_API_KEY` environment variable. */
10
+ apiKey?: string;
11
+ /** Default: the `VECSNAP_BASE_URL` environment variable, else `https://api.vecsnap.com/v1` (a proxy, a test server). */
12
+ baseUrl?: string;
13
+ /** Your own `fetch` (a test's, a proxy's). Default: the platform's. */
14
+ fetch?: typeof fetch;
15
+ }
16
+ export interface VectorizeInput {
17
+ /** The image itself (PNG, JPG, WebP, AVIF, GIF, BMP or TIFF), up to 4 MB — or `url`, or `inputKey`. */
18
+ file?: Blob | Uint8Array | ArrayBuffer;
19
+ /** A public https link to the image: we fetch it (up to 10 MB). */
20
+ url?: string;
21
+ /** An upload you already made (`createUpload`), for files up to 10 MB. */
22
+ inputKey?: string;
23
+ /** Its name: kept as the label and the download's name. Default: the file's or the URL's own. */
24
+ filename?: string;
25
+ preset?: "default";
26
+ options?: {
27
+ maxColors?: number;
28
+ };
29
+ /** Retry safely: the same key is the same conversion, never charged twice. Default: one made for this call. */
30
+ idempotencyKey?: string;
31
+ }
32
+ export interface WaitOptions {
33
+ /** Seconds the API holds each call open (0–60). Default 30. */
34
+ wait?: number;
35
+ /** How long `vectorize` waits in all, through a 202, before it gives up (`VecSnapError` `timeout`). Default 10 minutes. */
36
+ timeoutMs?: number;
37
+ signal?: AbortSignal;
38
+ }
39
+ export declare class VecSnap {
40
+ #private;
41
+ /** Every operation a key may call, generated from the API's document, bound to this client: `vecsnap.api.getCredits()`. */
42
+ readonly api: BoundOperations;
43
+ constructor(options?: VecSnapOptions);
44
+ /**
45
+ * Convert one image and wait for its SVG. The answer is the conversion and a link to each SVG file (`files`), valid
46
+ * until `filesExpireAt`. A conversion that outlasts one call (the API answers 202) is waited for here — read again with
47
+ * backoff, its files then asked for. A test key converts every image into the same sample, for free.
48
+ * @throws {VecSnapError} the API's refusal (`insufficient_credits`, `unsupported_type`, …) or `timeout` — past the 202,
49
+ * with `conversionId` and `idempotencyKey`: call again with that key to pick the same conversion up.
50
+ */
51
+ vectorize(input: VectorizeInput, options?: WaitOptions): Promise<Vectorized>;
52
+ /** One conversion as it stands. @throws {VecSnapError} `not_found` */
53
+ conversion(id: string, signal?: AbortSignal): Promise<Conversion>;
54
+ /** The bytes of a vectorized image's SVG (`web` by default; `design`, …: each of `files`). */
55
+ download(result: Pick<Vectorized, "files">, format?: string): Promise<Uint8Array>;
56
+ }
57
+ type Operations = typeof operations;
58
+ /** The generated operations, each with this client already given. */
59
+ export type BoundOperations = {
60
+ [K in keyof Operations as Operations[K] extends (...args: never[]) => unknown ? K : never]: Operations[K] extends (options: infer O) => infer R ? (options?: Omit<NonNullable<O>, "client">) => R : never;
61
+ };
package/dist/index.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * `@vecsnap/sdk` — the VecSnap API from TypeScript and JavaScript (`developers.md` § 8; audit
3
+ * `developer-platform-2026-10-23` § 13).
4
+ *
5
+ * import { VecSnap } from "@vecsnap/sdk";
6
+ * const vecsnap = new VecSnap(); // reads VECSNAP_API_KEY
7
+ * const result = await vecsnap.vectorize({ file: await readFile("logo.png"), filename: "logo.png" });
8
+ * await writeFile("logo.svg", await vecsnap.download(result));
9
+ *
10
+ * Every operation a key may call is GENERATED from the API's own document (`./generated/`, never edited by hand —
11
+ * `npm --prefix web run gen:clients`) and reachable as `vecsnap.api.<operationId>`. This file adds what generation cannot:
12
+ * `vectorize` sends a file as a form and WAITS through a 202 (a conversion that outlasts the call), every refusal is a
13
+ * `VecSnapError` with its code, and `verifyWebhook` checks an event your server received. No runtime dependency: `fetch`
14
+ * and Web Crypto, so it runs in Node 18+, Deno, Bun and edge runtimes.
15
+ */
16
+ import { createClient } from "./generated/client/index.js";
17
+ import * as operations from "./generated/sdk.gen.js";
18
+ import { VecSnapError } from "./errors.js";
19
+ export { VecSnapError } from "./errors.js";
20
+ export { signWebhook, verifyWebhook, WebhookVerificationError, WEBHOOK_TOLERANCE_SECONDS } from "./webhooks.js";
21
+ /** Where the API answers. */
22
+ export const DEFAULT_BASE_URL = "https://api.vecsnap.com/v1";
23
+ /** The statuses a conversion ends in: it changes no more. */
24
+ const ENDED = new Set(["completed", "failed", "expired", "canceled"]);
25
+ export class VecSnap {
26
+ /** Every operation a key may call, generated from the API's document, bound to this client: `vecsnap.api.getCredits()`. */
27
+ api;
28
+ #client;
29
+ #fetch;
30
+ #baseUrl;
31
+ #apiKey;
32
+ constructor(options = {}) {
33
+ const apiKey = options.apiKey ?? globalThis.process?.env?.VECSNAP_API_KEY;
34
+ if (!apiKey)
35
+ throw new VecSnapError("missing_api_key", "no API key: pass { apiKey } or set VECSNAP_API_KEY (vecsnap.com/app/developers)", 0);
36
+ this.#apiKey = apiKey;
37
+ const env = globalThis.process?.env;
38
+ this.#baseUrl = (options.baseUrl ?? env?.VECSNAP_BASE_URL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
39
+ this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
40
+ this.#client = createClient({ baseUrl: this.#baseUrl, fetch: this.#fetch, auth: () => apiKey });
41
+ this.api = bind(this.#client);
42
+ }
43
+ /**
44
+ * Convert one image and wait for its SVG. The answer is the conversion and a link to each SVG file (`files`), valid
45
+ * until `filesExpireAt`. A conversion that outlasts one call (the API answers 202) is waited for here — read again with
46
+ * backoff, its files then asked for. A test key converts every image into the same sample, for free.
47
+ * @throws {VecSnapError} the API's refusal (`insufficient_credits`, `unsupported_type`, …) or `timeout` — past the 202,
48
+ * with `conversionId` and `idempotencyKey`: call again with that key to pick the same conversion up.
49
+ */
50
+ async vectorize(input, options = {}) {
51
+ const given = [input.file, input.url, input.inputKey].filter((x) => x !== undefined).length;
52
+ if (given !== 1)
53
+ throw new VecSnapError("invalid_request", 'give exactly one of "file", "url" or "inputKey"', 0);
54
+ const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
55
+ const deadline = Date.now() + (options.timeoutMs ?? 10 * 60_000);
56
+ const first = await this.#vectorizeOnce(input, idempotencyKey, options.wait ?? 30, options.signal);
57
+ if (first.done)
58
+ return first.body;
59
+ // A 202: the conversion exists and finishes on its own. Wait for it here — and if this call cannot, say which
60
+ // conversion and which key, so the caller picks the SAME one up (never a second charge, review 13f #2).
61
+ const id = first.body.id;
62
+ try {
63
+ let delay = 1_000;
64
+ for (;;) {
65
+ if (Date.now() + delay > deadline)
66
+ throw new VecSnapError("timeout", `conversion ${id} had not ended within the time given`, 0);
67
+ await sleep(delay, options.signal);
68
+ delay = Math.min(delay * 1.6, 10_000);
69
+ let conversion;
70
+ try {
71
+ conversion = await this.conversion(id, options.signal);
72
+ }
73
+ catch (error) {
74
+ // A 429 or the API's own trouble while waiting: wait longer, never give the conversion up for it.
75
+ if (error instanceof VecSnapError && error.transient) {
76
+ delay = Math.max(delay, (error.retryAfter ?? 0) * 1000);
77
+ continue;
78
+ }
79
+ throw error;
80
+ }
81
+ // Its files from the conversion itself — never the request sent again, whose URL may be gone (review 13f #1).
82
+ if (ENDED.has(conversion.status))
83
+ return await this.#withFiles(conversion, options.signal);
84
+ }
85
+ }
86
+ catch (error) {
87
+ if (error instanceof VecSnapError) {
88
+ error.conversionId = id;
89
+ error.idempotencyKey = idempotencyKey;
90
+ }
91
+ throw error;
92
+ }
93
+ }
94
+ /** One conversion as it stands. @throws {VecSnapError} `not_found` */
95
+ async conversion(id, signal) {
96
+ return unwrap(await operations.getConversion({ client: this.#client, path: { id }, signal }));
97
+ }
98
+ /** An ended conversion with a link to each of its files (an image not unlocked has none), as `vectorize` answers. */
99
+ async #withFiles(conversion, signal) {
100
+ const files = {};
101
+ let expiresIn = Infinity;
102
+ if (conversion.status === "completed" && conversion.unlocked) {
103
+ for (const format of conversion.result?.formats ?? []) {
104
+ const link = await unwrap(await operations.downloadConversion({ client: this.#client, path: { id: conversion.id }, query: { format: format.id }, signal }));
105
+ files[format.id] = link.url;
106
+ expiresIn = Math.min(expiresIn, link.expiresIn);
107
+ }
108
+ }
109
+ return { ...conversion, files, filesExpireAt: new Date(Date.now() + (Number.isFinite(expiresIn) ? expiresIn : 0) * 1000).toISOString() };
110
+ }
111
+ /** The bytes of a vectorized image's SVG (`web` by default; `design`, …: each of `files`). */
112
+ async download(result, format = "web") {
113
+ const link = result.files[format];
114
+ if (!link)
115
+ throw new VecSnapError("format_unavailable", `no "${format}" file: ${Object.keys(result.files).join(", ") || "none"} (an image not unlocked has none)`, 0);
116
+ const response = await this.#fetch(link);
117
+ if (!response.ok)
118
+ throw new VecSnapError("download_failed", `the file answered ${response.status} (links last until filesExpireAt)`, response.status);
119
+ return new Uint8Array(await response.arrayBuffer());
120
+ }
121
+ async #vectorizeOnce(input, idempotencyKey, wait, signal) {
122
+ const headers = { authorization: `Bearer ${this.#apiKey}`, "idempotency-key": idempotencyKey, accept: "application/json" };
123
+ let body;
124
+ if (input.file !== undefined) {
125
+ const form = new FormData();
126
+ const blob = input.file instanceof Blob ? input.file : new Blob([input.file]);
127
+ form.set("file", blob, input.filename ?? "image");
128
+ form.set("wait", String(wait));
129
+ if (input.preset)
130
+ form.set("preset", input.preset);
131
+ if (input.options)
132
+ form.set("options", JSON.stringify(input.options));
133
+ if (input.filename)
134
+ form.set("filename", input.filename);
135
+ body = form;
136
+ }
137
+ else {
138
+ headers["content-type"] = "application/json";
139
+ body = JSON.stringify({ url: input.url, inputKey: input.inputKey, wait, preset: input.preset, options: input.options, filename: input.filename });
140
+ }
141
+ const response = await this.#fetch(`${this.#baseUrl}/vectorize`, { method: "POST", headers, body, signal });
142
+ if (response.status === 200)
143
+ return { done: true, body: (await response.json()) };
144
+ if (response.status === 202)
145
+ return { done: false, body: (await response.json()) };
146
+ throw await VecSnapError.from(response);
147
+ }
148
+ }
149
+ function bind(client) {
150
+ const bound = {};
151
+ for (const [name, operation] of Object.entries(operations)) {
152
+ if (typeof operation === "function")
153
+ bound[name] = (options = {}) => operation({ ...options, client });
154
+ }
155
+ return bound;
156
+ }
157
+ /** A generated call's answer, or its refusal thrown as a `VecSnapError` (the one reading of an error, `VecSnapError.fromBody`). */
158
+ async function unwrap(result) {
159
+ if (result.data !== undefined && result.response?.ok)
160
+ return result.data;
161
+ return Promise.reject(VecSnapError.fromBody(result.response?.status ?? 0, result.error ?? null, result.response?.headers ?? null));
162
+ }
163
+ /** A pause that an abort ends at once — its listener removed either way, so a long wait leaves none behind. */
164
+ function sleep(ms, signal) {
165
+ if (signal?.aborted)
166
+ return Promise.reject(signal.reason);
167
+ return new Promise((done, fail) => {
168
+ const aborted = () => {
169
+ clearTimeout(timer);
170
+ fail(signal.reason);
171
+ };
172
+ const timer = setTimeout(() => {
173
+ signal?.removeEventListener("abort", aborted);
174
+ done();
175
+ }, ms);
176
+ signal?.addEventListener("abort", aborted, { once: true });
177
+ });
178
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Checking an event VecSnap sent your server — the Standard Webhooks scheme (https://www.standardwebhooks.com):
3
+ *
4
+ * signed = `${webhook-id}.${webhook-timestamp}.${raw body}`
5
+ * webhook-signature: v1,<base64 HMAC-SHA256(base64-decode(secret after "whsec_"), signed)> (space-separated, several
6
+ * during a secret's roll — any one matching is enough)
7
+ *
8
+ * Web Crypto only: it runs in Node 18+, Deno, Bun, Cloudflare Workers and Vercel's edge alike. Pass the RAW body — the
9
+ * bytes as they arrived, before any JSON parsing — or the signature cannot match.
10
+ */
11
+ import type { WebhookEvent } from "./generated/types.gen.ts";
12
+ /** How far `webhook-timestamp` may be from now: the reference libraries' five minutes, either way. */
13
+ export declare const WEBHOOK_TOLERANCE_SECONDS: number;
14
+ export declare class WebhookVerificationError extends Error {
15
+ readonly name = "WebhookVerificationError";
16
+ readonly reason: "missing_headers" | "malformed_timestamp" | "stale" | "bad_signature" | "bad_secret";
17
+ constructor(reason: WebhookVerificationError["reason"], message: string);
18
+ }
19
+ type HeaderSource = Headers | Record<string, string | string[] | undefined>;
20
+ /** `v1,<base64>` of the event, signed with `secret` — what we send; your tests can sign their own events with it. */
21
+ export declare function signWebhook(body: string, secret: string, id: string, timestamp: number): Promise<string>;
22
+ /**
23
+ * The event, once its signature and timestamp are checked — or a `WebhookVerificationError` saying why not.
24
+ *
25
+ * const event = await verifyWebhook(rawBody, request.headers, process.env.VECSNAP_WEBHOOK_SECRET!);
26
+ * if (event.type === "conversion.completed") … // dedupe on event.id: an event may come more than once
27
+ */
28
+ export declare function verifyWebhook(body: string, headers: HeaderSource, secret: string, now?: Date): Promise<WebhookEvent>;
29
+ export {};
@@ -0,0 +1,69 @@
1
+ /** How far `webhook-timestamp` may be from now: the reference libraries' five minutes, either way. */
2
+ export const WEBHOOK_TOLERANCE_SECONDS = 5 * 60;
3
+ export class WebhookVerificationError extends Error {
4
+ name = "WebhookVerificationError";
5
+ reason;
6
+ constructor(reason, message) {
7
+ super(message);
8
+ this.reason = reason;
9
+ }
10
+ }
11
+ /** A header by its name, whatever case the framework kept it in (a `Headers`, or a plain object: `Webhook-Id`, `webhook-id`). */
12
+ function header(headers, name) {
13
+ if (typeof headers.get === "function")
14
+ return headers.get(name);
15
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
16
+ const value = entry?.[1];
17
+ return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
18
+ }
19
+ function base64ToBytes(text) {
20
+ const binary = atob(text);
21
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
22
+ }
23
+ function bytesToBase64(bytes) {
24
+ let binary = "";
25
+ for (const byte of bytes)
26
+ binary += String.fromCharCode(byte);
27
+ return btoa(binary);
28
+ }
29
+ /** Equal in constant time for equal lengths: no early exit a timing could read. */
30
+ function same(a, b) {
31
+ if (a.length !== b.length)
32
+ return false;
33
+ let diff = 0;
34
+ for (let i = 0; i < a.length; i++)
35
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
36
+ return diff === 0;
37
+ }
38
+ /** `v1,<base64>` of the event, signed with `secret` — what we send; your tests can sign their own events with it. */
39
+ export async function signWebhook(body, secret, id, timestamp) {
40
+ const match = /^(?:v1,)?whsec_([A-Za-z0-9+/]+={0,2})$/.exec(secret.trim());
41
+ if (!match)
42
+ throw new WebhookVerificationError("bad_secret", "a webhook secret is whsec_ followed by base64");
43
+ const key = await crypto.subtle.importKey("raw", base64ToBytes(match[1]), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
44
+ const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${timestamp}.${body}`));
45
+ return `v1,${bytesToBase64(new Uint8Array(mac))}`;
46
+ }
47
+ /**
48
+ * The event, once its signature and timestamp are checked — or a `WebhookVerificationError` saying why not.
49
+ *
50
+ * const event = await verifyWebhook(rawBody, request.headers, process.env.VECSNAP_WEBHOOK_SECRET!);
51
+ * if (event.type === "conversion.completed") … // dedupe on event.id: an event may come more than once
52
+ */
53
+ export async function verifyWebhook(body, headers, secret, now = new Date()) {
54
+ const id = header(headers, "webhook-id");
55
+ const timestamp = header(headers, "webhook-timestamp");
56
+ const signatures = header(headers, "webhook-signature");
57
+ if (!id || !timestamp || !signatures)
58
+ throw new WebhookVerificationError("missing_headers", "webhook-id, webhook-timestamp and webhook-signature are required");
59
+ if (!/^\d{1,12}$/.test(timestamp))
60
+ throw new WebhookVerificationError("malformed_timestamp", "webhook-timestamp is not a number of seconds");
61
+ if (Math.abs(Math.floor(now.getTime() / 1000) - Number(timestamp)) > WEBHOOK_TOLERANCE_SECONDS) {
62
+ throw new WebhookVerificationError("stale", "webhook-timestamp is more than 5 minutes from now: a replay, or a clock to set");
63
+ }
64
+ const expected = await signWebhook(body, secret, id, Number(timestamp));
65
+ if (!signatures.split(" ").some((signature) => same(signature, expected))) {
66
+ throw new WebhookVerificationError("bad_signature", "no webhook-signature matches this secret: a forged event, or another endpoint's secret");
67
+ }
68
+ return JSON.parse(body);
69
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@vecsnap/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The VecSnap API from TypeScript and JavaScript: turn an image into a clean SVG in one call.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "sideEffects": false,
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.json",
25
+ "test": "node --test test/*.test.ts"
26
+ },
27
+ "devDependencies": {
28
+ "typescript": "5.9.3"
29
+ },
30
+ "homepage": "https://vecsnap.com/docs/sdks/node",
31
+ "keywords": [
32
+ "vecsnap",
33
+ "svg",
34
+ "vectorize",
35
+ "vector",
36
+ "image",
37
+ "sdk"
38
+ ]
39
+ }