@openmirai/typeforge 0.1.7 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -7
- package/dist/adapters/axios/index.d.ts +1 -2
- package/dist/adapters/axios/index.js +1 -43
- package/dist/adapters/fetch/index.d.ts +1 -2
- package/dist/adapters/fetch/index.js +1 -77
- package/dist/cli.d.ts +1 -2
- package/dist/cli.js +5 -168
- package/dist/http/types.d.ts +1 -2
- package/dist/http/types.js +1 -2
- package/dist/http/validate.d.ts +1 -2
- package/dist/http/validate.js +1 -21
- package/dist/index.d.ts +1 -4
- package/dist/index.js +1 -13
- package/dist/init-UsJVICy2.js +129 -0
- package/dist/routes/index.d.ts +1 -2
- package/dist/routes/index.js +1 -38
- package/dist/validation/zod.d.ts +1 -2
- package/dist/validation/zod.js +1 -8
- package/package.json +6 -7
- package/assets/typeforge-logo.png +0 -0
- package/dist/adapters/axios/index.d.ts.map +0 -1
- package/dist/adapters/axios/index.js.map +0 -1
- package/dist/adapters/fetch/index.d.ts.map +0 -1
- package/dist/adapters/fetch/index.js.map +0 -1
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/http/types.d.ts.map +0 -1
- package/dist/http/validate.d.ts.map +0 -1
- package/dist/http/validate.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/init-BBNO0SYd.js +0 -2029
- package/dist/init-BBNO0SYd.js.map +0 -1
- package/dist/routes/index.d.ts.map +0 -1
- package/dist/routes/index.js.map +0 -1
- package/dist/validation/zod.d.ts.map +0 -1
- package/dist/validation/zod.js.map +0 -1
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import{existsSync as e,mkdirSync as t,readFileSync as n,readdirSync as r,statSync as i,writeFileSync as a}from"node:fs";import{dirname as o,join as s,parse as c,relative as l,resolve as u}from"node:path";import d from"chalk";import{mkdir as f,readFile as p,writeFile as m}from"node:fs/promises";function h(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function g(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?!0:Array.isArray(e)?e.every(g):typeof e==`object`&&e?Object.values(e).every(g):!1}function _(e){return g(e)&&typeof e==`object`&&!!e&&!Array.isArray(e)}function v(e){return Array.isArray(e)&&e.every(g)}function y(e){let t=JSON.parse(e);if(!g(t))throw TypeError(`JSON text did not parse to a valid JSON value`);return t}function b(e){let t=y(e);if(!_(t))throw TypeError(`JSON text did not parse to a JSON object`);return t}function x(e){return v(e)?e.filter(h):[]}function S(t){if(!e(t))return{};try{let e=b(n(t,`utf8`)),r={};return typeof e.apiRoot==`string`&&(r.apiRoot=e.apiRoot),r}catch{return{}}}function C(t){if(!e(t))return{};try{let e=b(n(t,`utf8`)).typeforge;if(typeof e!=`object`||!e||Array.isArray(e))return{};let r={};return typeof e.apiRoot==`string`&&(r.apiRoot=e.apiRoot),r}catch{return{}}}function w(e){let t=e.match(/defineSourceConfig\s*(?:<[^>]*>)?\s*\(\s*\{([\s\S]*)\}\s*\)/);return t?.[1]===void 0?e:`{${t[1]}}`}function T(e){let t=w(e),n={},r=t.match(/pathPrefix:\s*["'`]([^"'`]+)["'`]/);r?.[1]!==void 0&&(n.pathPrefix=r[1]);let i=t.match(/functionsDir:\s*["'`]([^"'`]+)["'`]/);i?.[1]!==void 0&&(n.functionsDir=i[1]);let a=t.match(/typesDir:\s*["'`]([^"'`]+)["'`]/);a?.[1]!==void 0&&(n.typesDir=a[1]);let o=t.match(/ignorePaths:\s*\[([\s\S]*?)\]/);if(o?.[1]!==void 0){let e=[...o[1].matchAll(/["'`]([^"'`]+)["'`]/g)].map(e=>e[1]).filter(e=>e!==void 0);e.length>0&&(n.ignorePaths=e)}/stripApiPrefix:\s*true/.test(t)&&(n.stripApiPrefix=!0);let s=t.match(/routeEnumName:\s*["'`]([^"'`]+)["'`]/);s?.[1]!==void 0&&(n.routeEnumName=s[1]);let c=t.match(/generationMode:\s*["'`](authoritative|merge)["'`]/);(c?.[1]===`authoritative`||c?.[1]===`merge`)&&(n.generationMode=c[1]);let l=t.match(/naming:\s*["'`](path|operationId)["'`]/);(l?.[1]===`path`||l?.[1]===`operationId`)&&(n.naming=l[1]),/resolveMapKeyRefs:\s*false/.test(t)&&(n.resolveMapKeyRefs=!1),/unwrapResponseData:\s*true/.test(t)&&(n.unwrapResponseData=!0),/tanstackQuery:\s*true/.test(t)&&(n.tanstackQuery=!0);let u=t.match(/importBase:\s*["'`]([^"'`]+)["'`]/);u?.[1]!==void 0&&(n.importBase=u[1]);let d=t.match(/maxRenderDepth:\s*(\d+)/)?.[1];d!==void 0&&(n.maxRenderDepth=Number.parseInt(d,10));let f=E(t);f!==void 0&&(n.queryExtends=f);let p=t.match(/spec:\s*["'`]([^"'`]+)["'`]/);return p?.[1]!==void 0&&(n.spec=p[1]),n}function E(e){let t=e.match(/queryExtends:\s*\{([\s\S]*?)\}/)?.[1];if(t===void 0)return;let n={},r=e=>t.match(RegExp(`${e}:\\s*["'\`]([^"'\`]+)["'\`]`))?.[1],i=r(`page`),a=r(`limit`),o=r(`sortBy`),s=r(`sortOrder`),c=r(`paginationTypeName`),l=r(`paginationImportPath`),u=r(`sortTypeName`),d=r(`sortImportPath`);return i!==void 0&&(n.page=i),a!==void 0&&(n.limit=a),o!==void 0&&(n.sortBy=o),s!==void 0&&(n.sortOrder=s),c!==void 0&&(n.paginationTypeName=c),l!==void 0&&(n.paginationImportPath=l),u!==void 0&&(n.sortTypeName=u),d!==void 0&&(n.sortImportPath=d),Object.keys(n).length>0?n:void 0}function D(e){let t=S(u(e,`typeforge.json`)),n=C(u(e,`package.json`));return{apiRoot:t.apiRoot??n.apiRoot??`src/api`}}function ee(t,r,i){let a=u(t,r,i,`source.ts`);return e(a)?T(n(a,`utf8`)):{}}function te(t,r){let i=u(t,r,`models.ts`);if(e(i))return n(i,`utf8`)}function ne(t,n){return e(u(t,n,`query-scope.ts`))}function re(t,r){let i=u(t,r,`http.ts`);if(!e(i))return`injected`;let a=n(i,`utf8`);return/export\s+(const|function)\s+httpFetch\b/.test(a)||/export\s*\{[^}]*\bhttpFetch\b/.test(a)?`singleton`:`injected`}function ie(t,n){let a=u(t,n);return e(a)?r(a).filter(t=>{let n=s(a,t);return i(n).isDirectory()?e(s(n,`source.ts`)):!1}):[]}function ae(e){let t=``,n=0,r=e.length,i=!1;for(;n<r;){let a=e[n];if(i){t+=a,a===`\\`?(n++,n<r&&(t+=e[n])):a===`"`&&(i=!1),n++;continue}if(a===`"`){i=!0,t+=a,n++;continue}if(a===`/`&&e[n+1]===`/`){for(;n<r&&e[n]!==`
|
|
2
|
+
`;)n++;continue}if(a===`/`&&e[n+1]===`*`){for(n+=2;n<r&&(e[n]!==`*`||e[n+1]!==`/`);)n++;n+=2;continue}t+=a,n++}return t.replace(/,(\s*[}\]])/g,`$1`)}function oe(e){let t=u(e),n=c(t).root;for(;;){let e=se(t);if(e!==void 0)return e;if(t===n)return;t=o(t)}}function se(t){let r=u(t,`tsconfig.json`);if(e(r))try{let e=JSON.parse(ae(n(r,`utf8`)));if(typeof e!=`object`||!e||Array.isArray(e))return;let i=e.compilerOptions;if(typeof i!=`object`||!i||Array.isArray(i))return;let a=i,o=a.paths;if(typeof o!=`object`||!o||Array.isArray(o))return;let s=typeof a.baseUrl==`string`?a.baseUrl:`.`,c={};for(let[e,t]of Object.entries(o))Array.isArray(t)&&t.every(e=>typeof e==`string`)&&(c[e]=t);return Object.keys(c).length===0?void 0:{baseDir:t,paths:c,resolvedBaseUrl:u(t,s)}}catch{return}}function ce(e,t){for(let[n,r]of Object.entries(t.paths))for(let i of r)if(n.endsWith(`/*`)&&i.endsWith(`/*`)){let r=n.slice(0,-2),a=i.slice(0,-2),o=u(t.resolvedBaseUrl,a);if(e.startsWith(`${o}/`))return`${r}/${e.slice(o.length+1)}`;if(e===o)return r}else if(!n.includes(`*`)&&!i.includes(`*`)){let r=u(t.resolvedBaseUrl,i);if(O(e)===O(r))return n}}function O(e){return e.replace(/\.(d\.ts|ts|js)$/,``)}function k(e){return e.replace(/\.d\.ts$/,``).replace(/\.ts$/,``)}function le(e,t){let n=o(k(e)),r=k(t),i=l(n,r).replace(/\\/g,`/`);return i.startsWith(`.`)?i:`./${i}`}function A(e){let{fromAbsolutePath:t,toAbsolutePath:n,importBase:r,generatedDir:i,tsconfigPaths:a}=e;if(r!==void 0&&i!==void 0){let e=i.replace(/\/$/,``),t=k(n);if(t.startsWith(`${e}/`))return`${r}/${t.slice(e.length+1)}`;if(t===e)return r}let o=le(t,n);if(a!==void 0&&(o.match(/\.\.\//g)??[]).length>=3){let e=ce(n,a);if(e!==void 0)return e}return o}function ue(e,t,n){return s(e,t,`${n}.ts`)}function de(e){return e.split(`/`).filter(Boolean).map(e=>e.replace(/[{}]/g,``).replace(/[^a-zA-Z0-9]/g,`_`).toUpperCase()).join(`_`)}function fe(e,t=!1){return(t?e.replace(/^\/api\//,`/`):e).replace(/\{(\w+)\}/g,`:$1`)}function pe(e,t){let n=e.split(`/`).filter(Boolean).map(e=>e.replace(/[{[\]}/]/g,``).split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)).join(``);return`${t===`get`?`get`:t}${n}`}function me(e){return e.kind===`array`?`array`:e.kind===`object`?`object`:e.kind===`ref`?`ref:${e.ref??`unknown`}`:e.kind===`oneOf`||e.kind===`anyOf`||e.kind===`allOf`?e.kind:e.enum!==void 0&&e.enum.length>0?`enum`:e.kind}function he(e){let t=Number.parseInt(e,10);return!Number.isNaN(t)&&t>=200&&t<300}function ge(e){return e.enum!==void 0&&e.enum.length>0?e.enum.map(e=>JSON.stringify(e)).join(` | `):e.kind===`number`?`number`:e.kind===`boolean`?`boolean`:`string`}function _e(e){let t=new Map;for(let n of e.operations)for(let e of n.pathParams)t.has(e.name)||t.set(e.name,e.schema);return t}function ve(e,t){let n=e.get(t);return n===void 0?`string`:ge(n)}function ye(e,t){let n=e.split(`/`).filter(Boolean).map(e=>e.replace(/[{[\]}/]/g,``).split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)).join(``);return`${t.toUpperCase()}${n}`}function be(e){let t=e.requestBody?.schema;return t!==void 0&&!xe(t)}function xe(e){return e.kind===`unknown`?!0:e.kind===`object`?e.properties===void 0||Object.keys(e.properties).length===0:!1}function Se(e){return e.responses.find(e=>he(e.statusCode)&&e.schema!==void 0)?.schema}function Ce(e){return(e.match(/\{([^}]+)\}/g)??[]).map(e=>e.slice(1,-1))}function we(e,t,n){let r=e.replace(/\{([^}]+)\}/g,`[$1]`).split(`/`).filter(Boolean).join(`/`),i=ue(n.functionsDir,e,t.toUpperCase()),a=s(n.typesDir,r,t.toUpperCase());return A({fromAbsolutePath:i,generatedDir:n.generatedDir,toAbsolutePath:a,...n.importBase===void 0?{}:{importBase:n.importBase},...n.tsconfigPaths===void 0?{}:{tsconfigPaths:n.tsconfigPaths}})}function Te(e,t,n){let r=ue(t.functionsDir,e,n.toUpperCase()),i=s(t.generatedDir,`runtime`);return A({fromAbsolutePath:r,generatedDir:t.generatedDir,toAbsolutePath:i,...t.importBase===void 0?{}:{importBase:t.importBase},...t.tsconfigPaths===void 0?{}:{tsconfigPaths:t.tsconfigPaths}})}function Ee(e,t,n){let r=e.pathParams.find(e=>e.name===n);return ve(r===void 0?t:new Map([[n,r.schema]]),n)}function De(e){let t=[];for(let n of e.paths)for(let r of n.operations)t.push({content:Oe(n,r,e),relativePath:`${n.cleanPath}/${r.method.toUpperCase()}.ts`});return t}function Oe(e,t,n){let r=t.method,i=pe(e.cleanPath,r),a=de(e.path),o=ye(e.cleanPath,r),s=Ce(e.path),c=_e(e),l=`${ke(i)}Props`,u=`${ke(i)}QueryOptionsProps`,d=r!==`get`&&be(t),f=t.queryParams.length>0,p=we(e.cleanPath,r,n),m=Te(e.cleanPath,n,r),h=[`// Auto-generated from OpenAPI spec`,`// Path: ${r.toUpperCase()} ${e.path}`,`// DO NOT EDIT - This file is automatically generated`,``];h.push(`import type {`),h.push(` ${o}Response,`),f&&h.push(` ${o}Params,`),d&&h.push(` ${o}Body,`),h.push(`} from "${p}";`),h.push(``);let g=n.hasQueryScope?`, RouteTargets`:``;n.httpMode===`singleton`?h.push(`import { httpFetch, Routes${g}${n.hasQueryScope?`, getQueryScopeKey, queryOptions`:``} } from "${m}";`):h.push(`import { Routes${g}${n.hasQueryScope?`, getQueryScopeKey, queryOptions`:``} } from "${m}";`);let _=n.httpMode===`injected`?`HTTPFetch, `:``,v=f?``:`, QueryParams`;h.push(`import type { ${_}HTTPFetchConfig${v}${n.hasQueryScope?`, QueryScope`:``} } from "${m}";`),h.push(``),h.push(`export interface ${l} {`),n.httpMode===`injected`&&h.push(` http: HTTPFetch;`);for(let e of s)h.push(` ${e}: ${Ee(t,c,e)};`);if(f){let e=t.queryParams.some(e=>e.required)?``:`?`;h.push(` params${e}: ${o}Params;`)}d&&h.push(` body: ${o}Body;`);let y=f?`Omit<HTTPFetchConfig<${o}Params, ${o}Response>, "params" | "signal">`:`Omit<HTTPFetchConfig<QueryParams, ${o}Response>, "params" | "signal">`;h.push(` config?: ${y};`),h.push(` signal?: AbortSignal;`),h.push(`}`),h.push(``),r===`get`&&n.hasQueryScope&&(h.push(`export interface ${u} extends ${l} {`),h.push(` queryScope: QueryScope;`),h.push(`}`),h.push(``));let b=n.httpMode===`singleton`?`httpFetch`:`props.http`,x=[...n.httpMode===`injected`?[`http`]:[],...s.map(e=>e),...f?[`params`]:[],...d?[`body`]:[],`config`,`signal`];h.push(`export async function ${i}(props: ${l}): Promise<${o}Response> {`),x.length>0&&(h.push(` const { ${x.join(`, `)} } = props;`),h.push(``));let S=`Routes.${a}`;s.length>0&&(S=`Routes.${a}({ ${s.map(e=>`${e}`).join(`, `)} })`);let C=f?`{ ...config, params, signal }`:`{ ...config, signal }`,w=f?`<${o}Response, ${o}Params>`:`<${o}Response>`,T=`<${o}Response, ${d?`${o}Body`:`undefined`}${f?`, ${o}Params`:``}>`,E=d?`body`:`undefined`,D=f?`{ ...config, params, signal }`:`{ ...config, signal }`;switch(r){case`get`:h.push(` const { data } = await ${b}.get${w}(${S}, ${C});`);break;case`post`:h.push(` const { data } = await ${b}.post${T}(${S}, ${E}, ${D});`);break;case`put`:h.push(` const { data } = await ${b}.put${T}(${S}, ${E}, ${D});`);break;case`patch`:h.push(` const { data } = await ${b}.patch${T}(${S}, ${E}, ${D});`);break;case`delete`:{let e=C;d&&(e=f?`{ ...config, data: body, params, signal }`:`{ ...config, data: body, signal }`),h.push(` const { data } = await ${b}.delete${w}(${S}, ${e});`);break}}if(h.push(` return data;`),h.push(`}`),r===`get`&&n.hasQueryScope){let e=`${i}QueryOptions`;h.push(``),h.push(`export function ${e}(props: ${u}) {`),h.push(` const { ${f?`params, `:``}queryScope } = props;`),h.push(` return queryOptions({`),h.push(` queryKey: [RouteTargets.${a}, ...getQueryScopeKey(queryScope)${s.length>0?`, ${s.map(e=>`props.${e}`).join(`, `)}`:``}${f?`, params`:``}],`),h.push(` queryFn: ({ signal }) => ${i}({ ...props, signal }).then((data) => data),`),s.length>0&&h.push(` enabled: [${s.map(e=>`props.${e}`).join(`, `)}].every(Boolean),`),h.push(` });`),h.push(`}`)}return h.push(``),h.join(`
|
|
3
|
+
`)}function ke(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ae(e){let t=[`// Auto-generated from OpenAPI spec`,`// DO NOT EDIT - This file is automatically generated`,``,`export type { HTTPFetch, HTTPFetchConfig, QueryParams } from "../../http";`];return e.httpMode===`singleton`&&t.push(`export { httpFetch } from "../../http";`),t.push(`export { Routes, RouteTargets, buildRoute } from "./routes";`),e.hasQueryScope&&(t.push(`export type { QueryScope } from "../../query-scope";`),t.push(`export { getQueryScopeKey } from "../../query-scope";`),t.push(`export { queryOptions } from "@tanstack/react-query";`)),t.push(``),t.join(`
|
|
4
|
+
`)}function je(e){return(e.match(/\{([^}]+)\}/g)??[]).map(e=>e.slice(1,-1))}function Me(e){let t=new Set,n=[];for(let r of e.paths){let i=de(r.path);t.has(i)||(t.add(i),n.push({enumName:i,pathParamNames:je(r.path),pathParamSchemas:_e(r),routeValue:fe(r.path,e.stripApiPrefix===!0)}))}return n}function Ne(e){let t=[`export type RouteParams = {`];for(let n of e){if(n.pathParamNames.length===0){t.push(` ${n.enumName}: undefined;`);continue}t.push(` ${n.enumName}: {`);for(let e of n.pathParamNames)t.push(` ${e}: ${ve(n.pathParamSchemas,e)};`);t.push(` };`)}return t.push(`};`,`export type RouteKey = keyof RouteParams;`,``),t}function Pe(e){let t=Me(e),n=[`// Auto-generated from OpenAPI spec`,`// DO NOT EDIT - This file is automatically generated`,``,`import {`,` buildRouteFromHandlers,`,` createRouteHandlers,`,`} from "@openmirai/typeforge/routes";`,``,...Ne(t),`export enum ${e.routeEnumName} {`];for(let e of t)n.push(` ${e.enumName} = "${e.routeValue}",`);return n.push(`}`,``),e.routeEnumName!==`RouteTargets`&&(n.push(`export { ${e.routeEnumName} as RouteTargets };`),n.push(``)),n.push(`export const Routes = createRouteHandlers<RouteParams>(${e.routeEnumName});`),n.push(`export const buildRoute = buildRouteFromHandlers<RouteParams>(Routes);`,``),n.join(`
|
|
5
|
+
`)}function Fe(e,t,n,r){let i=j(e,n),a=j(t,n);if(r!==void 0)for(let[e,t]of i.entries())t.startsWith(r)&&!a.has(e)&&i.delete(e);return Pe({paths:[...new Map([...i,...a]).entries()].map(([,e])=>({cleanPath:e.replace(/:[^/]+/g,e=>`{${e.slice(1)}}`),operations:[],path:e.includes(`:`)?e.replace(/:([^/]+)/g,`{$1}`):e})),routeEnumName:n,stripApiPrefix:!1})}function j(e,t){let n=new Map,r=e.indexOf(`export enum ${t} {`);if(r===-1)return n;let i=e.slice(r),a=i.indexOf(`}`);if(a===-1)return n;let o=i.slice(0,a),s=/(\w+)\s*=\s*"([^"]+)"/g,c;for(;(c=s.exec(o))!==null;){let e=c[1],t=c[2];e!==void 0&&t!==void 0&&n.set(e,t)}return n}function M(e,t){if(e.kind!==`ref`||e.ref===void 0)return e;let n=e.ref.split(`/`).pop();return n===void 0||t[n]===void 0?{kind:`unknown`}:t[n]}function N(e,t,n=new Set){if(e.kind===`object`)return e;if(e.kind===`ref`){let r=Ie(e);if(r===void 0||n.has(r))return;let i=t[r];return i===void 0?void 0:N(i,t,new Set([...n,r]))}if(e.kind!==`allOf`||e.allOf===void 0)return;let r={},i=new Set;for(let a of e.allOf){let e=N(a,t,n);if(e?.properties===void 0)return;for(let[t,n]of Object.entries(e.properties)){let e=r[t];r[t]=e===void 0?{...n}:{required:e.required||n.required,schema:JSON.stringify(e.schema)===JSON.stringify(n.schema)?e.schema:{allOf:[e.schema,n.schema],kind:`allOf`}},n.required&&i.add(t)}}return{kind:`object`,properties:r,required:[...i]}}function Ie(e){if(e.kind===`ref`&&e.ref!==void 0)return e.ref.split(`/`).pop()}function Le(e,t){return e.kind===`ref`?M(e,t):e}function P(e,t){if(e===void 0)return;let n=N(e,t);if(n?.properties===void 0)return;let r=[];for(let[e,i]of Object.entries(n.properties))r.push({kind:e===`data`?`generic`:me(Le(i.schema,t)),name:e,required:i.required});return r.sort((e,t)=>e.name.localeCompare(t.name)),{fields:r,schema:n}}function F(e){return JSON.stringify(e.fields.map(e=>({kind:e.kind,name:e.name,required:e.required})))}function Re(e,t,n){let r=P(e,t);return r!==void 0&&F(r)===F(n)}const ze=new Set([`error`,`message`,`requestId`,`success`,`timestamp`]);function I(e){let t=new Set(e.fields.map(e=>e.name));return t.has(`data`)?!0:t.has(`success`)?[...t].every(e=>ze.has(e)):!1}function Be(e,t){let n=P(e,t);return n!==void 0&&I(n)}function Ve(e){let t=[];for(let n of e.paths)for(let r of n.operations){let i=r.responses.find(e=>he(e.statusCode)&&e.schema!==void 0);if(i?.schema===void 0)continue;let a=P(i.schema,e.components.schemas);a!==void 0&&t.push({method:r.method.toUpperCase(),path:n.path,shape:a})}return t}function L(e){let t=Ve(e),n=new Map;for(let e of t){let t=F(e.shape),r=n.get(t)??[];r.push(e),n.set(t,r)}if(t.length===0)return{groups:n,mode:`raw`,operations:t};if(n.size===1){let e=t[0]?.shape;return e!==void 0&&I(e)?{groups:n,mode:`shared`,operations:t,shared:e}:{groups:n,mode:`raw`,operations:t}}let r=[...n.entries()].filter(([,e])=>{let t=e[0];return t!==void 0&&I(t.shape)});if(r.length===0)return{groups:n,mode:`raw`,operations:t};if(r.length===1){let e=r[0],i=e?.[1][0];if(e!==void 0&&e[1].length===t.length&&i!==void 0)return{groups:n,mode:`shared`,operations:t,shared:i.shape}}return{groups:n,mode:`mixed`,operations:t}}function He(e){if(e.shared!==void 0)return e.shared;if(e.mode!==`mixed`)return;let t,n=0;for(let r of e.groups.values()){let e=r[0];e===void 0||!I(e.shape)||e.shape.fields.some(e=>e.name===`data`)&&r.length>n&&(n=r.length,t=e.shape)}return t}function Ue(e){let t=e.match(/export\s+interface\s+BaseResponse\s*<[^>]*>\s*\{([\s\S]*?)\}/);if(t===null){let t=e.match(/export\s+interface\s+BaseResponse\s*\{([\s\S]*?)\}/);return t===null?void 0:We(t[1])}return We(t[1])}function We(e){let t=[],n=/^\s*(\w+)(\?)?:\s*([^;]+);/gm,r;for(;(r=n.exec(e))!==null;){let[,e,n,i]=r;e!==void 0&&i!==void 0&&t.push({kind:i.trim().replace(/\s+/g,` `),name:e,required:n===void 0})}return t.sort((e,t)=>e.name.localeCompare(t.name)),{fields:t,sourcePath:`models.ts`}}function Ge(e,t){let n=[],r=new Map(e.fields.filter(e=>e.name!==`data`).map(e=>[e.name,e])),i=new Map(t.fields.filter(e=>e.name!==`data`&&e.name!==`T`).map(e=>[e.name,e]));for(let[e,t]of r.entries()){let r=i.get(e);if(r===void 0){n.push({field:e,issue:`missing`,spec:t});continue}t.required!==r.required&&n.push({field:e,issue:`required-changed`,spec:t,user:r}),t.kind!==r.kind&&e!==`data`&&n.push({field:e,issue:`type-changed`,spec:t,user:r})}for(let[e,t]of i.entries())r.has(e)||n.push({field:e,issue:`extra`,user:t});return n}function Ke(e,t,n){return t===void 0?`unknown`:e.kind===`generic`?n:e.kind}function R(e,t=`T`){let n=[`export interface BaseResponse<${t}> {`];for(let r of e.fields){if(r.name===`data`){n.push(` data?: ${t};`);continue}let i=r.required?``:`?`,a=e.schema.properties?.[r.name],o=Ke(r,a,t);n.push(` ${r.name}${i}: ${o};`)}return n.push(`}`),n.join(`
|
|
6
|
+
`)}const qe=[`get`,`post`,`put`,`patch`,`delete`];function Je(e){return v(e)?e.filter(_):[]}function Ye(e){return e.split(`/`).at(-1)??e}function Xe(e){return e.replace(/^\//,``).replace(/\{([^}]+)\}/g,`[$1]`)}function z(e){if(!_(e))return{kind:`unknown`};if(typeof e.$ref==`string`)return{kind:`ref`,ref:Ye(e.$ref)};if(v(e.oneOf)&&e.oneOf.length>0)return{kind:`oneOf`,oneOf:e.oneOf.map(z)};if(v(e.anyOf)&&e.anyOf.length>0)return{anyOf:e.anyOf.map(z),kind:`anyOf`};if(v(e.allOf)&&e.allOf.length>0)return{allOf:e.allOf.map(z),kind:`allOf`};let t=typeof e.type==`string`?e.type:void 0,n=e.nullable===!0;if(t===`array`){let t={kind:`array`};return e.items!==void 0&&(t.items=z(e.items)),n&&(t.nullable=!0),t}if(t===`object`||t===void 0&&(_(e.properties)||e.additionalProperties!==void 0))return Ze(e,n);if(t===`integer`||t===`number`){let t={kind:`number`};return typeof e.format==`string`&&(t.format=e.format),n&&(t.nullable=!0),Array.isArray(e.enum)&&(t.enum=x(e.enum)),typeof e[`x-map-key-ref`]==`string`&&(t[`x-map-key-ref`]=e[`x-map-key-ref`]),t}if(t===`string`){let t={kind:`string`};return typeof e.format==`string`&&(t.format=e.format),n&&(t.nullable=!0),Array.isArray(e.enum)&&(t.enum=x(e.enum)),typeof e[`x-map-key-ref`]==`string`&&(t[`x-map-key-ref`]=e[`x-map-key-ref`]),t}if(t===`boolean`){let e={kind:`boolean`};return n&&(e.nullable=!0),e}return t===`null`?{kind:`null`}:{kind:`unknown`}}function Ze(e,t){let n={kind:`object`};if(t&&(n.nullable=!0),_(e.properties)){let t=v(e.required)?e.required.filter(e=>typeof e==`string`):[],r={};for(let[n,i]of Object.entries(e.properties))r[n]={required:t.includes(n),schema:z(i)};n.properties=r,t.length>0&&(n.required=t)}return e.additionalProperties!==void 0&&(n.additionalProperties=typeof e.additionalProperties==`boolean`?e.additionalProperties:z(e.additionalProperties)),typeof e[`x-map-key-ref`]==`string`&&(n[`x-map-key-ref`]=e[`x-map-key-ref`]),n}function Qe(e){if(_(e.schema))return z(e.schema);let t={};return e.enum!==void 0&&(t.enum=e.enum),typeof e.format==`string`&&(t.format=e.format),typeof e.type==`string`&&(t.type=e.type),z(t)}function $e(e,t){let n={},r=_(e.definitions)?e.definitions:{};for(let[e,t]of Object.entries(r))n[e]=z(t);let i=tt(e,`swagger2`,t);return{components:{schemas:n},key:``,paths:i}}function et(e,t){let n={},r=_(e.components)?e.components:{},i=_(r.schemas)?r.schemas:{};for(let[e,t]of Object.entries(i))n[e]=z(t);let a=tt(e,`openapi3`,t);return{components:{schemas:n},key:``,paths:a}}function tt(e,t,n){let r=[],i=e.paths;if(!_(i))return r;for(let[e,a]of Object.entries(i)){if(n.pathPrefix!==void 0&&!e.startsWith(n.pathPrefix)||n.ignorePaths?.includes(e)||!_(a))continue;let i=Je(a.parameters),o=[];for(let e of qe){let n=a[e];if(!_(n))continue;let r=at(e,n,i,t);o.push(r)}o.length>0&&r.push({cleanPath:Xe(e),operations:o,path:e})}return r}function nt(e,t){let n=new Map;for(let t of e)typeof t.name==`string`&&n.set(t.name,t);for(let e of t)typeof e.name==`string`&&n.set(e.name,e);return[...n.values()]}function rt(e){return _(e.schema)?z(e.schema):{kind:`unknown`}}function it(e,t){return t===`openapi3`?rt(e):Qe(e)}function at(e,t,n,r){let i=nt(n,Je(t.parameters)),a=[],o=[];for(let e of i)typeof e.name==`string`&&(e.in===`path`?a.push({name:e.name,schema:it(e,r)}):e.in===`query`&&o.push({name:e.name,required:e.required===!0,schema:it(e,r)}));let s=r===`swagger2`?ot(i):st(t),c={method:e,pathParams:a,queryParams:o,responses:ct(t,r)};return typeof t.operationId==`string`&&(c.operationId=t.operationId),s!==void 0&&(c.requestBody=s),c}function ot(e){let t=e.find(e=>e.in===`body`);if(t===void 0)return;let n=_(t.schema)?z(t.schema):{kind:`unknown`};return{required:t.required===!0,schema:n}}function st(e){if(!_(e.requestBody))return;let t=e.requestBody,n=_(t.content)?t.content:{},r=_(n[`application/json`])?n[`application/json`]:{},i=_(r.schema)?z(r.schema):{kind:`unknown`};return{required:t.required===!0,schema:i}}function ct(e,t){let n=[];if(!_(e.responses))return n;for(let[r,i]of Object.entries(e.responses)){if(!_(i)){n.push({statusCode:r});continue}let e={statusCode:r};if(t===`swagger2`)_(i.schema)&&(e.schema=z(i.schema));else{let t=_(i.content)?i.content:{},n=_(t[`application/json`])?t[`application/json`]:{};_(n.schema)&&(e.schema=z(n.schema))}n.push(e)}return n}function lt(e,t){if(!_(e))return{components:{schemas:{}},key:``,paths:[]};let n={};return t.pathPrefix!==void 0&&(n.pathPrefix=t.pathPrefix),t.ignorePaths!==void 0&&(n.ignorePaths=t.ignorePaths),e.swagger===`2.0`?$e(e,n):typeof e.openapi==`string`&&e.openapi.startsWith(`3.`)?et(e,n):{components:{schemas:{}},key:``,paths:[]}}function ut(){return process.env.NO_COLOR===void 0&&process.stdout.isTTY===!0}function B(e,t){return ut()?e(t):t}function V(e){return B(d.bold,e)}function H(e){return B(d.red,e)}function U(e){return B(d.dim,e)}function W(e){return B(d.cyan,e)}function G(e){return B(d.yellow,e)}function dt(e){return B(d.white,e)}var K=class extends Error{cycle;schemaPath;sourceKey;constructor(e,t,n){super(ft(e,t,n)),this.name=`RecursiveRefError`,this.cycle=t,this.schemaPath=n,this.sourceKey=e}};function ft(e,t,n){return[V(H(`typeforge: recursive schema reference in source "${e}"`)),``,V(`Cycle:`),` ${t.join(` → `)}`,``,V(`At:`),U(` ${n}`),``,V(`Fix:`),` • Add a known-type override in known-types.ts for this shape, or`,` • Simplify the OpenAPI schema to remove the circular reference`,W(` • typeforge generate --source ${e} --spec <path>`)].join(`
|
|
7
|
+
`)}function pt(e,t){let n=e.kind===`ref`?M(e,t):e;return n.kind===`object`?n:void 0}function mt(e){return e.slice().toSorted((e,t)=>e.localeCompare(t))}function ht(e,t,n){let r=pt(e,t);if(r?.properties===void 0)return!1;let i=mt(Object.keys(r.properties)),a=mt(n);return i.length===a.length&&i.every((e,t)=>e===a[t])}function gt(e,t,n){let r=pt(e,t);if(r?.properties===void 0)return!1;let i=Object.keys(r.properties);if(n.maxPropertyCount!==void 0&&i.length>n.maxPropertyCount||n.exactProperties!==void 0&&!ht(e,t,n.exactProperties))return!1;if(n.requireProperties!==void 0){for(let e of n.requireProperties)if(!(e in r.properties))return!1}if(n.excludeProperties!==void 0){for(let e of n.excludeProperties)if(e in r.properties)return!1}return n.exactProperties!==void 0||n.requireProperties!==void 0}function q(e){if(e===void 0)return;let t=[...e.matchAll(/["'`]([^"'`]+)["'`]/g)].map(e=>e[1]);return t.length>0?t:void 0}function _t(e){let t=[],n=e.matchAll(/\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g);for(let e of n){let n=e[1];if(n===void 0||!n.includes(`typeName`))continue;let r=n.match(/name:\s*["'`]([^"'`]+)["'`]/)?.[1],i=n.match(/typeName:\s*["'`]([^"'`]+)["'`]/)?.[1];if(r===void 0||i===void 0)continue;let a={name:r,typeName:i},o=n.match(/importPath:\s*(null|["'`]([^"'`]*)["'`])/)?.[2];n.includes(`importPath: null`)?a.importPath=null:o!==void 0&&(a.importPath=o);let s=q(n.match(/exactProperties:\s*\[([\s\S]*?)\]/)?.[1]);s!==void 0&&(a.exactProperties=s);let c=q(n.match(/requireProperties:\s*\[([\s\S]*?)\]/)?.[1]);c!==void 0&&(a.requireProperties=c);let l=q(n.match(/excludeProperties:\s*\[([\s\S]*?)\]/)?.[1]);l!==void 0&&(a.excludeProperties=l);let u=n.match(/maxPropertyCount:\s*(\d+)/)?.[1];u!==void 0&&(a.maxPropertyCount=Number.parseInt(u,10)),t.push(a)}return t}function vt(t,r){let i=u(t,r,`known-types.ts`);return e(i)?_t(n(i,`utf8`)).map(e=>({importPath:e.importPath??null,matcher:(t,n)=>gt(t,n,e),name:e.name,typeName:e.typeName})):[]}function yt(e,t){return vt(e,t)}function bt(e,t,n){for(let r of n)if(r.matcher(e,t))return{importPath:r.importPath,rule:r,typeName:r.typeName}}function xt(e){return` `.repeat(e)}function St(e){return typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):e===null?`null`:`unknown`}function Ct(e){return[...new Set(e.map(St))].join(` | `)}function J(e,t){return t.nullable===!0?`${e} | null`:e}function wt(e){return decodeURIComponent(e.replace(/~1/g,`/`).replace(/~0/g,`~`))}function Tt(e,t){if(Array.isArray(e)){let n=Number(t);return!Number.isInteger(n)||n<0||n>=e.length?void 0:e[n]}if(_(e)&&t in e)return e[t]}function Et(e,t){if(!t.startsWith(`#/`))return;let n=e;for(let e of t.slice(2).split(`/`).map(wt))if(n=n===void 0?void 0:Tt(n,e),n===void 0)return;return z(n)}function Dt(e,t){let n=e[`x-map-key-ref`];if(n===void 0)return`string`;if(t.rawSpec!==void 0){let e=Et(t.rawSpec,n);if(e!==void 0)return X(e,{...t,depth:(t.depth??0)+1})}let r=n.split(`/`).pop();return r!==void 0&&t.components[r]!==void 0?X(t.components[r],{...t,depth:(t.depth??0)+1}):`string`}function Ot(e,t){let n=[...e.refStack??[],t];throw new K(e.sourceKey??`unknown`,n,e.schemaPath??t)}function Y(e,t){let n=e.schemaPath??`schema`;return{...e,schemaPath:`${n}.${t}`}}function X(e,t){let n=t.depth??0,r=t.maxDepth??50;if(n>r)throw new K(t.sourceKey??`unknown`,t.refStack??[],`${t.schemaPath??`schema`} (max depth ${r} exceeded)`);let i={...t,depth:n+1},a=t.knownTypes??[];if(a.length>0){let n=bt(e,t.components,a);if(n!==void 0)return t.knownTypeImports!==void 0&&!t.knownTypeImports.has(n.typeName)&&t.knownTypeImports.set(n.typeName,n.importPath),J(n.typeName,e)}if(e.enum!==void 0&&e.enum.length>0)return J(Ct(e.enum),e);if(e.kind===`ref`){let n=Ie(e);if(n===void 0)return`unknown`;let r=t.visitedRefs??new Set,a=t.refStack??[];return r.has(n)&&Ot(t,n),X(M(e,t.components),{...i,refStack:[...a,n],visitedRefs:new Set([...r,n])})}switch(e.kind){case`string`:return J(`string`,e);case`number`:return J(`number`,e);case`boolean`:return J(`boolean`,e);case`null`:return`null`;case`unknown`:return`unknown`;case`array`:{let t=e.items===void 0?`unknown`:X(e.items,Y(i,`[]`));return J(t===`TiptapDocument`?`TiptapDocument`:`${t.includes(` | `)?`(${t})`:t}[]`,e)}case`object`:{if(e.properties===void 0)return e.additionalProperties===!0?J(`Record<string, unknown>`,e):typeof e.additionalProperties==`object`&&e.additionalProperties!==null?J(`Record<${t.resolveMapKeyRefs!==!1&&e[`x-map-key-ref`]!==void 0?Dt(e,t):`string`}, ${X(e.additionalProperties,Y(i,`value`))}>`,e):J(`Record<string, unknown>`,e);let r=[`{`];for(let[t,a]of Object.entries(e.properties)){let e=a.required?``:`?`,o=X(a.schema,Y(i,t));r.push(`${xt(n+1)}${t}${e}: ${o};`)}return r.push(`${xt(n)}}`),J(r.join(`
|
|
8
|
+
`),e)}case`oneOf`:case`anyOf`:{let t=e[e.kind];if(t===void 0||t.length===0)return`unknown`;let n=t.map(e=>X(e,i)),r=n.filter(e=>e!==`Record<string, unknown>`);return J((r.length>0?r:n).join(` | `),e)}case`allOf`:{let t=e.allOf;return t===void 0||t.length===0?`unknown`:J(t.map(e=>X(e,i)).join(` & `),e)}default:return`unknown`}}function Z(e,t,n){let r={components:e.source.components.schemas,knownTypeImports:n,knownTypes:e.knownTypes??[],maxDepth:e.maxRenderDepth??50,resolveMapKeyRefs:e.resolveMapKeyRefs!==!1,schemaPath:t};return e.sourceKey!==void 0&&(r.sourceKey=e.sourceKey),e.rawSpec!==void 0&&(r.rawSpec=e.rawSpec),r}function kt(e){let t=[],n=new Map;for(let[t,r]of e.entries()){let e=n.get(r)??[];e.push(t),n.set(r,e)}for(let[e,r]of n.entries())e!==null&&t.push(`import type { ${r.join(`, `)} } from "${e}";`);return t}function At(e,t,n,r){if(t.queryParams.length===0)return;let i=n.queryExtends,a=i?.page??`page`,o=i?.limit??`limit`,s=i?.sortBy??`sortBy`,c=i?.sortOrder??`sortOrder`,l=t.queryParams.some(e=>e.name===a),u=t.queryParams.some(e=>e.name===o),d=t.queryParams.find(e=>e.name===s),f=t.queryParams.some(e=>e.name===c),p=l&&u,m=d!==void 0&&f,h=new Set([p?a:void 0,p?o:void 0,m?s:void 0,m?c:void 0].filter(e=>e!==void 0)),g=t.queryParams.filter(e=>!h.has(e.name)),_=[];if(m&&d!==void 0&&d.schema.enum!==void 0&&d.schema.enum.length>0&&i?.sortTypeName!==void 0){let e=[...new Set(d.schema.enum.map(e=>JSON.stringify(e)))].join(` | `);_.push(`${i.sortTypeName}<${e}>`),i.sortImportPath!==void 0&&r.set(i.sortTypeName,i.sortImportPath)}if(p&&i?.paginationTypeName!==void 0&&(_.push(i.paginationTypeName),i.paginationImportPath!==void 0&&r.set(i.paginationTypeName,i.paginationImportPath)),_.length>0&&g.length===0)return`export type ${e}Params = ${_.join(` & `)};`;let v=[];_.length>0?v.push(`export interface ${e}Params extends ${_.join(`, `)} {`):v.push(`export interface ${e}Params {`);for(let t of g)jt(t,v,n,r,e);return v.push(`}`),v.join(`
|
|
9
|
+
`)}function jt(e,t,n,r,i){let a=e.required?``:`?`,o=X(e.schema,Z(n,`${i}Params.${e.name}`,r));t.push(` ${e.name}${a}: ${o};`)}function Mt(e,t,n,r){if(!be(t)||t.requestBody===void 0)return;let i=X(t.requestBody.schema,Z(n,`${e}Body`,r));return i.startsWith(`{`)?`export interface ${e}Body ${i}`:`export type ${e}Body = ${i};`}function Nt(e,t){return N(e,t)??e}function Pt(e,t,n,r,i,a){let o=Se(t);if(o===void 0)return`export type ${e}Response = unknown;`;let s=Nt(o,n.source.components.schemas),c=s.kind===`object`&&s.properties?.data!==void 0?s.properties.data.schema:void 0,l=s.kind===`object`&&s.properties?.success!==void 0&&Be(o,n.source.components.schemas);return n.unwrapResponseData===!0&&l?c===void 0?`export type ${e}Response = null;`:`export type ${e}Response = ${X(c,Z(n,`${e}Response.data`,i))};`:c===void 0?`export type ${e}Response = ${X(o,Z(n,`${e}Response`,i))};`:r===`shared`||r===`mixed`&&n.sharedEnvelope!==void 0&&Re(o,n.source.components.schemas,n.sharedEnvelope)?`export type ${e}Response = import("${a}").BaseResponse<${X(c,Z(n,`${e}Response.data`,i))}> & Omit<${X(o,Z(n,`${e}Response`,i))}, "data">;`:`export type ${e}Response = ${X(o,Z(n,`${e}Response`,i))};`}function Ft(e){let t=[];for(let n of e.source.paths)for(let r of n.operations){let i=ye(n.cleanPath,r.method),a=new Map,o=[`// Auto-generated from OpenAPI spec`,`// Path: ${r.method.toUpperCase()} ${n.path}`,`// DO NOT EDIT - This file is automatically generated`,``],s=At(i,r,e,a);s!==void 0&&o.push(s,``);let c=Mt(i,r,e,a);c!==void 0&&o.push(c,``);let l=A({fromAbsolutePath:`${e.typesDir}/${n.cleanPath}/${r.method.toUpperCase()}.d.ts`,toAbsolutePath:e.baseFile.replace(/\.d\.ts$/,``).replace(/\.ts$/,``),...e.tsconfigPaths===void 0?{}:{tsconfigPaths:e.tsconfigPaths}});o.push(Pt(i,r,e,e.envelopeMode,a,l));let u=kt(a),d=[...u,...u.length>0?[``]:[],...o].join(`
|
|
10
|
+
`).trimEnd();t.push({content:`${d}\n`,relativePath:`${n.cleanPath}/${r.method.toUpperCase()}.d.ts`})}return t}function It(e){return[`// Auto-generated from OpenAPI spec`,`// DO NOT EDIT - This file is automatically generated`,``,R(e),``].join(`
|
|
11
|
+
`)}function Lt(e,t,n,r,i,a=[]){let o=[V(H(`typeforge: base response mismatch in source "${e}"`)),``];o.push(V(`Spec envelope:`));for(let e of t.fields)o.push(` ${e.name}${e.required?``:`?`}: ${e.kind}`);o.push(``),o.push(V(`Your ${n} BaseResponse:`)),o.push(r),o.push(``),o.push(V(`Conflicts:`));for(let e of i)e.issue===`missing`?o.push(G(` • ${e.field}: present in spec, missing in your type`)):e.issue===`extra`?o.push(G(` • ${e.field}: extra field in your type`)):e.issue===`type-changed`?o.push(G(` • ${e.field}: spec is ${e.spec?.kind}, your type is ${e.user?.kind}`)):o.push(G(` • ${e.field}: required/optional mismatch`));if(a.length>0){o.push(``),o.push(U(`Also not matching the spec envelope:`));for(let e of a.slice(0,3))o.push(U(` ${e.method} ${e.path}`))}return o.push(``),o.push(V(`Fix:`)),o.push(` • Update models.ts to match the spec, or`),o.push(W(` • typeforge generate --source ${e} --spec <path> --accept-base`)),o.join(`
|
|
12
|
+
`)}function Rt(e,t,n,r){let i=`${` `.repeat(e+1)}:${`${` `.repeat(Math.max(n-t,1))}|`}`;return r===void 0?i:`${i}\n${` `.repeat(e+n+3)}\`${U(`-- ${r}`)}`}function zt(e){return[U(` ,-[${e.file}:${e.line}:${e.column}]`),dt(`${String(e.line).padStart(4,` `)} | ${e.source}`),Rt(7+e.highlightStart,e.highlightStart,e.highlightEnd,e.label),U(" `----")].join(`
|
|
13
|
+
`)}function Bt(e){let t=[` ${(e.severity??`error`)===`error`?H(`×`):G(`!`)} ${V(`${e.code}`)}: ${e.message}`];return e.snippet!==void 0&&t.push(zt(e.snippet)),e.help!==void 0&&t.push(` ${U(`help:`)} ${e.help}`),t.join(`
|
|
14
|
+
`)}function Vt(e,t){return[V(e),...t.map(e=>` ${W(e)}`)].join(`
|
|
15
|
+
`)}async function Q(e){let t;switch(e.kind){case`file`:t=u(e.path);break;case`local-override`:t=u(e.path);break;case`env`:{let n=process.env[e.varName];if(n===void 0)throw Error(`Environment variable ${e.varName} is not set`);t=u(n);break}}return y(await p(t,`utf8`))}function Ht(t,r){if(r.specFlag!==void 0)return{kind:`file`,path:r.specFlag};let i=`OPENAPI_SPEC_${t.toUpperCase().replace(/-/g,`_`)}`;if(process.env[i]!==void 0)return{kind:`env`,varName:i};if(r.sourceConfigSpec!==void 0)return{kind:`file`,path:r.sourceConfigSpec};let a=r.localOverridePath??`./typeforge.local.json`;if(e(a))try{let e=b(n(a,`utf8`))[t];if(typeof e==`string`)return{kind:`local-override`,path:e}}catch{}if(r.snapshotPath!==void 0&&e(r.snapshotPath))return{kind:`file`,path:r.snapshotPath};throw Error(Wt(t,i,r,a))}function Ut(t){return t===void 0?U(`not configured`):e(t)?U(`found at ${t}`):U(`not found at ${t}`)}function Wt(t,n,r,i){let a=r.specFlag===void 0?U(`not provided`):r.specFlag,o=U(`not set`),s=r.sourceConfigSpec===void 0?U(`not set in source.ts`):r.sourceConfigSpec,c=e(i)?U(`found at ${i} (no entry for "${t}")`):U(`not found at ${i}`),{snapshotPath:l}=r,u=Ut(l),d=[` --spec flag: ${a}`,` ${n} env: ${o}`,` source.ts spec: ${s}`,` local override: ${c}`,` committed snapshot: ${u}`].join(`
|
|
16
|
+
`),f=[`typeforge generate --source ${t} --spec ./path/to/swagger.json`,`export ${n}=./path/to/swagger.json`];return[Bt({code:`typeforge/spec-not-found`,help:`Provide one of the resolution paths above, for example with --spec or an env var.`,message:`No OpenAPI spec found for source "${t}"`,severity:`error`}),``,V(`Tried:`),d,``,Vt(`Fix:`,f)].join(`
|
|
17
|
+
`)}async function Gt(e,t=!1){let n=[];for(let r of e){await f(o(r.path),{recursive:!0});let e;try{e=await p(r.path,`utf8`)}catch{e=void 0}e!==r.content&&(n.push(r.path),t||await m(r.path,r.content,`utf8`))}return{changed:n,written:t?0:n.length}}function Kt(e,t){let n=D(e).apiRoot??`src/api`,r=ee(e,n,t),i=u(e,n,t),a=s(i,`generated`),c=r.functionsDir===void 0?s(a,`functions`):u(e,r.functionsDir),l=r.typesDir===void 0?s(a,`types`):u(e,r.typesDir);return{apiRoot:n,baseFile:r.typesDir===void 0?s(a,`base.ts`):s(o(l),`base.d.ts`),cwd:e,functionsDir:c,generatedDir:a,hasQueryScope:r.tanstackQuery===!0&&ne(e,n),httpMode:re(e,n),routesFile:s(a,`routes.ts`),snapshotPath:s(i,`spec.json`),sourceConfig:r,sourceDir:i,sourceKey:t,typesDir:l}}function qt(e,t,n){let r=L(t);if(r.mode!==`shared`||r.shared===void 0)return{mode:r.mode};let i=te(e.cwd,e.apiRoot);if(i===void 0)return{mode:r.mode};let a=Ue(i);if(a===void 0)return{mode:r.mode};let o=Ge(r.shared,a);if(o.length===0||n)return{mode:r.mode};let s=a.fields.map(e=>` ${e.name}${e.required?``:`?`}: ${e.kind};`).join(`
|
|
18
|
+
`);return{error:Lt(e.sourceKey,r.shared,a.sourcePath,s,o),mode:r.mode}}function Jt(t,r,i){let o=u(t,r,`models.ts`);if(!e(o))return;let s=n(o,`utf8`).replace(/export\s+interface\s+BaseResponse\s*<[^>]*>\s*\{[\s\S]*?\}/,i);a(o,s,`utf8`)}async function Yt(t){let r=t.cwd??process.cwd(),i=Kt(r,t.sourceKey),a={snapshotPath:i.snapshotPath};t.specFlag!==void 0&&(a.specFlag=t.specFlag),i.sourceConfig.spec!==void 0&&(a.sourceConfigSpec=i.sourceConfig.spec);let o=await Q(Ht(t.sourceKey,a)),c={};i.sourceConfig.ignorePaths!==void 0&&(c.ignorePaths=i.sourceConfig.ignorePaths),i.sourceConfig.pathPrefix!==void 0&&(c.pathPrefix=i.sourceConfig.pathPrefix);let l=lt(o,c);l.key=t.sourceKey;let u=qt(i,l,t.acceptBase===!0);if(u.error!==void 0)throw Error(u.error);let d=L(l),f=[],p=He(d);p!==void 0&&(f.push({content:It(p),path:i.baseFile}),t.acceptBase===!0&&Jt(r,i.apiRoot,R(p)));let m={baseFile:i.baseFile,envelopeMode:d.mode,knownTypes:yt(r,i.apiRoot),source:l,sourceKey:t.sourceKey,typesDir:i.typesDir};i.sourceConfig.resolveMapKeyRefs!==void 0&&(m.resolveMapKeyRefs=i.sourceConfig.resolveMapKeyRefs),i.sourceConfig.unwrapResponseData!==void 0&&(m.unwrapResponseData=i.sourceConfig.unwrapResponseData),p!==void 0&&(m.sharedEnvelope=p);let h=oe(i.typesDir);h!==void 0&&(m.tsconfigPaths=h),i.sourceConfig.maxRenderDepth!==void 0&&(m.maxRenderDepth=i.sourceConfig.maxRenderDepth),i.sourceConfig.queryExtends!==void 0&&(m.queryExtends=i.sourceConfig.queryExtends),_(o)&&(m.rawSpec=o);let g=Ft(m);for(let e of g)f.push({content:e.content,path:s(i.typesDir,e.relativePath)});let v=i.sourceConfig.routeEnumName??`RouteTargets`,y={paths:l.paths,routeEnumName:v};i.sourceConfig.stripApiPrefix===!0&&(y.stripApiPrefix=!0);let b=Pe(y),x=b;i.sourceConfig.generationMode===`merge`&&e(i.routesFile)&&(x=Fe(n(i.routesFile,`utf8`),b,v,i.sourceConfig.pathPrefix)),f.push({content:x,path:i.routesFile}),f.push({content:Ae({hasQueryScope:i.hasQueryScope,httpMode:i.httpMode}),path:s(i.generatedDir,`runtime.ts`)});let S=oe(i.functionsDir),C={functionsDir:i.functionsDir,generatedDir:i.generatedDir,hasQueryScope:i.hasQueryScope,httpMode:i.httpMode,paths:l.paths,routeEnumName:v,typesDir:i.typesDir};i.sourceConfig.importBase===void 0?S!==void 0&&(C.tsconfigPaths=S):C.importBase=i.sourceConfig.importBase;let w=De(C);for(let e of w)f.push({content:e.content,path:s(i.functionsDir,e.relativePath)});return{changed:(await Gt(f,t.check===!0)).changed,check:t.check===!0,files:f.length,sourceKey:t.sourceKey}}function Xt(e){return e===`packages`?`packages/utils/src/api`:`src/api`}function $(n,r){return e(n)?`skipped`:(t(s(n,`..`),{recursive:!0}),a(n,r,`utf8`),`created`)}function Zt(n){let r=n.cwd??process.cwd(),i=n.layout??`monolith`,o=u(r,`typeforge.json`),c=D(r),l=e(o)?c.apiRoot??`src/api`:Xt(i),d=u(r,l),f=s(d,n.sourceKey),p=`import type { HTTPFetch, HTTPFetchConfig } from "@openmirai/typeforge/http";
|
|
19
|
+
|
|
20
|
+
export type { HTTPFetch, HTTPFetchConfig };
|
|
21
|
+
|
|
22
|
+
export const httpFetch: HTTPFetch = {
|
|
23
|
+
delete: async <TResponse>(
|
|
24
|
+
_route: string,
|
|
25
|
+
_config?: HTTPFetchConfig
|
|
26
|
+
): Promise<{ data: TResponse }> => {
|
|
27
|
+
throw new Error("Implement httpFetch.delete");
|
|
28
|
+
},
|
|
29
|
+
get: async <TResponse>(
|
|
30
|
+
_route: string,
|
|
31
|
+
_config?: HTTPFetchConfig
|
|
32
|
+
): Promise<{ data: TResponse }> => {
|
|
33
|
+
throw new Error("Implement httpFetch.get");
|
|
34
|
+
},
|
|
35
|
+
patch: async <TResponse, TBody = unknown>(
|
|
36
|
+
_route: string,
|
|
37
|
+
_body: TBody,
|
|
38
|
+
_config?: HTTPFetchConfig
|
|
39
|
+
): Promise<{ data: TResponse }> => {
|
|
40
|
+
throw new Error("Implement httpFetch.patch");
|
|
41
|
+
},
|
|
42
|
+
post: async <TResponse, TBody = unknown>(
|
|
43
|
+
_route: string,
|
|
44
|
+
_body: TBody,
|
|
45
|
+
_config?: HTTPFetchConfig
|
|
46
|
+
): Promise<{ data: TResponse }> => {
|
|
47
|
+
throw new Error("Implement httpFetch.post");
|
|
48
|
+
},
|
|
49
|
+
put: async <TResponse, TBody = unknown>(
|
|
50
|
+
_route: string,
|
|
51
|
+
_body: TBody,
|
|
52
|
+
_config?: HTTPFetchConfig
|
|
53
|
+
): Promise<{ data: TResponse }> => {
|
|
54
|
+
throw new Error("Implement httpFetch.put");
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
`;n.client===`axios`?p=`import axiosBase from "axios";
|
|
58
|
+
import { createAxiosAdapter } from "@openmirai/typeforge/adapters/axios";
|
|
59
|
+
|
|
60
|
+
const axios = axiosBase.create({
|
|
61
|
+
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
axios.interceptors.request.use(
|
|
65
|
+
async (config) => {
|
|
66
|
+
// Add auth headers, tracing, or Content-Type defaults here.
|
|
67
|
+
return config;
|
|
68
|
+
},
|
|
69
|
+
(error) => Promise.reject(error),
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
axios.interceptors.response.use(
|
|
73
|
+
(response) => response,
|
|
74
|
+
(error) => Promise.reject(error),
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
export const httpFetch = createAxiosAdapter(axios);
|
|
78
|
+
export { axios };
|
|
79
|
+
export type { HTTPFetch, HTTPFetchConfig } from "@openmirai/typeforge/adapters/axios";
|
|
80
|
+
`:n.client===`fetch`&&(p=`import { createFetchAdapter } from "@openmirai/typeforge/adapters/fetch";
|
|
81
|
+
|
|
82
|
+
export const httpFetch = createFetchAdapter({
|
|
83
|
+
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
export type { HTTPFetch, HTTPFetchConfig } from "@openmirai/typeforge/adapters/fetch";
|
|
87
|
+
`);let m=[],h=[],g=s(d,`http.ts`);$(g,p)===`created`?m.push(g):h.push(g);let _=s(f,`source.ts`);$(_,`import { defineSourceConfig } from "@openmirai/typeforge";
|
|
88
|
+
|
|
89
|
+
export default defineSourceConfig({
|
|
90
|
+
// Path to the OpenAPI spec file, relative to the project root.
|
|
91
|
+
// Set this so \`typeforge generate --source <key>\` (or --all) works
|
|
92
|
+
// without a per-invocation --spec flag.
|
|
93
|
+
// spec: "./specs/acme.json",
|
|
94
|
+
pathPrefix: "/api/acme/v3",
|
|
95
|
+
stripApiPrefix: true,
|
|
96
|
+
routeEnumName: "RouteTargets",
|
|
97
|
+
generationMode: "authoritative",
|
|
98
|
+
naming: "path",
|
|
99
|
+
ignorePaths: [],
|
|
100
|
+
maxRenderDepth: 50,
|
|
101
|
+
resolveMapKeyRefs: true,
|
|
102
|
+
queryExtends: {
|
|
103
|
+
page: "page",
|
|
104
|
+
limit: "limit",
|
|
105
|
+
sortBy: "sortBy",
|
|
106
|
+
sortOrder: "sortOrder",
|
|
107
|
+
paginationTypeName: "OffsetLimitQuery",
|
|
108
|
+
paginationImportPath: "./pagination",
|
|
109
|
+
sortTypeName: "SortParams",
|
|
110
|
+
sortImportPath: "./pagination",
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
`)===`created`?m.push(_):h.push(_);let v=s(d,`known-types.ts`);$(v,`/** Map OpenAPI object shapes to your own TypeScript types by property pattern. */
|
|
114
|
+
export const knownTypes = [
|
|
115
|
+
// {
|
|
116
|
+
// name: "BlobAsset",
|
|
117
|
+
// typeName: "BlobAsset",
|
|
118
|
+
// importPath: "./blob/types",
|
|
119
|
+
// exactProperties: ["id", "url", "file"],
|
|
120
|
+
// },
|
|
121
|
+
// {
|
|
122
|
+
// name: "TiptapNode",
|
|
123
|
+
// typeName: "TiptapNode",
|
|
124
|
+
// importPath: "./tiptap/types",
|
|
125
|
+
// requireProperties: ["type"],
|
|
126
|
+
// excludeProperties: ["courseCount"],
|
|
127
|
+
// },
|
|
128
|
+
];
|
|
129
|
+
`)===`created`?m.push(v):h.push(v);let y=u(r,`typeforge.json`);return e(y)||(a(y,`${JSON.stringify({apiRoot:l},null,2)}\n`,`utf8`),m.push(y)),t(s(f,`generated`),{recursive:!0}),{created:m,skipped:h}}export{Ht as a,K as c,L as d,R as f,D as g,ie as h,Q as i,z as l,Ue as m,Kt as n,yt as o,Ge as p,Yt as r,bt as s,Zt as t,lt as u};
|
package/dist/routes/index.d.ts
CHANGED
|
@@ -29,5 +29,4 @@ declare function buildRouteFromRegistry<T extends RouteParamsShape>(routes: Rout
|
|
|
29
29
|
type SearchParamValue = string | number | boolean;
|
|
30
30
|
declare function appendSearchParams(baseUrl: string, params?: Record<string, SearchParamValue | null | undefined>): string;
|
|
31
31
|
//#endregion
|
|
32
|
-
export { type BuildRouteFn, type RouteBuilderFn, type RouteHandlers, type RouteKeyFromParams, type RouteParamsFor, type RouteParamsMap, type RouteParamsShape, type RouteRegistry, type RouteSearchParams, type SearchParamValue, appendSearchParams, buildRouteFromHandlers, buildRouteFromRegistry, createRouteHandlers };
|
|
33
|
-
//# sourceMappingURL=index.d.ts.map
|
|
32
|
+
export { type BuildRouteFn, type RouteBuilderFn, type RouteHandlers, type RouteKeyFromParams, type RouteParamsFor, type RouteParamsMap, type RouteParamsShape, type RouteRegistry, type RouteSearchParams, type SearchParamValue, appendSearchParams, buildRouteFromHandlers, buildRouteFromRegistry, createRouteHandlers };
|
package/dist/routes/index.js
CHANGED
|
@@ -1,38 +1 @@
|
|
|
1
|
-
|
|
2
|
-
function appendSearchParams(baseUrl, params) {
|
|
3
|
-
if (params === void 0 || Object.keys(params).length === 0) return baseUrl;
|
|
4
|
-
const [path, existingQuery] = baseUrl.split("?");
|
|
5
|
-
const searchParams = new URLSearchParams(existingQuery ?? "");
|
|
6
|
-
for (const [key, value] of Object.entries(params)) if (value !== null && value !== void 0) searchParams.set(key, String(value));
|
|
7
|
-
const queryString = searchParams.toString();
|
|
8
|
-
return queryString.length > 0 ? `${path}?${queryString}` : path ?? baseUrl;
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
//#region src/routes/build.ts
|
|
12
|
-
/** Mirrors FE getDynamicRoute, with RouteParams typing and encodeURIComponent. */
|
|
13
|
-
function createRouteHandlers(targets) {
|
|
14
|
-
return Object.fromEntries(Object.entries(targets).map(([key, value]) => {
|
|
15
|
-
if (!/:[^/]+/.test(value)) return [key, value];
|
|
16
|
-
return [key, (params, searchParams) => {
|
|
17
|
-
let result = value;
|
|
18
|
-
for (const [paramKey, paramValue] of Object.entries(params)) result = result.replaceAll(`:${paramKey}`, encodeURIComponent(String(paramValue)));
|
|
19
|
-
return appendSearchParams(result, searchParams);
|
|
20
|
-
}];
|
|
21
|
-
}));
|
|
22
|
-
}
|
|
23
|
-
function buildRouteFromHandlers(routes) {
|
|
24
|
-
const buildRoute = ((key, ...params) => {
|
|
25
|
-
const route = routes[key];
|
|
26
|
-
if (typeof route === "function") return route(params[0]);
|
|
27
|
-
return route;
|
|
28
|
-
});
|
|
29
|
-
return buildRoute;
|
|
30
|
-
}
|
|
31
|
-
/** @deprecated Use createRouteHandlers + buildRouteFromHandlers instead. */
|
|
32
|
-
function buildRouteFromRegistry(routes) {
|
|
33
|
-
return buildRouteFromHandlers(routes);
|
|
34
|
-
}
|
|
35
|
-
//#endregion
|
|
36
|
-
export { appendSearchParams, buildRouteFromHandlers, buildRouteFromRegistry, createRouteHandlers };
|
|
37
|
-
|
|
38
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
function e(e,t){if(t===void 0||Object.keys(t).length===0)return e;let[n,r]=e.split(`?`),i=new URLSearchParams(r??``);for(let[e,n]of Object.entries(t))n!=null&&i.set(e,String(n));let a=i.toString();return a.length>0?`${n}?${a}`:n??e}function t(t){return Object.fromEntries(Object.entries(t).map(([t,n])=>/:[^/]+/.test(n)?[t,(t,r)=>{let i=n;for(let[e,n]of Object.entries(t))i=i.replaceAll(`:${e}`,encodeURIComponent(String(n)));return e(i,r)}]:[t,n]))}function n(e){return((t,...n)=>{let r=e[t];return typeof r==`function`?r(n[0]):r})}function r(e){return n(e)}export{e as appendSearchParams,n as buildRouteFromHandlers,r as buildRouteFromRegistry,t as createRouteHandlers};
|
package/dist/validation/zod.d.ts
CHANGED
|
@@ -7,5 +7,4 @@ interface ZodLikeSchema<T> {
|
|
|
7
7
|
}
|
|
8
8
|
declare function createZodValidator<T>(schema: ZodLikeSchema<T>): ResponseValidator<T>;
|
|
9
9
|
//#endregion
|
|
10
|
-
export { type ResponseValidator, ZodLikeSchema, createZodValidator };
|
|
11
|
-
//# sourceMappingURL=zod.d.ts.map
|
|
10
|
+
export { type ResponseValidator, ZodLikeSchema, createZodValidator };
|
package/dist/validation/zod.js
CHANGED
|
@@ -1,8 +1 @@
|
|
|
1
|
-
|
|
2
|
-
function createZodValidator(schema) {
|
|
3
|
-
return (value) => schema.parse(value);
|
|
4
|
-
}
|
|
5
|
-
//#endregion
|
|
6
|
-
export { createZodValidator };
|
|
7
|
-
|
|
8
|
-
//# sourceMappingURL=zod.js.map
|
|
1
|
+
function e(e){return t=>e.parse(t)}export{e as createZodValidator};
|
package/package.json
CHANGED
|
@@ -1,22 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openmirai/typeforge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Typeforge: headless OpenAPI to TypeScript codegen CLI and HTTPFetch runtime",
|
|
5
|
-
"homepage": "https://github.com/openmirai/
|
|
5
|
+
"homepage": "https://github.com/openmirai/typeforge#readme",
|
|
6
6
|
"bugs": {
|
|
7
|
-
"url": "https://github.com/openmirai/
|
|
7
|
+
"url": "https://github.com/openmirai/typeforge/issues"
|
|
8
8
|
},
|
|
9
9
|
"license": "MIT",
|
|
10
10
|
"repository": {
|
|
11
11
|
"type": "git",
|
|
12
|
-
"url": "git+https://github.com/openmirai/
|
|
12
|
+
"url": "git+https://github.com/openmirai/typeforge.git"
|
|
13
13
|
},
|
|
14
14
|
"bin": {
|
|
15
|
-
"openapi-codegen": "./dist/cli.js",
|
|
16
15
|
"typeforge": "./dist/cli.js"
|
|
17
16
|
},
|
|
18
17
|
"files": [
|
|
19
|
-
"assets/typeforge-logo.png",
|
|
20
18
|
"dist"
|
|
21
19
|
],
|
|
22
20
|
"type": "module",
|
|
@@ -59,6 +57,7 @@
|
|
|
59
57
|
},
|
|
60
58
|
"scripts": {
|
|
61
59
|
"build": "tsdown",
|
|
60
|
+
"check:package": "node scripts/check-package.mjs",
|
|
62
61
|
"typecheck": "tsc -p tsconfig.json --pretty false && tsc -p tsconfig.tools.json --pretty false",
|
|
63
62
|
"format": "oxfmt --check .",
|
|
64
63
|
"format:fix": "oxfmt --write .",
|
|
@@ -69,7 +68,7 @@
|
|
|
69
68
|
"test:coverage": "vitest run --coverage",
|
|
70
69
|
"prepare": "husky",
|
|
71
70
|
"release": "release-it",
|
|
72
|
-
"verify": "pnpm format && pnpm lint && pnpm typecheck && pnpm build && pnpm test:coverage"
|
|
71
|
+
"verify": "pnpm format && pnpm lint && pnpm typecheck && pnpm build && pnpm check:package && pnpm test:coverage"
|
|
73
72
|
},
|
|
74
73
|
"dependencies": {
|
|
75
74
|
"chalk": "5.6.2"
|
|
Binary file
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/json/types.ts","../../../src/http/validate.ts","../../../src/http/types.ts","../../../src/adapters/axios/index.ts"],"mappings":";;KAUY;KAEA,cAAc,eAAe;;;KCZ7B,kBAAkB,MAAM,mBAAmB;;;UCOtC,gBACf,yBAAyB,aACzB;EAEA,SAAS;EACT,SAAS;EACT,UAAU;EACV,mBAAmB,kBAAkB;;UAGtB;EACf,IAAI,WAAW,yBAAyB,aACtC,eACA,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,KAAK,WAAW,iBAAiB,yBAAyB,aACxD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,IAAI,WAAW,iBAAiB,yBAAyB,aACvD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,MAAM,WAAW,iBAAiB,yBAAyB,aACzD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,OAAO,WAAW,yBAAyB,aACzC,eACA,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;;;;iBCLL,mBAAmB,UAAU,gBAAgB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/http/validate.ts","../../../src/adapters/axios/index.ts"],"sourcesContent":["export type ResponseValidator<T> = (value: unknown) => T;\n\nexport class ResponseValidationError extends Error {\n override readonly cause: unknown;\n\n constructor(message: string, cause: unknown) {\n super(message);\n this.name = \"ResponseValidationError\";\n this.cause = cause;\n }\n}\n\nexport function coerceResponseData<T>(\n value: unknown,\n validator?: ResponseValidator<T>\n): T {\n if (validator === undefined) {\n return value as T;\n }\n\n try {\n return validator(value);\n } catch (error) {\n throw new ResponseValidationError(\"Response validation failed\", error);\n }\n}\n","import type { AxiosInstance, AxiosRequestConfig } from \"axios\";\n\nimport { coerceResponseData } from \"../../http/validate\";\nimport type { HTTPFetch, HTTPFetchConfig } from \"../../http/types\";\nimport type { QueryParams } from \"../../json/types\";\n\nfunction toAxiosConfig<TParams extends object>(\n config?: HTTPFetchConfig<TParams, unknown>\n): AxiosRequestConfig | undefined {\n if (config === undefined) {\n return undefined;\n }\n\n const axiosConfig: AxiosRequestConfig = {};\n if (config.signal !== undefined) {\n axiosConfig.signal = config.signal;\n }\n if (config.params !== undefined) {\n axiosConfig.params = config.params;\n }\n if (config.headers !== undefined) {\n axiosConfig.headers = config.headers;\n }\n return axiosConfig;\n}\n\nfunction mapResponse<TResponse, TParams extends object>(\n data: unknown,\n config?: HTTPFetchConfig<TParams, TResponse>\n): { data: TResponse } {\n return {\n data: coerceResponseData<TResponse>(data, config?.validateResponse),\n };\n}\n\nexport function createAxiosAdapter(instance: AxiosInstance): HTTPFetch {\n return {\n delete: <TResponse, TParams extends object = QueryParams>(\n route: string,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) =>\n instance\n .delete<TResponse>(route, toAxiosConfig(config))\n .then((response) => mapResponse(response.data, config)),\n get: <TResponse, TParams extends object = QueryParams>(\n route: string,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) =>\n instance\n .get<TResponse>(route, toAxiosConfig(config))\n .then((response) => mapResponse(response.data, config)),\n patch: <TResponse, TBody = unknown, TParams extends object = QueryParams>(\n route: string,\n body: TBody,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) =>\n instance\n .patch<TResponse>(route, body, toAxiosConfig(config))\n .then((response) => mapResponse(response.data, config)),\n post: <TResponse, TBody = unknown, TParams extends object = QueryParams>(\n route: string,\n body: TBody,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) =>\n instance\n .post<TResponse>(route, body, toAxiosConfig(config))\n .then((response) => mapResponse(response.data, config)),\n put: <TResponse, TBody = unknown, TParams extends object = QueryParams>(\n route: string,\n body: TBody,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) =>\n instance\n .put<TResponse>(route, body, toAxiosConfig(config))\n .then((response) => mapResponse(response.data, config)),\n };\n}\n\nexport type { HTTPFetch, HTTPFetchConfig } from \"../../http/types\";\n"],"mappings":";AAEA,IAAa,0BAAb,cAA6C,MAAM;CACjD;CAEA,YAAY,SAAiB,OAAgB;EAC3C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;AAEA,SAAgB,mBACd,OACA,WACG;CACH,IAAI,cAAc,KAAA,GAChB,OAAO;CAGT,IAAI;EACF,OAAO,UAAU,KAAK;CACxB,SAAS,OAAO;EACd,MAAM,IAAI,wBAAwB,8BAA8B,KAAK;CACvE;AACF;;;ACnBA,SAAS,cACP,QACgC;CAChC,IAAI,WAAW,KAAA,GACb;CAGF,MAAM,cAAkC,CAAC;CACzC,IAAI,OAAO,WAAW,KAAA,GACpB,YAAY,SAAS,OAAO;CAE9B,IAAI,OAAO,WAAW,KAAA,GACpB,YAAY,SAAS,OAAO;CAE9B,IAAI,OAAO,YAAY,KAAA,GACrB,YAAY,UAAU,OAAO;CAE/B,OAAO;AACT;AAEA,SAAS,YACP,MACA,QACqB;CACrB,OAAO,EACL,MAAM,mBAA8B,MAAM,QAAQ,gBAAgB,EACpE;AACF;AAEA,SAAgB,mBAAmB,UAAoC;CACrE,OAAO;EACL,SACE,OACA,WAEA,SACG,OAAkB,OAAO,cAAc,MAAM,CAAC,CAAC,CAC/C,MAAM,aAAa,YAAY,SAAS,MAAM,MAAM,CAAC;EAC1D,MACE,OACA,WAEA,SACG,IAAe,OAAO,cAAc,MAAM,CAAC,CAAC,CAC5C,MAAM,aAAa,YAAY,SAAS,MAAM,MAAM,CAAC;EAC1D,QACE,OACA,MACA,WAEA,SACG,MAAiB,OAAO,MAAM,cAAc,MAAM,CAAC,CAAC,CACpD,MAAM,aAAa,YAAY,SAAS,MAAM,MAAM,CAAC;EAC1D,OACE,OACA,MACA,WAEA,SACG,KAAgB,OAAO,MAAM,cAAc,MAAM,CAAC,CAAC,CACnD,MAAM,aAAa,YAAY,SAAS,MAAM,MAAM,CAAC;EAC1D,MACE,OACA,MACA,WAEA,SACG,IAAe,OAAO,MAAM,cAAc,MAAM,CAAC,CAAC,CAClD,MAAM,aAAa,YAAY,SAAS,MAAM,MAAM,CAAC;CAC5D;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/json/types.ts","../../../src/http/validate.ts","../../../src/http/types.ts","../../../src/adapters/fetch/index.ts"],"mappings":";KAUY;KAEA,cAAc,eAAe;;;KCZ7B,kBAAkB,MAAM,mBAAmB;;;UCOtC,gBACf,yBAAyB,aACzB;EAEA,SAAS;EACT,SAAS;EACT,UAAU;EACV,mBAAmB,kBAAkB;;UAGtB;EACf,IAAI,WAAW,yBAAyB,aACtC,eACA,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,KAAK,WAAW,iBAAiB,yBAAyB,aACxD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,IAAI,WAAW,iBAAiB,yBAAyB,aACvD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,MAAM,WAAW,iBAAiB,yBAAyB,aACzD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,OAAO,WAAW,yBAAyB,aACzC,eACA,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;;;;UCnCJ;EACf;EACA,UAAU;EACV,eAAe;;iBAqED,mBACd,UAAS,sBACR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/json/types.ts","../../../src/http/validate.ts","../../../src/adapters/fetch/index.ts"],"sourcesContent":["export type JsonPrimitive = string | number | boolean | null;\n\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\nexport type JsonArray = Array<JsonValue>;\n\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type QueryParamValue = string | number | boolean | null | undefined;\n\nexport type QueryParams = Record<string, QueryParamValue>;\n\nexport function isJsonPrimitive(value: JsonValue): value is JsonPrimitive {\n return (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n );\n}\n\nexport function isJsonValue(value: unknown): value is JsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n\n if (Array.isArray(value)) {\n return value.every(isJsonValue);\n }\n\n if (typeof value === \"object\" && value !== null) {\n return Object.values(value).every(isJsonValue);\n }\n\n return false;\n}\n\nexport function isJsonObject(value: unknown): value is JsonObject {\n return (\n isJsonValue(value) &&\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n );\n}\n\nexport function isJsonArray(value: unknown): value is JsonArray {\n return Array.isArray(value) && value.every(isJsonValue);\n}\n\nexport function parseJson(text: string): JsonValue {\n const parsed: unknown = JSON.parse(text);\n if (!isJsonValue(parsed)) {\n throw new TypeError(\"JSON text did not parse to a valid JSON value\");\n }\n return parsed;\n}\n\nexport function readJsonObject(text: string): JsonObject {\n const parsed = parseJson(text);\n if (!isJsonObject(parsed)) {\n throw new TypeError(\"JSON text did not parse to a JSON object\");\n }\n return parsed;\n}\n\nexport function readJsonPrimitives(\n values: JsonValue | undefined\n): Array<JsonPrimitive> {\n if (!isJsonArray(values)) {\n return [];\n }\n\n return values.filter(isJsonPrimitive);\n}\n","export type ResponseValidator<T> = (value: unknown) => T;\n\nexport class ResponseValidationError extends Error {\n override readonly cause: unknown;\n\n constructor(message: string, cause: unknown) {\n super(message);\n this.name = \"ResponseValidationError\";\n this.cause = cause;\n }\n}\n\nexport function coerceResponseData<T>(\n value: unknown,\n validator?: ResponseValidator<T>\n): T {\n if (validator === undefined) {\n return value as T;\n }\n\n try {\n return validator(value);\n } catch (error) {\n throw new ResponseValidationError(\"Response validation failed\", error);\n }\n}\n","import type { JsonValue, QueryParams } from \"../../json/types\";\nimport { parseJson } from \"../../json/types\";\nimport { coerceResponseData } from \"../../http/validate\";\nimport type { HTTPFetch, HTTPFetchConfig } from \"../../http/types\";\n\nexport interface FetchAdapterOptions {\n baseURL?: string;\n headers?: Record<string, string>;\n fetch?: typeof fetch;\n}\n\nfunction appendQuery(url: string, params?: object): string {\n if (params === undefined || Object.keys(params).length === 0) {\n return url;\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n search.append(key, String(value));\n }\n\n const query = search.toString();\n if (query.length === 0) {\n return url;\n }\n\n return `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${query}`;\n}\n\nfunction readResponseBody(text: string): JsonValue | undefined {\n if (text.length === 0) {\n return undefined;\n }\n return parseJson(text);\n}\n\nasync function request<TResponse, TParams extends object>(\n method: string,\n route: string,\n options: FetchAdapterOptions,\n body?: unknown,\n config?: HTTPFetchConfig<TParams, TResponse>\n): Promise<{ data: TResponse }> {\n const fetchImpl = options.fetch ?? globalThis.fetch;\n const baseURL = options.baseURL ?? \"\";\n const url = appendQuery(`${baseURL}${route}`, config?.params);\n\n const headers: Record<string, string> = {\n ...options.headers,\n ...config?.headers,\n };\n\n const init: RequestInit = {\n headers,\n method,\n };\n if (config?.signal !== undefined) {\n init.signal = config.signal;\n }\n\n if (body !== undefined) {\n headers[\"Content-Type\"] ??= \"application/json\";\n init.body = JSON.stringify(body);\n }\n\n const response = await fetchImpl(url, init);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status} ${response.statusText}`);\n }\n\n const text = await response.text();\n const parsed = readResponseBody(text);\n return {\n data: coerceResponseData<TResponse>(parsed, config?.validateResponse),\n };\n}\n\nexport function createFetchAdapter(\n options: FetchAdapterOptions = {}\n): HTTPFetch {\n return {\n delete: <TResponse, TParams extends object = QueryParams>(\n route: string,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) =>\n request<TResponse, TParams>(\"DELETE\", route, options, undefined, config),\n get: <TResponse, TParams extends object = QueryParams>(\n route: string,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) => request<TResponse, TParams>(\"GET\", route, options, undefined, config),\n patch: <TResponse, TBody = unknown, TParams extends object = QueryParams>(\n route: string,\n body: TBody,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) => request<TResponse, TParams>(\"PATCH\", route, options, body, config),\n post: <TResponse, TBody = unknown, TParams extends object = QueryParams>(\n route: string,\n body: TBody,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) => request<TResponse, TParams>(\"POST\", route, options, body, config),\n put: <TResponse, TBody = unknown, TParams extends object = QueryParams>(\n route: string,\n body: TBody,\n config?: HTTPFetchConfig<TParams, TResponse>\n ) => request<TResponse, TParams>(\"PUT\", route, options, body, config),\n };\n}\n\nexport type { HTTPFetch, HTTPFetchConfig } from \"../../http/types\";\n"],"mappings":";AAuBA,SAAgB,YAAY,OAAoC;CAC9D,IACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU,WAEjB,OAAO;CAGT,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,MAAM,WAAW;CAGhC,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,WAAW;CAG/C,OAAO;AACT;AAeA,SAAgB,UAAU,MAAyB;CACjD,MAAM,SAAkB,KAAK,MAAM,IAAI;CACvC,IAAI,CAAC,YAAY,MAAM,GACrB,MAAM,IAAI,UAAU,+CAA+C;CAErE,OAAO;AACT;;;AC7DA,IAAa,0BAAb,cAA6C,MAAM;CACjD;CAEA,YAAY,SAAiB,OAAgB;EAC3C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;AAEA,SAAgB,mBACd,OACA,WACG;CACH,IAAI,cAAc,KAAA,GAChB,OAAO;CAGT,IAAI;EACF,OAAO,UAAU,KA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QAA4B,UAAU,OAAO,SAAS,KAAA,GAAW,MAAM;EACzE,MACE,OACA,WACG,QAA4B,OAAO,OAAO,SAAS,KAAA,GAAW,MAAM;EACzE,QACE,OACA,MACA,WACG,QAA4B,SAAS,OAAO,SAAS,MAAM,MAAM;EACtE,OACE,OACA,MACA,WACG,QAA4B,QAAQ,OAAO,SAAS,MAAM,MAAM;EACrE,MACE,OACA,MACA,WACG,QAA4B,OAAO,OAAO,SAAS,MAAM,MAAM;CACtE;AACF"}
|
package/dist/cli.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","names":[],"sources":["../src/cli.ts"],"mappings":";UASU;EACR;;EAEA;;EAEA,SAAS;EACT;EACA;EACA;EACA;EACA;EACA;;iBAGc,UAAU,MAAM,gBAAgB"}
|
package/dist/cli.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { realpathSync } from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { listSourceKeys, loadProjectConfig } from \"./config/load\";\nimport { generateForSource } from \"./generate/index\";\nimport type { GenerateOptions } from \"./generate/index\";\nimport { initProject } from \"./init/index\";\nimport type { InitOptions } from \"./init/index\";\n\ninterface ParsedArgs {\n command?: string;\n /** Populated by the first --source value; kept for init (single-source) compat. */\n source?: string;\n /** All --source values collected for multi-source generate. */\n sources: Array<string>;\n spec?: string;\n client?: \"axios\" | \"fetch\" | \"custom\";\n layout?: \"monolith\" | \"packages\";\n check?: boolean;\n acceptBase?: boolean;\n all?: boolean;\n}\n\nexport function parseArgs(argv: Array<string>): ParsedArgs {\n const parsed: ParsedArgs = { sources: [] };\n const positional: Array<string> = [];\n\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n if (arg === undefined) {\n continue;\n }\n\n if (arg === \"--check\") {\n parsed.check = true;\n continue;\n }\n if (arg === \"--accept-base\") {\n parsed.acceptBase = true;\n continue;\n }\n if (arg === \"--all\") {\n parsed.all = true;\n continue;\n }\n if (arg.startsWith(\"--source=\")) {\n const value = arg.slice(\"--source=\".length);\n parsed.sources.push(value);\n if (parsed.source === undefined) {\n parsed.source = value;\n }\n continue;\n }\n if (arg === \"--source\") {\n const value = argv[index + 1];\n if (value !== undefined) {\n parsed.sources.push(value);\n if (parsed.source === undefined) {\n parsed.source = value;\n }\n index += 1;\n }\n continue;\n }\n if (arg.startsWith(\"--spec=\")) {\n parsed.spec = arg.slice(\"--spec=\".length);\n continue;\n }\n if (arg === \"--spec\") {\n const value = argv[index + 1];\n if (value !== undefined) {\n parsed.spec = value;\n index += 1;\n }\n continue;\n }\n if (arg.startsWith(\"--client=\")) {\n const value = arg.slice(\"--client=\".length);\n if (value === \"axios\" || value === \"fetch\" || value === \"custom\") {\n parsed.client = value;\n }\n continue;\n }\n if (arg === \"--client\") {\n const value = argv[index + 1];\n if (value === \"axios\" || value === \"fetch\" || value === \"custom\") {\n parsed.client = value;\n index += 1;\n }\n continue;\n }\n if (arg.startsWith(\"--layout=\")) {\n const value = arg.slice(\"--layout=\".length);\n if (value === \"monolith\" || value === \"packages\") {\n parsed.layout = value;\n }\n continue;\n }\n if (arg === \"--layout\") {\n const value = argv[index + 1];\n if (value === \"monolith\" || value === \"packages\") {\n parsed.layout = value;\n index += 1;\n }\n continue;\n }\n if (!arg.startsWith(\"-\")) {\n positional.push(arg);\n }\n }\n\n const command = positional[0];\n if (command !== undefined) {\n parsed.command = command;\n }\n return parsed;\n}\n\nfunction printHelp(): void {\n process.stdout.write(`typeforge — headless OpenAPI TypeScript codegen\n\nUsage:\n typeforge init --source <key> --client axios|fetch|custom [--layout monolith|packages]\n typeforge generate --source <key> [--source <key2> ...] [--spec <path>] [--check] [--accept-base]\n typeforge generate --all [--check] [--accept-base]\n typeforge check --source <key> [--spec <path>]\n typeforge accept-base --source <key> [--spec <path>]\n\nMulti-source generate:\n Provide multiple --source flags, or use --all to generate every source under apiRoot.\n Configure per-source spec paths in each source.ts:\n import { defineSourceConfig } from \"@openmirai/typeforge\";\n export default defineSourceConfig({ spec: \"./specs/acme.json\", ... });\n`);\n}\n\nasync function runGenerate(args: ParsedArgs): Promise<number> {\n if (args.check === true && args.acceptBase === true) {\n process.stderr.write(\n \"typeforge: --accept-base is not allowed with --check\\n\"\n );\n return 1;\n }\n\n const cwd = process.cwd();\n const projectConfig = loadProjectConfig(cwd);\n const apiRoot = projectConfig.apiRoot ?? \"src/api\";\n let sources: Array<string>;\n if (args.all === true) {\n sources = listSourceKeys(cwd, apiRoot);\n } else if (args.sources.length > 0) {\n sources = args.sources;\n } else {\n sources = [];\n }\n\n if (sources.length === 0) {\n process.stderr.write(\"typeforge: --source <key> or --all is required\\n\");\n return 1;\n }\n\n let exitCode = 0;\n for (const sourceKey of sources) {\n try {\n const generateOptions: GenerateOptions = { sourceKey };\n if (args.acceptBase === true) {\n generateOptions.acceptBase = true;\n }\n if (args.check === true) {\n generateOptions.check = true;\n }\n if (args.spec !== undefined) {\n generateOptions.specFlag = args.spec;\n }\n\n const result = await generateForSource(generateOptions);\n\n if (args.check === true) {\n if (result.changed.length > 0) {\n process.stderr.write(\n `typeforge: stale generated files for \"${sourceKey}\":\\n`\n );\n for (const file of result.changed) {\n process.stderr.write(` ${file}\\n`);\n }\n exitCode = 1;\n } else {\n process.stdout.write(`typeforge: \"${sourceKey}\" is up to date\\n`);\n }\n } else {\n process.stdout.write(\n `typeforge: generated ${result.files} files for \"${sourceKey}\" (${result.changed.length} changed)\\n`\n );\n }\n } catch (error) {\n exitCode = 1;\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`${message}\\n`);\n }\n }\n\n return exitCode;\n}\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n\n if (\n args.command === undefined ||\n args.command === \"help\" ||\n args.command === \"--help\" ||\n args.command === \"-h\"\n ) {\n printHelp();\n process.exit(0);\n }\n\n if (args.command === \"init\") {\n if (args.source === undefined || args.client === undefined) {\n process.stderr.write(\"typeforge: init requires --source and --client\\n\");\n process.exit(1);\n }\n\n const initOptions: InitOptions = {\n client: args.client,\n sourceKey: args.source,\n };\n if (args.layout !== undefined) {\n initOptions.layout = args.layout;\n }\n\n const result = initProject(initOptions);\n\n for (const file of result.created) {\n process.stdout.write(`created ${file}\\n`);\n }\n for (const file of result.skipped) {\n process.stdout.write(`skipped ${file} (already exists)\\n`);\n }\n process.exit(0);\n }\n\n if (\n args.command === \"generate\" ||\n args.command === \"check\" ||\n args.command === \"accept-base\"\n ) {\n if (args.command === \"check\") {\n args.check = true;\n }\n if (args.command === \"accept-base\") {\n args.acceptBase = true;\n }\n process.exit(await runGenerate(args));\n }\n\n process.stderr.write(`typeforge: unknown command \"${args.command}\"\\n`);\n printHelp();\n process.exit(1);\n}\n\n// Only auto-execute when this file is the Node.js entry point.\n// Guarding with import.meta.url allows the module to be safely imported\n// in tests without triggering process.exit.\nconst isEntryPoint = ((): boolean => {\n const entry = process.argv[1];\n if (entry === undefined) {\n return false;\n }\n try {\n return import.meta.url === pathToFileURL(realpathSync(entry)).href;\n } catch {\n return false;\n }\n})();\n\nif (isEntryPoint) {\n main().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`${message}\\n`);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;AAuBA,SAAgB,UAAU,MAAiC;CACzD,MAAM,SAAqB,EAAE,SAAS,CAAC,EAAE;CACzC,MAAM,aAA4B,CAAC;CAEnC,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;EACnD,MAAM,MAAM,KAAK;EACjB,IAAI,QAAQ,KAAA,GACV;EAGF,IAAI,QAAQ,WAAW;GACrB,OAAO,QAAQ;GACf;EACF;EACA,IAAI,QAAQ,iBAAiB;GAC3B,OAAO,aAAa;GACpB;EACF;EACA,IAAI,QAAQ,SAAS;GACnB,OAAO,MAAM;GACb;EACF;EACA,IAAI,IAA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,QAAQ;EACN,OAAO;CACT;AACF,EAAA,CAEe,GACb,KAAK,CAAC,CAAC,OAAO,UAAmB;CAC/B,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CACrE,QAAQ,OAAO,MAAM,GAAG,QAAQ,GAAG;CACnC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
package/dist/http/types.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../src/json/types.ts","../../src/http/types.ts"],"mappings":";;KAUY;KAEA,cAAc,eAAe;;;UCLxB,gBACf,yBAAyB,aACzB;EAEA,SAAS;EACT,SAAS;EACT,UAAU;EACV,mBAAmB,kBAAkB;;UAGtB;EACf,IAAI,WAAW,yBAAyB,aACtC,eACA,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,KAAK,WAAW,iBAAiB,yBAAyB,aACxD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,IAAI,WAAW,iBAAiB,yBAAyB,aACvD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,MAAM,WAAW,iBAAiB,yBAAyB,aACzD,eACA,MAAM,OACN,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM;;EACnB,OAAO,WAAW,yBAAyB,aACzC,eACA,SAAS,gBAAgB,SAAS,aACjC;IAAU,MAAM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validate.d.ts","names":[],"sources":["../../src/http/validate.ts"],"mappings":";KAAY,kBAAkB,MAAM,mBAAmB;cAE1C,gCAAgC;WACzB;EAElB,YAAY,iBAAiB;;iBAOf,mBAAmB,GACjC,gBACA,YAAY,kBAAkB,KAC7B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validate.js","names":[],"sources":["../../src/http/validate.ts"],"sourcesContent":["export type ResponseValidator<T> = (value: unknown) => T;\n\nexport class ResponseValidationError extends Error {\n override readonly cause: unknown;\n\n constructor(message: string, cause: unknown) {\n super(message);\n this.name = \"ResponseValidationError\";\n this.cause = cause;\n }\n}\n\nexport function coerceResponseData<T>(\n value: unknown,\n validator?: ResponseValidator<T>\n): T {\n if (validator === undefined) {\n return value as T;\n }\n\n try {\n return validator(value);\n } catch (error) {\n throw new ResponseValidationError(\"Response validation failed\", error);\n }\n}\n"],"mappings":";AAEA,IAAa,0BAAb,cAA6C,MAAM;CACjD;CAEA,YAAY,SAAiB,OAAgB;EAC3C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;AAEA,SAAgB,mBACd,OACA,WACG;CACH,IAAI,cAAc,KAAA,GAChB,OAAO;CAGT,IAAI;EACF,OAAO,UAAU,KAAK;CACxB,SAAS,OAAO;EACd,MAAM,IAAI,wBAAwB,8BAA8B,KAAK;CACvE;AACF"}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/json/types.ts","../src/parser/types.ts","../src/parser/index.ts","../src/parser/loader.ts","../src/http/validate.ts","../src/http/types.ts","../src/config/types.ts","../src/config/define.ts","../src/generate/index.ts","../src/init/index.ts","../src/envelope-guard/index.ts","../src/emitters/recursive-ref-error.ts","../src/plugins/known-types/types.ts","../src/plugins/known-types/index.ts"],"mappings":";KAAY;UAEK;GACd,cAAc;;KAGL,YAAY,MAAM;KAElB,YAAY,gBAAgB,aAAa;KAEzC;KAEA,cAAc,eAAe;;;UCVxB;EACf,SAAS,MAAM;;UAGA;EACf;EACA,OAAO,MAAM;EACb;IAAc,SAAS,eAAe;;;UAGvB;EACf;EACA;EACA,YAAY,MAAM;;UAGH;EACf,QAAQ;EACR;EACA,YAAY,MAAM;EAClB,aAAa,MAAM;EACnB,cAAc;EACd,WAAW,MAAM;;KAGP;UAEK;EACf;EACA,QAAQ;;UAGO;EACf;EACA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AAe;;EAEf;;;;;;;;;EASA;;;;;;EAMA;;;;;;;;iBC1Dc,mBAAmB,QAAQ,eAAe;;;UC4BzC;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA,SAAS;EACT;;UAGe;EACf;EACA;EACA;EACA,cAAc;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGc,qBACd,aACA,oBACC;iBAsGmB,kBACpB,SAAS,kBACR,QAAQ;;;KCrKC;KACA;UAEK;EACf;EACA;EACA,QAAQ;EACR,SAAS;;iBAyIK,YAAY,SAAS;EACnC,SAAS;EACT,SAAS;;;;KCrJC;UAEK;EACf;EACA;EACA;;UAGe;EACf,QAAQ,MAAM;EACd,QAAQ;;UAGO;EACf;EACA;EACA,OAAO;;UAGQ;EACf,MAAM;EACN,SAAS;EACT,YAAY,MAAM;EAClB,QAAQ,YAAY,MAAM;;UAGX;EACf;EACA;EACA,OAAO;EACP,OAAO;;UAGQ;EACf,QAAQ,MAAM;EACd;;iBA2Hc,gBAAgB,QAAQ,WAAW;iBAiFnC,sBACd,kBACC;iBAqCa,mBACd,MAAM,eACN,MAAM,wBACL,MAAM;iBAiEO,2BACd,OAAO,eACP;;;cC9VW,0BAA0B;WAC5B,OAAO;WACP;WACA;EAET,YAAY,mBAAmB,OAAO,eAAe;;;;UCLtC;EACf;EACA;EACA;EACA,UAAU,QAAQ,UAAU,YAAY,eAAe;;;UAIxC;EACf;EACA;EACA;EACA,kBAAkB;EAClB,oBAAoB;EACpB,oBAAoB;EACpB;;UAGe;EACf,MAAM;EACN;EACA;;;;iBCXc,mBACd,aACA,kBACC,MAAM;iBAIO,eACd,QAAQ,UACR,YAAY,eAAe,WAC3B,OAAO,MAAM,iBACZ"}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/config/define.ts"],"sourcesContent":["import type { SourceConfig } from \"./types\";\n\n/**\n * Identity helper for `source.ts`. Use it so the object is checked against\n * `SourceConfig` and editors can autocomplete fields.\n */\nexport function defineSourceConfig(config: SourceConfig): SourceConfig {\n return config;\n}\n"],"mappings":";;;;;;AAMA,SAAgB,mBAAmB,QAAoC;CACrE,OAAO;AACT"}
|