@invowerk-dev/sdk 0.0.0-bootstrap.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,132 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
3
+ let lastEventId;
4
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
5
+ const createStream = async function* () {
6
+ let retryDelay = sseDefaultRetryDelay ?? 3000;
7
+ let attempt = 0;
8
+ const signal = options.signal ?? new AbortController().signal;
9
+ while (true) {
10
+ if (signal.aborted)
11
+ break;
12
+ attempt++;
13
+ const headers = options.headers instanceof Headers
14
+ ? options.headers
15
+ : new Headers(options.headers);
16
+ if (lastEventId !== undefined) {
17
+ headers.set('Last-Event-ID', lastEventId);
18
+ }
19
+ try {
20
+ const requestInit = {
21
+ redirect: 'follow',
22
+ ...options,
23
+ body: options.serializedBody,
24
+ headers,
25
+ signal,
26
+ };
27
+ let request = new Request(url, requestInit);
28
+ if (onRequest) {
29
+ request = await onRequest(url, requestInit);
30
+ }
31
+ // fetch must be assigned here, otherwise it would throw the error:
32
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
33
+ const _fetch = options.fetch ?? globalThis.fetch;
34
+ const response = await _fetch(request);
35
+ if (!response.ok)
36
+ throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
37
+ if (!response.body)
38
+ throw new Error('No body in SSE response');
39
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
40
+ let buffer = '';
41
+ const abortHandler = () => {
42
+ try {
43
+ reader.cancel();
44
+ }
45
+ catch {
46
+ // noop
47
+ }
48
+ };
49
+ signal.addEventListener('abort', abortHandler);
50
+ try {
51
+ while (true) {
52
+ const { done, value } = await reader.read();
53
+ if (done)
54
+ break;
55
+ buffer += value;
56
+ buffer = buffer.replace(/\r\n?/g, '\n'); // normalize line endings
57
+ const chunks = buffer.split('\n\n');
58
+ buffer = chunks.pop() ?? '';
59
+ for (const chunk of chunks) {
60
+ const lines = chunk.split('\n');
61
+ const dataLines = [];
62
+ let eventName;
63
+ for (const line of lines) {
64
+ if (line.startsWith('data:')) {
65
+ dataLines.push(line.replace(/^data:\s*/, ''));
66
+ }
67
+ else if (line.startsWith('event:')) {
68
+ eventName = line.replace(/^event:\s*/, '');
69
+ }
70
+ else if (line.startsWith('id:')) {
71
+ lastEventId = line.replace(/^id:\s*/, '');
72
+ }
73
+ else if (line.startsWith('retry:')) {
74
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
75
+ if (!Number.isNaN(parsed)) {
76
+ retryDelay = parsed;
77
+ }
78
+ }
79
+ }
80
+ let data;
81
+ let parsedJson = false;
82
+ if (dataLines.length) {
83
+ const rawData = dataLines.join('\n');
84
+ try {
85
+ data = JSON.parse(rawData);
86
+ parsedJson = true;
87
+ }
88
+ catch {
89
+ data = rawData;
90
+ }
91
+ }
92
+ if (parsedJson) {
93
+ if (responseValidator) {
94
+ await responseValidator(data);
95
+ }
96
+ if (responseTransformer) {
97
+ data = await responseTransformer(data);
98
+ }
99
+ }
100
+ onSseEvent?.({
101
+ data,
102
+ event: eventName,
103
+ id: lastEventId,
104
+ retry: retryDelay,
105
+ });
106
+ if (dataLines.length) {
107
+ yield data;
108
+ }
109
+ }
110
+ }
111
+ }
112
+ finally {
113
+ signal.removeEventListener('abort', abortHandler);
114
+ reader.releaseLock();
115
+ }
116
+ break; // exit loop on normal completion
117
+ }
118
+ catch (error) {
119
+ // connection failed or aborted; retry after delay
120
+ onSseError?.(error);
121
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
122
+ break; // stop after firing error
123
+ }
124
+ // exponential backoff: double retry each attempt, cap at 30s
125
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
126
+ await sleep(backoff);
127
+ }
128
+ }
129
+ };
130
+ const stream = createStream();
131
+ return { stream };
132
+ }
@@ -0,0 +1,83 @@
1
+ import type { Auth, AuthToken } from './auth.gen.js';
2
+ import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js';
3
+ export type HttpMethod = 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace';
4
+ export type Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never> = {
5
+ /**
6
+ * Returns the final request URL.
7
+ */
8
+ buildUrl: BuildUrlFn;
9
+ getConfig: () => Config;
10
+ request: RequestFn;
11
+ setConfig: (config: Config) => Config;
12
+ } & {
13
+ [K in HttpMethod]: MethodFn;
14
+ } & ([SseFn] extends [never] ? {
15
+ sse?: never;
16
+ } : {
17
+ sse: {
18
+ [K in HttpMethod]: SseFn;
19
+ };
20
+ });
21
+ export interface Config {
22
+ /**
23
+ * Auth token or a function returning auth token. The resolved value will be
24
+ * added to the request payload as defined by its `security` array.
25
+ */
26
+ auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
27
+ /**
28
+ * A function for serializing request body parameter. By default,
29
+ * {@link JSON.stringify()} will be used.
30
+ */
31
+ bodySerializer?: BodySerializer | null;
32
+ /**
33
+ * An object containing any HTTP headers that you want to pre-populate your
34
+ * `Headers` object with.
35
+ *
36
+ * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
37
+ */
38
+ headers?: RequestInit['headers'] | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown>;
39
+ /**
40
+ * The request method.
41
+ *
42
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
43
+ */
44
+ method?: Uppercase<HttpMethod>;
45
+ /**
46
+ * A function for serializing request query parameters. By default, arrays
47
+ * will be exploded in form style, objects will be exploded in deepObject
48
+ * style, and reserved characters are percent-encoded.
49
+ *
50
+ * This method will have no effect if the native `paramsSerializer()` Axios
51
+ * API function is used.
52
+ *
53
+ * {@link https://swagger.io/docs/specification/serialization/#query View examples}
54
+ */
55
+ querySerializer?: QuerySerializer | QuerySerializerOptions;
56
+ /**
57
+ * A function validating request data. This is useful if you want to ensure
58
+ * the request conforms to the desired shape, so it can be safely sent to
59
+ * the server.
60
+ */
61
+ requestValidator?: (data: unknown) => Promise<unknown>;
62
+ /**
63
+ * A function transforming response data before it's returned. This is useful
64
+ * for post-processing data, e.g., converting ISO strings into Date objects.
65
+ */
66
+ responseTransformer?: (data: unknown) => Promise<unknown>;
67
+ /**
68
+ * A function validating response data. This is useful if you want to ensure
69
+ * the response conforms to the desired shape, so it can be safely passed to
70
+ * the transformers and returned to the user.
71
+ */
72
+ responseValidator?: (data: unknown) => Promise<unknown>;
73
+ }
74
+ /**
75
+ * Arbitrary metadata passed through the `meta` request option.
76
+ */
77
+ export interface ClientMeta {
78
+ }
79
+ type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false;
80
+ export type OmitNever<T extends Record<string, unknown>> = {
81
+ [K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
82
+ };
83
+ export {};
@@ -0,0 +1,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js';
2
+ export interface PathSerializer {
3
+ path: Record<string, unknown>;
4
+ url: string;
5
+ }
6
+ export declare const PATH_PARAM_RE: RegExp;
7
+ export declare const defaultPathSerializer: ({ path, url: _url }: PathSerializer) => string;
8
+ export declare const getUrl: ({ baseUrl, path, query, querySerializer, url: _url, }: {
9
+ baseUrl?: string;
10
+ path?: Record<string, unknown>;
11
+ query?: Record<string, unknown>;
12
+ querySerializer: QuerySerializer;
13
+ url: string;
14
+ }) => string;
15
+ export declare function getValidRequestBody(options: {
16
+ body?: unknown;
17
+ bodySerializer?: BodySerializer | null;
18
+ serializedBody?: unknown;
19
+ }): unknown;
@@ -0,0 +1,87 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js';
3
+ export const PATH_PARAM_RE = /\{[^{}]+\}/g;
4
+ export const defaultPathSerializer = ({ path, url: _url }) => {
5
+ let url = _url;
6
+ const matches = _url.match(PATH_PARAM_RE);
7
+ if (matches) {
8
+ for (const match of matches) {
9
+ let explode = false;
10
+ let name = match.substring(1, match.length - 1);
11
+ let style = 'simple';
12
+ if (name.endsWith('*')) {
13
+ explode = true;
14
+ name = name.substring(0, name.length - 1);
15
+ }
16
+ if (name.startsWith('.')) {
17
+ name = name.substring(1);
18
+ style = 'label';
19
+ }
20
+ else if (name.startsWith(';')) {
21
+ name = name.substring(1);
22
+ style = 'matrix';
23
+ }
24
+ const value = path[name];
25
+ if (value === undefined || value === null) {
26
+ continue;
27
+ }
28
+ if (Array.isArray(value)) {
29
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
30
+ continue;
31
+ }
32
+ if (typeof value === 'object') {
33
+ url = url.replace(match, serializeObjectParam({
34
+ explode,
35
+ name,
36
+ style,
37
+ value: value,
38
+ valueOnly: true,
39
+ }));
40
+ continue;
41
+ }
42
+ if (style === 'matrix') {
43
+ url = url.replace(match, `;${serializePrimitiveParam({
44
+ name,
45
+ value: value,
46
+ })}`);
47
+ continue;
48
+ }
49
+ const replaceValue = encodeURIComponent(style === 'label' ? `.${value}` : value);
50
+ url = url.replace(match, replaceValue);
51
+ }
52
+ }
53
+ return url;
54
+ };
55
+ export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }) => {
56
+ const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
57
+ let url = (baseUrl ?? '') + pathUrl;
58
+ if (path) {
59
+ url = defaultPathSerializer({ path, url });
60
+ }
61
+ let search = query ? querySerializer(query) : '';
62
+ if (search.startsWith('?')) {
63
+ search = search.substring(1);
64
+ }
65
+ if (search) {
66
+ url += `?${search}`;
67
+ }
68
+ return url;
69
+ };
70
+ export function getValidRequestBody(options) {
71
+ const hasBody = options.body !== undefined;
72
+ const isSerializedBody = hasBody && options.bodySerializer;
73
+ if (isSerializedBody) {
74
+ if ('serializedBody' in options) {
75
+ const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== '';
76
+ return hasSerializedBody ? options.serializedBody : null;
77
+ }
78
+ // not all clients implement a serializedBody property (i.e., client-axios)
79
+ return options.body !== '' ? options.body : null;
80
+ }
81
+ // plain/text body
82
+ if (hasBody) {
83
+ return options.body;
84
+ }
85
+ // no body was provided
86
+ return undefined;
87
+ }
@@ -0,0 +1,3 @@
1
+ export { client, type CreateClientConfig } from './client.gen.js';
2
+ export { convertInvoice, explainCodes, generateInvoice, getMe, type Options, parseInvoice, renderInvoice, validateInvoice } from './sdk.gen.js';
3
+ export type { BodyRenderInvoice, Buyer, ClientOptions, ContentClass, ConvertInvoiceData, ConvertInvoiceError, ConvertInvoiceErrors, ConvertInvoiceResponse, ConvertInvoiceResponses, ConvertResponse, ConvertSelfValidation, CreditsInfo, DocumentTotals, ERechnungDe, ErrorClasses, Evidence, ExplainCodesData, ExplainCodesError, ExplainCodesErrors, ExplainCodesResponse, ExplainCodesResponses, ExplainResponse, Finding, Flavor, GenerateInvoiceData, GenerateInvoiceError, GenerateInvoiceErrors, GenerateInvoiceResponse, GenerateInvoiceResponses, GenerateRequest, GenerateResponse, GetMeData, GetMeResponse, GetMeResponses, HintInfo, InvoiceLine, MeResponse, ParseDetection, ParseInvoiceData, ParseInvoiceResponse, ParseInvoiceResponses, ParseResponse, PostalAddress, Problem, RateLimitInfo, RenderInvoiceData, RenderInvoiceError, RenderInvoiceErrors, RenderInvoiceResponse, RenderInvoiceResponses, RenderResponse, RuleExplanation, ScenarioInfo, SelfValidation, Seller, Syntax, TaxBreakdown, ValidateInvoiceData, ValidateInvoiceError, ValidateInvoiceErrors, ValidateInvoiceResponse, ValidateInvoiceResponses, ValidationResponse, ValidatorVersions } from './types.gen.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export { client } from './client.gen.js';
3
+ export { convertInvoice, explainCodes, generateInvoice, getMe, parseInvoice, renderInvoice, validateInvoice } from './sdk.gen.js';
@@ -0,0 +1,148 @@
1
+ import { type Client, type ClientMeta, type Options as Options2, type RequestResult, type TDataShape } from './client/index.js';
2
+ import type { ConvertInvoiceData, ConvertInvoiceErrors, ConvertInvoiceResponses, ExplainCodesData, ExplainCodesErrors, ExplainCodesResponses, GenerateInvoiceData, GenerateInvoiceErrors, GenerateInvoiceResponses, GetMeData, GetMeResponses, ParseInvoiceData, ParseInvoiceResponses, RenderInvoiceData, RenderInvoiceErrors, RenderInvoiceResponses, ValidateInvoiceData, ValidateInvoiceErrors, ValidateInvoiceResponses } from './types.gen.js';
3
+ export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
4
+ /**
5
+ * You can provide a client instance returned by `createClient()` instead of
6
+ * individual options. This might be also useful if you want to implement a
7
+ * custom client.
8
+ */
9
+ client?: Client;
10
+ /**
11
+ * You can pass arbitrary values through the `meta` object. This can be
12
+ * used to access values that aren't defined as part of the SDK function.
13
+ */
14
+ meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;
15
+ };
16
+ /**
17
+ * Your plan, remaining requests, and remaining credits
18
+ *
19
+ * Check where you stand before a call fails.
20
+ *
21
+ * Returns the plan this request runs on and whether your key was recognized.
22
+ * Without an `X-API-Key`, the call runs anonymously at the rate limit for
23
+ * calls without a key. It also returns the requests left in the current window
24
+ * and the features your plan includes. On plans priced in credits, it returns
25
+ * the credits left in the current billing period.
26
+ *
27
+ * This call does not count against your rate limit, so the numbers it reports
28
+ * are the numbers you have.
29
+ *
30
+ * **Credits:** free. This endpoint is not metered.
31
+ */
32
+ export declare const getMe: <ThrowOnError extends boolean = false>(options?: Options<GetMeData, ThrowOnError>) => RequestResult<GetMeResponses, unknown, ThrowOnError>;
33
+ /**
34
+ * Read an e-invoice into JSON
35
+ *
36
+ * Read an existing e-invoice into JSON keyed on EN 16931 Business Terms.
37
+ *
38
+ * The JSON in `model` is the request body of `POST /v1/generate`, so you can edit
39
+ * it and create the invoice again. Send an XML invoice (UBL or CII) or a
40
+ * ZUGFeRD / Factur-X PDF as the raw request body or as a multipart file part, at
41
+ * most 20 MB. A PDF may have at most 500 pages and 16 attachments. UBL credit
42
+ * notes are not supported. The answer also has `detection` (syntax, flavor,
43
+ * CustomizationID) and `source` (`xml` or `pdf-embedded`). A file that cannot be
44
+ * read returns 422; `detail` starts with an error code. More than 100,000 XML
45
+ * elements return 413; 429 means every slot is busy (callers without an API key
46
+ * share one), 504 that reading took longer than 20 s. Costs 2 credits.
47
+ *
48
+ * **Credits:** 2 per call.
49
+ */
50
+ export declare const parseInvoice: <ThrowOnError extends boolean = false>(options: Options<ParseInvoiceData, ThrowOnError>) => RequestResult<ParseInvoiceResponses, unknown, ThrowOnError>;
51
+ /**
52
+ * Convert an e-invoice between UBL and CII
53
+ *
54
+ * Convert an e-invoice between UBL and CII.
55
+ *
56
+ * Send the invoice as for `POST /v1/parse`: XML or a ZUGFeRD / Factur-X PDF, raw
57
+ * body or multipart file part, at most 20 MB. `target_syntax` is required (`ubl`
58
+ * or `cii`). `target_flavor` (`en16931` or `xrechnung`) is optional; without it
59
+ * the flavor of the source is kept. invowerk checks the converted XML before
60
+ * answering and never returns an invalid document. The answer is
61
+ * `application/xml`; `?format=json` returns `{xml, syntax, flavor,
62
+ * self_validation}`. Errors: 422 when the input cannot be read, with an error code
63
+ * at the start of `detail`; 500 when the converted XML fails the check (the
64
+ * credits are refunded); 413, 429 and 504 as for `POST /v1/parse`. Costs 3
65
+ * credits.
66
+ *
67
+ * **Credits:** 3 per call.
68
+ */
69
+ export declare const convertInvoice: <ThrowOnError extends boolean = false>(options: Options<ConvertInvoiceData, ThrowOnError>) => RequestResult<ConvertInvoiceResponses, ConvertInvoiceErrors, ThrowOnError>;
70
+ /**
71
+ * Create an e-invoice from JSON
72
+ *
73
+ * Create an EN 16931 e-invoice from JSON.
74
+ *
75
+ * The JSON body is keyed on EN 16931 Business Terms (BT-*). `syntax` selects UBL
76
+ * (default) or CII. `flavor` selects plain EN 16931 (default) or XRechnung, which
77
+ * requires `buyer_reference` (BT-10, the Leitweg-ID). invowerk writes your
78
+ * amounts as given. It does not compute or correct them. Before answering,
79
+ * invowerk checks the generated XML and never returns an invalid document. The
80
+ * answer is `application/xml`; `?format=json` returns
81
+ * `{xml, syntax, flavor, self_validation}`. Errors: 422 for invalid input, with
82
+ * details per field; 500 when the generated XML fails the check (the credits are
83
+ * refunded); 429 when every slot is busy (callers without an API key share
84
+ * one); 504 when it took longer than 20 s. Costs 5 credits.
85
+ *
86
+ * **Credits:** 5 per call.
87
+ */
88
+ export declare const generateInvoice: <ThrowOnError extends boolean = false>(options: Options<GenerateInvoiceData, ThrowOnError>) => RequestResult<GenerateInvoiceResponses, GenerateInvoiceErrors, ThrowOnError>;
89
+ /**
90
+ * Explain an error code
91
+ *
92
+ * Explain rule codes and invowerk's own `IW-*` Hinweise in German or English.
93
+ *
94
+ * For each code the answer has the title, what the rule requires, common causes,
95
+ * how to fix the invoice, the affected Business Terms and `explain_url`, the path
96
+ * of the German page under `/codes/`. The codes appear in `findings` and `hints`
97
+ * of `POST /v1/validate`. If any code has no explanation, the answer is HTTP 404
98
+ * and names those codes. Costs 0 credits; an API key is not needed and does not
99
+ * raise the rate limit.
100
+ *
101
+ * **Credits:** free. This endpoint is not metered.
102
+ */
103
+ export declare const explainCodes: <ThrowOnError extends boolean = false>(options: Options<ExplainCodesData, ThrowOnError>) => RequestResult<ExplainCodesResponses, ExplainCodesErrors, ThrowOnError>;
104
+ /**
105
+ * Render an e-invoice as HTML
106
+ *
107
+ * Render an XML e-invoice as a readable HTML page.
108
+ *
109
+ * Send an XML invoice (UBL or CII, e.g. XRechnung) as the raw request body or as
110
+ * a multipart `file` part. PDFs are not accepted. invowerk renders it with the
111
+ * KoSIT XRechnung visualization and answers with `text/html`; `?format=json`
112
+ * returns `{html, lang, flavor, syntax}` instead. `lang` sets the label language
113
+ * (`de` or `en`; otherwise `Accept-Language`, then `de`). Errors: 400 for an
114
+ * empty body, 415 for a file that is not an XML invoice, 422 for malformed XML or
115
+ * a DOCTYPE, 413 for more than 100,000 elements, 429 when every render slot is
116
+ * busy (callers without an API key share one), 504 when the render ran longer
117
+ * than 20 s. Costs 1 credit.
118
+ *
119
+ * **Credits:** 1 per call.
120
+ */
121
+ export declare const renderInvoice: <ThrowOnError extends boolean = false>(options?: Options<RenderInvoiceData, ThrowOnError>) => RequestResult<RenderInvoiceResponses, RenderInvoiceErrors, ThrowOnError>;
122
+ /**
123
+ * Check an e-invoice
124
+ *
125
+ * Check an e-invoice against EN 16931 and the German rules.
126
+ *
127
+ * Send an XML invoice (UBL or CII, e.g. XRechnung) or a ZUGFeRD / Factur-X PDF as
128
+ * the raw request body or as a multipart file part, at most 20 MB. A PDF may have
129
+ * at most 500 pages and 16 attachments. invowerk detects the format from the
130
+ * bytes, not from the Content-Type. A larger body gets HTTP 413. Otherwise the
131
+ * answer is always HTTP 200, because a failed check is a result, not an error.
132
+ * `valid` is the result, `findings` lists each problem, `e_rechnung_de` maps the
133
+ * result onto the BMF categories and `evidence` identifies the checked file.
134
+ * `hints` are extra observations that never change `valid`. For XRechnung the
135
+ * KoSIT validator decides `valid`. If it is unreachable, invowerk's own check
136
+ * with the same rules decides, `verdict_source` is `local` and the
137
+ * `X-EInvoice-Degraded` header is set (`official-lane-unavailable`;
138
+ * `pdfa-lane-unavailable` when the PDF/A check did not answer; comma-separated).
139
+ * `disagreement` is true when both checks ran and differ. For a PDF,
140
+ * `pdfa_verdict` is the PDF/A check with veraPDF. `?explain=true` adds the
141
+ * explanation for rules that have one, in `lang` (`de` or `en`). An XML file
142
+ * with more than 100,000 elements gets HTTP 413. HTTP 429 means every check
143
+ * slot is busy (callers without an API key share one), HTTP 504 that the check
144
+ * ran longer than 20 s. Costs 1 credit.
145
+ *
146
+ * **Credits:** 1 per call.
147
+ */
148
+ export declare const validateInvoice: <ThrowOnError extends boolean = false>(options: Options<ValidateInvoiceData, ThrowOnError>) => RequestResult<ValidateInvoiceResponses, ValidateInvoiceErrors, ThrowOnError>;
@@ -0,0 +1,188 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ import { client } from './client.gen.js';
3
+ import { formDataBodySerializer } from './client/index.js';
4
+ /**
5
+ * Your plan, remaining requests, and remaining credits
6
+ *
7
+ * Check where you stand before a call fails.
8
+ *
9
+ * Returns the plan this request runs on and whether your key was recognized.
10
+ * Without an `X-API-Key`, the call runs anonymously at the rate limit for
11
+ * calls without a key. It also returns the requests left in the current window
12
+ * and the features your plan includes. On plans priced in credits, it returns
13
+ * the credits left in the current billing period.
14
+ *
15
+ * This call does not count against your rate limit, so the numbers it reports
16
+ * are the numbers you have.
17
+ *
18
+ * **Credits:** free. This endpoint is not metered.
19
+ */
20
+ export const getMe = (options) => (options?.client ?? client).get({
21
+ security: [{ name: 'X-API-Key', type: 'apiKey' }],
22
+ url: '/v1/me',
23
+ ...options
24
+ });
25
+ /**
26
+ * Read an e-invoice into JSON
27
+ *
28
+ * Read an existing e-invoice into JSON keyed on EN 16931 Business Terms.
29
+ *
30
+ * The JSON in `model` is the request body of `POST /v1/generate`, so you can edit
31
+ * it and create the invoice again. Send an XML invoice (UBL or CII) or a
32
+ * ZUGFeRD / Factur-X PDF as the raw request body or as a multipart file part, at
33
+ * most 20 MB. A PDF may have at most 500 pages and 16 attachments. UBL credit
34
+ * notes are not supported. The answer also has `detection` (syntax, flavor,
35
+ * CustomizationID) and `source` (`xml` or `pdf-embedded`). A file that cannot be
36
+ * read returns 422; `detail` starts with an error code. More than 100,000 XML
37
+ * elements return 413; 429 means every slot is busy (callers without an API key
38
+ * share one), 504 that reading took longer than 20 s. Costs 2 credits.
39
+ *
40
+ * **Credits:** 2 per call.
41
+ */
42
+ export const parseInvoice = (options) => (options.client ?? client).post({
43
+ ...formDataBodySerializer,
44
+ security: [{ name: 'X-API-Key', type: 'apiKey' }],
45
+ url: '/v1/parse',
46
+ ...options,
47
+ headers: {
48
+ 'Content-Type': null,
49
+ ...options.headers
50
+ }
51
+ });
52
+ /**
53
+ * Convert an e-invoice between UBL and CII
54
+ *
55
+ * Convert an e-invoice between UBL and CII.
56
+ *
57
+ * Send the invoice as for `POST /v1/parse`: XML or a ZUGFeRD / Factur-X PDF, raw
58
+ * body or multipart file part, at most 20 MB. `target_syntax` is required (`ubl`
59
+ * or `cii`). `target_flavor` (`en16931` or `xrechnung`) is optional; without it
60
+ * the flavor of the source is kept. invowerk checks the converted XML before
61
+ * answering and never returns an invalid document. The answer is
62
+ * `application/xml`; `?format=json` returns `{xml, syntax, flavor,
63
+ * self_validation}`. Errors: 422 when the input cannot be read, with an error code
64
+ * at the start of `detail`; 500 when the converted XML fails the check (the
65
+ * credits are refunded); 413, 429 and 504 as for `POST /v1/parse`. Costs 3
66
+ * credits.
67
+ *
68
+ * **Credits:** 3 per call.
69
+ */
70
+ export const convertInvoice = (options) => (options.client ?? client).post({
71
+ ...formDataBodySerializer,
72
+ security: [{ name: 'X-API-Key', type: 'apiKey' }],
73
+ url: '/v1/convert',
74
+ ...options,
75
+ headers: {
76
+ 'Content-Type': null,
77
+ ...options.headers
78
+ }
79
+ });
80
+ /**
81
+ * Create an e-invoice from JSON
82
+ *
83
+ * Create an EN 16931 e-invoice from JSON.
84
+ *
85
+ * The JSON body is keyed on EN 16931 Business Terms (BT-*). `syntax` selects UBL
86
+ * (default) or CII. `flavor` selects plain EN 16931 (default) or XRechnung, which
87
+ * requires `buyer_reference` (BT-10, the Leitweg-ID). invowerk writes your
88
+ * amounts as given. It does not compute or correct them. Before answering,
89
+ * invowerk checks the generated XML and never returns an invalid document. The
90
+ * answer is `application/xml`; `?format=json` returns
91
+ * `{xml, syntax, flavor, self_validation}`. Errors: 422 for invalid input, with
92
+ * details per field; 500 when the generated XML fails the check (the credits are
93
+ * refunded); 429 when every slot is busy (callers without an API key share
94
+ * one); 504 when it took longer than 20 s. Costs 5 credits.
95
+ *
96
+ * **Credits:** 5 per call.
97
+ */
98
+ export const generateInvoice = (options) => (options.client ?? client).post({
99
+ security: [{ name: 'X-API-Key', type: 'apiKey' }],
100
+ url: '/v1/generate',
101
+ ...options,
102
+ headers: {
103
+ 'Content-Type': 'application/json',
104
+ ...options.headers
105
+ }
106
+ });
107
+ /**
108
+ * Explain an error code
109
+ *
110
+ * Explain rule codes and invowerk's own `IW-*` Hinweise in German or English.
111
+ *
112
+ * For each code the answer has the title, what the rule requires, common causes,
113
+ * how to fix the invoice, the affected Business Terms and `explain_url`, the path
114
+ * of the German page under `/codes/`. The codes appear in `findings` and `hints`
115
+ * of `POST /v1/validate`. If any code has no explanation, the answer is HTTP 404
116
+ * and names those codes. Costs 0 credits; an API key is not needed and does not
117
+ * raise the rate limit.
118
+ *
119
+ * **Credits:** free. This endpoint is not metered.
120
+ */
121
+ export const explainCodes = (options) => (options.client ?? client).get({
122
+ security: [{ name: 'X-API-Key', type: 'apiKey' }],
123
+ url: '/v1/explain',
124
+ ...options
125
+ });
126
+ /**
127
+ * Render an e-invoice as HTML
128
+ *
129
+ * Render an XML e-invoice as a readable HTML page.
130
+ *
131
+ * Send an XML invoice (UBL or CII, e.g. XRechnung) as the raw request body or as
132
+ * a multipart `file` part. PDFs are not accepted. invowerk renders it with the
133
+ * KoSIT XRechnung visualization and answers with `text/html`; `?format=json`
134
+ * returns `{html, lang, flavor, syntax}` instead. `lang` sets the label language
135
+ * (`de` or `en`; otherwise `Accept-Language`, then `de`). Errors: 400 for an
136
+ * empty body, 415 for a file that is not an XML invoice, 422 for malformed XML or
137
+ * a DOCTYPE, 413 for more than 100,000 elements, 429 when every render slot is
138
+ * busy (callers without an API key share one), 504 when the render ran longer
139
+ * than 20 s. Costs 1 credit.
140
+ *
141
+ * **Credits:** 1 per call.
142
+ */
143
+ export const renderInvoice = (options) => (options?.client ?? client).post({
144
+ ...formDataBodySerializer,
145
+ security: [{ name: 'X-API-Key', type: 'apiKey' }],
146
+ url: '/v1/render',
147
+ ...options,
148
+ headers: {
149
+ 'Content-Type': null,
150
+ ...options?.headers
151
+ }
152
+ });
153
+ /**
154
+ * Check an e-invoice
155
+ *
156
+ * Check an e-invoice against EN 16931 and the German rules.
157
+ *
158
+ * Send an XML invoice (UBL or CII, e.g. XRechnung) or a ZUGFeRD / Factur-X PDF as
159
+ * the raw request body or as a multipart file part, at most 20 MB. A PDF may have
160
+ * at most 500 pages and 16 attachments. invowerk detects the format from the
161
+ * bytes, not from the Content-Type. A larger body gets HTTP 413. Otherwise the
162
+ * answer is always HTTP 200, because a failed check is a result, not an error.
163
+ * `valid` is the result, `findings` lists each problem, `e_rechnung_de` maps the
164
+ * result onto the BMF categories and `evidence` identifies the checked file.
165
+ * `hints` are extra observations that never change `valid`. For XRechnung the
166
+ * KoSIT validator decides `valid`. If it is unreachable, invowerk's own check
167
+ * with the same rules decides, `verdict_source` is `local` and the
168
+ * `X-EInvoice-Degraded` header is set (`official-lane-unavailable`;
169
+ * `pdfa-lane-unavailable` when the PDF/A check did not answer; comma-separated).
170
+ * `disagreement` is true when both checks ran and differ. For a PDF,
171
+ * `pdfa_verdict` is the PDF/A check with veraPDF. `?explain=true` adds the
172
+ * explanation for rules that have one, in `lang` (`de` or `en`). An XML file
173
+ * with more than 100,000 elements gets HTTP 413. HTTP 429 means every check
174
+ * slot is busy (callers without an API key share one), HTTP 504 that the check
175
+ * ran longer than 20 s. Costs 1 credit.
176
+ *
177
+ * **Credits:** 1 per call.
178
+ */
179
+ export const validateInvoice = (options) => (options.client ?? client).post({
180
+ ...formDataBodySerializer,
181
+ security: [{ name: 'X-API-Key', type: 'apiKey' }],
182
+ url: '/v1/validate',
183
+ ...options,
184
+ headers: {
185
+ 'Content-Type': null,
186
+ ...options.headers
187
+ }
188
+ });