UNPKG

@gqty/cli

Version:

## Visit [https://gqty.dev/docs/cli/codegen](https://gqty.dev/docs/cli/codegen)

5 lines (4 loc) 2.56 kB
#!/usr/bin/env node import{readFile as u}from"fs/promises";import{extname as p}from"path";import"@graphql-codegen/core";import"@graphql-codegen/typescript";import"@graphql-tools/utils";import{schemaFromExecutor as w}from"@graphql-tools/wrap";import*as g from"@inquirer/prompts";import"commander";import"cosmiconfig";import{fetch as y}from"cross-fetch";import v from"fast-glob";import{buildSchema as S,printSchema as x}from"graphql";import"lodash-es/sortBy.js";import"prettier";import{convertHeadersInput as E}from"./convertHeadersInput.mjs";import{logger as l}from"./logger.mjs";const F=[".gql",".graphql"];class d extends Error{constructor(e,s){super(`Received status code ${s.status} when introspecting ${s.url}`),this.request=e,this.response=s}name="FetchError"}const q=async(t,e)=>{var s;const i=[];e.headersByEndpoint||(e.headersByEndpoint={});for(const o of t){const{headers:a,headersByEndpoint:h}=e,m=async()=>{var r;const n=await b(o,{headers:a!=null?a:(r=h[o])==null?void 0:r.headers,silent:e.silent});n!==void 0&&i.push(n)};try{await m()}catch(r){if(r instanceof d&&r.response.status===401&&a===void 0&&((s=h[o])==null?void 0:s.headers)===void 0){process.stdout.write("\r");const n=await $();if(n===void 0)throw r;h[r.response.url]={headers:n};try{await m()}catch(c){throw c}}else throw r}}if(i.length===0)throw new Error("No schemas found.");return e.silent||(l.successProgress("Schema introspection completed."),console.log("")),S(i.join(` `))},b=async(t,e)=>{if(f(t)){e!=null&&e.silent||l.infoProgress(`Fetching schema from remote endpoint '${t}'...`);const i=await w(async({document:o,variables:a,extensions:h={}})=>{const{print:m}=await import("graphql"),r={method:"POST",headers:{"Content-Type":"application/json",...e==null?void 0:e.headers},body:JSON.stringify({query:m(o),variables:a,extensions:{...h,endpoint:t}})},n=await y(t,r);if(n.status>=400)throw new d(r,n);const c=await n.text();try{return JSON.parse(c)}catch{throw new SyntaxError(`Invalid JSON received from ${t}: "${c.length>50?c.slice(0,50).replace(/\n/g,"")+"...":c}".`)}});return x(i)}else{const s=await v(t).then(o=>o.filter(a=>F.includes(p(a))));if(s.length===0)return;const i=[];for(const o of s)e!=null&&e.silent||l.infoProgress(`Reading schema file ${o} ...`),i.push(await u(o,{encoding:"utf-8"}));return i.join(` `)}},$=async()=>{if(!process.stdin.isTTY)return;const t=await g.input({message:"Any request headers? (Authorization: Bearer <token>, X-Foo: <bar>)"});return E(t.split(/,/))},f=t=>/^https?:\/\//.test(t);export{d as FetchError,q as fetchSchemas,f as isURL};