@davixlabs/h2i-sdk 0.0.0-stage → 1.2.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/index.js ADDED
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+ // @davixlabs/h2i-sdk -- official Node.js client for the Davix H2I API.
3
+ // Everything API-specific (endpoints, parameters, enums, limits, errors) is generated from the
4
+ // canonical Davix H2I contract; the runtime in ./src is hand-written and contract-agnostic.
5
+ const { DavixH2I, DavixH2IResponse, SDK_VERSION } = require('./src/client');
6
+ const errors = require('./src/errors');
7
+ const { ENUMS } = require('./src/generated/enums');
8
+ const { ErrorCodes } = require('./src/generated/error-codes');
9
+ const contract = require('./src/generated/contract.json');
10
+
11
+ module.exports = {
12
+ DavixH2I,
13
+ DavixH2IResponse,
14
+ ...errors,
15
+ enums: ENUMS,
16
+ ErrorCodes,
17
+ SDK_VERSION,
18
+ CONTRACT_VERSION: contract.contractVersion,
19
+ contract,
20
+ };
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@davixlabs/h2i-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0",
4
+ "description": "Official Node.js SDK for the Davix H2I API. Typed methods, machine-readable metadata (enums, minimum/maximum, defaults), structured errors and a safe generic request() -- all generated from the canonical Davix H2I contract.",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "license": "SEE LICENSE IN LICENSE",
8
+ "private": false,
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Davixlabs/Davix-H2I-App.git",
12
+ "directory": "sdk/node"
13
+ },
14
+ "publishConfig": {
15
+ "registry": "https://registry.npmjs.org",
16
+ "access": "public"
17
+ },
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "files": [
22
+ "LICENSE",
23
+ "index.js",
24
+ "index.d.ts",
25
+ "src",
26
+ "README.md"
27
+ ],
28
+ "keywords": [
29
+ "h2i",
30
+ "image",
31
+ "pdf",
32
+ "api",
33
+ "sdk"
34
+ ],
35
+ "scripts": {
36
+ "typecheck": "tsc --noEmit -p tsconfig.json",
37
+ "test": "node --test test/*.test.js"
38
+ },
39
+ "sideEffects": false
40
+ }
package/src/client.js ADDED
@@ -0,0 +1,447 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const crypto = require('crypto');
5
+ const pkg = require('../package.json');
6
+ const bundledContract = require('./generated/contract.json');
7
+ const { ENDPOINTS } = require('./generated/api');
8
+ const { ENUMS } = require('./generated/enums');
9
+ const errors = require('./errors');
10
+ const { assertPublicPath, expandPath } = require('./paths');
11
+ const { Schema } = require('./schema');
12
+ const { buildForm } = require('./multipart');
13
+
14
+ const DEFAULT_BASE_URL = 'https://app.h2i.davixlabs.io';
15
+ const SDK_VERSION = pkg.version;
16
+ const SUPPORTED_SCHEMA_MAJOR = 1;
17
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
18
+ const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
19
+
20
+ function isLocalHost(hostname) {
21
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1' || hostname.endsWith('.localhost');
22
+ }
23
+
24
+ function sleep(ms, signal) {
25
+ return new Promise((resolve, reject) => {
26
+ const t = setTimeout(resolve, ms);
27
+ if (signal) signal.addEventListener('abort', () => { clearTimeout(t); reject(signal.reason || new errors.DavixH2IError('Aborted.')); }, { once: true });
28
+ });
29
+ }
30
+
31
+ class DavixH2IResponse {
32
+ constructor({ status, headers, data, requestId, idempotencyKey, attempts }) {
33
+ this.status = status;
34
+ this.headers = headers; // plain object, lower-cased names
35
+ this.data = data; // parsed JSON (or text/Buffer for non-JSON)
36
+ this.requestId = requestId || null; // Request-Id header, else body.request_id
37
+ this.idempotencyKey = idempotencyKey || null; // the key this call was sent with (if any)
38
+ this.attempts = attempts || 1; // number of HTTP attempts made (1 = no retry)
39
+ }
40
+ /** Every output object with a `url` (signed download URLs) found in the response body. */
41
+ files() {
42
+ const out = [];
43
+ (function walk(v) {
44
+ if (Array.isArray(v)) v.forEach(walk);
45
+ else if (v && typeof v === 'object') { if (typeof v.url === 'string') out.push(v); Object.values(v).forEach(walk); }
46
+ }(this.data));
47
+ return out;
48
+ }
49
+ /** True when the server accepted an async job (HTTP 202). */
50
+ get accepted() { return this.status === 202; }
51
+ /** The job id of an async (202) response, else null. */
52
+ get jobId() { return this.data && this.data.job_id !== undefined ? this.data.job_id : null; }
53
+ }
54
+
55
+ class DavixH2I {
56
+ /**
57
+ * @param {object} options
58
+ * @param {string} options.apiKey Davix H2I API key (sent in the X-Api-Key header, never in the URL or body).
59
+ * @param {string} [options.baseUrl] Default https://app.h2i.davixlabs.io. http:// is refused except for localhost.
60
+ * @param {number} [options.timeoutMs] Per-attempt timeout (default 60000).
61
+ * @param {number} [options.maxRetries] Retries for safe/idempotent failures (default 2, 0 disables).
62
+ * @param {string} [options.authScheme] 'x-api-key' (default) or 'bearer' (Authorization: Bearer).
63
+ * @param {boolean} [options.autoIdempotencyKey] Generate one Idempotency-Key per call for endpoints that honour it
64
+ * (default true). The SAME key is reused for every retry of that call, so a retry can never bill twice.
65
+ * @param {boolean} [options.validate] Validate params locally before sending (default false; the server always validates).
66
+ * @param {function} [options.fetch] Custom fetch implementation (tests, proxies).
67
+ * @param {boolean} [options.allowInsecure] Permit plain http:// to non-local hosts (not recommended).
68
+ */
69
+ constructor(options = {}) {
70
+ const apiKey = options.apiKey;
71
+ if (typeof apiKey !== 'string' || apiKey.trim() === '') throw new errors.DavixH2IConfigError('Davix H2I: options.apiKey is required.');
72
+ if (/[\r\n]/.test(apiKey)) throw new errors.DavixH2IConfigError('Davix H2I: options.apiKey contains invalid characters.');
73
+ const base = new URL(options.baseUrl || DEFAULT_BASE_URL);
74
+ if (base.protocol !== 'https:' && !(base.protocol === 'http:' && (isLocalHost(base.hostname) || options.allowInsecure))) {
75
+ throw new errors.DavixH2IConfigError('Davix H2I: baseUrl must use https:// (http:// is only allowed for localhost, or with allowInsecure).');
76
+ }
77
+ if (base.username || base.password) throw new errors.DavixH2IConfigError('Davix H2I: credentials in baseUrl are not allowed.');
78
+ // Non-enumerable: console.log(client), util.inspect and JSON.stringify never reveal the key.
79
+ Object.defineProperty(this, '_apiKey', { value: apiKey.trim(), enumerable: false, writable: false });
80
+ this._base = base;
81
+ this.baseUrl = base.origin + base.pathname.replace(/\/+$/, '');
82
+ this.timeoutMs = options.timeoutMs === undefined ? 60000 : options.timeoutMs;
83
+ this.maxRetries = options.maxRetries === undefined ? 2 : options.maxRetries;
84
+ this.authScheme = options.authScheme || 'x-api-key';
85
+ if (!['x-api-key', 'bearer'].includes(this.authScheme)) throw new errors.DavixH2IConfigError('Davix H2I: authScheme must be "x-api-key" or "bearer".');
86
+ this.autoIdempotencyKey = options.autoIdempotencyKey !== false;
87
+ this.validateParams = Boolean(options.validate);
88
+ this.maxRetryDelayMs = options.maxRetryDelayMs === undefined ? 30000 : options.maxRetryDelayMs;
89
+ this.userAgent = `davix-h2i-node/${SDK_VERSION}${options.userAgentSuffix ? ` ${options.userAgentSuffix}` : ''}`;
90
+ this._fetch = options.fetch || (typeof fetch === 'function' ? fetch.bind(globalThis) : null);
91
+ if (!this._fetch) throw new errors.DavixH2IConfigError('Davix H2I: a global fetch is required (Node 18+), or pass options.fetch.');
92
+
93
+ this._live = null; // live contract after contract.refresh()
94
+ this._schemaCache = new Map();
95
+ this._errorIndex = null;
96
+ this._routeIndex = null;
97
+
98
+ const self = this;
99
+ /** Bundled vs live metadata. The bundled contract ships with this SDK; the live one comes from GET /v1/contract. */
100
+ this.contract = {
101
+ bundled: bundledContract,
102
+ get live() { return self._live; },
103
+ get active() { return self._live || bundledContract; },
104
+ get version() { return (self._live || bundledContract).contractVersion; },
105
+ fetch: () => self._fetchContract(),
106
+ refresh: async () => { const c = await self._fetchContract(); self._useLive(c); return c; },
107
+ reset: () => { self._live = null; self._schemaCache.clear(); self._errorIndex = null; self._routeIndex = null; },
108
+ // LIVE slices (one small GET each; the server answers with ETag/gzip). They return the response body.
109
+ endpoints: () => self._slice('contract.endpoints'),
110
+ endpoint: id => self._slice('contract.endpoints.{id}', { id }),
111
+ fields: id => self._slice('contract.endpoints.{id}.fields', { id }),
112
+ field: (id, name) => self._slice('contract.endpoints.{id}.fields.{name}', { id, name }),
113
+ actions: id => self._slice('contract.endpoints.{id}.actions', { id }),
114
+ response: id => self._slice('contract.endpoints.{id}.response', { id }),
115
+ errorsOf: id => self._slice('contract.endpoints.{id}.errors', { id }),
116
+ examples: id => self._slice('contract.endpoints.{id}.examples', { id }),
117
+ categories: () => self._slice('contract.categories'),
118
+ category: name => self._slice('contract.categories.{name}', { name }),
119
+ enums: () => self._slice('contract.enums'),
120
+ enum: name => self._slice('contract.enums.{name}', { name }),
121
+ errorCodes: () => self._slice('contract.errors'),
122
+ error: code => self._slice('contract.errors.{code}', { code }),
123
+ schemas: () => self._slice('contract.schemas'),
124
+ schemaOf: name => self._slice('contract.schemas.{name}', { name }),
125
+ auth: () => self._slice('contract.auth'),
126
+ };
127
+
128
+ /** Enum constants generated from the contract: h2i.enums.ImageFormat.WEBP === 'webp'. */
129
+ this.enums = ENUMS;
130
+
131
+ // typed namespaces: h2i.images.resize(...), h2i.ai.documents.summarize(...)
132
+ for (const [id, ns, method] of ENDPOINTS) {
133
+ let target = this;
134
+ for (const part of ns) {
135
+ if (!Object.prototype.hasOwnProperty.call(target, part)) target[part] = {};
136
+ target = target[part];
137
+ }
138
+ if (ns.length === 1 && ns[0] === 'capabilities' && method === 'get') continue; // replaced by the capabilities() function below
139
+ target[method] = (params, callOptions) => this.call(id, params, callOptions);
140
+ }
141
+ this._installCapabilities();
142
+ }
143
+
144
+ async _slice(id, params = {}) { return (await this.call(id, params)).data; }
145
+
146
+ // -------------------------------------------------------------------- metadata
147
+ /** The schema of one endpoint by id ("images.resize"); throws if unknown. */
148
+ schema(id) {
149
+ const c = this.contract.active;
150
+ let s = this._schemaCache.get(id);
151
+ if (!s) {
152
+ // a contract id ("jobs.{id}", "images.resize") or the SDK name ("jobs.get" = namespace.method)
153
+ const endpoint = c.endpoints.find(e => e.id === id) || c.endpoints.find(e => `${e.sdk.namespace.join('.')}.${e.sdk.method}` === id);
154
+ if (!endpoint) throw new errors.DavixH2IConfigError(`Unknown endpoint "${id}". See h2i.schemas().`);
155
+ s = new Schema(endpoint);
156
+ this._schemaCache.set(id, s);
157
+ }
158
+ return s;
159
+ }
160
+ /** Looks up an endpoint schema by HTTP method + path template ("POST", "/v1/images/resize"); null if unknown. */
161
+ schemaForRoute(method, pathTemplate) {
162
+ const e = this.contract.active.endpoints.find(x => x.method === String(method).toUpperCase() && x.path === pathTemplate);
163
+ return e ? this.schema(e.id) : null;
164
+ }
165
+ /** All endpoint schemas, optionally filtered ({ category: 'Images', audience: 'public' }). */
166
+ schemas(filter = {}) {
167
+ return this.contract.active.endpoints
168
+ .filter(e => (!filter.category || e.category === filter.category) && (!filter.audience || e.audience === filter.audience))
169
+ .map(e => this.schema(e.id));
170
+ }
171
+
172
+ _useLive(c) {
173
+ if (!c || typeof c !== 'object' || !Array.isArray(c.endpoints)) throw new errors.DavixH2IConfigError('The live contract is malformed.');
174
+ if (Math.floor(c.metadataSchemaVersion) !== SUPPORTED_SCHEMA_MAJOR) {
175
+ throw new errors.DavixH2IConfigError(`The live contract uses metadata schema ${c.metadataSchemaVersion}, which this SDK version (${SDK_VERSION}) does not understand. Upgrade the SDK.`);
176
+ }
177
+ this._live = c;
178
+ this._schemaCache.clear();
179
+ this._errorIndex = null;
180
+ this._routeIndex = null;
181
+ }
182
+ async _fetchContract() {
183
+ const res = await this._send('GET', '/v1/contract', { attach: false, retry: true });
184
+ return res.data;
185
+ }
186
+
187
+ // ------------------------------------------------------------------ capabilities
188
+ _installCapabilities() {
189
+ const self = this;
190
+ const fn = async function capabilities(category) {
191
+ const res = await self.call('capabilities', {}, {});
192
+ const data = res.data;
193
+ if (!category) return res;
194
+ if (!data || typeof data !== 'object' || !(category in data)) throw new errors.DavixH2IConfigError(`No runtime capability group "${category}". Available: ${Object.keys(data || {}).join(', ')}.`);
195
+ return Object.assign(Object.create(DavixH2IResponse.prototype), res, { data: data[category] });
196
+ };
197
+ /** STATIC capabilities: what the contract guarantees (bundled, no request). */
198
+ fn.static = (category) => {
199
+ const cap = this.contract.active.capabilities;
200
+ if (!category) return cap;
201
+ if (!cap.categories[category]) throw new errors.DavixH2IConfigError(`Unknown category "${category}". Available: ${Object.keys(cap.categories).join(', ')}.`);
202
+ return cap.categories[category];
203
+ };
204
+ /** ACCOUNT capabilities: subscription, plan limits and usage of the calling key (individual customer keys only). */
205
+ fn.account = async () => {
206
+ const [subscription, usage, account] = await Promise.all([this.call('subscription', {}), this.call('usage', {}), this.call('account', {})]);
207
+ return { subscription: subscription.data, usage: usage.data, account: account.data, requestIds: [subscription.requestId, usage.requestId, account.requestId] };
208
+ };
209
+ /** RUNTIME: one section ("pdfs") or one feature ("pdfs", "ocr") instead of the whole document. */
210
+ fn.section = name => this._slice('capabilities.{section}', { section: name });
211
+ fn.feature = (section, feature) => this._slice('capabilities.{section}.{feature}', { section, feature });
212
+ this.capabilities = fn;
213
+ }
214
+
215
+ // ---------------------------------------------------------------- typed calls
216
+ /**
217
+ * Calls an endpoint by contract id. Parameters are placed by the contract: path/query/header
218
+ * parameters, then a JSON or multipart body. Used by every generated method
219
+ * (h2i.images.resize(p) === h2i.call('images.resize', p)).
220
+ */
221
+ async call(id, params = {}, options = {}) {
222
+ const schema = this.schema(id);
223
+ const endpoint = schema._endpoint;
224
+ if (params === null || typeof params !== 'object' || Array.isArray(params)) throw new errors.DavixH2IConfigError(`${id}: params must be an object.`);
225
+ if (options.validate === true || (options.validate === undefined && this.validateParams)) {
226
+ const v = schema.validate(params);
227
+ if (!v.valid) throw new errors.DavixH2IConfigError(`${id}: invalid parameters: ${v.errors.map(e => e.message).join(' ')}`, { code: 'sdk_validation_failed', details: { errors: v.errors } });
228
+ }
229
+ const pathValues = {};
230
+ const query = {};
231
+ const headers = {};
232
+ const body = {};
233
+ const known = new Set();
234
+ for (const f of endpoint.request.fields) {
235
+ known.add(f.name);
236
+ if (f.location === 'header' && f.standard) continue; // e.g. Idempotency-Key: use options.idempotencyKey
237
+ const v = params[f.name];
238
+ if (f.location === 'path') pathValues[f.name] = v;
239
+ else if (v === undefined || v === null) continue;
240
+ else if (f.location === 'query') query[f.name] = v;
241
+ else if (f.location === 'header') headers[f.name] = String(v);
242
+ else body[f.name] = v;
243
+ }
244
+ if (options.strict) {
245
+ const unknown = Object.keys(params).filter(k => !known.has(k));
246
+ if (unknown.length) throw new errors.DavixH2IConfigError(`${id}: unknown parameter(s): ${unknown.join(', ')}.`);
247
+ }
248
+ // parameters the contract does not list (a newer server) are passed through in the body
249
+ for (const [k, v] of Object.entries(params)) if (!known.has(k) && v !== undefined && v !== null) body[k] = v;
250
+
251
+ const urlPath = expandPath(endpoint.path, pathValues);
252
+ const isMultipart = endpoint.request.contentType === 'multipart/form-data';
253
+ const isJson = endpoint.request.contentType === 'application/json';
254
+ const hasBody = Object.keys(body).length > 0;
255
+ let payload = null;
256
+ let contentType = null;
257
+ if (hasBody || isMultipart) {
258
+ if (isMultipart) payload = await buildForm(endpoint.request.fields.filter(f => f.location === 'form'), body);
259
+ else if (isJson || !endpoint.request.contentType) { payload = JSON.stringify(body); contentType = 'application/json'; }
260
+ }
261
+ const eligible = Boolean(endpoint.idempotency && endpoint.idempotency.supported) && endpoint.method === 'POST';
262
+ return this._send(endpoint.method, urlPath, {
263
+ query, headers, payload, contentType, eligibleForIdempotency: eligible, endpoint, options,
264
+ });
265
+ }
266
+
267
+ // --------------------------------------------------------------- generic call
268
+ /**
269
+ * Generic escape hatch for endpoints this SDK version does not know yet:
270
+ * await h2i.request('POST', '/v1/new-feature', { json: {...} })
271
+ * await h2i.request('POST', '/v1/new-upload', { form: { image: './a.png', mode: 'x' } })
272
+ * It reuses authentication, retries, idempotency, serialization and error handling, and can
273
+ * ONLY reach the public API (/v1/...): internal, admin and absolute URLs are refused.
274
+ */
275
+ async request(method, urlPath, options = {}) {
276
+ const policy = this.contract.active.requestPolicy;
277
+ const m = String(method).toUpperCase();
278
+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(m)) throw new errors.DavixH2IConfigError(`request(): unsupported method "${method}".`);
279
+ assertPublicPath(urlPath, policy);
280
+ const endpoint = this.contract.active.endpoints.find(e => e.method === m && matchTemplate(e.path, urlPath));
281
+ let payload = null;
282
+ let contentType = null;
283
+ if (options.json !== undefined && options.form !== undefined) throw new errors.DavixH2IConfigError('request(): pass either json or form, not both.');
284
+ if (options.json !== undefined) { payload = JSON.stringify(options.json); contentType = 'application/json'; }
285
+ else if (options.form !== undefined) {
286
+ const fields = endpoint ? endpoint.request.fields.filter(f => f.location === 'form') : null;
287
+ payload = await buildForm(fields, options.form);
288
+ }
289
+ const eligible = m === 'POST' && Boolean(endpoint && endpoint.idempotency && endpoint.idempotency.supported);
290
+ return this._send(m, urlPath, {
291
+ query: options.query || {}, headers: options.headers || {}, payload, contentType, eligibleForIdempotency: eligible, endpoint, options,
292
+ });
293
+ }
294
+
295
+ // ------------------------------------------------------------------- downloads
296
+ /**
297
+ * Downloads a signed output URL returned by Davix H2I (a `url` string or a result object with
298
+ * `url`). Only URLs on the configured Davix H2I host are fetched, and the API key is NEVER sent:
299
+ * signed URLs are self-authenticating (the signing secret stays on the server).
300
+ * Returns { buffer, contentType, size } or, with { dest }, writes the file and returns { path, contentType, size }.
301
+ */
302
+ async download(urlOrResult, options = {}) {
303
+ const raw = typeof urlOrResult === 'string' ? urlOrResult : urlOrResult && urlOrResult.url;
304
+ if (typeof raw !== 'string') throw new errors.DavixH2IConfigError('download(): pass a URL string or an object with a "url" property.');
305
+ const url = new URL(raw, this._base);
306
+ if (url.origin !== this._base.origin) throw new errors.DavixH2IConfigError('download(): refusing to fetch a URL that is not on the configured Davix H2I host.');
307
+ if (!/^\/(render|image|pdf|ai|data|documents)\/[^/\\]+$/.test(url.pathname)) throw new errors.DavixH2IConfigError('download(): not a Davix H2I output URL.');
308
+ const controller = new AbortController();
309
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs || this.timeoutMs);
310
+ let res;
311
+ try {
312
+ res = await this._fetch(url.toString(), { method: 'GET', redirect: 'error', signal: controller.signal, headers: { 'user-agent': this.userAgent } });
313
+ } catch (err) {
314
+ throw new errors.DavixH2INetworkError(`Download failed: ${err.message}`, { cause: err });
315
+ } finally { clearTimeout(timer); }
316
+ if (!res.ok) {
317
+ const requestId = res.headers.get('request-id');
318
+ let body = null;
319
+ try { body = await res.json(); } catch (_) { /* not json */ }
320
+ throw this._apiError(res.status, body, requestId, res.headers);
321
+ }
322
+ const buffer = Buffer.from(await res.arrayBuffer());
323
+ const contentType = res.headers.get('content-type');
324
+ if (options.dest) {
325
+ await fs.promises.mkdir(path.dirname(path.resolve(options.dest)), { recursive: true });
326
+ await fs.promises.writeFile(options.dest, buffer);
327
+ return { path: options.dest, contentType, size: buffer.length };
328
+ }
329
+ return { buffer, contentType, size: buffer.length };
330
+ }
331
+
332
+ // ---------------------------------------------------------------------- core
333
+ _errorMeta(code) {
334
+ if (!this._errorIndex) this._errorIndex = new Map(this.contract.active.errors.map(e => [e.code, e]));
335
+ return this._errorIndex.get(code) || null;
336
+ }
337
+
338
+ _apiError(status, body, requestId, headers) {
339
+ const err = body && typeof body === 'object' ? (body.error || {}) : {};
340
+ const code = err.code || (body && body.code) || null;
341
+ const meta = code ? this._errorMeta(code) : null;
342
+ const retryAfterHeader = headers && headers.get ? headers.get('retry-after') : null;
343
+ let retryAfterMs = null;
344
+ if (retryAfterHeader && Number.isFinite(Number(retryAfterHeader))) retryAfterMs = Number(retryAfterHeader) * 1000;
345
+ else if (err.details && Number.isFinite(Number(err.details.retry_after_seconds))) retryAfterMs = Number(err.details.retry_after_seconds) * 1000;
346
+ const Cls = errors.classFor(status, meta ? meta.family : null);
347
+ return new Cls((err.message || (body && body.message)) || `Davix H2I API error (HTTP ${status})`, {
348
+ code, status, hint: err.hint, details: err.details, requestId: requestId || (body && body.request_id), renewalUrl: err.renewal_url,
349
+ retryable: meta ? meta.retryable : (status === 503 || status === 504), retryAfterMs, body,
350
+ });
351
+ }
352
+
353
+ _shouldRetry(method, idempotencyKey, failure) {
354
+ const safe = IDEMPOTENT_METHODS.has(method) || Boolean(idempotencyKey);
355
+ if (failure.network) return safe; // connection-level failure: only when repeating cannot duplicate work
356
+ const { status, error } = failure;
357
+ if (status === 429) return error.retryable; // e.g. rate_limit_exceeded; never monthly_quota_exceeded
358
+ if (status === 503 || status === 504) return error.retryable && safe;
359
+ return false; // 4xx and 500 are not retried
360
+ }
361
+
362
+ async _send(method, urlPath, ctx) {
363
+ const options = ctx.options || {};
364
+ const attach = ctx.attach !== false;
365
+ const url = new URL(this.baseUrl + urlPath);
366
+ if (url.origin !== this._base.origin) throw new errors.DavixH2IConfigError('Resolved URL left the configured Davix H2I host.');
367
+ for (const [k, v] of Object.entries(ctx.query || {})) {
368
+ if (Array.isArray(v)) v.forEach(x => url.searchParams.append(k, String(x)));
369
+ else url.searchParams.set(k, typeof v === 'boolean' ? (v ? 'true' : 'false') : String(v));
370
+ }
371
+ const headers = { accept: 'application/json', 'user-agent': this.userAgent };
372
+ if (attach) {
373
+ if (this.authScheme === 'bearer') headers.authorization = `Bearer ${this._apiKey}`;
374
+ else headers['x-api-key'] = this._apiKey;
375
+ }
376
+ for (const [k, v] of Object.entries(Object.assign({}, ctx.headers, options.headers))) {
377
+ const lk = k.toLowerCase();
378
+ if (['x-api-key', 'authorization', 'host'].includes(lk)) throw new errors.DavixH2IConfigError(`Header "${k}" is managed by the SDK and cannot be overridden.`);
379
+ headers[lk] = String(v);
380
+ }
381
+ if (ctx.contentType) headers['content-type'] = ctx.contentType;
382
+
383
+ let idempotencyKey = options.idempotencyKey || null;
384
+ const retryOpt = options.retry === false ? 0 : (options.maxRetries !== undefined ? options.maxRetries : this.maxRetries);
385
+ if (idempotencyKey) {
386
+ if (!/^[A-Za-z0-9._:-]{8,128}$/.test(idempotencyKey)) throw new errors.DavixH2IConfigError('idempotencyKey must be 8-128 characters from [A-Za-z0-9._:-].');
387
+ } else if (this.autoIdempotencyKey && ctx.eligibleForIdempotency && retryOpt > 0) {
388
+ idempotencyKey = `h2i-${crypto.randomUUID()}`; // one key per logical call, reused for every retry of it
389
+ }
390
+ if (idempotencyKey) headers['idempotency-key'] = idempotencyKey;
391
+
392
+ const timeoutMs = options.timeoutMs === undefined ? this.timeoutMs : options.timeoutMs;
393
+ let attempt = 0;
394
+ for (;;) {
395
+ attempt += 1;
396
+ const controller = new AbortController();
397
+ const onAbort = () => controller.abort(options.signal.reason);
398
+ if (options.signal) { if (options.signal.aborted) throw new errors.DavixH2IError('Aborted.'); options.signal.addEventListener('abort', onAbort, { once: true }); }
399
+ const timer = timeoutMs ? setTimeout(() => controller.abort(new errors.DavixH2ITimeoutError(`Request timed out after ${timeoutMs} ms.`)), timeoutMs) : null;
400
+ let res;
401
+ try {
402
+ res = await this._fetch(url.toString(), { method, headers, body: ctx.payload || undefined, signal: controller.signal, redirect: 'error' });
403
+ } catch (err) {
404
+ const timedOut = err instanceof errors.DavixH2ITimeoutError || (controller.signal.aborted && controller.signal.reason instanceof errors.DavixH2ITimeoutError);
405
+ if (options.signal && options.signal.aborted) throw err;
406
+ const netErr = timedOut ? new errors.DavixH2ITimeoutError(`Request timed out after ${timeoutMs} ms.`, { cause: err }) : new errors.DavixH2INetworkError(`Network error: ${err.message}`, { cause: err });
407
+ if (attempt <= retryOpt && this._shouldRetry(method, idempotencyKey, { network: true })) { await this._backoff(attempt, null, options.signal); continue; }
408
+ throw netErr;
409
+ } finally {
410
+ if (timer) clearTimeout(timer);
411
+ if (options.signal) options.signal.removeEventListener('abort', onAbort);
412
+ }
413
+ const requestIdHeader = res.headers.get('request-id');
414
+ const headersObj = {};
415
+ res.headers.forEach((v, k) => { headersObj[k.toLowerCase()] = v; });
416
+ const ct = res.headers.get('content-type') || '';
417
+ let data = null;
418
+ if (ct.includes('json')) { try { data = await res.json(); } catch (_) { data = null; } }
419
+ else { const buf = Buffer.from(await res.arrayBuffer()); data = ct.startsWith('text/') ? buf.toString('utf8') : buf; }
420
+ if (res.ok) {
421
+ const requestId = requestIdHeader || (data && typeof data === 'object' && !Buffer.isBuffer(data) ? data.request_id : null);
422
+ return new DavixH2IResponse({ status: res.status, headers: headersObj, data, requestId, idempotencyKey, attempts: attempt });
423
+ }
424
+ const error = this._apiError(res.status, data, requestIdHeader, res.headers);
425
+ if (attempt <= retryOpt && this._shouldRetry(method, idempotencyKey, { status: res.status, error })) {
426
+ await this._backoff(attempt, error.retryAfterMs, options.signal);
427
+ continue;
428
+ }
429
+ throw error;
430
+ }
431
+ }
432
+
433
+ async _backoff(attempt, retryAfterMs, signal) {
434
+ const base = Math.min(8000, 500 * 2 ** (attempt - 1));
435
+ let delay = Math.random() * base; // full jitter
436
+ if (retryAfterMs !== null && retryAfterMs !== undefined) delay = Math.max(delay, retryAfterMs);
437
+ await sleep(Math.min(delay, this.maxRetryDelayMs), signal);
438
+ }
439
+ }
440
+
441
+ // "/v1/jobs/{id}" matches "/v1/jobs/12" (used only to find contract metadata for a generic request)
442
+ function matchTemplate(template, concrete) {
443
+ const re = new RegExp(`^${template.replace(/[.*+?^${}()|[\]\\]/g, m => (m === '{' || m === '}' ? m : `\\${m}`)).replace(/\{[A-Za-z0-9_]+\}/g, '[^/]+')}$`);
444
+ return re.test(concrete);
445
+ }
446
+
447
+ module.exports = { DavixH2I, DavixH2IResponse, DEFAULT_BASE_URL, SDK_VERSION, ENUMS };
package/src/errors.js ADDED
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+ // Error types. The set of error CODES (and their HTTP status / retryability / family) comes
3
+ // from the generated contract (see ./generated/contract.json -> errors); the classes below are
4
+ // keyed by the contract's error *family*, so a code added to the contract is automatically
5
+ // represented without an SDK release. Nothing here invents error codes.
6
+
7
+ class DavixH2IError extends Error {
8
+ constructor(message, details = {}) {
9
+ super(message);
10
+ this.name = this.constructor.name;
11
+ this.code = details.code || null; // Davix H2I error code from the API (error.code), e.g. "invalid_parameter"
12
+ this.status = details.status === undefined ? null : details.status; // HTTP status (null for client-side/network errors)
13
+ this.hint = details.hint || null; // error.hint
14
+ this.details = details.details || null; // error.details (field, allowed, value, limit, ...)
15
+ this.requestId = details.requestId || null; // Request-Id header / request_id body field
16
+ this.renewalUrl = details.renewalUrl || null; // error.renewal_url (key_expired)
17
+ this.retryable = Boolean(details.retryable); // from the contract's error catalog
18
+ this.retryAfterMs = details.retryAfterMs === undefined ? null : details.retryAfterMs;
19
+ this.body = details.body === undefined ? null : details.body; // the parsed error response body
20
+ if (details.cause) this.cause = details.cause;
21
+ }
22
+ }
23
+
24
+ class DavixH2IApiError extends DavixH2IError {}
25
+ class DavixH2IValidationError extends DavixH2IApiError {} // family: request
26
+ class DavixH2IUploadError extends DavixH2IApiError {} // family: upload
27
+ class DavixH2IAuthenticationError extends DavixH2IApiError {} // family: auth
28
+ class DavixH2IPlanError extends DavixH2IApiError {} // family: plan (entitlements / endpoint access)
29
+ class DavixH2IQuotaError extends DavixH2IApiError {} // family: quota
30
+ class DavixH2IRateLimitError extends DavixH2IQuotaError {} // HTTP 429
31
+ class DavixH2IProcessingError extends DavixH2IApiError {} // family: processing
32
+ class DavixH2IServerError extends DavixH2IApiError {} // family: server, or any 5xx
33
+ class DavixH2INotFoundError extends DavixH2IApiError {} // HTTP 404
34
+ class DavixH2IConflictError extends DavixH2IApiError {} // HTTP 409
35
+ class DavixH2IAiError extends DavixH2IApiError {} // family: ai
36
+ class DavixH2IKeyError extends DavixH2IApiError {} // family: keys
37
+ class DavixH2IJobError extends DavixH2IApiError {} // family: jobs
38
+ class DavixH2ISignedUrlError extends DavixH2IApiError {} // family: signed-url
39
+
40
+ class DavixH2INetworkError extends DavixH2IError {} // connection failed / DNS / TLS
41
+ class DavixH2ITimeoutError extends DavixH2INetworkError {} // client-side timeout
42
+ class DavixH2IConfigError extends DavixH2IError {} // SDK misuse (bad option, forbidden path, invalid parameter)
43
+
44
+ const BY_FAMILY = {
45
+ request: DavixH2IValidationError, upload: DavixH2IUploadError, auth: DavixH2IAuthenticationError, plan: DavixH2IPlanError,
46
+ quota: DavixH2IQuotaError, processing: DavixH2IProcessingError, server: DavixH2IServerError, ai: DavixH2IAiError,
47
+ keys: DavixH2IKeyError, jobs: DavixH2IJobError, 'signed-url': DavixH2ISignedUrlError,
48
+ };
49
+
50
+ // Picks the most specific class for an API error response.
51
+ function classFor(status, family) {
52
+ if (status === 429) return DavixH2IRateLimitError;
53
+ if (status === 404 && !BY_FAMILY[family]) return DavixH2INotFoundError;
54
+ if (status === 409) return DavixH2IConflictError;
55
+ if (BY_FAMILY[family]) return BY_FAMILY[family];
56
+ if (status >= 500) return DavixH2IServerError;
57
+ if (status === 401 || status === 403) return DavixH2IAuthenticationError;
58
+ if (status === 404) return DavixH2INotFoundError;
59
+ return DavixH2IApiError;
60
+ }
61
+
62
+ module.exports = {
63
+ DavixH2IError, DavixH2IApiError, DavixH2IValidationError, DavixH2IUploadError, DavixH2IAuthenticationError, DavixH2IPlanError,
64
+ DavixH2IQuotaError, DavixH2IRateLimitError, DavixH2IProcessingError, DavixH2IServerError, DavixH2INotFoundError, DavixH2IConflictError,
65
+ DavixH2IAiError, DavixH2IKeyError, DavixH2IJobError, DavixH2ISignedUrlError,
66
+ DavixH2INetworkError, DavixH2ITimeoutError, DavixH2IConfigError, classFor,
67
+ };