@webority/api-contract 0.156.0 → 0.158.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/README.md +14 -1
- package/dist/call.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/emitFile.js +6 -6
- package/dist/load.js +1 -1
- package/dist/types/call.d.ts +19 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -38,6 +38,18 @@ export const operations = {
|
|
|
38
38
|
} as const;
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
An operation whose 2xx replies mix a file with JSON has no single reply kind, so the generator refuses it with a `ContractError`: give each reply its own operation. A file beside an empty reply (such as a 200 file and a 204) is `'blob'`, and its response type is `Blob | undefined`.
|
|
42
|
+
|
|
43
|
+
## Call options
|
|
44
|
+
|
|
45
|
+
`buildContractRequest(entry, request, options)` builds the request for one operation. The typed caller in `@webority/web-core` and `@webority/mobile-core` runs it on every call, and a portal or phone app can import it from `@webority/api-contract/call`. It checks the options before anything is sent, and a call that breaks a rule throws `ContractCallError`.
|
|
46
|
+
|
|
47
|
+
- `headers`: headers the contract does not declare, such as an idempotency key or an account id. They are merged with the headers the contract declares. A name must be a valid HTTP header name. `Content-Type` and `Content-Length` are refused, because the body decides them. A name that repeats a header the request already sets is refused, in any letter case, and so is a name given twice in the same call. Each value must be a string with no line break or NUL, and `headers` must be an object, not a list.
|
|
48
|
+
- `skipErrorLog`: `true`, `false` or left out. `true` keeps every failure of the call out of the client's log, so the caller logs it itself. Any other value is refused.
|
|
49
|
+
- `expectedStatuses`: a non-empty list of distinct failure statuses from 400 to 599 that the caller handles. A failure with one of them still rejects, but the client logs it as handled, not as an error. It cannot be combined with `skipErrorLog: true`, because that already keeps every failure out of the log and the list would never be read.
|
|
50
|
+
|
|
51
|
+
`contractReply(entry, status, data)` gives the value a call resolves to. It is `undefined` for an operation with `replyKind: 'none'`, and for a 204 or 205 status on any operation, because the HTTP client hands those over as an empty string or an empty Blob. Otherwise it is the response data.
|
|
52
|
+
|
|
41
53
|
## OpenAPI versions
|
|
42
54
|
|
|
43
55
|
The same contract written for 3.0, 3.1 and 3.2 gives the same file where the meaning is the same.
|
|
@@ -49,7 +61,8 @@ Read in every version:
|
|
|
49
61
|
- `$ref` with sibling keywords: the reference still names the type, and a sibling `type` list or `oneOf` / `anyOf` with a null member makes it nullable.
|
|
50
62
|
- `prefixItems` with `items` as a tuple. A position at or after `minItems` is optional; `items: false` or `maxItems` equal to the number of positions closes the tuple.
|
|
51
63
|
- `unevaluatedProperties` and `patternProperties`, written as a record. A record cannot name a key pattern, so its value type is the union of the pattern value types.
|
|
52
|
-
- File content: `format: binary` (3.0), `contentMediaType` with no `type` (3.1 and later) and a file body or reply with no schema or an empty schema, all as `Blob`. A body or reply of type `application/octet-stream`, `application/pdf`, `application/zip`, `application/gzip` or `image/*`, `audio/*`, `video/*`
|
|
64
|
+
- File content: `format: binary` (3.0), `contentMediaType` with no `type` (3.1 and later) and a file body or reply with no schema or an empty schema, all as `Blob`. A body or reply of type `application/octet-stream`, `application/pdf`, `application/zip`, `application/gzip` or `image/*`, `audio/*`, `video/*` is a file in every version whatever its schema says, because the bytes on the wire are the file.
|
|
65
|
+
- A body of type `multipart/form-data` or `application/x-www-form-urlencoded` is typed `FormData`.
|
|
53
66
|
- `$defs` of a component schema, and local `$ref`s to them such as `#/components/schemas/Pet/$defs/Tag`: each entry becomes its own named type.
|
|
54
67
|
- `paths` is optional from 3.1: a document with none has no operations.
|
|
55
68
|
- A path item that is a `$ref` to `#/components/pathItems/<name>` (3.1 and later).
|
package/dist/call.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g,n=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e));function r(e){let t=[];for(let[r,i]of Object.entries(e??{})){if(i==null)continue;let e=encodeURIComponent(r);for(let r of Array.isArray(i)?i:[i])r!=null&&t.push(`${e}=${n(r)}`)}return t.join(`&`)}
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g,n=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e));function r(e){let t=[];for(let[r,i]of Object.entries(e??{})){if(i==null)continue;let e=encodeURIComponent(r);for(let r of Array.isArray(i)?i:[i])r!=null&&t.push(`${e}=${n(r)}`)}return t.join(`&`)}var i=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,a=[`content-type`,`content-length`],o=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s(t,n,r){if(r===void 0)return n;if(!o(r))throw new e(`${t} needs call headers as an object of header names to string values`);let s=new Set(Object.keys(n??{}).map(e=>e.toLowerCase())),c={...n};for(let[n,o]of Object.entries(r)){if(!i.test(n))throw new e(`${t} has a call header named "${n}", which is not a valid header name`);let r=n.toLowerCase();if(a.includes(r))throw new e(`${t} sets "${n}" as a call header; the body decides it`);if(s.has(r))throw new e(`${t} sets "${n}" twice; set a header the contract declares on the request's headers only`);if(typeof o!=`string`||/[\r\n\0]/.test(o))throw new e(`${t} needs call header "${n}" as a string with no line break`);s.add(r),c[n]=o}return c}function c(t,n){let r=n?.skipErrorLog,i=n?.expectedStatuses;if(r!==void 0&&typeof r!=`boolean`)throw new e(`${t} needs skipErrorLog as true or false`);if(i===void 0)return{skipErrorLog:r,expectedStatuses:void 0};if(!Array.isArray(i)||i.length===0)throw new e(`${t} needs expectedStatuses as a non-empty list of failure statuses`);for(let n of i)if(!Number.isInteger(n)||n<400||n>599)throw new e(`${t} lists ${String(n)} in expectedStatuses; only a failure status from 400 to 599 is expected`);if(new Set(i).size!==i.length)throw new e(`${t} lists a status twice in expectedStatuses`);if(r===!0)throw new e(`${t} sets skipErrorLog and expectedStatuses; skipErrorLog already keeps every failure out of the log`);return{skipErrorLog:r,expectedStatuses:i}}function l(e,t,n){return e.replyKind===`none`||t===204||t===205?void 0:n}function u(n,i,a){let o=`${n.method} ${n.path}`,l=n.path.replace(t,(t,n)=>{let r=i.path?.[n],a=r===void 0?``:String(r);if(a===``)throw new e(`${o} needs a non-empty path value for "${n}"`);if(a===`.`||a===`..`)throw new e(`${o} needs a path value for "${n}" other than "." or ".."`);return encodeURIComponent(a)}),u=r(i.query);return{method:n.method,url:u===``?l:`${l}?${u}`,headers:s(o,i.headers,a?.headers),data:i.body,responseType:n.replyKind===`blob`?`blob`:`json`,...c(o,a)}}export{e as ContractCallError,u as buildContractRequest,l as contractReply};
|
package/dist/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{emitFile as e}from"./emitFile.js";import{findGaps as t,formatGaps as n}from"./gaps.js";import{loadContract as r}from"./load.js";import{ContractError as i}from"./model.js";import{createHash as a}from"node:crypto";import{basename as o}from"node:path";var s=`usage: webority-api-contract generate <contract.json> --out <file.ts> [--check] [--strict]`,c=`the contract has gaps that loosen the types; fix them in the backend`;async function l(e,t){let[n,...r]=e,i=n===`generate`?u(r):null;return i===null?(t.err(s),2):d(i,t)}function u(e){let t=[],n=[],r=!1,i=!1,a=!1;for(let o of e)if(a){if(o.startsWith(`-`))return null;n.push(o),a=!1}else if(o===`--out`)a=!0;else if(o===`--check`)r=!0;else if(o===`--strict`)i=!0;else if(o.startsWith(`-`))return null;else t.push(o);let[o,...s]=t,[c,...l]=n;return a||o===void 0||c===void 0||s.length>0||l.length>0?null:{contract:o,out:c,check:r,strict:i}}async function d(s,l){let u;try{u=await l.readText(s.contract)}catch(e){return l.err(`cannot read ${s.contract}: ${h(e)}`),2}let d;try{d=r(u)}catch(e){if(!(e instanceof i))throw e;return l.err(e.message),2}let p=t(d);if(s.strict&&p.length>0)return m(l,n(p)),l.err(c),1;let g={name:o(s.contract),sha256:a(`sha256`).update(u).digest(`hex`)},_=e(d,g);if(s.check)return f(s,_,l);try{await l.writeText(s.out,_)}catch(e){return l.err(`cannot write ${s.out}: ${h(e)}`),2}let v=d.operations.filter(e=>e.id!==``).length;return l.out(`wrote ${s.out} (${d.schemas.size} schemas, ${v} operations)`),p.length>0&&m(l,n(p)),0}async function f(e,t,n){return await p(e.out,n)===t?0:(n.err(`${e.out} is out of date with ${e.contract}; run: webority-api-contract generate ${e.contract} --out ${e.out}`),1)}async function p(e,t){try{return await t.readText(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}function m(e,t){for(let n of t.split(`
|
|
1
|
+
import{emitFile as e}from"./emitFile.js";import{findGaps as t,formatGaps as n}from"./gaps.js";import{loadContract as r}from"./load.js";import{ContractError as i}from"./model.js";import{createHash as a}from"node:crypto";import{basename as o}from"node:path";var s=`usage: webority-api-contract generate <contract.json> --out <file.ts> [--check] [--strict]`,c=`the contract has gaps that loosen the types; fix them in the backend`;async function l(e,t){let[n,...r]=e,i=n===`generate`?u(r):null;return i===null?(t.err(s),2):d(i,t)}function u(e){let t=[],n=[],r=!1,i=!1,a=!1;for(let o of e)if(a){if(o.startsWith(`-`))return null;n.push(o),a=!1}else if(o===`--out`)a=!0;else if(o===`--check`)r=!0;else if(o===`--strict`)i=!0;else if(o.startsWith(`-`))return null;else t.push(o);let[o,...s]=t,[c,...l]=n;return a||o===void 0||c===void 0||s.length>0||l.length>0?null:{contract:o,out:c,check:r,strict:i}}async function d(s,l){let u;try{u=await l.readText(s.contract)}catch(e){return l.err(`cannot read ${s.contract}: ${h(e)}`),2}let d;try{d=r(u)}catch(e){if(!(e instanceof i))throw e;return l.err(e.message),2}let p=t(d);if(s.strict&&p.length>0)return m(l,n(p)),l.err(c),1;let g={name:o(s.contract),sha256:a(`sha256`).update(u).digest(`hex`)},_;try{_=e(d,g)}catch(e){if(!(e instanceof i))throw e;return l.err(e.message),2}if(s.check)return f(s,_,l);try{await l.writeText(s.out,_)}catch(e){return l.err(`cannot write ${s.out}: ${h(e)}`),2}let v=d.operations.filter(e=>e.id!==``).length;return l.out(`wrote ${s.out} (${d.schemas.size} schemas, ${v} operations)`),p.length>0&&m(l,n(p)),0}async function f(e,t,n){return await p(e.out,n)===t?0:(n.err(`${e.out} is out of date with ${e.contract}; run: webority-api-contract generate ${e.contract} --out ${e.out}`),1)}async function p(e,t){try{return await t.readText(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return null;throw e}}function m(e,t){for(let n of t.split(`
|
|
2
2
|
`))e.err(n)}function h(e){return e instanceof Error?e.message:String(e)}export{l as run};
|
package/dist/emitFile.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{emitHubs as e}from"./emitHubs.js";import{emitType as t,literalType as n,stringEnumMembers as r}from"./emitSchema.js";import{propertyKey as
|
|
1
|
+
import{emitHubs as e}from"./emitHubs.js";import{emitType as t,literalType as n,stringEnumMembers as r}from"./emitSchema.js";import{ContractError as i}from"./model.js";import{propertyKey as a,quote as o,typeName as s,uniqueName as c}from"./names.js";var l=[`Blob`,`FormData`,`Record`,`Readonly`,`OperationId`,`OperationTypes`],u=`Blob`,d=[`multipart/form-data`,`application/x-www-form-urlencoded`];function f(t,n){let r=new Set(l),i=/* @__PURE__ */ new Map;for(let e of t.schemas.keys())i.set(e,c(s(e),r));let a=[m(n)];for(let[e,n]of t.schemas)a.push(...p(h(i,e),n,i));let o=t.operations.filter(e=>e.id!==``).map(e=>({operation:e,op:g(s(e.id),r)}));for(let{operation:e,op:t}of o)a.push(_(t,e,i)),a.push(x(t,e,i));return a.push(O(o,i,t.schemas)),a.push(`export type OperationId = keyof typeof operations;`),a.push(k(o)),a.push(...e(t.hubs,i,r)),`${a.join(`
|
|
2
2
|
|
|
3
|
-
`)}\n`}function
|
|
4
|
-
`)}\n};`}function
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
7
|
-
`)}export{
|
|
3
|
+
`)}\n`}function p(e,i,o){let s=r(i);return s===void 0?[`export type ${e} = ${t(i,o,0)};`]:[`export const ${e} = { ${s.map(e=>`${a(e)}: ${n(e)}`).join(`, `)} } as const;`,`export type ${e} = (typeof ${e})[keyof typeof ${e}];`]}function m(e){return`// Generated by @webority/api-contract from ${e.name} (sha256 ${e.sha256}). Do not edit: change the backend contract and generate again.`}function h(e,t){let n=e.get(t);if(n===void 0)throw Error(`no type name was made for schema ${t}`);return n}function g(e,t){for(let n=1;;n+=1){let r=n===1?e:`${e}${n}`,i=`${r}Request`,a=`${r}Response`;if(!t.has(r)&&!t.has(i)&&!t.has(a))return t.add(r),t.add(i),t.add(a),r}}function _(e,t,n){let r=t.parameters.filter(e=>e.place===`path`),i=t.parameters.filter(e=>e.place===`query`),a=t.parameters.filter(e=>e.place===`header`),o=[];return r.length>0&&o.push(v(`path`,r,!1,n)),i.length>0&&o.push(v(`query`,i,!i.some(e=>e.required),n)),a.length>0&&o.push(v(`headers`,a,!a.some(e=>e.required),n)),t.body!==null&&o.push(y(t.body,n)),o.length===0?`export type ${e}Request = Readonly<Record<string, never>>;`:`export type ${e}Request = {\n${o.join(`
|
|
4
|
+
`)}\n};`}function v(e,n,r,i){let o=n.map(e=>` readonly ${a(e.name)}${e.required?``:`?`}: ${t(e.schema,i,2)};`);return[` readonly ${e}${r?`?`:``}: {`,...o,` };`].join(`
|
|
5
|
+
`)}function y(e,t){let n=b(e,t);return` readonly body${e.required?``:`?`}: ${n};`}function b(e,n){return d.includes(w(e.contentType))?`FormData`:e.schema===null?`unknown`:t(e.schema,n,1)}function x(e,t,n){return`export type ${e}Response = ${C(t,n)};`}var S=`undefined`;function C(e,n){let r=[];for(let i of e.replies){if(!i.status.startsWith(`2`))continue;let e=i.schema===null?S:t(i.schema,n,0);r.includes(e)||r.push(e)}return r.length>0?r.join(` | `):S}function w(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}var T=`#/components/schemas/`;function E(e,n,r){let i=/* @__PURE__ */ new Set,a=e;for(;a.$ref?.startsWith(T);){let e=a.$ref.slice(21),t=r.get(e);if(t===void 0||i.has(e))return!1;i.add(e),a=t}return t(a,n,0)===u}function D(e,t,n){let r=!1,a=!1;for(let i of e.replies)i.status.startsWith(`2`)&&i.schema!==null&&(E(i.schema,t,n)?r=!0:a=!0);if(r&&a)throw new i(`${e.method} ${e.path} answers with a file and with JSON; give each its own operation`);return r?`blob`:a?`json`:`none`}function O(e,t,n){return e.length===0?`export const operations = {} as const;`:[`export const operations = {`,...e.map(({operation:e})=>{let r=D(e,t,n),i=`{ method: ${o(e.method)}, path: ${o(e.path)}, replyKind: ${o(r)} }`;return` ${a(e.id)}: ${i},`}),`} as const;`].join(`
|
|
6
|
+
`)}function k(e){return e.length===0?`export interface OperationTypes {}`:[`export interface OperationTypes {`,...e.map(({operation:e,op:t})=>` readonly ${a(e.id)}: { readonly request: ${t}Request; readonly response: ${t}Response };`),`}`].join(`
|
|
7
|
+
`)}export{f as emitFile};
|
package/dist/load.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ContractError as e}from"./model.js";var t=[{key:`get`,method:`GET`},{key:`post`,method:`POST`},{key:`put`,method:`PUT`},{key:`patch`,method:`PATCH`},{key:`delete`,method:`DELETE`}],n=[...t,{key:`query`,method:`QUERY`}],r=`application/json`,i=64,
|
|
1
|
+
import{ContractError as e}from"./model.js";var t=[{key:`get`,method:`GET`},{key:`post`,method:`POST`},{key:`put`,method:`PUT`},{key:`patch`,method:`PATCH`},{key:`delete`,method:`DELETE`}],n=[...t,{key:`query`,method:`QUERY`}],r=`application/json`,i=`multipart/form-data`,a=64,o=`3.0.x, 3.1.x and 3.2.x`,s=/^(3\.[012])(?:\.\d+(?:-[0-9A-Za-z.-]+)?)?$/,c=/* @__PURE__ */ new Map([[`3.0`,`3.0`],[`3.1`,`3.1`],[`3.2`,`3.2`]]),l=/^(?:application\/(?:octet-stream|pdf|zip|gzip)|(?:image|audio|video)\/)/,u={type:`string`,format:`binary`},d=[`properties`,`patternProperties`,`$defs`],f=[`allOf`,`oneOf`,`anyOf`,`prefixItems`],p=[`items`,`additionalProperties`,`unevaluatedProperties`];function m(e){let t=J(_(e)),n=h(t),r=g(t,n),i={version:n,components:J(t.components),leftOut:[]},a=v(i),o=b(r,i);return{version:n,title:Y(J(t.info).title)??``,schemas:a,operations:o,hubs:x(t),leftOut:i.leftOut}}function h(t){let n=Y(t.openapi),r=Y(t.swagger);if(n===void 0){let t=r===void 0?`has no openapi version`:`is Swagger ${r}, which is not supported`;throw new e(`contract ${t}: supported versions are ${o}`)}let i=s.exec(n)?.[1],a=i===void 0?void 0:c.get(i);if(a===void 0)throw new e(`contract is OpenAPI ${n}, which is not supported: supported versions are ${o}`);return a}function g(t,n){if(q(t.paths))return t.paths;if(n===`3.0`)throw new e(`contract has no paths`);if(t.paths!==void 0)throw new e(`contract paths is not an object`);return{}}function _(t){try{return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:`unknown error`;throw new e(`contract is not valid JSON: ${n}`)}}function v(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of Object.entries(J(e.components.schemas))){let i=H(r);t.set(n,i),e.version!==`3.0`&&y(t,n,i,0)}return t}function y(e,t,n,r){if(!(r>=a))for(let[i,a]of Object.entries(J(n.$defs))){let n=H(a),o=`${t}/$defs/${i}`;e.set(o,n),y(e,o,n,r+1)}}function b(e,r){let i=[],a=r.version===`3.2`?n:t;for(let[t,n]of Object.entries(e)){let e=J(D(r,n)),o=M(X(e.parameters),r,t);for(let{key:n,method:s}of a){let a=e[n];q(a)&&i.push(k(t,s,a,o,r))}r.version===`3.2`&&O(t,e,r)}return i}function x(t){let n=t[`x-webority-hubs`];if(n===void 0)return[];if(!q(n))throw new e(`x-webority-hubs is not an object`);return Object.entries(n).map(([e,t])=>S(`x-webority-hubs.${e}`,e,t))}function S(t,n,r){if(!q(r))throw new e(`${t} is not an object`);return{name:n,methods:C(`${t}.methods`,r.methods),events:C(`${t}.events`,r.events)}}function C(t,n){if(n===void 0)return[];if(!q(n))throw new e(`${t} is not an object`);return Object.entries(n).map(([e,n])=>w(`${t}.${e}`,e,n))}function w(t,n,r){if(!q(r))throw new e(`${t} is not an object`);let i=r.parameters;if(!Array.isArray(i))throw new e(`${t} has no parameters array`);return{name:n,parameters:i.map((e,n)=>T(`${t}.parameters[${n}]`,e)),result:r.result===void 0?null:E(`${t}.result`,r.result)}}function T(t,n){if(!q(n))throw new e(`${t} is not an object`);let r=Y(n.name);if(r===void 0)throw new e(`${t} has no name`);return{name:r,schema:E(`${t}.schema`,n.schema)}}function E(t,n){if(!q(n))throw new e(`${t} is not an object`);return H(n)}function D(e,t){return e.version===`3.0`?t:B(e.components,`pathItems`,t)}function O(e,t,n){for(let[r,i]of Object.entries(J(t.additionalOperations)))q(i)&&n.leftOut.push(`the ${r} operation of ${e}`)}function k(e,t,n,r,i){return{id:Y(n.operationId)??``,method:t,path:e,parameters:A(r,M(X(n.parameters),i,`${t} ${e}`)),body:F(n.requestBody,i),replies:I(n.responses,i)}}function A(e,t){let n=[...e,...t];return n.filter((e,t)=>n.every((n,r)=>r<=t||!j(e,n)))}function j(e,t){return e.name===t.name&&e.place===t.place}function M(e,t,n){let r=[];for(let i of e){let e=B(t.components,`parameters`,i);if(t.version===`3.2`&&q(e)&&e.in===`querystring`){t.leftOut.push(`the querystring parameter of ${n}`);continue}let a=N(e,t,n);a!==void 0&&r.push(a)}return r}function N(t,n,r){if(!q(t))throw new e(`a parameter of ${r} is not an object`);let i=Y(t.name);if(i===void 0)throw new e(`a parameter of ${r} has no name`);let a=Y(t.in);if(a===void 0)throw new e(`the parameter ${i} of ${r} has no "in"`);let o=P(a);if(o===void 0)n.leftOut.push(`the ${a} parameter ${i} of ${r}`);else return{name:i,place:o,required:o===`path`||t.required===!0,schema:H(t.schema)}}function P(e){if(e===`path`||e===`query`||e===`header`)return e}function F(e,t){let n=B(t.components,`requestBodies`,e);if(!q(n))return null;let r=L(n.content,t);return{required:n.required===!0,contentType:r.contentType,schema:r.schema}}function I(e,t){return Object.entries(J(e)).map(([e,n])=>({status:e,schema:L(J(B(t.components,`responses`,n)).content,t).schema}))}function L(e,t){let n=J(e),r=R(Object.keys(n));return{contentType:r,schema:z(r,J(B(t.components,`mediaTypes`,n[r])),t.version)}}function R(e){return e.includes(r)?r:e.includes(i)?i:e[0]??``}function z(e,t,n){if(l.test(e.trim().toLowerCase()))return u;let r=q(t.schema)?H(t.schema):null;return n===`3.0`?r:r===null&&n===`3.2`&&q(t.itemSchema)?{type:`array`,items:H(t.itemSchema)}:r}function B(t,n,r){let i=J(t[n]),a=/* @__PURE__ */ new Set,o=r;for(;q(o)&&`$ref`in o;){let t=Y(o.$ref),r=`#/components/${n}/`,s=t?.startsWith(r)?t.slice(r.length):void 0;if(s===void 0||!Object.hasOwn(i,s))throw new e(`contract has a $ref that does not resolve: ${t??`a $ref that is not a string`}`);if(a.has(s))throw new e(`contract has a $ref cycle: ${[...a,s].join(` -> `)}`);a.add(s),o=i[s]}return o}function V(e){return q(e)}function H(e){return V(e)?(U(J(e),1),e):{}}function U(t,n){if(n>a)throw new e(`a schema is nested more than ${a} levels deep`);G(t.enum);for(let e of d)for(let r of Object.values(J(t[e])))W(r,n);for(let e of f)for(let r of X(t[e]))W(r,n);for(let e of p)W(t[e],n)}function W(e,t){q(e)&&U(e,t+1)}function G(t){if(t!==void 0&&(!Array.isArray(t)||!t.every(K)))throw new e(`a schema enum has a value that is not a string, number, boolean or null`)}function K(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function J(e){return q(e)?e:{}}function Y(e){return typeof e==`string`?e:void 0}function X(e){return Array.isArray(e)?e:[]}export{m as loadContract};
|
package/dist/types/call.d.ts
CHANGED
|
@@ -13,6 +13,15 @@ export interface OperationShape {
|
|
|
13
13
|
};
|
|
14
14
|
readonly response: unknown;
|
|
15
15
|
}
|
|
16
|
+
/** What a single call adds to what the contract declares for its operation. */
|
|
17
|
+
export interface ContractCallOptions {
|
|
18
|
+
/** Headers the contract does not declare (an idempotency key, an account id); a declared header is set on the request instead. */
|
|
19
|
+
readonly headers?: Readonly<Record<string, string>> | undefined;
|
|
20
|
+
/** The client logs no failure of this call; the caller logs it itself. */
|
|
21
|
+
readonly skipErrorLog?: boolean | undefined;
|
|
22
|
+
/** Failure statuses the caller handles itself: one still rejects, and the client logs it as handled, not as an error. */
|
|
23
|
+
readonly expectedStatuses?: readonly number[] | undefined;
|
|
24
|
+
}
|
|
16
25
|
export interface ContractRequest {
|
|
17
26
|
readonly method: OperationEntry["method"];
|
|
18
27
|
/** The path with its values filled in, and the query string when the request has one. */
|
|
@@ -20,8 +29,17 @@ export interface ContractRequest {
|
|
|
20
29
|
readonly headers: Readonly<Record<string, string>> | undefined;
|
|
21
30
|
readonly data: unknown;
|
|
22
31
|
readonly responseType: "json" | "blob";
|
|
32
|
+
readonly skipErrorLog: boolean | undefined;
|
|
33
|
+
readonly expectedStatuses: readonly number[] | undefined;
|
|
23
34
|
}
|
|
24
35
|
export declare class ContractCallError extends Error {
|
|
25
36
|
constructor(message: string);
|
|
26
37
|
}
|
|
27
|
-
|
|
38
|
+
/**
|
|
39
|
+
* The reply a call resolves to: nothing for an operation that answers with no body or for a 204 or 205 (axios hands
|
|
40
|
+
* those over as an empty string or an empty Blob), otherwise the body. It keeps the reply type the caller reads the
|
|
41
|
+
* body as, because the generated contract types every operation that can answer with no body as `undefined` or a union
|
|
42
|
+
* holding it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function contractReply<TReply>(entry: OperationEntry, status: number, data: TReply): TReply;
|
|
45
|
+
export declare function buildContractRequest(entry: OperationEntry, request: OperationShape["request"], options?: ContractCallOptions): ContractRequest;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/api-contract",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.158.0",
|
|
4
4
|
"description": "Generates one TypeScript file of API types from a backend OpenAPI 3.0, 3.1 or 3.2 contract, as plain text, with no runtime dependencies.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/node": "25.6.0",
|
|
30
|
-
"@webority/biome-config": "0.
|
|
30
|
+
"@webority/biome-config": "0.158.0",
|
|
31
31
|
"typescript": "^7.0.2",
|
|
32
32
|
"vite": "^8.3.6",
|
|
33
33
|
"vitest": "5.1.0"
|