@getcronit/pylon-dev
Version:
CLI for creating a Pylon
293 lines (247 loc) • 42.2 kB
JavaScript
import{program as G}from"commander";import{spawn as ct}from"child_process";import $ from"consola";import lt from"dotenv";var ce="2.0.0-canary-20260317113404.1a39ad4b34ee59425656d7efe6deca94c22a84a8";import{PostHog as Ae}from"posthog-node";import je from"conf";import{readFileSync as Re}from"fs";import{randomUUID as le}from"crypto";var Ee={distinctId:{type:"string",default:le()}},Le=new je({projectName:"pylon",schema:Ee}),E=Le.get("distinctId"),L=le(),A=new Ae("phc_KN4qCOcCdkXp6sHLIuMWGRfzZWuNht69oqv5Kw5rGxj",{host:"https://eu.i.posthog.com",disabled:process.env.PYLON_DISABLE_TELEMETRY==="true"}),_e=()=>{let c;try{c=JSON.parse(Re("./package.json","utf8"))}catch{c={}}let s=c.dependencies||{},t=c.devDependencies||{},e=c.peerDependencies||{};return{dependencies:s,devDependencies:t,peerDependencies:e}},_=_e(),te=async()=>{try{let s=(await import(`${process.cwd()}/.pylon/config.js`)).config,t=JSON.parse(JSON.stringify(s));return Object.keys(t).length===0?!1:t}catch{return!1}};import We from"path";import{context as Ge}from"esbuild";import He from"esbuild-plugin-tsc";import he from"fs/promises";import M from"path";import pe from"fs/promises";async function I(c,s){try{if(await pe.readFile(c,"utf8")===s)return!1}catch(t){if(t.code!=="ENOENT")throw t}return await pe.writeFile(c,s,"utf8"),!0}import Be from"esbuild";import{readFileSync as Me}from"fs";import{dirname as qe,resolve as Ue}from"path";import v from"typescript";async function fe(c,s=".pylon/config.js"){let t=Ue(c),e=Me(t,"utf8"),o=v.createSourceFile(t,e,v.ScriptTarget.ESNext,!0),a=new Map,n=new Map;function i(f,y){if(v.isIdentifier(f))a.set(f.text,y);else if(v.isObjectBindingPattern(f)||v.isArrayBindingPattern(f))for(let T of f.elements)v.isBindingElement(T)&&i(T.name,y)}v.forEachChild(o,f=>{if(v.isVariableStatement(f))for(let y of f.declarationList.declarations)i(y.name,f);else if(v.isFunctionDeclaration(f)&&f.name)a.set(f.name.text,f);else if(v.isClassDeclaration(f)&&f.name)a.set(f.name.text,f);else if(v.isEnumDeclaration(f)&&f.name)a.set(f.name.text,f);else if(v.isInterfaceDeclaration(f)&&f.name)a.set(f.name.text,f);else if(v.isTypeAliasDeclaration(f)&&f.name)a.set(f.name.text,f);else if(v.isImportDeclaration(f)){let y=f.importClause;if(y&&(y.name&&n.set(y.name.text,f),y.namedBindings))if(v.isNamedImports(y.namedBindings))for(let T of y.namedBindings.elements)n.set(T.name.text,f);else v.isNamespaceImport(y.namedBindings)&&n.set(y.namedBindings.name.text,f)}});let l=new Set,h=new Set,d=new Set;function r(f){if(d.has(f))return;d.add(f);let y=a.get(f);y&&(l.add(y),p(y));let T=n.get(f);T&&h.add(T)}function p(f){v.forEachChild(f,y=>{if(v.isIdentifier(y)){let T=y.parent;if(v.isPropertyAccessExpression(T)&&T.name===y||v.isPropertyAssignment(T)&&T.name===y||v.isMethodDeclaration(T)&&T.name===y||v.isClassDeclaration(T)&&T.name===y||v.isFunctionDeclaration(T)&&T.name===y)return;r(y.text)}else p(y)})}let u=a.get("config");u&&(l.add(u),p(u));let m=[];for(let f of o.statements)v.isImportDeclaration(f)?h.has(f)&&m.push(f.getFullText(o).trim()):l.has(f)&&m.push(f.getFullText(o).trim());let g=m.join(`
`);!a.has("config")&&!g.includes("export const config")&&(g+=`
export const config = {}`),await Be.build({stdin:{contents:g,resolveDir:qe(t),sourcefile:t,loader:"ts"},bundle:!0,format:"esm",outfile:s,packages:"external"})}import Je from"fs/promises";import H from"path";var ue=({getBuildDefs:c,outputDir:s})=>({name:"inject-code",setup(t){t.onLoad({filter:/src[\/\\]index\.ts$/,namespace:"file"},async e=>{if(H.relative(process.cwd(),e.path)!==H.join("src","index.ts"))return;let{typeDefs:a,resolvers:n}=c(),i=me(n),l=await Je.readFile(e.path,"utf-8"),h=H.join(process.cwd(),s,"schema.graphql");await I(h,a);let d=H.join(process.cwd(),s,"resolvers.js");return await I(d,`export const resolvers = ${i}`),{loader:"ts",contents:`import {executeConfig} from "@getcronit/pylon"
var __internalPylonConfig = {config: {}}
try {
__internalPylonConfig = await import('./config.js')
} catch (e) {
}
await executeConfig(__internalPylonConfig.config)
`+l+`
import {handler as __internalPylonHandler} from "@getcronit/pylon"
app.use(__internalPylonHandler({
typeDefs: ${JSON.stringify(a)},
graphql,
resolvers: ${i},
}))
await executeConfig(__internalPylonConfig.config, {
pluginsStrategy: "last"
})
`}})}});function me(c){return`{${Object.entries(c).map(([t,e])=>{if(e!==void 0)return typeof e=="string"?`${t}:${e}`:typeof e=="function"?`${t}:${e.toString()}`:typeof e=="object"&&!Array.isArray(e)?`${t}:${me(e)}`:`${t}:${JSON.stringify(e)}`}).join(",")}}`}import Qe from"path";import ye from"fs/promises";import B from"consola";var de=({dir:c,onBuild:s})=>({name:"notify",async setup(t){let e=async()=>{let n=Qe.join(c,"schema.graphql");try{await ye.access(n)}catch{return null}return await ye.readFile(n,"utf-8")},o=await e(),a=Date.now();t.onStart(async()=>{a=Date.now(),B.start("[Pylon]: Building...")}),t.onEnd(async n=>{if(n.errors.length>0){for(let p of n.errors)B.error(`[Pylon]: ${p.text}
${p.location?`at ${p.location.file}:${p.location.line}:${p.location.column}`:""}
${p.detail?p.detail:""}`);throw new Error("Failed to build Pylon")}if(n.warnings.length>0)for(let p of n.warnings)B.warn(p);let i=Date.now()-a,l=Object.keys(n.metafile.inputs).length,h=Object.values(n.metafile.outputs).reduce((p,u)=>p+u.bytes,0),d=await e();B.success(`[Pylon]: Built in ${i}ms`);let r=d!==o;r&&(B.info("[Pylon]: Schema updated"),o=d),s&&await s({totalFiles:l,totalSize:h,schemaChanged:r,duration:i})})}});var W=class{sfiFilePath;outputDir;constructor(s,t="./.pylon"){this.sfiFilePath=s,this.outputDir=t}async initBuildPlugins(s){let t=M.join(process.cwd(),this.outputDir,"config.js");await fe(this.sfiFilePath,t);let e;try{e=(await import(t)).config}catch(n){console.error("Error loading config",n)}let o=[],a=e?.plugins||[];for(let n of a)if(n.build){let i=n.build({onBuild:s.onBuild});o.push(i)}return o}async build(s){let t=M.join(process.cwd(),this.sfiFilePath),e=M.join(process.cwd(),this.outputDir);await he.mkdir(e,{recursive:!0});let o={name:"write-on-end",setup(i){i.onEnd(async l=>{await Promise.all(l.outputFiles.map(async h=>{await he.mkdir(M.dirname(h.path),{recursive:!0}),await I(h.path,h.text)}))})}},a=await Ge({write:!1,platform:"node",logLevel:"silent",metafile:!0,entryPoints:[t],outdir:e,bundle:!0,format:"esm",sourcemap:"inline",packages:"external",plugins:[de({dir:e,onBuild:async i=>{await s.onBuild?.(i)}}),ue({getBuildDefs:s.getBuildDefs,outputDir:this.outputDir}),He({tsconfigPath:M.join(process.cwd(),"tsconfig.json")}),o]});s.skipInitialBuild||await a.rebuild();let n=await this.initBuildPlugins({onBuild:()=>{s.onBuild?.({totalFiles:0,totalSize:0,schemaChanged:!1,duration:0})}});if(!s.skipInitialBuild)for(let i of n)await(await i).rebuild();return{watch:async()=>{for(let i of n)await(await i).watch();return await a.watch()},rebuild:async()=>{for(let i of n)await(await i).rebuild();await a.rebuild()},dispose:async()=>{for(let i of n)await(await i).dispose();await a.dispose()},cancel:async()=>{for(let i of n)await(await i).cancel();await a.cancel()}}}};import x from"typescript";import ne from"consola";import P from"typescript";import w from"typescript";import b from"typescript";var ge=c=>(c.flags&b.TypeFlags.Object||c.flags&b.TypeFlags.NonPrimitive)&&c.getProperties().length===0&&c.getCallSignatures().length===0,O=(c,s)=>{let t=c.typeToTypeNode(s,void 0,void 0),e=!!(t&&(t.kind===b.SyntaxKind.ArrayType||t.kind===b.SyntaxKind.TupleType));return!e&&(s.getSymbol()?.getName()==="Array"||s.getBaseTypes()?.some(a=>a.getSymbol()?.getName()==="Array"))?!0:e};var N=c=>c.flags&b.TypeFlags.String||c.flags&b.TypeFlags.Number||c.flags&b.TypeFlags.Boolean||c.flags&b.TypeFlags.StringLiteral||c.flags&b.TypeFlags.NumberLiteral||c.flags&b.TypeFlags.BooleanLiteral,Te=c=>!!(c.flags&b.TypeFlags.StringLiteral||c.flags&b.TypeFlags.NumberLiteral||c.flags&b.TypeFlags.BooleanLiteral),ie=c=>!!(c.flags&b.TypeFlags.Never),z=c=>c.getCallSignatures().length>0,C=c=>{if(N(c)||!c.isUnion())return!1;let s=c.types.filter(e=>!(e.flags&b.TypeFlags.Undefined||e.flags&b.TypeFlags.Null));return s.length===0?!1:s.every(e=>e.flags&b.TypeFlags.StringLiteral||e.flags&b.TypeFlags.NumberLiteral||e.flags&b.TypeFlags.BooleanLiteral)},q=c=>c.getSymbol()?.getName()==="Promise",U=c=>{if(c.objectFlags&b.ObjectFlags.Reference){let e=c.typeArguments;if(e&&e.length>0)return e[0]}},be=c=>{if(!c.isUnion())return{type:c,wasOptional:!1};let t=c.types.filter(e=>!(e.flags&b.TypeFlags.Undefined||e.flags&b.TypeFlags.Null)).length!==c.types.length;return{type:c.getNonNullableType(),wasOptional:t}};function Se(c,s){let t=s;if(t.isUnion()){let a=t.types.filter(l=>!(l.flags&b.TypeFlags.Object&&l.objectFlags&b.ObjectFlags.Reference&&l.typeArguments?.length)),n=t.types.filter(l=>l.flags&b.TypeFlags.Object&&l.objectFlags&b.ObjectFlags.Reference&&l.typeArguments?.length).map(l=>l.typeArguments[0]),i=a.filter(l=>!n.some(h=>h===l));t=c.getUnionType(i)}let e=[];if(O(c,t)||N(t)||C(t))return e;let o=[];o=t.resolvedProperties||t.getProperties()||[];for(let a of o)(a.valueDeclaration&&!(b.getCombinedModifierFlags(a.valueDeclaration)&b.ModifierFlags.Private)&&!a.getName().startsWith("#"))!==!1&&e.push(a);return e}var F=c=>{let s=c.replace(/[^0-9a-zA-Z_]/g,"_");for(;s.startsWith("_");)s=s.slice(1);return s||"JSONObject"},V=c=>!!c.getSymbol()?.getDeclarations()?.some(s=>s.getSourceFile().fileName.includes("@repeaterjs"));var Y=class{checker;schema;program;typesNameMap=new Map;inputsNameMap=new Map;unions=[];enums=[];constructor(s,t,e){this.checker=s,this.schema=t,this.program=e}getExistingTypeByName(s,t){for(let[e,o]of t.entries())if(o===s)return e}getUniqueName(s,t,e,o){let a=t,n=1;for(;;){let i=this.getExistingTypeByName(a,e);if(!i)break;if(this.checker.isTypeAssignableTo(s,i)&&this.checker.isTypeAssignableTo(i,s))return a;let l=`_${n}`;a=o?o(l):`${t}${l}`,n++}return a}isTypeSymbol(s){return s?!!(s.flags&(w.SymbolFlags.TypeAlias|w.SymbolFlags.Interface|w.SymbolFlags.Class|w.SymbolFlags.Enum|w.SymbolFlags.Type)):!1}getTypeDefinition=(s,t={isInputType:!1,dryRun:!1})=>{let{type:e,wasOptional:o}=be(s);if(e.flags&w.TypeFlags.Void||e.flags&w.TypeFlags.Undefined||e.flags&w.TypeFlags.Null)return{name:"Void",isList:!1,isRequired:!1};if(e.flags&w.TypeFlags.Any||ie(e))return{name:ie(e)?"JSONObject":"Any",isList:!1,isRequired:t.isRequired!==void 0?t.isRequired:!o};if(V(e)){let r=this.checker.getTypeArguments(e)[0];if(r)return this.getTypeDefinition(r,t)}if(q(e)){let r=U(e);if(r)return this.getTypeDefinition(r,t)}let a=t.isRequired!==void 0?t.isRequired:!o;if(ge(e))return{name:"JSONObject",isList:!1,isRequired:a};let n=t.isInputType?this.inputsNameMap:this.typesNameMap;if(n.has(e))return{name:n.get(e),isList:!1,isRequired:a};let i=e.aliasSymbol?.escapedName?.toString()||e.symbol?.escapedName.toString(),l=e.getProperty("__typename");if(l){let r=l.valueDeclaration??e.aliasSymbol?.getDeclarations()?.[0]??e.symbol?.getDeclarations()?.[0];if(r){let p=this.checker.getTypeOfSymbolAtLocation(l,r);p&&p.flags&w.TypeFlags.StringLiteral&&(i=p.value)}}if(i==="__type"||i==="__object"||!i){let r=e.aliasSymbol||e.symbol;if(r){let p=r.getDeclarations();if(p)for(let u of p){if(u.name){i=u.name.escapedText?.toString();break}let m=u.parent;for(;m;){if((w.isVariableDeclaration(m)||w.isPropertyDeclaration(m)||w.isPropertySignature(m)||w.isParameter(m)||w.isPropertyAssignment(m))&&w.isIdentifier(m.name)){i=m.name.escapedText.toString();break}m=m.parent}if(i)break}}}let h=t.propertyName;(i==="__type"||i==="__object"||!i||t.isInputType&&h&&!e.aliasSymbol)&&!N(e)&&!(i&&this.schema.scalars.includes(i))&&h&&(i=h.charAt(0).toUpperCase()+h.slice(1));let d=r=>{let p=r.aliasSymbol||r.symbol;if(!p)return!1;let u=p.getDeclarations();return u?u.some(m=>{let g=m.getSourceFile();return this.program.isSourceFileDefaultLibrary(g)||g.fileName.includes("node_modules/typescript/lib")}):!1};if(i){let r=e,p=this.checker.getTypeArguments(r);p.length===0&&e.aliasTypeArguments&&(p=e.aliasTypeArguments);let u=d(e),m=!!e.aliasSymbol,g=m&&!u;if(p.length>0&&!g&&(!e.aliasSymbol||e.aliasSymbol.escapedName.toString()!==i||e.aliasTypeArguments)){let f=p;u&&m&&(f=p.filter((S,D)=>D===0?!0:!(Te(S)||C(S))));let T=f.map(S=>this.getTypeDefinition(S,{...t,dryRun:t.dryRun}).name).join("");u&&m?i=T:i.startsWith(T)||(i=`${T}${i}`)}i=F(i),i=i.charAt(0).toUpperCase()+i.slice(1)}if(i==="JsonValue"||i==="JsonObject")return{name:"JSON",isList:!1,isRequired:a};if(i==="JsonArray")return{name:"JSON",isList:!0,isRequired:!0,isListRequired:a};if(i&&!this.schema.scalars.includes(i)){t.isInputType&&!i.endsWith("Input")&&!C(e)&&(i=`${i}Input`);let r;if(e.aliasTypeArguments||e.typeArguments){let p=e,u=this.checker.getTypeArguments(p);if(u.length===0&&e.aliasTypeArguments&&(u=e.aliasTypeArguments),u.length>0){let m=u[0],f=this.getTypeDefinition(m,{...t,dryRun:t.dryRun}).name;if(i.startsWith(f)){let y=i.slice(f.length);r=T=>`${f}${T}${y}`}}}i=this.getUniqueName(e,i,n,r)}if(i&&this.schema.scalars.includes(i))return{name:i,isList:!1,isRequired:a};if(n.has(e))return{name:n.get(e),isList:!1,isRequired:a};if(O(this.checker,e)){let r=this.checker.getIndexTypeOfType(e,w.IndexKind.Number);if(r){let p=this.getTypeDefinition(r,t);return{name:p.name,isList:!0,isRequired:p.isRequired,isListRequired:a}}}else if(C(e)){let r=this.checker.typeToTypeNode(e,void 0,void 0),u=e.types.map(m=>{if(m.isLiteral()){let g=m.value?.toString();if(!g)throw new Error("Enum member name is undefined");return F(g)}throw new Error("Invalid type for enum member")});u.length>0&&(i=i||r.typeName?.symbol?.escapedName,i||(i=u.join("_").toUpperCase(),i=t.isInputType?`${i}Input`:i),t.dryRun||this.enums.find(m=>m.name===i)||(this.enums.push({name:i,values:u,rawType:e}),this.typesNameMap.set(e,i),this.inputsNameMap.set(e,i)))}else if(N(e)){let r=this.checker.typeToString(e);return e.flags&w.TypeFlags.StringLiteral?r="String":e.flags&w.TypeFlags.NumberLiteral?r="Number":e.flags&w.TypeFlags.BooleanLiteral?r="Boolean":e.flags&w.TypeFlags.String?r="String":e.flags&w.TypeFlags.Number?r="Number":e.flags&w.TypeFlags.Boolean&&(r="Boolean"),{name:F(r),isList:!1,isRequired:a}}else if(e.isIntersection()){let p=e.types.map(u=>this.getTypeDefinition(u,t).name);i=F(i||p.join("And"))}else if(e.isUnion()){let r=e.types,p=e.types.length===r.length,u=r.some(y=>{let T=O(this.checker,y)?this.checker.getIndexTypeOfType(y,w.IndexKind.Number):y;return T?N(T)||C(T):!0}),m=[...new Set(r.map(y=>this.getTypeDefinition(y,{...t,isRequired:p})))],g=m.filter(y=>y.isList);for(let y of g){let T=m.findIndex(S=>S.name===y.name&&!S.isList);T>-1&&m.splice(T,1)}let f=m.map(y=>y.name);if(i=F(i||f.join("Or")),i&&(i=this.getUniqueName(e,i,n)),m.length>1&&!t.isInputType&&!u)t.dryRun||this.unions.find(y=>y.name===i)||this.unions.push({name:i,types:f,rawType:e});else{if(m.some(S=>S.name==="JSON"||S.name==="JSONObject"||S.name==="Any"))return{name:"JSON",isList:!1,isRequired:a};let y=m[0];if(!y)throw new Error("Cannot get type definition");let T=m.some(S=>S.isList&&S.name===y.name);return{name:y.name,isList:T,isRequired:a}}}else if(z(e)){let p=e.getCallSignatures()[0]?.getReturnType();if(p&&q(p)){let u=U(p);u&&(p=u)}if(p)return this.getTypeDefinition(p,t)}return i||(i="JSONObject"),t.dryRun||n.set(e,i),{name:i,isList:!1,isRequired:a}};getUnions(){return this.unions}getEnums(){return this.enums}typeDefinitionToGraphQLType=s=>{let t=s.name,{isList:e,isRequired:o,isListRequired:a}=s;return o&&(t=`${t}!`),e&&(t=`[${t}]`,a&&(t=`${t}!`)),t}};var J={String:"string",ID:"string",Int:"number",Float:"number",Boolean:"boolean",Number:"number",Any:"any",Void:"void",JSONObject:"object",File:"File",Date:"Date",JSON:"object"},ve=Object.keys(J);var K=class{schema;checker;program;sfiFile;typeDefinitionBuilder;constructor(s,t,e){this.schema={types:[],inputs:[],interfaces:[],unions:[],enums:[],scalars:ve},this.checker=s,this.sfiFile=t,this.program=e,this.typeDefinitionBuilder=new Y(s,this.schema,e)}parse(s){let t=this.makeReferenceSchema(s);for(let[e,o]of t.types){let a;s.Query===e?a="Query":s.Mutation===e?a="Mutation":s.Subscription===e&&(a="Subscription"),this.processSchemaReference(e,o,a,"types")}for(let[e,o]of t.inputs)this.processSchemaReference(e,o,void 0,"inputs");this.extractForbiddenFieldNamesFromSchema(),this.schema.unions=this.typeDefinitionBuilder.getUnions().map(e=>({...e,description:this.getTypeDocumentation(e.rawType)})),this.schema.enums=this.typeDefinitionBuilder.getEnums().map(e=>({...e,description:this.getTypeDocumentation(e.rawType)})),this.schema.types=this.schema.types.filter(e=>!this.schema.enums.find(o=>o.name===e.name)),this.schema.inputs=this.schema.inputs.filter(e=>!this.schema.enums.find(o=>o.name===e.name)),this.schema.unions.forEach(e=>{let o=this.checkIfInterfaceIsPossibleForUnion(e,this.schema.types);o&&(this.schema.interfaces.push(o),this.schema.unions=this.schema.unions.filter(a=>a.name!==e.name),this.schema.types.map(a=>{if(e.types.includes(a.name))return a.implements||(a.implements=[]),a.implements.push(o.name),a}))});for(let[e,o]of t.inheritanceMap){let a=F(this.checker.typeToString(e)),n=`I${a}`,i=this.schema.types.find(l=>l.name===a);if(i){let l=this.schema.interfaces.find(d=>d.name===n);if(!l){l={name:n,description:i.description,fields:[...i.fields],implements:[],__resolveType:void 0};let d=e.getBaseTypes();d&&d.forEach(r=>{let u=`I${F(this.checker.typeToString(r))}`;if(t.inheritanceMap.has(r))l.implements.push(u);else{let m=r.getSymbol();if(m){for(let[g]of t.inheritanceMap)if(g.getSymbol()===m){l.implements.push(u);break}}}}),this.schema.interfaces.push(l)}i.implements||(i.implements=[]),i.implements.includes(n)||i.implements.push(n);let h=d=>{for(let r of d){let p=F(this.checker.typeToString(r)),u=this.schema.types.find(g=>g.name===p);u&&(u.implements||(u.implements=[]),u.implements.includes(n)||u.implements.push(n));let m=t.inheritanceMap.get(r);if(!m){let g=r.getSymbol();if(g){for(let[f,y]of t.inheritanceMap)if(f.getSymbol()===g){m=y;break}}}m&&h(m)}};h(o),this.schema.types.forEach(d=>{d.fields.forEach(r=>{r.type.name===a&&(r.type.name=n)})})}}for(let[e,o]of t.classImplementsMap){this.schema.types.map(a=>{let n=this.schema.types.find(i=>i.rawType===e);return n&&(n.implements=Array.from(new Set([...n.implements||[],...o.map(i=>this.checker.typeToString(i))]))),a});for(let a of o){let n=this.schema.types.find(i=>i.rawType===a);n&&(this.schema.interfaces.push({name:this.checker.typeToString(a),description:this.getTypeDocumentation(a),fields:n.fields}),this.schema.types=this.schema.types.filter(i=>i.rawType!==a))}}this.schema.types=this.schema.types.map(e=>((e.implements||this.schema.unions.find(o=>o.types.includes(e.name)))&&(e.fields=e.fields.filter(o=>o.type.name!=="Void")),e)),this.schema.unions=this.schema.unions.map(e=>({...e,__resolveType:this.getResolveTypeForUnionOrInterface(e,this.schema.types)})),this.schema.interfaces=this.schema.interfaces.map(e=>({...e,__resolveType:this.getResolveTypeForUnionOrInterface(e,this.schema.types)}))}checkIfInterfaceIsPossibleForUnion(s,t){let e=s.types.map(n=>{let i=t.find(l=>l.name===n);if(!i)throw new Error(`Type ${n} not found`);return i}),a=e[0].fields.filter(n=>e.every(i=>i.fields.some(l=>JSON.stringify(l)===JSON.stringify(n))));return a.length>0?{name:s.name,description:s.description,fields:a}:null}getResolveTypeForUnionOrInterface(s,t){let e="types"in s?t.filter(i=>s.types.includes(i.name)):t.filter(i=>i.implements?.includes(s.name));e.sort((i,l)=>l.fields.length-i.fields.length);let o=new Map;e.forEach(i=>{let l=i.fields.map(h=>h.name).sort().join(", ");if(o.has(l)){let h=o.get(l);ne.warn(`Warning: Union types "${i.name}" and "${h?.name}" have the same fields: [${l}].
Consider differentiating these types by adding unique fields or using different type names.
This may cause ambiguity in type resolution.`)}else o.set(l,i)});let n=`function resolveType(node) { if (!node || typeof node !== 'object') return null; ${e.map(i=>{let l=e.filter(r=>r.name!==i.name),h=new Set(l.flatMap(r=>r.fields.map(p=>p.name))),d=i.fields.find(r=>r.type.isRequired&&!h.has(r.name));if(d)return`if ("${d.name}" in node && node["${d.name}"] !== undefined) { return '${i.name}'; }`;{let r=i.fields.map(p=>`"${p.name}" in node && node["${p.name}"] !== undefined`).join(" && ");return r.length>0?`if (${r}) { return '${i.name}'; }`:""}}).filter(i=>i.length>0).join(" ")} return null; }`;return new Function("return "+n)()}toString(){let{typeDefinitionToGraphQLType:s}=this.typeDefinitionBuilder,t=o=>o?`"""
${o}
"""
`:"",e="";for(let o of this.schema.inputs){e+=t(o.description),e+=`input ${o.name} {
`,o.fields.length===0&&(e+=` _ : String
`);for(let a of o.fields)e+=`${t(a.type.description)}`,e+=` ${a.name}: ${s(a.type)}
`;e+=`}
`}for(let o of this.schema.types)if(o.fields.length!==0){e+=t(o.description),e+=`type ${o.name}`,o.implements&&(e+=` implements ${[...o.implements].sort((a,n)=>a.localeCompare(n)).join(" & ")}`),e+=` {
`;for(let a of o.fields){let n="";a.args.length>0&&(n=`(${a.args.map(i=>`${t(i.type.description)}${i.name}: ${s(i.type)}`).join(", ")})`),e+=`${t(a.type.description)}`,e+=`${a.name}${n}: ${s(a.type)}
`}e+=`}
`}for(let o of this.schema.unions)e+=t(o.description),e+=`union ${o.name} = ${o.types.join(" | ")}
`;for(let o of this.schema.interfaces){e+=t(o.description),e+=`interface ${o.name}`,o.implements&&o.implements.length>0&&(e+=` implements ${[...o.implements].sort((a,n)=>a.localeCompare(n)).join(" & ")}`),e+=` {
`;for(let a of o.fields)e+=`${t(a.type.description)}`,e+=`${a.name}: ${s(a.type)}
`;e+=`}
`}for(let o of this.schema.scalars)e+=`scalar ${o}
`;for(let o of this.schema.enums){e+=t(o.description),e+=`enum ${o.name} {
`;for(let a of o.values)e+=` ${a}
`;e+=`}
`}return e}getSchema(){return this.schema}getResolvers(){let s={};for(let t of this.schema.unions)s[t.name]={__resolveType:t.__resolveType};for(let t of this.schema.interfaces)s[t.name]={__resolveType:t.__resolveType};return s}processSchemaReference(s,t,e,o="types"){let{getTypeDefinition:a}=this.typeDefinitionBuilder,n=o==="inputs",i=a(s,{isInputType:n}),l=e||i.name,h=this.schema[o].find(d=>d.name===l);if(h){if(h.fields.length>0)return}else{if(this.schema.scalars.includes(l))return;this.schema[o].push({name:l,description:this.getTypeDocumentation(s),fields:[],rawType:O(this.checker,s)&&(s.getNumberIndexType()||s.getStringIndexType())||s}),h=this.schema[o][this.schema[o].length-1]}for(let[d,r]of Object.entries(t)){let p=r.returnType,u=a(p,{isInputType:n,propertyName:d});if(o==="types"){let m={name:d,type:{...u,description:this.getSymbolDocumentation(r.symbol)},args:[]};if(r.args)for(let[g,f]of Object.entries(r.args)){let y=f,T=a(y.type,{isInputType:!0,propertyName:d+g.charAt(0).toUpperCase()+g.slice(1),isRequired:f.isRequired});this.schema.scalars.includes(this.checker.typeToString(y.type))&&(T.name=this.checker.typeToString(y.type)),m.args.push({name:g,type:{...T,description:y.documentation}})}h.fields.push(m)}else if(o==="inputs"){let m={name:d,type:{...u,description:this.getTypeDocumentation(p)}};h.fields.find(g=>g.name===m.name)||h.fields.push(m)}}}getSymbolDocumentation(s){let t="";t+=P.displayPartsToString(s.getDocumentationComment(this.checker));let e=s.getJsDocTags(this.checker).map(o=>`@${o.name} ${P.displayPartsToString(o.text)}`).join(`
`);return e&&(t+=`
`+e),t}getTypeDocumentation=s=>{let t=s.getSymbol();return t?this.getSymbolDocumentation(t):""};extractForbiddenFieldNamesFromSchema(){let s=/^[_A-Za-z][_0-9A-Za-z]*$/,t=e=>s.test(e)?e.startsWith("__"):!0;for(let e of this.schema.types)e.fields=e.fields.filter(o=>!t(o.name));for(let e of this.schema.inputs)e.fields=e.fields.filter(o=>!t(o.name))}makeReferenceSchema(s){let t={types:new Map,inputs:new Map,classImplementsMap:new Map,inheritanceMap:new Map},e=(n,i={},l="types",h=[])=>{if(t[l].has(n))return;if(V(n)){let r=this.checker.getTypeArguments(n)[0];e(r,i,l,[...h,"REPEATER_ITEM"]);return}if(this.checker.typeToString(n)!=="[]"&&!this.schema.scalars.includes(this.checker.typeToString(n))&&!N(n)){if(q(n)){if(l==="inputs")return;let r=U(n);r&&e(r,i,l,[...h,"PROMISE"]);return}if(n.getSymbol()?.flags&P.SymbolFlags.Class){let r=n.getBaseTypes();r&&r.forEach(p=>{p.getSymbol()?.flags&P.SymbolFlags.Class&&(t.inheritanceMap.has(p)||t.inheritanceMap.set(p,[]),t.inheritanceMap.get(p).push(n),e(p))})}if(n.isUnion())if(C(n))t[l].has(n)||t[l].set(n,{}),e(n,i,l,[...h,"ENUM"]);else if(l==="types")n.types.forEach(r=>{r.flags&P.TypeFlags.Null||r.flags&P.TypeFlags.Undefined||N(r)||e(r,i,l,[...h,r.symbol?.getName()||`N/A ${this.checker.typeToString(r)}`])});else{let r=n.getNonNullableType();r.isUnion()&&!N(r)&&(ne.warn(`Warning: Union types in input fields are not supported yet. Defaulting to the first type (${this.checker.typeToString(r)}) at path: ${h.join(" > ")}`),r=r.types[0]),e(r,i,l,[...h,"NON_NULLABLE"])}else if(z(n)){if(l==="inputs")return;if(!i.parentType)throw new Error("Cannot have a function without a parent type");let r=n.getCallSignatures()[0],p=r?.getParameters()||[],u=r?.getReturnType(),m=t[l].get(i.parentType)[i.propetyName];p.forEach(g=>{let f=this.checker.getTypeOfSymbolAtLocation(g,this.sfiFile);if(this.checker.isTupleType(f))f.target.labeledElementDeclarations.forEach((S,D)=>{let R=this.checker.getTypeAtLocation(S),oe=S.name.text,Ce=this.checker.getSymbolAtLocation(S),Ie=this.getSymbolDocumentation(Ce||g);m.args[oe]={type:R,isRequired:S.initializer===void 0?void 0:!1,documentation:Ie},e(R,{parentType:n},"inputs",[...h,oe])});else if(g.valueDeclaration&&P.isParameter(g.valueDeclaration)&&g.valueDeclaration.dotDotDotToken)ne.warn(`Warning: Rest parameters without explicit names are not supported. Skipping rest parameter at path: ${h.join(" > ")}.
Unsupported: \`function example(...args: any[]) { }\`.
Supported: \`function example(...namedArgs: [first: string, second: number]) { }\`.
Please provide named rest parameters to ensure proper type resolution.`);else{let y=g.valueDeclaration;m.args&&(m.args[g.escapedName]={type:f,isRequired:y.initializer===void 0?void 0:!1,documentation:this.getSymbolDocumentation(g)},e(f,{parentType:n},"inputs",[...h,g.escapedName]))}}),u&&e(u,i,l,[...h,"RETURN_TYPE"])}else if(O(this.checker,n)){let r=this.checker.getIndexTypeOfType(n,P.IndexKind.Number);r&&!N(r)&&(t[l].has(n)||t[l].set(n,{}),e(r,i,l,[...h,"ITEM_TYPE"]))}else if(!N(n)){let r=Se(this.checker,n);t[l].has(n)||t[l].set(n,{}),r.forEach(p=>{let u=this.checker.getTypeOfSymbolAtLocation(p,this.sfiFile);t[l].get(n)[p.escapedName]||(t[l].get(n)[p.escapedName]={symbol:p,returnType:u,args:{}}),e(u,{propetyName:p.escapedName,parentType:n},l,[...h,p.escapedName])})}}};s.Query&&e(s.Query),s.Mutation&&e(s.Mutation),s.Subscription&&e(s.Subscription);let o=this.program.getSourceFiles();for(let n of o)n.isDeclarationFile||P.forEachChild(n,i=>{if(P.isClassDeclaration(i)||P.isInterfaceDeclaration(i)){let l=this.checker.getTypeAtLocation(i),h=i.heritageClauses;h&&h.forEach(d=>{d.types.forEach(r=>{let p=this.checker.getTypeAtLocation(r),u=p,m=p.getSymbol();if(m){for(let y of t.inheritanceMap.keys())if(y.getSymbol()===m){u=y;break}}t.inheritanceMap.has(u)||t.inheritanceMap.set(u,[]);let g=t.inheritanceMap.get(u),f=l.getSymbol();f&&!g.some(y=>y.getSymbol()===f)&&g.push(l)})})}});let a=!0;for(;a;){a=!1;for(let[n,i]of t.inheritanceMap){let l=t.types.has(n);if(!l){let d=n.getSymbol();if(d){for(let r of t.types.keys())if(r.getSymbol()===d){l=!0;break}}}let h=!1;for(let d of i){if(t.types.has(d)){h=!0;break}let r=d.getSymbol();if(r){for(let p of t.types.keys())if(p.getSymbol()===r){h=!0;break}}if(h)break}if(l)for(let d of i){let r=t.types.has(d);if(!r){let p=d.getSymbol();if(p){for(let u of t.types.keys())if(u.getSymbol()===p){r=!0;break}}}r||(e(d),a=!0)}else h&&(e(n),a=!0)}}return t}};import j from"path";var Z=class{program;checker;sfiFile;sfi;sfiFilePath;constructor(s){this.sfiFilePath=s;let t=this.loadTsConfigOptions(),e=x.sys.readDirectory(j.dirname(this.sfiFilePath),[".ts"],[".d.ts"]).concat([j.join(j.dirname(this.sfiFilePath),"..","pylon.d.ts")]);this.program=x.createProgram(e,t),this.checker=this.program.getTypeChecker(),this.loadSfi()}loadSfi(){let t=this.program.getSourceFiles().find(n=>j.resolve(n.fileName)===this.sfiFilePath);if(!t)throw new Error("Could not find index.ts (pylon entrypoint)");this.sfiFile=t;let e=this.checker.getSymbolAtLocation(t),a=this.checker.getExportsOfModule(e).find(n=>n.escapedName==="graphql");if(!a)throw new Error("Could not find graphql export");this.sfi=a}loadTsConfigOptions(){let s={target:x.ScriptTarget.ESNext,module:x.ModuleKind.CommonJS,strict:!0,esModuleInterop:!0,skipLibCheck:!1,forceConsistentCasingInFileNames:!0,noImplicitAny:!0,experimentalDecorators:!0},t=x.findConfigFile(j.dirname(this.sfiFilePath),x.sys.fileExists,"tsconfig.json");if(!t)return console.log("Could not find tsconfig.json"),s;let e=x.readConfigFile(t,x.sys.readFile);return e.error?(console.log("Could not read tsconfig.json",e.error),s):x.parseJsonConfigFileContent(e.config,x.sys,j.dirname(t)).options}build(){let s=this.checker.getTypeOfSymbolAtLocation(this.sfi,this.sfiFile),t=s.getProperty("Query"),e=s.getProperty("Mutation"),o=s.getProperty("Subscription"),a=t?this.checker.getTypeOfSymbolAtLocation(t,this.sfiFile):void 0,n=e?this.checker.getTypeOfSymbolAtLocation(e,this.sfiFile):void 0,i=o?this.checker.getTypeOfSymbolAtLocation(o,this.sfiFile):void 0,l=new K(this.checker,this.sfiFile,this.program);return l.parse({Query:a,Mutation:n,Subscription:i}),{typeDefs:l.toString(),schema:l.getSchema(),resolvers:l.getResolvers()}}};var se=async c=>await new W(c.sfiFilePath,c.outputFilePath).build({getBuildDefs:()=>{let e=new Z(We.join(process.cwd(),c.sfiFilePath)).build();return{typeDefs:e.typeDefs,resolvers:e.resolvers}},onBuild:c.onBuild,skipInitialBuild:c.skipInitialBuild});import{generateClient as ze}from"@gqty/cli";import Ve from"esbuild";import X from"fs/promises";import{buildSchema as Ye}from"graphql";import ee from"path";var we=ee.join(process.cwd(),".pylon/schema.graphql"),Q=ee.join(process.cwd(),".pylon/client/index.ts"),re=async({schemaChanged:c})=>{try{await X.access(we)}catch{throw new Error("Schema not found. Please run `pylon build` or `pylon dev` first.")}if(!c)try{await X.access(Q);return}catch{}let s=await X.readFile(we,"utf-8"),t=Ye(s);await X.mkdir(ee.dirname(Q),{recursive:!0}),await I(Q,Ke),await ze(t,{endpoint:"will-be-overwritten",frameworks:["react"],destination:Q,react:!0,scalarTypes:{Number:"number",JSONObject:"Record<string, unknown>"}}),await Ve.build({entryPoints:[Q],bundle:!0,outfile:ee.join(process.cwd(),".pylon/client/index.js"),packages:"external",format:"esm",platform:"node"})},Ke=`/**
* GQty: You can safely modify this file based on your needs.
*/
import {createReactClient} from '@gqty/react'
import {
Cache,
createClient,
defaultResponseHandler,
type QueryFetcher
} from 'gqty'
import {
generatedSchema,
scalarsEnumsHash,
type GeneratedSchema
} from './schema.generated'
const queryFetcher: QueryFetcher = async function (
{query, variables, operationName},
fetchOptions
) {
const headers = new Headers({});
let fetchToUse: typeof fetch | typeof app.request = fetch
try {
// 1. Try importing Pylon \u2014 if this works, we're on the server
const moduleNameToPreventBundling = '@getcronit/pylon'
const { app, getContext } = await import(moduleNameToPreventBundling)
fetchToUse = app.request
// 2. Get headers from the original server request and forward them
const context = getContext()
for (const [key, value] of context.req.raw.headers.entries()) {
headers.append(key, value)
// Set Accept-Encoding header to identity so the internal fetch returns JSON
headers.set('Accept-Encoding', 'identity')
headers.set('X-Pylon-Internal', 'true')
}
} catch {
// 3. Pylon not available \u2014 fallback to default fetch (runs in browser)
// No additional headers are needed; browser sends cookies automatically
}
const formData = buildGraphQLMultipartForm(query, variables);
const response = await fetchToUse('/graphql', {
method: 'POST',
headers,
body: formData,
mode: 'cors',
...fetchOptions
})
const serverVersion = response.headers.get('X-Pylon-Version')
if (
serverVersion &&
typeof window !== 'undefined' &&
(window as any).__PYLON_VERSION__ &&
serverVersion !== (window as any).__PYLON_VERSION__
) {
const isMutation = query.trim().startsWith('mutation')
if (!isMutation) {
window.location.reload()
}
}
return await defaultResponseHandler(response)
}
function buildGraphQLMultipartForm(query, variables) {
const form = new FormData();
const operations = { query, variables: structuredClone(variables) };
const map = {};
const files = [];
let fileIndex = 0;
// Helper to find all files in variables
function recurse(value, path = []) {
if (value instanceof File || value instanceof Blob) {
map[fileIndex] = [\`variables.\${path.join(".")}\`];
set(operations.variables, path, null);
files.push({ index: fileIndex, file: value });
fileIndex++;
} else if (Array.isArray(value)) {
value.forEach((item, i) => recurse(item, [...path, i]));
} else if (value && typeof value === "object") {
Object.entries(value).forEach(([key, val]) =>
recurse(val, [...path, key])
);
}
}
recurse(variables);
form.append("operations", JSON.stringify(operations));
form.append("map", JSON.stringify(map));
files.forEach(({ index, file }) => {
form.append(index, file);
});
return form;
}
// Utility to set a value at a path inside an object
function set(obj, path, value) {
let curr = obj;
for (let i = 0; i < path.length - 1; i++) {
curr = curr[path[i]];
}
curr[path[path.length - 1]] = value;
}
export const cache = new Cache(
undefined,
/**
* Default option is immediate cache expiry but keep it for 5 minutes,
* allowing soft refetches in background.
*/
{
maxAge: Infinity,
staleWhileRevalidate: 5 * 60 * 1000,
normalization: true
}
)
export const client = createClient<GeneratedSchema>({
schema: generatedSchema,
scalars: scalarsEnumsHash,
cache,
fetchOptions: {
fetcher: queryFetcher
}
})
export const pageClient = () => {
const client = createClient<GeneratedSchema>({
schema: generatedSchema,
scalars: scalarsEnumsHash,
cache: new Cache(
undefined,
{
maxAge: Infinity,
staleWhileRevalidate: 5 * 60 * 1000,
normalization: true
}
),
fetchOptions: {
fetcher: queryFetcher
}
})
const react = createReactClient(client, {
defaults: {
suspense: false
}
})
return {client, ...react, pageClient}
}
// Core functions
export const {resolve, subscribe, schema} = client
// Legacy functions
export const {query, mutation, mutate, subscription, resolved, refetch, track} =
client
export const {
graphql,
useQuery,
usePaginatedQuery,
useTransactionQuery,
useLazyQuery,
useRefetch,
useMutation,
useMetaState,
prepareReactRender,
useHydrateCache,
prepareQuery
} = createReactClient<GeneratedSchema>(client, {
defaults: {
// Enable Suspense, you can override this option for each hook.
suspense: false
}
})
export * from './schema.generated'`;import Ne from"fs/promises";import{buildClientSchema as Ze,getIntrospectionQuery as Xe,isEnumType as et,isInputObjectType as tt,isInterfaceType as Pe,isListType as it,isNonNullType as nt,isObjectType as ae,isScalarType as xe,isUnionType as Fe}from"graphql";var k=c=>nt(c)?{tsType:k(c.ofType).tsType,isNullable:!1}:it(c)?{tsType:`Array<${k(c.ofType).tsType}>`,isNullable:!0}:xe(c)?Object.keys(J).includes(c.name)?{tsType:c.name,isNullable:!0}:{tsType:c.name,isNullable:!0}:{tsType:c.name,isNullable:!0};async function De(c,s){let t=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:Xe()})}),{data:e}=await t.json(),o=Ze(e),a=o.getTypeMap(),n=`// AUTO-GENERATED BY PYLON INTROSPECT
`;for(let[d,r]of Object.entries(J))r==="Date"||r==="File"||(n+=`type ${d} = ${r} & {readonly brand?: unique symbol};
`);n+=`
`;for(let d in a){if(d.startsWith("__"))continue;let r=a[d];if(ae(r)){let p=["Query","Mutation","Subscription"].includes(d);n+=`export interface ${d} {
`,n+=` readonly __typename${p?"?":""}: '${d}';
`;for(let[u,m]of Object.entries(r.getFields())){let{tsType:g,isNullable:f}=k(m.type);if(m.args.length>0){let y=m.args.map(T=>{let{tsType:S,isNullable:D}=k(T.type);return`${T.name}${D?"?":""}: ${S}`}).join(", ");n+=` ${u}(${y}): ${g}${f?" | null":""};
`}else n+=` ${u}${f?"?":""}: ${g};
`}n+=`}
`}else if(Pe(r)){let p=o.getPossibleTypes(r);if(p.length>0){let u=p.map(m=>m.name).join(" | ");n+=`export type ${d} = ${u};
`}else{n+=`export interface ${d} {
`,n+=` readonly __typename: string;
`;for(let[u,m]of Object.entries(r.getFields())){let{tsType:g,isNullable:f}=k(m.type);if(m.args.length>0){let y=m.args.map(T=>{let{tsType:S,isNullable:D}=k(T.type);return`${T.name}${D?"?":""}: ${S}`}).join(", ");n+=` ${u}(${y}): ${g}${f?" | null":""};
`}else n+=` ${u}${f?"?":""}: ${g};
`}n+=`}
`}}else if(tt(r)){n+=`export interface ${d} {
`;for(let[p,u]of Object.entries(r.getFields())){let{tsType:m,isNullable:g}=k(u.type);n+=` ${p}${g?"?":""}: ${m};
`}n+=`}
`}else if(et(r)){let p=r.getValues().map(u=>`'${u.name}'`).join(" | ");n+=`export type ${d} = ${p};
`}else if(Fe(r)){let p=r.getTypes().map(u=>u.name).join(" | ");n+=`export type ${d} = ${p};
`}else xe(r)&&(Object.keys(J).includes(d)||(n+=`export type ${d} = any;
`))}let i=s.substring(0,s.lastIndexOf("/"));i&&await Ne.mkdir(i,{recursive:!0});let l=`export interface RemoteRegistry {
`;l+=` delegate: {
`;let h=["Query","Mutation"];for(let d of h){let r=a[d];if(r&&ae(r))for(let[p,u]of Object.entries(r.getFields())){let{tsType:m,isNullable:g}=k(u.type),f="{}",y=u.args;y.length>0&&(f=`{ ${y.map(S=>{let{tsType:D,isNullable:R}=k(S.type);return`${S.name}${R?"?":""}: ${D}`}).join("; ")} }`),l+=` '${d}.${p}': {
`,l+=` args: ${f};
`,l+=` return: ${m}${g?" | null":""};
`,l+=` };
`}}l+=` };
`,l+=` types: {
`;for(let[d,r]of Object.entries(a))d.startsWith("__")||["Query","Mutation","Subscription"].includes(d)||(ae(r)||Pe(r)||Fe(r))&&(l+=` '${d}': ${d};
`);l+=` };
`,l+=`}
`,await Ne.writeFile(s,n+l)}import{execSync as st,spawnSync as rt}from"child_process";function $e(c,s){if(process.platform==="win32"){st("taskkill /pid "+c+" /T /F");return}ot(c).forEach(function(e){ke(e,s)}),ke(c,s)}function at(){let c=rt("ps",["-A","-o","pid,ppid"],{encoding:"utf-8",stdio:"pipe"});return c.error||!c.stdout?[]:c.stdout.trim().split(`
`).slice(1).map(function(t){let e=t.match(/\s*(\d+)\s*(\d+)/);return e===null?null:{pid:Number(e[1]),ppid:Number(e[2])}}).filter(t=>t!=null)}function ot(c){let s=at(),t={},e=[];s.forEach(function(a){t[a.ppid]=t[a.ppid]||[],t[a.ppid].push(a.pid)});let o=function(a){t[a]=t[a]||[],t[a].forEach(function(n){e.push(n),o(n)})};return o(c),e}function ke(c,s){try{process.kill(c,s)}catch(t){if(t.code!=="ESRCH")throw t}}lt.config();G.name("pylon-dev").description("Pylon Development CLI").version(ce);G.command("build").description("Build the Pylon Schema").action(async()=>{let c=await se({sfiFilePath:"./src/index.ts",outputFilePath:"./.pylon",onBuild:async({totalFiles:t,totalSize:e,duration:o,schemaChanged:a})=>{try{A.capture({distinctId:E,event:"build completed",properties:{duration:o,totalFiles:t,totalSize:e,schemaChanged:a,dependencies:_,isDevelopment:!1,$session_id:L}}),await re({schemaChanged:a})}catch(n){$.error("Error during build callback",n)}}}),s=async()=>{await c.dispose(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s),process.on("SIGHUP",s),await c.rebuild(),await c.dispose()});G.command("pull").description("Fetch a remote GraphQL API and generate strictly-typed Pylon Gateway models.").argument("<url>","The remote GraphQL endpoint URL").option("-n, --name <name>","The name of the remote service (used for the generated filename)","remote").option("-o, --output <dir>","The directory to output the generated types","./src/generated").action(async(c,s)=>{try{let t=`${s.output}/${s.name}.ts`;$.start(`Pulling ${s.name} schema from ${c}...`),await De(c,t),$.success(`Remote types generated successfully at ${t}`)}catch(t){$.error(`Failed to pull ${s.name} remote schema:`,t),process.exit(1)}});G.command("dev").description("Start the Pylon Development Server").option("-c, --command <command>","Command to run the server","bun run .pylon/index.js").action(async c=>{let s=null,t=async()=>{if(s&&s.pid){try{$e(s.pid)}catch(o){$.error("Failed to kill server process",o)}s=null}},e=null;await new Promise(async(o,a)=>{try{e=await se({sfiFilePath:"./src/index.ts",outputFilePath:"./.pylon",onBuild:async({schemaChanged:i,totalFiles:l,totalSize:h,duration:d})=>{try{await re({schemaChanged:i}),await t(),s=await pt(c.command),A.capture({distinctId:E,event:"build completed",properties:{duration:d,totalFiles:l,totalSize:h,schemaChanged:i,dependencies:_,pylonConfig:await te(),isDevelopment:!0,$session_id:L}})}catch(r){$.error("Error during dev build callback",r)}},skipInitialBuild:!0}),await e.watch(),$.box(`Pylon is up and running!
Press \`Ctrl + C\` to stop the server.
Encounter any issues? Report them here:
https://github.com/getcronit/pylon/issues
We value your feedback\u2014help us make Pylon even better!`);let n=async()=>{e&&await e.dispose(),await t(),process.exit(0)};process.on("SIGINT",n),process.on("SIGTERM",n),process.on("SIGHUP",n),process.on("exit",()=>t()),A.capture({distinctId:E,event:"dev server started",properties:{command:c.command,dependencies:_,pylonConfig:await te(),$session_id:L}})}catch(n){e&&await e.dispose(),await t(),a(n)}})});var pt=async c=>{let[s,...t]=c.split(" "),e=ct(s,t,{stdio:"inherit",env:{...process.env,NODE_ENV:"development",FORCE_COLOR:"1"}});return e.on("error",o=>{$.error(o)}),e};try{await G.parseAsync(process.argv)}catch(c){$.error(c),A.captureException(c,E,{$session_id:L,dependencies:_})}finally{await A.shutdown()}
//# sourceMappingURL=index.js.map