UNPKG

@levo-so/client

Version:

<img alt="Levo" src="https://static.levocdn.com/png/Levo-Logo.png" width="50" height="50">

112 lines (102 loc) 9.72 kB
#!/usr/bin/env node import F from"chalk";import{hideBin as o}from"yargs/helpers";import S from"yargs/yargs";import p from"node:fs";import q from"chalk";import v from"package-json";import J from"node:fs";var U=()=>{let m=process.cwd(),w="npm",W=J.readdirSync(m);if(W.includes("package-lock.json"))w="npm";if(W.includes("yarn.lock"))w="yarn";if(W.includes("pnpm-lock.yaml"))w="pnpm";if(W.includes("bun.lockb"))w="bun";return w},X=(m)=>{switch(m){case"npm":return"npm i";case"yarn":return"yarn add";case"pnpm":return"pnpm add";case"bun":return"bun add";default:return"npm i"}};import I from"node:path";var Q=()=>{let m=process.cwd();return I.join(m,"node_modules","@levo-so/client")};var Y=async()=>{let m=Q(),w=JSON.parse(p.readFileSync(`${m}/package.json`,{encoding:"utf-8"})),W=w.name,K=w.version;console.log(q.bgMagenta.bold(` ${W} v${K} `));let{version:y}=await v(W);if(K!==y){console.log(`${q.blueBright("Update available:")} v${K} → v${y}`);let A=U(),j=X(A);console.log(q.gray("Run:"),q.bold(`${j} @levo-so/client@latest`),q.gray(`to update. `))}};import z from"chalk";import V from"cross-fetch";var Z=async({endpoint:m,workspace:w})=>{let W=await V(`${m}/v1/bevy/collection/export-schema`,{headers:{"Levo-Workspace":w},signal:AbortSignal.timeout(30000)}),K=await W.json();if(!W.ok){if(console.error(z.red(`We could not get the schema for the workspace. (${W.status} - ${W.statusText})`)),!K.status)console.error(z.red(`[${K.content.code}] ${K.content.title} - ${K.content.description}`));return null}if(!K.status)return console.error(z.red(`We could not get the schema for the workspace. (${W.status} - ${W.statusText})`)),console.error(z.red(`[${K.content.code}] ${K.content.title} - ${K.content.description}`)),null;if(!K.content.data)return console.error(z.red("We could not get the schema for the workspace.")),null;return K.content.data};var C=(m,w,W={})=>{let{nested:K=!1,array:y=!1,level:A=1,kind:j="root"}=W,O=K?`{ `:`type ${m}_${j} = { `,L=[...new Array(A).keys()].map(()=>"\t").join(""),R=[...new Array(A-1).keys()].map(()=>"\t").join("");for(let[x,$]of Object.entries(w)){if($.readonly&&["create","update"].includes(j))continue;if($.kind==="collection"&&$.options?.relationship==="o2m"&&["create","update"].includes(j))continue;if(O+=[`${L}/**`,`${L} * "${$.label}" field in the "${m}" collection. ${L} *`,$.helper_text?`${L} * Description: ${$.helper_text} ${L} *`:"",`${L} * Required: ${$.required?"Yes":"No"} ${L} *`,`${L} * Unique: ${$.unique?"Yes":"No"} ${L} *`,`${L} * Type: ${$.kind} ${L} *`,$.min?`${L} * Min: ${$.min} ${L} *`:"",$.max?`${L} * Max: ${$.max} ${L} *`:"",$.values?.length>0?`${L} * Values: ${$.values.map((E)=>`"${E}"`).join(", ")} ${L} *`:"",typeof $.default_value!=="undefined"?`${L} * Default Value: ${JSON.stringify($.default_value)} ${L} *`:"",$.readonly?`${L} * Readonly: ${$.readonly?"Yes":"No"} ${L} *`:"",$.formats?.length>0?`${L} * Formats: ${$.formats.map((E)=>`"${E}"`).join(", ")} ${L} *`:"",`${L} */ `].filter(Boolean).join(` `),$.kind==="collection"&&$.options?.relationship==="m2o"){if(j==="root")if($.required)O+=`${L}${x}: string | ${$.options?.collection_key}_root; `;else O+=`${L}${x}: string | ${$.options?.collection_key}_root | null; `;else if(j==="create")O+=$.required?`${L}${x}: string; `:`${L}${x}?: string | null; `;else if(j==="update")O+=$.required?`${L}${x}?: string; `:`${L}${x}?: string | null; `}if($.kind==="collection"&&$.options?.relationship==="o2m")O+=`${L}${x}: ${$.options?.collection_key}_root[]; `;if($.kind==="collection"&&$.options?.relationship==="m2m")if(j==="root")O+=`${L}${x}: string[] | ${$.options?.collection_key}_root[]; `;else if(j==="create"&&$.required)O+=`${L}${x}: string[] | ${$.options?.collection_key}_root[]; `;else O+=`${L}${x}?: string[] | ${$.options?.collection_key}_root[]; `;if($.kind==="date")if(j!=="update"&&$.required)O+=`${L}${x}: Date | string; `;else if(j==="root")O+=`${L}${x}: Date | string | null; `;else O+=`${L}${x}?: Date | string | null; `;if($.kind==="string"){let E="";if($.values?.length>0){if(E=`${$.values.map((G)=>`"${G}"`).join(" | ")}`,typeof $.options?.custom_input!=="undefined"&&$.options?.custom_input)E+=" | string"}else E="string";if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: ${E}; `;else O+=`${L}${x}?: ${E}; `}if($.kind==="number")if(j!=="update"&&$.required)O+=`${L}${x}: number; `;else if(j==="root")O+=`${L}${x}: number | null; `;else O+=`${L}${x}?: number | null; `;if($.kind==="boolean")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: boolean; `;else O+=`${L}${x}?: boolean; `;if($.kind==="json")if(j!=="update"&&$.required)O+=`${L}${x}: FieldValueType['json']; `;else if(j==="root")O+=`${L}${x}: FieldValueType['json'] | null; `;else O+=`${L}${x}?: FieldValueType['json'] | null; `;if($.kind==="array-string")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: string[]; `;else O+=`${L}${x}?: string[]; `;if($.kind==="file")if(j!=="update"&&$.required)O+=`${L}${x}: FieldValueType['file']; `;else if(j==="root")O+=`${L}${x}: FieldValueType['file'] | null; `;else O+=`${L}${x}?: FieldValueType['file'] | null; `;if($.kind==="array-number")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: number[]; `;else O+=`${L}${x}?: number[]; `;if($.kind==="array-boolean")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: boolean[]; `;else O+=`${L}${x}?: boolean[]; `;if($.kind==="array-date")if(j!=="update"&&$.required)O+=`${L}${x}: (Date | string)[]; `;else O+=`${L}${x}?: (Date | string | null)[]; `;if($.kind==="array-json")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: FieldValueType['array-json']; `;else O+=`${L}${x}?: FieldValueType['array-json']; `;if($.kind==="array-file")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: FieldValueType['array-file']; `;else O+=`${L}${x}?: FieldValueType['array-file']; `;if($.kind==="location")if(j!=="update"&&$.required)O+=`${L}${x}: FieldValueType['location']; `;else if(j==="root")O+=`${L}${x}: FieldValueType['location'] | null; `;else O+=`${L}${x}?: FieldValueType['location'] | null; `;if($.kind==="array-location")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: FieldValueType['array-location']; `;else O+=`${L}${x}?: FieldValueType['array-location']; `;if($.kind==="identifier"){if(j==="root")O+=`${L}${x}: string; `;else if(j==="create")O+=`${L}${x}?: string; `}if($.kind==="record")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: ${C(x,$?.fields||{},{nested:!0,array:!1,level:A+1,kind:j})}; `;else O+=`${L}${x}?: ${C(x,$?.fields||{},{nested:!0,array:!1,level:A+1,kind:j})}; `;if($.kind==="group")if(j==="root"||j==="create"&&$.required)O+=`${L}${x}: ${C(x,$?.fields||{},{nested:!0,array:!0,level:A+1,kind:j})}; `;else O+=`${L}${x}?: ${C(x,$?.fields||{},{nested:!0,array:!0,level:A+1,kind:j})}; `}return O+=y?`${R}}[]`:`${R}}`,O};var _=({file:m,fields:w,collections:W})=>{for(let K of Object.keys(w)){let y=W[K];if(y.module_name)continue;m+=` /** * The create type for the "${y.name}" (\`${y.key}\`) collection. * * This type is used to create a new ${y.name} record. */ `.trimStart(),m+=C(K,w[K],{kind:"create"}),m+=` `}return m};var B=({file:m,fields:w,collections:W})=>{for(let K of Object.keys(w)){let y=W[K];m+=` /** * The root type for the "${y.name}" (\`${y.key}\`) collection. */ `.trimStart(),m+=C(K,w[K],{kind:"root"}),m+=` `}return m};var D=({file:m,fields:w})=>{return m+=`export const LevoCollectionKey = {${Object.keys(w).map((W)=>` ${W}: '${W}' as const`)} };`,m+=` `,m+="export type ILevoCollection = keyof typeof LevoCollectionKey;",m+=` `,m+=`export type LevoCollectionRoot = {${Object.keys(w).map((W)=>` ${W}: ${W}_root`)} };`,m+=` `,m+=`export type LevoCollectionCreateInput = {${Object.keys(w).map((W)=>` ${W}: ${W}_create`)} };`,m+=` `,m+=`export type LevoCollectionUpdateInput = {${Object.keys(w).map((W)=>` ${W}: ${W}_update`)} };`,m+=` `,m};var N=({file:m,fields:w,collections:W})=>{for(let K of Object.keys(w)){let y=W[K];m+=` /** * The update type for the "${y.name}" (\`${y.key}\`) collection. * * This type is used to update an existing ${y.name} record. * */ `.trimStart(),m+=C(K,w[K],{kind:"update"}),m+=` `}return m};import P from"node:fs";import M from"node:fs/promises";import h from"node:path";import H from"chalk";var T=async(m)=>{let w=Q();if(!P.existsSync(w)){console.log(H.red("node_modules directory for @levo-so/client not found. Are you sure you have installed the package?"));return}let W="generated.d.ts",K=h.join(w,"dist",W);try{await M.writeFile(K,m),console.log("✔",H.bold("Types generated successfully"),H.grey("to"),H.grey(K.replace(process.cwd(),".")))}catch(y){console.error(H.red("We could not write the generated types.")),console.error(y)}};var u=S(o(process.argv)).options({workspace:{type:"string",demandOption:!0,alias:"w",description:"The ID or the Slug of the Workspace"},key:{type:"string",demandOption:!0,description:"Your API Key for the Levo API"},endpoint:{type:"string",demandOption:!1,alias:"e",description:"The endpoint to use for the API (Optional)"}}).argv;(async()=>{await Y();let{endpoint:m="https://public-api.levo.so",workspace:w}=u;console.log(F.gray("Generating schema for collections in"),F.bold.blue(w),`workspace${F.gray(".")}`);let W=await Z({endpoint:m,workspace:w});if(!W)return;let{collections:K,fields:y}=W;if(typeof y!=="object"||typeof K!=="object"){console.error(F.red("We could not get the schema for the workspace."));return}console.log(F.gray("Generating types for"),F.bold.blue(Object.keys(K).length),`collections${F.gray(".")}`);let A=`import type { FieldValueType } from './types/lema'; `;A=B({file:A,fields:y,collections:K}),A=_({file:A,fields:y,collections:K}),A=N({file:A,fields:y,collections:K}),A=D({file:A,fields:y}),await T(A),process.exit(0)})();