@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/LICENSE +10 -0
- package/README.md +54 -2
- package/index.d.ts +21589 -0
- package/index.js +20 -0
- package/package.json +38 -4
- package/src/client.js +447 -0
- package/src/errors.js +67 -0
- package/src/generated/api.js +395 -0
- package/src/generated/contract.json +1 -0
- package/src/generated/enums.js +2890 -0
- package/src/generated/error-codes.js +100 -0
- package/src/multipart.js +109 -0
- package/src/paths.js +47 -0
- package/src/schema.js +174 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// GENERATED from the Davix H2I API contract (3.0.0). Do not edit.
|
|
3
|
+
// Every error code the API can return (error.code), for comparisons such as err.code === ErrorCodes.RATE_LIMIT_EXCEEDED.
|
|
4
|
+
const ErrorCodes = Object.freeze({
|
|
5
|
+
AI_CONFIGURATION_ERROR: "ai_configuration_error",
|
|
6
|
+
AI_FEATURE_UNAVAILABLE: "ai_feature_unavailable",
|
|
7
|
+
AI_GENERATION_FAILED: "ai_generation_failed",
|
|
8
|
+
AI_INPUT_INVALID: "ai_input_invalid",
|
|
9
|
+
AI_INPUT_TOO_LARGE: "ai_input_too_large",
|
|
10
|
+
AI_MODEL_INCOMPATIBLE: "ai_model_incompatible",
|
|
11
|
+
AI_MODEL_NOT_FOUND: "ai_model_not_found",
|
|
12
|
+
AI_NOT_CONFIGURED: "ai_not_configured",
|
|
13
|
+
AI_OUTPUT_INVALID: "ai_output_invalid",
|
|
14
|
+
AI_PARAMETER_UNSUPPORTED: "ai_parameter_unsupported",
|
|
15
|
+
AI_PROCESSING_FAILED: "ai_processing_failed",
|
|
16
|
+
AI_PROVIDER_UNAVAILABLE: "ai_provider_unavailable",
|
|
17
|
+
AI_QUOTA_EXCEEDED: "ai_quota_exceeded",
|
|
18
|
+
AI_RATE_LIMITED: "ai_rate_limited",
|
|
19
|
+
AI_SECURITY_REJECTED: "ai_security_rejected",
|
|
20
|
+
AI_TIMEOUT: "ai_timeout",
|
|
21
|
+
API_KEY_LOCATION_NOT_ALLOWED: "api_key_location_not_allowed",
|
|
22
|
+
ASSISTANT_UNAVAILABLE: "assistant_unavailable",
|
|
23
|
+
ASYNC_LIMIT_REACHED: "async_limit_reached",
|
|
24
|
+
ASYNC_NOT_ALLOWED: "async_not_allowed",
|
|
25
|
+
ASYNC_REQUIRES_CUSTOMER_KEY: "async_requires_customer_key",
|
|
26
|
+
CERTIFICATE_LIMIT_REACHED: "certificate_limit_reached",
|
|
27
|
+
CERTIFICATES_UNAVAILABLE: "certificates_unavailable",
|
|
28
|
+
CONVERSATION_FULL: "conversation_full",
|
|
29
|
+
DATA_CONVERSION_FAILED: "data_conversion_failed",
|
|
30
|
+
DEMO_BUSY: "demo_busy",
|
|
31
|
+
DEMO_FORBIDDEN: "demo_forbidden",
|
|
32
|
+
DEMO_LIMIT_REACHED: "demo_limit_reached",
|
|
33
|
+
DEMO_NOT_AVAILABLE: "demo_not_available",
|
|
34
|
+
DEMO_UNAVAILABLE: "demo_unavailable",
|
|
35
|
+
DEPENDENCY_UNAVAILABLE: "dependency_unavailable",
|
|
36
|
+
DIMENSION_EXCEEDED: "dimension_exceeded",
|
|
37
|
+
DUPLICATE_CERTIFICATE_NAME: "duplicate_certificate_name",
|
|
38
|
+
DUPLICATE_PRESET_NAME: "duplicate_preset_name",
|
|
39
|
+
DUPLICATE_TEMPLATE_NAME: "duplicate_template_name",
|
|
40
|
+
ENDPOINT_API_DISABLED: "endpoint_api_disabled",
|
|
41
|
+
ENDPOINT_DISABLED: "endpoint_disabled",
|
|
42
|
+
ENDPOINT_NOT_ALLOWED: "endpoint_not_allowed",
|
|
43
|
+
EXPIRED: "expired",
|
|
44
|
+
FILE_TOO_LARGE: "file_too_large",
|
|
45
|
+
FONT_UNAVAILABLE: "font_unavailable",
|
|
46
|
+
FORBIDDEN: "forbidden",
|
|
47
|
+
FORMAT_NOT_ALLOWED: "format_not_allowed",
|
|
48
|
+
HTML_RENDER_FAILED: "html_render_failed",
|
|
49
|
+
HTML_TOO_LARGE: "html_too_large",
|
|
50
|
+
IDEMPOTENCY_KEY_CONFLICT: "idempotency_key_conflict",
|
|
51
|
+
IMAGE_PROCESSING_FAILED: "image_processing_failed",
|
|
52
|
+
INTERNAL_ERROR: "internal_error",
|
|
53
|
+
INVALID_API_KEY: "invalid_api_key",
|
|
54
|
+
INVALID_IDEMPOTENCY_KEY: "invalid_idempotency_key",
|
|
55
|
+
INVALID_PARAMETER: "invalid_parameter",
|
|
56
|
+
INVALID_SIGNATURE: "invalid_signature",
|
|
57
|
+
INVALID_UPLOAD: "invalid_upload",
|
|
58
|
+
JOB_NOT_CANCELLABLE: "job_not_cancellable",
|
|
59
|
+
JOB_NOT_FOUND: "job_not_found",
|
|
60
|
+
KEY_EXPIRED: "key_expired",
|
|
61
|
+
KEY_LIMIT_REACHED: "key_limit_reached",
|
|
62
|
+
KEY_NOT_FOUND: "key_not_found",
|
|
63
|
+
KEY_QUOTA_EXCEEDED: "key_quota_exceeded",
|
|
64
|
+
MESSAGE_TOO_LONG: "message_too_long",
|
|
65
|
+
MISSING_FIELD: "missing_field",
|
|
66
|
+
MONTHLY_QUOTA_EXCEEDED: "monthly_quota_exceeded",
|
|
67
|
+
NO_SPEECH: "no_speech",
|
|
68
|
+
NOT_FOUND: "not_found",
|
|
69
|
+
NOT_LINKED: "not_linked",
|
|
70
|
+
PDF_PAGE_LIMIT_EXCEEDED: "pdf_page_limit_exceeded",
|
|
71
|
+
PDF_TOOL_FAILED: "pdf_tool_failed",
|
|
72
|
+
PLAN_QUOTA_NOT_CONFIGURED: "plan_quota_not_configured",
|
|
73
|
+
PLAN_RESOLUTION_FAILED: "plan_resolution_failed",
|
|
74
|
+
RATE_LIMIT_EXCEEDED: "rate_limit_exceeded",
|
|
75
|
+
RATE_LIMIT_STORE_UNAVAILABLE: "rate_limit_store_unavailable",
|
|
76
|
+
RATE_LIMIT_UNAVAILABLE: "rate_limit_unavailable",
|
|
77
|
+
RATE_LIMITED: "rate_limited",
|
|
78
|
+
RENDER_SIZE_EXCEEDED: "render_size_exceeded",
|
|
79
|
+
REQUEST_OPEN: "request_open",
|
|
80
|
+
REVOKE_FAILED: "revoke_failed",
|
|
81
|
+
ROTATE_FAILED: "rotate_failed",
|
|
82
|
+
SERVER_BUSY: "server_busy",
|
|
83
|
+
STORAGE_FULL: "storage_full",
|
|
84
|
+
SUBSCRIPTION_CHARGEBACK: "subscription_chargeback",
|
|
85
|
+
SUBSCRIPTION_DISABLED: "subscription_disabled",
|
|
86
|
+
SUBSCRIPTION_PAUSED: "subscription_paused",
|
|
87
|
+
SUBSCRIPTION_REFUNDED: "subscription_refunded",
|
|
88
|
+
TIMEOUT: "timeout",
|
|
89
|
+
TOO_MANY_CHATS: "too_many_chats",
|
|
90
|
+
TOO_MANY_FILES: "too_many_files",
|
|
91
|
+
TOTAL_UPLOAD_EXCEEDED: "total_upload_exceeded",
|
|
92
|
+
TRANSCRIPTION_FAILED: "transcription_failed",
|
|
93
|
+
UNAUTHORIZED: "unauthorized",
|
|
94
|
+
UNSUPPORTED_MEDIA_TYPE: "unsupported_media_type",
|
|
95
|
+
URL_BLOCKED: "url_blocked",
|
|
96
|
+
URL_FETCH_FAILED: "url_fetch_failed",
|
|
97
|
+
WORDPRESS_UNAVAILABLE: "wordpress_unavailable",
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
module.exports = { ErrorCodes };
|
package/src/multipart.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { DavixH2IConfigError } = require('./errors');
|
|
5
|
+
const { isFileLike, isPlainObject } = require('./schema');
|
|
6
|
+
|
|
7
|
+
const TYPES = {
|
|
8
|
+
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.gif': 'image/gif', '.avif': 'image/avif',
|
|
9
|
+
'.svg': 'image/svg+xml', '.tif': 'image/tiff', '.tiff': 'image/tiff', '.pdf': 'application/pdf', '.json': 'application/json',
|
|
10
|
+
'.csv': 'text/csv', '.xml': 'application/xml', '.txt': 'text/plain', '.md': 'text/markdown', '.html': 'text/html',
|
|
11
|
+
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
12
|
+
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
13
|
+
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
14
|
+
'.odt': 'application/vnd.oasis.opendocument.text', '.ods': 'application/vnd.oasis.opendocument.spreadsheet',
|
|
15
|
+
'.odp': 'application/vnd.oasis.opendocument.presentation', '.rtf': 'application/rtf', '.epub': 'application/epub+zip',
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function contentTypeFor(filename) {
|
|
19
|
+
return TYPES[path.extname(String(filename || '')).toLowerCase()] || 'application/octet-stream';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function collect(stream) {
|
|
23
|
+
const chunks = [];
|
|
24
|
+
for await (const chunk of stream) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
|
|
25
|
+
return Buffer.concat(chunks);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Normalizes every supported file representation to { blob, filename }.
|
|
29
|
+
// string filesystem path
|
|
30
|
+
// Buffer | Uint8Array bytes (filename "file" unless wrapped)
|
|
31
|
+
// Blob | File as is
|
|
32
|
+
// Readable / async iterable fully read into memory (fetch multipart cannot stream)
|
|
33
|
+
// { path } filesystem path
|
|
34
|
+
// { data, filename, contentType } data = Buffer | Uint8Array | string | stream
|
|
35
|
+
async function toFile(input, fallbackName) {
|
|
36
|
+
if (typeof input === 'string') {
|
|
37
|
+
const data = await fs.promises.readFile(input).catch(err => { throw new DavixH2IConfigError(`Cannot read file "${input}": ${err.code || err.message}`); });
|
|
38
|
+
const filename = path.basename(input);
|
|
39
|
+
return { blob: new Blob([data], { type: contentTypeFor(filename) }), filename };
|
|
40
|
+
}
|
|
41
|
+
if (typeof Blob !== 'undefined' && input instanceof Blob) {
|
|
42
|
+
return { blob: input, filename: input.name || fallbackName };
|
|
43
|
+
}
|
|
44
|
+
if (Buffer.isBuffer(input) || input instanceof Uint8Array) {
|
|
45
|
+
return { blob: new Blob([input], { type: contentTypeFor(fallbackName) }), filename: fallbackName };
|
|
46
|
+
}
|
|
47
|
+
if (input instanceof ArrayBuffer) {
|
|
48
|
+
return { blob: new Blob([input], { type: contentTypeFor(fallbackName) }), filename: fallbackName };
|
|
49
|
+
}
|
|
50
|
+
if (input && typeof input === 'object' && typeof input.path === 'string' && input.data === undefined) {
|
|
51
|
+
const f = await toFile(input.path, fallbackName);
|
|
52
|
+
return { blob: input.contentType ? new Blob([f.blob], { type: input.contentType }) : f.blob, filename: input.filename || f.filename };
|
|
53
|
+
}
|
|
54
|
+
if (input && typeof input === 'object' && input.data !== undefined) {
|
|
55
|
+
let data = input.data;
|
|
56
|
+
if (typeof data === 'string') data = Buffer.from(data);
|
|
57
|
+
else if (!Buffer.isBuffer(data) && !(data instanceof Uint8Array) && !(data instanceof ArrayBuffer) && !(typeof Blob !== 'undefined' && data instanceof Blob)) data = await collect(data);
|
|
58
|
+
const filename = input.filename || fallbackName;
|
|
59
|
+
return { blob: new Blob([data], { type: input.contentType || contentTypeFor(filename) }), filename };
|
|
60
|
+
}
|
|
61
|
+
if (input && (typeof input.pipe === 'function' || typeof input[Symbol.asyncIterator] === 'function')) {
|
|
62
|
+
const data = await collect(input);
|
|
63
|
+
return { blob: new Blob([data], { type: contentTypeFor(fallbackName) }), filename: input.path ? path.basename(String(input.path)) : fallbackName };
|
|
64
|
+
}
|
|
65
|
+
throw new DavixH2IConfigError('Unsupported file value: use a path, Buffer, Blob, stream or { data, filename, contentType }.');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function scalarToString(v) {
|
|
69
|
+
if (typeof v === 'boolean') return v ? 'true' : 'false';
|
|
70
|
+
return String(v);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Appends one (non-file) value the way the server expects multipart values: scalars as text,
|
|
74
|
+
// objects/arrays as a JSON string (contract encoding "json-string").
|
|
75
|
+
function appendValue(form, name, value) {
|
|
76
|
+
if (value === undefined || value === null) return;
|
|
77
|
+
if (typeof value === 'object') form.append(name, typeof value === 'string' ? value : JSON.stringify(value));
|
|
78
|
+
else form.append(name, scalarToString(value));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// contractFields: the endpoint's form fields, or null for an endpoint the SDK does not know.
|
|
82
|
+
// A plain string is read from disk ONLY for a contract field of type "file"; for fields the
|
|
83
|
+
// contract does not know, only explicit file objects (Buffer/Blob/stream/{path}/{data}) are
|
|
84
|
+
// treated as files, so an ordinary text value can never make the SDK read a local file.
|
|
85
|
+
async function buildForm(contractFields, params) {
|
|
86
|
+
const form = new FormData();
|
|
87
|
+
const known = new Map((contractFields || []).map(f => [f.name, f]));
|
|
88
|
+
for (const [name, value] of Object.entries(params)) {
|
|
89
|
+
if (value === undefined || value === null) continue;
|
|
90
|
+
const field = known.get(name);
|
|
91
|
+
const asFiles = field
|
|
92
|
+
? field.type === 'file'
|
|
93
|
+
: ((typeof value === 'object' && !Array.isArray(value) && isFileLike(value)) || (Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'object' && isFileLike(v))));
|
|
94
|
+
if (asFiles) {
|
|
95
|
+
const list = Array.isArray(value) ? value : [value];
|
|
96
|
+
let i = 0;
|
|
97
|
+
for (const item of list) {
|
|
98
|
+
i += 1;
|
|
99
|
+
const { blob, filename } = await toFile(item, list.length > 1 ? `${name}-${i}` : name);
|
|
100
|
+
form.append(name, blob, filename || name);
|
|
101
|
+
}
|
|
102
|
+
} else {
|
|
103
|
+
appendValue(form, name, value);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return form;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
module.exports = { buildForm, toFile, contentTypeFor };
|
package/src/paths.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The client-side boundary that keeps the generic request() from ever reaching internal or
|
|
3
|
+
// admin routes: only paths inside the public API namespace (/v1/...) and the public OpenAPI
|
|
4
|
+
// documents (/openapi.json, /openapi/...) are allowed. The policy itself (pattern, blocked prefixes) is part of the contract
|
|
5
|
+
// (contract.requestPolicy); the structural checks below do not depend on it and cannot be
|
|
6
|
+
// disabled.
|
|
7
|
+
const { DavixH2IConfigError } = require('./errors');
|
|
8
|
+
|
|
9
|
+
function assertPublicPath(path, policy) {
|
|
10
|
+
if (typeof path !== 'string' || path === '') throw new DavixH2IConfigError('request(): path must be a non-empty string.');
|
|
11
|
+
if (/[\u0000-\u001f\u007f\s\\]/.test(path)) throw new DavixH2IConfigError('request(): path contains forbidden characters.');
|
|
12
|
+
if (!path.startsWith('/') || path.startsWith('//')) throw new DavixH2IConfigError('request(): path must be a site-relative path starting with a single "/"; absolute URLs are not allowed.');
|
|
13
|
+
if (path.includes('://') || /^\/[a-z][a-z0-9+.-]*:/i.test(path)) throw new DavixH2IConfigError('request(): absolute URLs are not allowed.');
|
|
14
|
+
if (/[?#]/.test(path)) throw new DavixH2IConfigError('request(): put the query string in the `query` option, not in the path.');
|
|
15
|
+
let decoded;
|
|
16
|
+
try { decoded = decodeURIComponent(path); } catch (_) { throw new DavixH2IConfigError('request(): path is not valid percent-encoding.'); }
|
|
17
|
+
// a second decode catches double-encoded traversal (%252e%252e)
|
|
18
|
+
let decoded2 = decoded;
|
|
19
|
+
try { decoded2 = decodeURIComponent(decoded); } catch (_) { /* keep first decode */ }
|
|
20
|
+
for (const candidate of [path, decoded, decoded2]) {
|
|
21
|
+
if (/(^|\/)\.\.?(\/|$)/.test(candidate)) throw new DavixH2IConfigError('request(): path traversal is not allowed.');
|
|
22
|
+
if (/\/\//.test(candidate.slice(1))) throw new DavixH2IConfigError('request(): empty path segments are not allowed.');
|
|
23
|
+
const lower = candidate.toLowerCase();
|
|
24
|
+
for (const prefix of (policy && policy.blockedPrefixes) || []) {
|
|
25
|
+
if (lower === prefix || lower.startsWith(`${prefix}/`)) throw new DavixH2IConfigError(`request(): ${prefix} is not part of the public API and cannot be called through this SDK.`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const extra = (policy && policy.extraAllowedPaths) || [];
|
|
29
|
+
if (extra.includes(path)) return path;
|
|
30
|
+
const re = new RegExp((policy && policy.allowedPathPattern) || '^/v1/');
|
|
31
|
+
if (!re.test(path) || !(path.startsWith('/v1/') || path.startsWith('/openapi/'))) {
|
|
32
|
+
throw new DavixH2IConfigError('request(): only public API paths under /v1/ (and the /openapi/ documents) are allowed.');
|
|
33
|
+
}
|
|
34
|
+
return path;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Expands {name} placeholders with percent-encoded values. A value can never introduce a
|
|
38
|
+
// path separator or traversal: "/" and "." sequences are encoded.
|
|
39
|
+
function expandPath(template, values) {
|
|
40
|
+
return template.replace(/\{([A-Za-z0-9_]+)\}/g, (_, name) => {
|
|
41
|
+
const v = values[name];
|
|
42
|
+
if (v === undefined || v === null || v === '') throw new DavixH2IConfigError(`Missing required path parameter "${name}".`);
|
|
43
|
+
return encodeURIComponent(String(v)).replace(/\./g, '%2E');
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { assertPublicPath, expandPath };
|
package/src/schema.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The metadata API. A Schema is a read-only view of one endpoint of the Davix H2I contract
|
|
3
|
+
// (bundled with this SDK, or the live copy from GET /v1/contract after contract.refresh()).
|
|
4
|
+
//
|
|
5
|
+
// const s = h2i.schema('images.resize');
|
|
6
|
+
// s.fields.width.minimum // 1
|
|
7
|
+
// s.fields.resizeMode.enum // ['fit', 'cover', 'pad', 'force']
|
|
8
|
+
// s.fields.width.behavior // { onOutOfRange: 'unspecified', ... } how the SERVER treats a bad value
|
|
9
|
+
// s.validate({ width: 'x' }) // { valid, errors, warnings } (advisory -- the server is authoritative)
|
|
10
|
+
//
|
|
11
|
+
// validate() distinguishes what the server REJECTS (errors) from what it silently CLAMPS or
|
|
12
|
+
// replaces by a default (warnings), because that is how Davix H2I really behaves.
|
|
13
|
+
|
|
14
|
+
const FILE_TYPES = new Set(['file']);
|
|
15
|
+
|
|
16
|
+
function isPlainObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v) && !isFileLike(v); }
|
|
17
|
+
function isFileLike(v) {
|
|
18
|
+
if (v === null || typeof v !== 'object') return false;
|
|
19
|
+
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(v)) return true;
|
|
20
|
+
if (v instanceof Uint8Array || v instanceof ArrayBuffer) return true;
|
|
21
|
+
if (typeof Blob !== 'undefined' && v instanceof Blob) return true;
|
|
22
|
+
if (typeof v.pipe === 'function' || typeof v[Symbol.asyncIterator] === 'function') return true;
|
|
23
|
+
return typeof v.path === 'string' || v.data !== undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
class FieldSchema {
|
|
27
|
+
constructor(def, path) {
|
|
28
|
+
Object.assign(this, def); // every contract property (type, enum, minimum, maximum, default, description, behavior, ...)
|
|
29
|
+
Object.defineProperty(this, '_path', { value: path, enumerable: false });
|
|
30
|
+
if (def.properties) {
|
|
31
|
+
const props = {};
|
|
32
|
+
for (const p of def.properties) props[p.name] = new FieldSchema(p, `${path}.${p.name}`);
|
|
33
|
+
this.properties = props;
|
|
34
|
+
}
|
|
35
|
+
if (def.items) this.items = new FieldSchema(def.items, `${path}[]`);
|
|
36
|
+
Object.freeze(this);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Advisory check of one value. Returns { valid, errors: [], warnings: [] }. */
|
|
40
|
+
validate(value) {
|
|
41
|
+
const errors = [];
|
|
42
|
+
const warnings = [];
|
|
43
|
+
check(this, value, this._path, errors, warnings);
|
|
44
|
+
return { valid: errors.length === 0, errors, warnings };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The value the server will use when the field is omitted (undefined = no default / server decides). */
|
|
48
|
+
get defaultValue() { return this.default; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function push(list, path, rule, message, field) {
|
|
52
|
+
list.push({ path, rule, message, behavior: (field.behavior && (field.behavior.note || field.behavior.onOutOfRange)) ? field.behavior : undefined });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function check(field, value, path, errors, warnings) {
|
|
56
|
+
if (value === undefined || value === null) {
|
|
57
|
+
if (field.required && value === undefined) push(errors, path, 'required', `${path} is required.`, field);
|
|
58
|
+
if (value === null && !field.nullable && field.required) push(errors, path, 'nullable', `${path} must not be null.`, field);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const behavior = field.behavior || {};
|
|
62
|
+
const rangeList = ['clamp', 'fallback', 'passthrough'].includes(behavior.onOutOfRange) ? warnings : errors;
|
|
63
|
+
const invalidList = ['ignore', 'fallback', 'normalize', 'passthrough'].includes(behavior.onInvalid) ? warnings : errors;
|
|
64
|
+
|
|
65
|
+
switch (field.type) {
|
|
66
|
+
case 'string': {
|
|
67
|
+
if (typeof value !== 'string') { push(invalidList, path, 'type', `${path} must be a string.`, field); return; }
|
|
68
|
+
if (field.minLength !== undefined && value.length < field.minLength) push(rangeList, path, 'minLength', `${path} must be at least ${field.minLength} characters.`, field);
|
|
69
|
+
if (field.maxLength !== undefined && value.length > field.maxLength) push(rangeList, path, 'maxLength', `${path} must be at most ${field.maxLength} characters.`, field);
|
|
70
|
+
if (field.pattern && !new RegExp(field.pattern).test(value)) push(invalidList, path, 'pattern', `${path} has an invalid format.`, field);
|
|
71
|
+
if (field.enum && !field.enum.includes(value) && !field.enum.includes(value.toLowerCase())) push(invalidList, path, 'enum', `${path} must be one of: ${field.enum.join(', ')}.`, field);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
case 'integer':
|
|
75
|
+
case 'number': {
|
|
76
|
+
let n = value;
|
|
77
|
+
if (typeof n === 'string' && n.trim() !== '' && Number.isFinite(Number(n))) n = Number(n);
|
|
78
|
+
if (typeof n !== 'number' || !Number.isFinite(n)) { push(invalidList, path, 'type', `${path} must be a number.`, field); return; }
|
|
79
|
+
if (field.type === 'integer' && !Number.isInteger(n)) { push(invalidList, path, 'type', `${path} must be an integer.`, field); return; }
|
|
80
|
+
if (field.enum && !field.enum.includes(n)) push(invalidList, path, 'enum', `${path} must be one of: ${field.enum.join(', ')}.`, field);
|
|
81
|
+
if (field.minimum !== undefined && n < field.minimum) push(rangeList, path, 'minimum', `${path} must be >= ${field.minimum}.`, field);
|
|
82
|
+
if (field.maximum !== undefined && n > field.maximum) push(rangeList, path, 'maximum', `${path} must be <= ${field.maximum}.`, field);
|
|
83
|
+
if (field.exclusiveMinimum !== undefined && n <= field.exclusiveMinimum) push(rangeList, path, 'exclusiveMinimum', `${path} must be > ${field.exclusiveMinimum}.`, field);
|
|
84
|
+
if (field.exclusiveMaximum !== undefined && n >= field.exclusiveMaximum) push(rangeList, path, 'exclusiveMaximum', `${path} must be < ${field.exclusiveMaximum}.`, field);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
case 'boolean': {
|
|
88
|
+
if (typeof value === 'boolean' || value === 'true' || value === 'false') return;
|
|
89
|
+
push(invalidList, path, 'type', `${path} must be a boolean.`, field);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
case 'file': {
|
|
93
|
+
const list = Array.isArray(value) ? value : [value];
|
|
94
|
+
if (!(field.file && field.file.multiple) && list.length > 1) push(errors, path, 'maxFiles', `${path} accepts a single file.`, field);
|
|
95
|
+
if (field.file && field.file.minFiles && list.length < field.file.minFiles) push(errors, path, 'minFiles', `${path} needs at least ${field.file.minFiles} files.`, field);
|
|
96
|
+
if (field.file && field.file.maxFiles && list.length > field.file.maxFiles) push(errors, path, 'maxFiles', `${path} accepts at most ${field.file.maxFiles} files.`, field);
|
|
97
|
+
for (const f of list) if (typeof f !== 'string' && !isFileLike(f)) push(errors, path, 'type', `${path} must be a file path, Buffer, Blob, stream or { data, filename }.`, field);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
case 'array': {
|
|
101
|
+
let arr = value;
|
|
102
|
+
if (typeof arr === 'string' && field.encoding === 'json-string') { try { arr = JSON.parse(arr); } catch (_) { push(invalidList, path, 'type', `${path} must be JSON.`, field); return; } }
|
|
103
|
+
if (!Array.isArray(arr)) { push(invalidList, path, 'type', `${path} must be an array.`, field); return; }
|
|
104
|
+
if (field.minItems !== undefined && arr.length < field.minItems) push(rangeList, path, 'minItems', `${path} needs at least ${field.minItems} items.`, field);
|
|
105
|
+
if (field.maxItems !== undefined && arr.length > field.maxItems) push(rangeList, path, 'maxItems', `${path} accepts at most ${field.maxItems} items.`, field);
|
|
106
|
+
if (field.items) arr.forEach((item, i) => check(field.items, item, `${path}[${i}]`, errors, warnings));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
case 'object': {
|
|
110
|
+
let obj = value;
|
|
111
|
+
if (typeof obj === 'string' && field.encoding === 'json-string') { try { obj = JSON.parse(obj); } catch (_) { push(invalidList, path, 'type', `${path} must be JSON.`, field); return; } }
|
|
112
|
+
if (!isPlainObject(obj)) { push(invalidList, path, 'type', `${path} must be an object.`, field); return; }
|
|
113
|
+
for (const [name, prop] of Object.entries(field.properties || {})) check(prop, obj[name], `${path}.${name}`, errors, warnings);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
default:
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
class Schema {
|
|
121
|
+
constructor(endpoint) {
|
|
122
|
+
this.id = endpoint.id;
|
|
123
|
+
this.name = endpoint.name;
|
|
124
|
+
this.description = endpoint.description;
|
|
125
|
+
this.category = endpoint.category;
|
|
126
|
+
this.method = endpoint.method;
|
|
127
|
+
this.path = endpoint.path;
|
|
128
|
+
this.audience = endpoint.audience;
|
|
129
|
+
this.auth = endpoint.auth;
|
|
130
|
+
this.requestContentType = endpoint.request.contentType;
|
|
131
|
+
this.responseContentType = endpoint.response.contentType;
|
|
132
|
+
this.responseStatuses = endpoint.response.statuses.slice();
|
|
133
|
+
this.deprecated = Boolean(endpoint.deprecated);
|
|
134
|
+
this.idempotent = Boolean(endpoint.idempotency && endpoint.idempotency.supported);
|
|
135
|
+
this.async = Boolean(endpoint.platform && endpoint.platform.jobEligible);
|
|
136
|
+
this.actions = endpoint.actions || null;
|
|
137
|
+
this.errors = (endpoint.errors || []).slice();
|
|
138
|
+
this.notes = endpoint.notes || null;
|
|
139
|
+
this.sdk = endpoint.sdk;
|
|
140
|
+
const fields = {};
|
|
141
|
+
for (const f of endpoint.request.fields) fields[f.name] = new FieldSchema(f, f.name);
|
|
142
|
+
this.fields = Object.freeze(fields);
|
|
143
|
+
Object.defineProperty(this, '_endpoint', { value: endpoint, enumerable: false });
|
|
144
|
+
Object.freeze(this);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** All fields as an array (contract order). */
|
|
148
|
+
get fieldList() { return Object.values(this.fields); }
|
|
149
|
+
/** Names of the required fields. */
|
|
150
|
+
get required() { return this.fieldList.filter(f => f.required).map(f => f.name); }
|
|
151
|
+
/** Fields of one location: 'path' | 'query' | 'header' | 'form' | 'json'. */
|
|
152
|
+
fieldsIn(location) { return this.fieldList.filter(f => f.location === location); }
|
|
153
|
+
/** Fields that belong to one action of this endpoint (see schema.actions). */
|
|
154
|
+
fieldsForAction(actionName) {
|
|
155
|
+
const a = this.actions && this.actions.items.find(x => x.name === actionName);
|
|
156
|
+
if (!a) return [];
|
|
157
|
+
return a.fields.map(n => this.fields[n]).filter(Boolean);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Advisory validation of a params object. The server remains the final authority. */
|
|
161
|
+
validate(params = {}) {
|
|
162
|
+
const errors = [];
|
|
163
|
+
const warnings = [];
|
|
164
|
+
for (const f of this.fieldList) {
|
|
165
|
+
if (f.standard && f.location === 'header') continue;
|
|
166
|
+
check(f, params[f.name], f.name, errors, warnings);
|
|
167
|
+
}
|
|
168
|
+
const known = new Set(this.fieldList.map(f => f.name));
|
|
169
|
+
const unknown = Object.keys(params).filter(k => !known.has(k));
|
|
170
|
+
return { valid: errors.length === 0, errors, warnings, unknown };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
module.exports = { Schema, FieldSchema, FILE_TYPES, isFileLike, isPlainObject };
|