@webority/api-contract 0.163.0 → 0.165.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  Copyright (c) Webority Technologies. All rights reserved.
2
2
 
3
- This software and its NuGet packages are the proprietary and confidential property
3
+ This software and its Webority packages are the proprietary and confidential property
4
4
  of Webority Technologies. They are published publicly only for the convenience of
5
5
  Webority's own projects and internal consumption.
6
6
 
package/README.md CHANGED
@@ -48,6 +48,8 @@ An operation whose 2xx replies mix a file with JSON has no single reply kind, so
48
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
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
50
 
51
+ An operation the server marks `[Idempotent]` (its OpenAPI operation carries `x-webority-idempotent: true`) is emitted with `idempotent: true` after its `replyKind`. The web and phone cores send a fresh `Idempotency-Key` per call for such an operation and resend that same key when a reply is lost, so an app needs no code of its own for the key.
52
+
51
53
  `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
54
 
53
55
  ## OpenAPI versions
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(`&`)}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(t,n){let r=n?.reply,i=n?.replacesSession;if(r!==void 0&&r!==`body`&&r!==`full`)throw new e(`${t} needs reply as "body" or "full"`);if(i!==void 0&&typeof i!=`boolean`)throw new e(`${t} needs replacesSession as true or false`);return{reply:r??`body`,replacesSession:i}}var u=e=>e>=200&&e<300||e===304;function d(e,t,n,r){let i={};for(let[e,t]of Object.entries(n))t!=null&&(i[e.toLowerCase()]=Array.isArray(t)?t.map(String).join(`, `):String(t));return t===304?{status:304,notModified:!0,headers:i,body:void 0}:{status:t,notModified:!1,headers:i,body:f(e,t,r)}}function f(e,t,n){return e.replyKind===`none`||t===204||t===205?void 0:n}function p(n,i,a){let o=`${n.method} ${n.path}`,u=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)}),d=r(i.query);return{method:n.method,url:d===``?u:`${u}?${d}`,headers:s(o,i.headers,a?.headers),data:i.body,responseType:n.replyKind===`blob`?`blob`:`json`,...c(o,a),...l(o,a)}}var m=[`page`,`pageSize`,`sortBy`,`sortOrder`,`search`],h=e=>String(e).padStart(2,`0`),g=e=>e instanceof Date?`${e.getFullYear()}-${h(e.getMonth()+1)}-${h(e.getDate())}`:e,_=e=>e==null||typeof e==`string`&&e.trim()===``,v=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date),y=m;function b(t,n,r){if(!_(r)){if(typeof r==`string`||r instanceof Date)return g(r);throw new e(`listQuery needs "${t}.${n}" as a yyyy-MM-dd string or a Date`)}}function x(t){let n={},{filters:r,...i}=t;for(let e of m){let t=i[e];_(t)||(n[e]=typeof t==`string`?t.trim():t)}n.sortBy===void 0&&delete n.sortOrder;for(let[t,i]of Object.entries(r??{})){if(y.includes(t))throw new e(`listQuery has a filter named "${t}", which the list query reserves (${m.join(`, `)})`);if(Array.isArray(i)){let e=i.filter(e=>!_(e));e.length>0&&(n[t]=e)}else if(v(i)){let e=b(t,`from`,i.from),r=b(t,`to`,i.to);e!==void 0&&(n[`${t}From`]=e),r!==void 0&&(n[`${t}To`]=r)}else i instanceof Date?n[t]=g(i):_(i)||(n[t]=i)}return n}export{e as ContractCallError,p as buildContractRequest,d as contractFullReply,f as contractReply,u as isFullReplyStatus,x as listQuery};
1
+ var e=`Idempotency-Key`,t=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},n=/\{([^{}]+)\}/g,r=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e));function i(e){let t=[];for(let[n,i]of Object.entries(e??{})){if(i==null)continue;let e=encodeURIComponent(n);for(let n of Array.isArray(i)?i:[i])n!=null&&t.push(`${e}=${r(n)}`)}return t.join(`&`)}var a=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,o=[`content-type`,`content-length`],s=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function c(e,n,r){if(r===void 0)return n;if(!s(r))throw new t(`${e} needs call headers as an object of header names to string values`);let i=new Set(Object.keys(n??{}).map(e=>e.toLowerCase())),c={...n};for(let[n,s]of Object.entries(r)){if(!a.test(n))throw new t(`${e} has a call header named "${n}", which is not a valid header name`);let r=n.toLowerCase();if(o.includes(r))throw new t(`${e} sets "${n}" as a call header; the body decides it`);if(i.has(r))throw new t(`${e} sets "${n}" twice; set a header the contract declares on the request's headers only`);if(typeof s!=`string`||/[\r\n\0]/.test(s))throw new t(`${e} needs call header "${n}" as a string with no line break`);i.add(r),c[n]=s}return c}function l(e,n){let r=n?.skipErrorLog,i=n?.expectedStatuses;if(r!==void 0&&typeof r!=`boolean`)throw new t(`${e} 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 t(`${e} 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 t(`${e} lists ${String(n)} in expectedStatuses; only a failure status from 400 to 599 is expected`);if(new Set(i).size!==i.length)throw new t(`${e} lists a status twice in expectedStatuses`);if(r===!0)throw new t(`${e} sets skipErrorLog and expectedStatuses; skipErrorLog already keeps every failure out of the log`);return{skipErrorLog:r,expectedStatuses:i}}function u(e,n){let r=n?.reply,i=n?.replacesSession;if(r!==void 0&&r!==`body`&&r!==`full`)throw new t(`${e} needs reply as "body" or "full"`);if(i!==void 0&&typeof i!=`boolean`)throw new t(`${e} needs replacesSession as true or false`);return{reply:r??`body`,replacesSession:i}}var d=e=>e>=200&&e<300||e===304;function f(e,t,n,r){let i={};for(let[e,t]of Object.entries(n))t!=null&&(i[e.toLowerCase()]=Array.isArray(t)?t.map(String).join(`, `):String(t));return t===304?{status:304,notModified:!0,headers:i,body:void 0}:{status:t,notModified:!1,headers:i,body:p(e,t,r)}}function p(e,t,n){return e.replyKind===`none`||t===204||t===205?void 0:n}function m(e,r,a){let o=`${e.method} ${e.path}`,s=e.path.replace(n,(e,n)=>{let i=r.path?.[n],a=i===void 0?``:String(i);if(a===``)throw new t(`${o} needs a non-empty path value for "${n}"`);if(a===`.`||a===`..`)throw new t(`${o} needs a path value for "${n}" other than "." or ".."`);return encodeURIComponent(a)}),d=i(r.query);return{method:e.method,url:d===``?s:`${s}?${d}`,headers:c(o,r.headers,a?.headers),data:r.body,responseType:e.replyKind===`blob`?`blob`:`json`,...l(o,a),...u(o,a)}}var h=[`page`,`pageSize`,`sortBy`,`sortOrder`,`search`],g=e=>String(e).padStart(2,`0`),_=e=>e instanceof Date?`${e.getFullYear()}-${g(e.getMonth()+1)}-${g(e.getDate())}`:e,v=e=>e==null||typeof e==`string`&&e.trim()===``,y=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date),b=h;function x(e,n,r){if(!v(r)){if(typeof r==`string`||r instanceof Date)return _(r);throw new t(`listQuery needs "${e}.${n}" as a yyyy-MM-dd string or a Date`)}}function S(e){let n={},{filters:r,...i}=e;for(let e of h){let t=i[e];v(t)||(n[e]=typeof t==`string`?t.trim():t)}n.sortBy===void 0&&delete n.sortOrder;for(let[e,i]of Object.entries(r??{})){if(b.includes(e))throw new t(`listQuery has a filter named "${e}", which the list query reserves (${h.join(`, `)})`);if(Array.isArray(i)){let t=i.filter(e=>!v(e));t.length>0&&(n[e]=t)}else if(y(i)){let t=x(e,`from`,i.from),r=x(e,`to`,i.to);t!==void 0&&(n[`${e}From`]=t),r!==void 0&&(n[`${e}To`]=r)}else i instanceof Date?n[e]=_(i):v(i)||(n[e]=i)}return n}export{t as ContractCallError,e as IDEMPOTENCY_KEY_HEADER,m as buildContractRequest,f as contractFullReply,p as contractReply,d as isFullReplyStatus,S as listQuery};
package/dist/emitFile.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import{emitHubs as e}from"./emitHubs.js";import{emitType as t,literalType as n,pad as r,stringEnumMembers as i}from"./emitSchema.js";import{ContractError as a}from"./model.js";import{propertyKey as o,quote as s,typeName as c,uniqueName as l}from"./names.js";var u=[`Blob`,`FormData`,`Record`,`Readonly`,`OperationId`,`OperationTypes`],d=`Blob`,f=[`multipart/form-data`,`application/x-www-form-urlencoded`];function p(t,n){let r=new Set(u),i=/* @__PURE__ */ new Map;for(let e of t.schemas.keys())i.set(e,l(c(e),r));let a=[h(n)];for(let[e,n]of t.schemas)a.push(...m(g(i,e),n,i));let o=t.operations.filter(e=>e.id!==``).map(e=>({operation:e,op:_(c(e.id),r)}));for(let{operation:e,op:t}of o)a.push(v(t,e,i)),a.push(S(t,e,i));return a.push(k(o,i,t.schemas)),a.push(`export type OperationId = keyof typeof operations;`),a.push(A(o)),a.push(...e(t.hubs,i,r)),`${a.join(`
2
2
 
3
- `)}\n`}function m(e,r,a){let s=i(r);return s===void 0?[`export type ${e} = ${t(r,a,0)};`]:[`export const ${e} = { ${s.map(e=>`${o(e)}: ${n(e)}`).join(`, `)} } as const;`,`export type ${e} = (typeof ${e})[keyof typeof ${e}];`]}function h(e){return`// Generated by @webority/api-contract from ${e.name} (sha256 ${e.sha256}). Do not edit: change the backend contract and generate again.`}function g(e,t){let n=e.get(t);if(n===void 0)throw Error(`no type name was made for schema ${t}`);return n}function _(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 v(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(y(`path`,r,!1,n)),i.length>0&&o.push(y(`query`,i,!i.some(e=>e.required),n)),a.length>0&&o.push(y(`headers`,a,!a.some(e=>e.required),n)),t.body!==null&&o.push(b(t.body,n)),o.length===0?`export type ${e}Request = Readonly<Record<string, never>>;`:`export type ${e}Request = {\n${o.join(`
3
+ `)}\n`}function m(e,a,s){let c=i(a);if(c===void 0)return[`export type ${e} = ${t(a,s,0)};`];let l=c.map(e=>`${o(e)}: ${n(e)}`),u=`export const ${e} = { ${l.join(`, `)} } as const;`;return[u.length<=140?u:[`export const ${e} = {`,...l.map(e=>`${r(1)}${e},`),`} as const;`].join(`
4
+ `),`export type ${e} = (typeof ${e})[keyof typeof ${e}];`]}function h(e){return`// Generated by @webority/api-contract from ${e.name} (sha256 ${e.sha256}). Do not edit: change the backend contract and generate again.`}function g(e,t){let n=e.get(t);if(n===void 0)throw Error(`no type name was made for schema ${t}`);return n}function _(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 v(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(y(`path`,r,!1,n)),i.length>0&&o.push(y(`query`,i,!i.some(e=>e.required),n)),a.length>0&&o.push(y(`headers`,a,!a.some(e=>e.required),n)),t.body!==null&&o.push(b(t.body,n)),o.length===0?`export type ${e}Request = Readonly<Record<string, never>>;`:`export type ${e}Request = {\n${o.join(`
4
5
  `)}\n};`}function y(e,n,i,a){let s=n.map(e=>`${r(2)}readonly ${o(e.name)}${e.required?``:`?`}: ${t(e.schema,a,2)};`);return[`${r(1)}readonly ${e}${i?`?`:``}: {`,...s,`${r(1)}};`].join(`
5
- `)}function b(e,t){let n=x(e,t);return`${r(1)}readonly body${e.required?``:`?`}: ${n};`}function x(e,n){return f.includes(T(e.contentType))?`FormData`:e.schema===null?`unknown`:t(e.schema,n,1)}function S(e,t,n){return`export type ${e}Response = ${w(t,n)};`}var C=`undefined`;function w(e,n){let r=[];for(let i of e.replies){if(!i.status.startsWith(`2`))continue;let e=i.schema===null?C:t(i.schema,n,0);r.includes(e)||r.push(e)}return r.length>0?r.join(` | `):C}function T(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}var E=`#/components/schemas/`;function D(e,n,r){let i=/* @__PURE__ */ new Set,a=e;for(;a.$ref?.startsWith(E);){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)===d}function O(e,t,n){let r=!1,i=!1;for(let a of e.replies)a.status.startsWith(`2`)&&a.schema!==null&&(D(a.schema,t,n)?r=!0:i=!0);if(r&&i)throw new a(`${e.method} ${e.path} answers with a file and with JSON; give each its own operation`);return r?`blob`:i?`json`:`none`}function k(e,t,n){return e.length===0?`export const operations = {} as const;`:[`export const operations = {`,...e.map(({operation:e})=>{let i=O(e,t,n),a=`{ method: ${s(e.method)}, path: ${s(e.path)}, replyKind: ${s(i)} }`;return`${r(1)}${o(e.id)}: ${a},`}),`} as const;`].join(`
6
- `)}function A(e){return e.length===0?`export interface OperationTypes {}`:[`export interface OperationTypes {`,...e.map(({operation:e,op:t})=>`${r(1)}readonly ${o(e.id)}: { readonly request: ${t}Request; readonly response: ${t}Response };`),`}`].join(`
6
+ `)}function b(e,t){let n=x(e,t);return`${r(1)}readonly body${e.required?``:`?`}: ${n};`}function x(e,n){return f.includes(T(e.contentType))?`FormData`:e.schema===null?`unknown`:t(e.schema,n,1)}function S(e,t,n){return`export type ${e}Response = ${w(t,n)};`}var C=`undefined`;function w(e,n){let r=[];for(let i of e.replies){if(!i.status.startsWith(`2`))continue;let e=i.schema===null?C:t(i.schema,n,0);r.includes(e)||r.push(e)}return r.length>0?r.join(` | `):C}function T(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}var E=`#/components/schemas/`;function D(e,n,r){let i=/* @__PURE__ */ new Set,a=e;for(;a.$ref?.startsWith(E);){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)===d}function O(e,t,n){let r=!1,i=!1;for(let a of e.replies)a.status.startsWith(`2`)&&a.schema!==null&&(D(a.schema,t,n)?r=!0:i=!0);if(r&&i)throw new a(`${e.method} ${e.path} answers with a file and with JSON; give each its own operation`);return r?`blob`:i?`json`:`none`}function k(e,t,n){return e.length===0?`export const operations = {} as const;`:[`export const operations = {`,...e.flatMap(({operation:e})=>{let i=O(e,t,n),a=o(e.id),c=e.idempotent===!0,l=`${r(1)}${a}: { method: ${s(e.method)}, path: ${s(e.path)}, replyKind: ${s(i)}${c?`, idempotent: true`:``} },`;return l.length<=140?[l]:[`${r(1)}${a}: {`,`${r(2)}method: ${s(e.method)},`,`${r(2)}path: ${s(e.path)},`,`${r(2)}replyKind: ${s(i)},`,...c?[`${r(2)}idempotent: true,`]:[],`${r(1)}},`]}),`} as const;`].join(`
7
+ `)}function A(e){return e.length===0?`export interface OperationTypes {}`:[`export interface OperationTypes {`,...e.flatMap(({operation:e,op:t})=>{let n=o(e.id),i=`${r(1)}readonly ${n}: { readonly request: ${t}Request; readonly response: ${t}Response };`;return i.length<=140?[i]:[`${r(1)}readonly ${n}: {`,`${r(2)}readonly request: ${t}Request;`,`${r(2)}readonly response: ${t}Response;`,`${r(1)}};`]}),`}`].join(`
7
8
  `)}export{p as emitFile};
package/dist/emitHubs.js CHANGED
@@ -1,4 +1,5 @@
1
- import{emitType as e,pad as t}from"./emitSchema.js";import{propertyKey as n,quote as r,typeName as i}from"./names.js";var a=[`Method`,`Event`,`Methods`,`Events`,`Invoke`,`On`],o=/^[A-Za-z_$][A-Za-z0-9_$]*$/,s=/* @__PURE__ */ new Set(/* @__PURE__ */ `await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.implements.import.in.instanceof.interface.let.new.null.package.private.protected.public.return.static.super.switch.this.throw.true.try.typeof.var.void.while.with.yield`.split(`.`));function c(e,t,n){let r=[],a=[...e].sort((e,t)=>b(e.name,t.name));for(let e of a){let a=l(i(e.name),n);r.push(...d(a,e,t))}return r}function l(e,t){for(let n=1;;n+=1){let r=n===1?e:`${e}${n}`,i=[r,...a.map(e=>`${r}${e}`)];if(i.every(e=>!t.has(e))){for(let e of i)t.add(e);return r}}}var u=`undefined`;function d(t,n,r){let i=y(n.methods),a=y(n.events),o=[m(t,i,a),`export type ${t}Method = keyof typeof ${t}.methods;`,`export type ${t}Event = keyof typeof ${t}.events;`,g(`${t}Methods`,i,t=>t.result===null?u:e(t.result,r,2),r),g(`${t}Events`,a,()=>u,r)];return i.length>0&&o.push(p(`export type ${t}Invoke = <K extends ${t}Method>(`,[`method: K`,`...args: ${t}Methods[K]["args"]`],`) => Promise<${t}Methods[K]["result"]>;`)),a.length>0&&o.push(p(`export type ${t}On = <K extends ${t}Event>(`,[`event: K`,`handler: (...args: ${t}Events[K]["args"]) => void`],`) => void;`)),o}var f=140;function p(e,n,r){let i=`${e}${n.join(`, `)}${r}`;if(i.length<=f)return i;let a=(n[n.length-1]??``).startsWith(`...`)?``:`,`;return[e,...n.map((e,r)=>`${t(1)}${e}${r===n.length-1?a:`,`}`),r].join(`
2
- `)}function m(e,n,r){return[`export const ${e} = {`,`${t(1)}methods: ${h(n)},`,`${t(1)}events: ${h(r)},`,`} as const;`].join(`
3
- `)}function h(e){return e.length===0?`{}`:`{ ${e.map(e=>`${n(e.name)}: ${r(e.name)}`).join(`, `)} }`}function g(e,r,i,a){if(r.length===0)return`export interface ${e} {}`;let o=r.map(e=>`${t(1)}readonly ${n(e.name)}: { readonly args: readonly [${_(e.parameters,a)}]; readonly result: ${i(e)} };`);return[`export interface ${e} {`,...o,`}`].join(`
4
- `)}function _(t,n){return t.map((t,r)=>`${v(t.name,r)}: ${e(t.schema,n,2)}`).join(`, `)}function v(e,t){return o.test(e)&&!s.has(e)?e:`arg${t}`}function y(e){return[...e].sort((e,t)=>b(e.name,t.name))}function b(e,t){return e<t?-1:+(e>t)}export{c as emitHubs};
1
+ import{emitType as e,pad as t}from"./emitSchema.js";import{propertyKey as n,quote as r,typeName as i}from"./names.js";var a=[`Method`,`Event`,`Methods`,`Events`,`Invoke`,`On`],o=/^[A-Za-z_$][A-Za-z0-9_$]*$/,s=/* @__PURE__ */ new Set(/* @__PURE__ */ `await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.implements.import.in.instanceof.interface.let.new.null.package.private.protected.public.return.static.super.switch.this.throw.true.try.typeof.var.void.while.with.yield`.split(`.`));function c(e,t,n){let r=[],a=[...e].sort((e,t)=>b(e.name,t.name));for(let e of a){let a=l(i(e.name),n);r.push(...d(a,e,t))}return r}function l(e,t){for(let n=1;;n+=1){let r=n===1?e:`${e}${n}`,i=[r,...a.map(e=>`${r}${e}`)];if(i.every(e=>!t.has(e))){for(let e of i)t.add(e);return r}}}var u=`undefined`;function d(t,n,r){let i=y(n.methods),a=y(n.events),o=[p(t,i,a),`export type ${t}Method = keyof typeof ${t}.methods;`,`export type ${t}Event = keyof typeof ${t}.events;`,h(`${t}Methods`,i,t=>t.result===null?u:e(t.result,r,2),r),h(`${t}Events`,a,()=>u,r)];return i.length>0&&o.push(f(`export type ${t}Invoke = <K extends ${t}Method>(`,[`method: K`,`...args: ${t}Methods[K]["args"]`],`) => Promise<${t}Methods[K]["result"]>;`)),a.length>0&&o.push(f(`export type ${t}On = <K extends ${t}Event>(`,[`event: K`,`handler: (...args: ${t}Events[K]["args"]) => void`],`) => void;`)),o}function f(e,n,r){let i=`${e}${n.join(`, `)}${r}`;if(i.length<=140)return i;let a=(n[n.length-1]??``).startsWith(`...`)?``:`,`;return[e,...n.map((e,r)=>`${t(1)}${e}${r===n.length-1?a:`,`}`),r].join(`
2
+ `)}function p(e,t,n){return[`export const ${e} = {`,...m(`methods`,t),...m(`events`,n),`} as const;`].join(`
3
+ `)}function m(e,i){if(i.length===0)return[`${t(1)}${e}: {},`];let a=i.map(e=>`${n(e.name)}: ${r(e.name)}`),o=`${t(1)}${e}: { ${a.join(`, `)} },`;return o.length<=140?[o]:[`${t(1)}${e}: {`,...a.map(e=>`${t(2)}${e},`),`${t(1)}},`]}function h(e,t,r,i){if(t.length===0)return`export interface ${e} {}`;let a=t.flatMap(e=>g(n(e.name),e.parameters,r(e),i));return[`export interface ${e} {`,...a,`}`].join(`
4
+ `)}function g(e,n,r,i){let a=_(n,i,2).join(`, `),o=`${t(1)}readonly ${e}: { readonly args: readonly [${a}]; readonly result: ${r} };`;if(o.length<=140||o.includes(`
5
+ `))return[o];let s=`${t(2)}readonly args: readonly [${a}];`;if(s.length<=140)return[`${t(1)}readonly ${e}: {`,s,`${t(2)}readonly result: ${r};`,`${t(1)}};`];let c=_(n,i,3).map(e=>`${t(3)}${e},`);return[`${t(1)}readonly ${e}: {`,`${t(2)}readonly args: readonly [`,...c,`${t(2)}];`,`${t(2)}readonly result: ${r};`,`${t(1)}};`]}function _(t,n,r){return t.map((t,i)=>`${v(t.name,i)}: ${e(t.schema,n,r)}`)}function v(e,t){return o.test(e)&&!s.has(e)?e:`arg${t}`}function y(e){return[...e].sort((e,t)=>b(e.name,t.name))}function b(e,t){return e<t?-1:+(e>t)}export{c as emitHubs};
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=`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};
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=Y(_(e)),n=h(t),r=g(t,n),i={version:n,components:Y(t.components),leftOut:[]},a=v(i),o=b(r,i);return{version:n,title:X(Y(t.info).title)??``,schemas:a,operations:o,hubs:x(t),leftOut:i.leftOut}}function h(t){let n=X(t.openapi),r=X(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(J(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(Y(e.components.schemas))){let i=U(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(Y(n.$defs))){let n=U(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=Y(D(r,n)),o=N(Z(e.parameters),r,t);for(let{key:n,method:s}of a){let a=e[n];J(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(!J(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(!J(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(!J(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(!J(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(!J(n))throw new e(`${t} is not an object`);let r=X(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(!J(n))throw new e(`${t} is not an object`);return U(n)}function D(e,t){return e.version===`3.0`?t:V(e.components,`pathItems`,t)}function O(e,t,n){for(let[r,i]of Object.entries(Y(t.additionalOperations)))J(i)&&n.leftOut.push(`the ${r} operation of ${e}`)}function k(e,t,n,r,i){let a=X(n.operationId)??``;return{id:a,method:t,path:e,parameters:j(r,N(Z(n.parameters),i,`${t} ${e}`)),body:I(n.requestBody,i),replies:L(n.responses,i),...A(a,t,n)}}function A(t,n,r){let i=r[`x-webority-idempotent`];if(i===void 0)return{};if(i!==!0)throw new e(`${t} has x-webority-idempotent ${JSON.stringify(i)}; the only valid value is true`);if(n!==`POST`&&n!==`PATCH`)throw new e(`${t} is ${n} and has x-webority-idempotent; only POST and PATCH operations may carry it`);return{idempotent:!0}}function j(e,t){let n=[...e,...t];return n.filter((e,t)=>n.every((n,r)=>r<=t||!M(e,n)))}function M(e,t){return e.name===t.name&&e.place===t.place}function N(e,t,n){let r=[];for(let i of e){let e=V(t.components,`parameters`,i);if(t.version===`3.2`&&J(e)&&e.in===`querystring`){t.leftOut.push(`the querystring parameter of ${n}`);continue}let a=P(e,t,n);a!==void 0&&r.push(a)}return r}function P(t,n,r){if(!J(t))throw new e(`a parameter of ${r} is not an object`);let i=X(t.name);if(i===void 0)throw new e(`a parameter of ${r} has no name`);let a=X(t.in);if(a===void 0)throw new e(`the parameter ${i} of ${r} has no "in"`);let o=F(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:U(t.schema)}}function F(e){if(e===`path`||e===`query`||e===`header`)return e}function I(e,t){let n=V(t.components,`requestBodies`,e);if(!J(n))return null;let r=R(n.content,t);return{required:n.required===!0,contentType:r.contentType,schema:r.schema}}function L(e,t){return Object.entries(Y(e)).map(([e,n])=>({status:e,schema:R(Y(V(t.components,`responses`,n)).content,t).schema}))}function R(e,t){let n=Y(e),r=z(Object.keys(n));return{contentType:r,schema:B(r,Y(V(t.components,`mediaTypes`,n[r])),t.version)}}function z(e){return e.includes(r)?r:e.includes(i)?i:e[0]??``}function B(e,t,n){if(l.test(e.trim().toLowerCase()))return u;let r=J(t.schema)?U(t.schema):null;return n===`3.0`?r:r===null&&n===`3.2`&&J(t.itemSchema)?{type:`array`,items:U(t.itemSchema)}:r}function V(t,n,r){let i=Y(t[n]),a=/* @__PURE__ */ new Set,o=r;for(;J(o)&&`$ref`in o;){let t=X(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 H(e){return J(e)}function U(e){return H(e)?(W(Y(e),1),e):{}}function W(t,n){if(n>a)throw new e(`a schema is nested more than ${a} levels deep`);K(t.enum);for(let e of d)for(let r of Object.values(Y(t[e])))G(r,n);for(let e of f)for(let r of Z(t[e]))G(r,n);for(let e of p)G(t[e],n)}function G(e,t){J(e)&&W(e,t+1)}function K(t){if(t!==void 0&&(!Array.isArray(t)||!t.every(q)))throw new e(`a schema enum has a value that is not a string, number, boolean or null`)}function q(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function J(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e){return J(e)?e:{}}function X(e){return typeof e==`string`?e:void 0}function Z(e){return Array.isArray(e)?e:[]}export{m as loadContract};
@@ -1,8 +1,10 @@
1
1
  export type ReplyKind = "json" | "blob" | "none";
2
+ export declare const IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
2
3
  export interface OperationEntry {
3
4
  readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "QUERY";
4
5
  readonly path: string;
5
6
  readonly replyKind: ReplyKind;
7
+ readonly idempotent?: true;
6
8
  }
7
9
  export interface OperationShape {
8
10
  readonly request: {
@@ -1,2 +1,3 @@
1
1
  import type { Hub } from "./model.js";
2
2
  export declare function emitHubs(hubs: readonly Hub[], schemaNames: ReadonlyMap<string, string>, taken: Set<string>): readonly string[];
3
+ export declare const LINE_WIDTH = 140;
@@ -46,6 +46,8 @@ export interface Operation {
46
46
  readonly parameters: readonly Parameter[];
47
47
  readonly body: RequestBody | null;
48
48
  readonly replies: readonly Reply[];
49
+ /** The server marks the operation retry-safe (`x-webority-idempotent`): callers send an Idempotency-Key. */
50
+ readonly idempotent?: true;
49
51
  }
50
52
  export interface HubParameter {
51
53
  readonly name: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/api-contract",
3
- "version": "0.163.0",
3
+ "version": "0.165.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.163.0",
30
+ "@webority/biome-config": "0.165.0",
31
31
  "typescript": "^7.0.2",
32
32
  "vite": "^8.3.6",
33
33
  "vitest": "5.1.0"