@samarium.sdk/new 0.21.2 → 0.22.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.
Files changed (2) hide show
  1. package/bin/samarium +220 -51
  2. package/package.json +2 -2
package/bin/samarium CHANGED
@@ -354,7 +354,7 @@ ${F.comment}`:F.comment}this.doc.range[2]=F.offset;break}default:this.errors.pus
354
354
  `)+1;while(F!==0)this.onNewLine(this.offset+F),F=this.source.indexOf(`
355
355
  `,F)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(D){let F=D.items[D.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,F.value){let P="end"in F.value?F.value.end:void 0;if((Array.isArray(P)?P[P.length-1]:void 0)?.type==="comment")P?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else if(F.sep)F.sep.push(this.sourceToken);else F.start.push(this.sourceToken);return;case"space":case"comment":if(F.value)D.items.push({start:[this.sourceToken]});else if(F.sep)F.sep.push(this.sourceToken);else{if(this.atIndentedComment(F.start,D.indent)){let B=D.items[D.items.length-2]?.value?.end;if(Array.isArray(B)){Array.prototype.push.apply(B,F.start),B.push(this.sourceToken),D.items.pop();return}}F.start.push(this.sourceToken)}return}if(this.indent>=D.indent){let P=!this.onKeyLine&&this.indent===D.indent,B=P&&(F.sep||F.explicitKey)&&this.type!=="seq-item-ind",Z=[];if(B&&F.sep&&!F.value){let q=[];for(let X=0;X<F.sep.length;++X){let J=F.sep[X];switch(J.type){case"newline":q.push(X);break;case"space":break;case"comment":if(J.indent>D.indent)q.length=0;break;default:q.length=0}}if(q.length>=2)Z=F.sep.splice(q[1])}switch(this.type){case"anchor":case"tag":if(B||F.value)Z.push(this.sourceToken),D.items.push({start:Z}),this.onKeyLine=!0;else if(F.sep)F.sep.push(this.sourceToken);else F.start.push(this.sourceToken);return;case"explicit-key-ind":if(!F.sep&&!F.explicitKey)F.start.push(this.sourceToken),F.explicitKey=!0;else if(B||F.value)Z.push(this.sourceToken),D.items.push({start:Z,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(F.explicitKey)if(!F.sep)if(D8(F.start,"newline"))Object.assign(F,{key:null,sep:[this.sourceToken]});else{let q=l8(F.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,key:null,sep:[this.sourceToken]}]})}else if(F.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(D8(F.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Z,key:null,sep:[this.sourceToken]}]});else if(lQ(F.key)&&!D8(F.sep,"newline")){let q=l8(F.start),X=F.key,J=F.sep;J.push(this.sourceToken),delete F.key,delete F.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,key:X,sep:J}]})}else if(Z.length>0)F.sep=F.sep.concat(Z,this.sourceToken);else F.sep.push(this.sourceToken);else if(!F.sep)Object.assign(F,{key:null,sep:[this.sourceToken]});else if(F.value||B)D.items.push({start:Z,key:null,sep:[this.sourceToken]});else if(D8(F.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else F.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let q=this.flowScalar(this.type);if(B||F.value)D.items.push({start:Z,key:q,sep:[]}),this.onKeyLine=!0;else if(F.sep)this.stack.push(q);else Object.assign(F,{key:q,sep:[]}),this.onKeyLine=!0;return}default:{let q=this.startBlockValue(D);if(q){if(P&&q.type!=="block-seq")D.items.push({start:Z});this.stack.push(q);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(D){let F=D.items[D.items.length-1];switch(this.type){case"newline":if(F.value){let P="end"in F.value?F.value.end:void 0;if((Array.isArray(P)?P[P.length-1]:void 0)?.type==="comment")P?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else F.start.push(this.sourceToken);return;case"space":case"comment":if(F.value)D.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(F.start,D.indent)){let B=D.items[D.items.length-2]?.value?.end;if(Array.isArray(B)){Array.prototype.push.apply(B,F.start),B.push(this.sourceToken),D.items.pop();return}}F.start.push(this.sourceToken)}return;case"anchor":case"tag":if(F.value||this.indent<=D.indent)break;F.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==D.indent)break;if(F.value||D8(F.start,"seq-item-ind"))D.items.push({start:[this.sourceToken]});else F.start.push(this.sourceToken);return}if(this.indent>D.indent){let P=this.startBlockValue(D);if(P){this.stack.push(P);return}}yield*this.pop(),yield*this.step()}*flowCollection(D){let F=D.items[D.items.length-1];if(this.type==="flow-error-end"){let P;do yield*this.pop(),P=this.peek(1);while(P&&P.type==="flow-collection")}else if(D.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!F||F.sep)D.items.push({start:[this.sourceToken]});else F.start.push(this.sourceToken);return;case"map-value-ind":if(!F||F.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(F.sep)F.sep.push(this.sourceToken);else Object.assign(F,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!F||F.value)D.items.push({start:[this.sourceToken]});else if(F.sep)F.sep.push(this.sourceToken);else F.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let B=this.flowScalar(this.type);if(!F||F.value)D.items.push({start:[],key:B,sep:[]});else if(F.sep)this.stack.push(B);else Object.assign(F,{key:B,sep:[]});return}case"flow-map-end":case"flow-seq-end":D.end.push(this.sourceToken);return}let P=this.startBlockValue(D);if(P)this.stack.push(P);else yield*this.pop(),yield*this.step()}else{let P=this.peek(2);if(P.type==="block-map"&&(this.type==="map-value-ind"&&P.indent===D.indent||this.type==="newline"&&!P.items[P.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&P.type!=="flow-collection"){let B=p5(P),Z=l8(B);mQ(D);let q=D.end.splice(1,D.end.length);q.push(this.sourceToken);let X={type:"block-map",offset:D.offset,indent:D.indent,items:[{start:Z,key:D,sep:q}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=X}else yield*this.lineEnd(D)}}flowScalar(D){if(this.onNewLine){let F=this.source.indexOf(`
356
356
  `)+1;while(F!==0)this.onNewLine(this.offset+F),F=this.source.indexOf(`
357
- `,F)+1}return{type:D,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(D){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let F=p5(D),P=l8(F);return P.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let F=p5(D),P=l8(F);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(D,F){if(this.type!=="comment")return!1;if(this.indent<=F)return!1;return D.every((P)=>P.type==="newline"||P.type==="space")}*documentEnd(D){if(this.type!=="doc-mode"){if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(D){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}ng.Parser=cQ});var sQ=Q((Zy)=>{var dQ=CP(),og=H6(),G6=U6(),tg=_F(),eg=i(),Dy=_P(),pQ=kP();function rQ(D){let F=D.prettyErrors!==!1;return{lineCounter:D.lineCounter||F&&new Dy.LineCounter||null,prettyErrors:F}}function Fy(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=Array.from(q.compose(Z.parse(D)));if(B&&P)for(let J of X)J.errors.forEach(G6.prettifyError(D,P)),J.warnings.forEach(G6.prettifyError(D,P));if(X.length>0)return X;return Object.assign([],{empty:!0},q.streamInfo())}function aQ(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=null;for(let J of q.compose(Z.parse(D),!0,D.length))if(!X)X=J;else if(X.options.logLevel!=="silent"){X.errors.push(new G6.YAMLParseError(J.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(B&&P)X.errors.forEach(G6.prettifyError(D,P)),X.warnings.forEach(G6.prettifyError(D,P));return X}function Py(D,F,P){let B=void 0;if(typeof F==="function")B=F;else if(P===void 0&&F&&typeof F==="object")P=F;let Z=aQ(D,P);if(!Z)return null;if(Z.warnings.forEach((q)=>tg.warn(Z.options.logLevel,q)),Z.errors.length>0)if(Z.options.logLevel!=="silent")throw Z.errors[0];else Z.errors=[];return Z.toJS(Object.assign({reviver:B},P))}function By(D,F,P){let B=null;if(typeof F==="function"||Array.isArray(F))B=F;else if(P===void 0&&F)P=F;if(typeof P==="string")P=P.length;if(typeof P==="number"){let Z=Math.round(P);P=Z<1?void 0:Z>8?{indent:8}:{indent:Z}}if(D===void 0){let{keepUndefined:Z}=P??F??{};if(!Z)return}if(eg.isDocument(D)&&!B)return D.toString(P);return new og.Document(D,B,P).toString(P)}Zy.parse=Py;Zy.parseAllDocuments=Fy;Zy.parseDocument=aQ;Zy.stringify=By});var iQ=Q((Ey)=>{var Hy=CP(),Uy=H6(),Wy=JP(),xP=U6(),Oy=n1(),K2=i(),zy=R2(),Qy=ED(),Gy=$2(),Ry=M2(),Iy=c5(),$y=uP(),My=_P(),Ky=kP(),r5=sQ(),nQ=a1();Ey.Composer=Hy.Composer;Ey.Document=Uy.Document;Ey.Schema=Wy.Schema;Ey.YAMLError=xP.YAMLError;Ey.YAMLParseError=xP.YAMLParseError;Ey.YAMLWarning=xP.YAMLWarning;Ey.Alias=Oy.Alias;Ey.isAlias=K2.isAlias;Ey.isCollection=K2.isCollection;Ey.isDocument=K2.isDocument;Ey.isMap=K2.isMap;Ey.isNode=K2.isNode;Ey.isPair=K2.isPair;Ey.isScalar=K2.isScalar;Ey.isSeq=K2.isSeq;Ey.Pair=zy.Pair;Ey.Scalar=Qy.Scalar;Ey.YAMLMap=Gy.YAMLMap;Ey.YAMLSeq=Ry.YAMLSeq;Ey.CST=Iy;Ey.Lexer=$y.Lexer;Ey.LineCounter=My.LineCounter;Ey.Parser=Ky.Parser;Ey.parse=r5.parse;Ey.parseAllDocuments=r5.parseAllDocuments;Ey.parseDocument=r5.parseDocument;Ey.stringify=r5.stringify;Ey.visit=nQ.visit;Ey.visitAsync=nQ.visitAsync});var $6={name:"@samarium.sdk/new",version:"0.21.2",main:"bin/samarium",type:"module",repository:{type:"git",url:"https://github.com/liontariai/samarium",directory:"packages/new"},keywords:["graphql","typescript","compiler","api","sdk","openapi","oas3","oas3.1","swagger","graphql-sdk","graphql-codegen"],homepage:"https://liontari.ai",bin:{samarium:"bin/samarium"},publishConfig:{access:"public"},files:["bin/**/*","README.md","package.json"],scripts:{prettier:"prettier --write .",bundle:"bun bundle.js",prepublishOnly:"bun run bundle",test:"bun test"},prettier:{tabWidth:4},devDependencies:{"bun-types":"^1.1.29","@samarium.sdk/make":"workspace:*"},peerDependencies:{typescript:"^5.0.0"},dependencies:{"@inquirer/prompts":"^5.0.5",commander:"^11.1.0","detect-indent":"^7.0.1",prettier:"^3.2.5",yaml:"^2.6.0"}};var XB=UD(qB(),1),{program:Hm,createCommand:Um,createArgument:Wm,createOption:Om,CommanderError:zm,InvalidArgumentError:Qm,InvalidOptionArgumentError:Gm,Command:JB,Argument:Rm,Option:Im,Help:$m}=XB.default;var RU=UD(u0(),1);var A3=UD(u0(),1);class Z2 extends Error{response;request;constructor(D,F){let P=`${Z2.extractMessage(D)}: ${JSON.stringify({response:D,request:F})}`;super(P);if(Object.setPrototypeOf(this,Z2.prototype),this.response=D,this.request=F,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,Z2)}static extractMessage(D){return D.errors?.[0]?.message??`GraphQL Error (Code: ${String(D.status)})`}}var C7=(D)=>D.toUpperCase(),R3=(D)=>{return typeof D==="function"?D():D},L7=(D,F)=>D.map((P,B)=>[P,F[B]]),v2=(D)=>{let F={};if(D instanceof Headers)F=oS(D);else if(Array.isArray(D))D.forEach(([P,B])=>{if(P&&B!==void 0)F[P]=B});else if(D)F=D;return F},oS=(D)=>{let F={};return D.forEach((P,B)=>{F[B]=P}),F},BU=(D)=>{try{let F=D();if(tS(F))return F.catch((P)=>{return PU(P)});return F}catch(F){return PU(F)}},PU=(D)=>{if(D instanceof Error)return D;return new Error(String(D))},tS=(D)=>{return typeof D==="object"&&D!==null&&"then"in D&&typeof D.then==="function"&&"catch"in D&&typeof D.catch==="function"&&"finally"in D&&typeof D.finally==="function"},I3=(D)=>{throw new Error(`Unhandled case: ${String(D)}`)},N1=(D)=>{return typeof D==="object"&&D!==null&&!Array.isArray(D)};var ZU=(D,F)=>{return D.documents?D:{documents:D,requestHeaders:F,signal:void 0}};var qU=(D,F,P)=>{return D.query?D:{query:D,variables:F,requestHeaders:P,signal:void 0}};var YU=UD(u0(),1);var w7="Accept",$3="Content-Type",u1="application/json",M3="application/graphql-response+json";var V7=(D)=>D.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),HU=(D)=>{let F=D.toLowerCase();return F.includes(M3)||F.includes(u1)},j7=(D)=>{try{if(Array.isArray(D))return{_tag:"Batch",executionResults:D.map(XU)};else if(N1(D))return{_tag:"Single",executionResult:XU(D)};else throw new Error(`Invalid execution result: result is not object or array.
357
+ `,F)+1}return{type:D,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(D){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let F=p5(D),P=l8(F);return P.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let F=p5(D),P=l8(F);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(D,F){if(this.type!=="comment")return!1;if(this.indent<=F)return!1;return D.every((P)=>P.type==="newline"||P.type==="space")}*documentEnd(D){if(this.type!=="doc-mode"){if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(D){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}ng.Parser=cQ});var sQ=Q((Zy)=>{var dQ=CP(),og=H6(),G6=U6(),tg=_F(),eg=i(),Dy=_P(),pQ=kP();function rQ(D){let F=D.prettyErrors!==!1;return{lineCounter:D.lineCounter||F&&new Dy.LineCounter||null,prettyErrors:F}}function Fy(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=Array.from(q.compose(Z.parse(D)));if(B&&P)for(let J of X)J.errors.forEach(G6.prettifyError(D,P)),J.warnings.forEach(G6.prettifyError(D,P));if(X.length>0)return X;return Object.assign([],{empty:!0},q.streamInfo())}function aQ(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=null;for(let J of q.compose(Z.parse(D),!0,D.length))if(!X)X=J;else if(X.options.logLevel!=="silent"){X.errors.push(new G6.YAMLParseError(J.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(B&&P)X.errors.forEach(G6.prettifyError(D,P)),X.warnings.forEach(G6.prettifyError(D,P));return X}function Py(D,F,P){let B=void 0;if(typeof F==="function")B=F;else if(P===void 0&&F&&typeof F==="object")P=F;let Z=aQ(D,P);if(!Z)return null;if(Z.warnings.forEach((q)=>tg.warn(Z.options.logLevel,q)),Z.errors.length>0)if(Z.options.logLevel!=="silent")throw Z.errors[0];else Z.errors=[];return Z.toJS(Object.assign({reviver:B},P))}function By(D,F,P){let B=null;if(typeof F==="function"||Array.isArray(F))B=F;else if(P===void 0&&F)P=F;if(typeof P==="string")P=P.length;if(typeof P==="number"){let Z=Math.round(P);P=Z<1?void 0:Z>8?{indent:8}:{indent:Z}}if(D===void 0){let{keepUndefined:Z}=P??F??{};if(!Z)return}if(eg.isDocument(D)&&!B)return D.toString(P);return new og.Document(D,B,P).toString(P)}Zy.parse=Py;Zy.parseAllDocuments=Fy;Zy.parseDocument=aQ;Zy.stringify=By});var iQ=Q((Ey)=>{var Hy=CP(),Uy=H6(),Wy=JP(),xP=U6(),Oy=n1(),K2=i(),zy=R2(),Qy=ED(),Gy=$2(),Ry=M2(),Iy=c5(),$y=uP(),My=_P(),Ky=kP(),r5=sQ(),nQ=a1();Ey.Composer=Hy.Composer;Ey.Document=Uy.Document;Ey.Schema=Wy.Schema;Ey.YAMLError=xP.YAMLError;Ey.YAMLParseError=xP.YAMLParseError;Ey.YAMLWarning=xP.YAMLWarning;Ey.Alias=Oy.Alias;Ey.isAlias=K2.isAlias;Ey.isCollection=K2.isCollection;Ey.isDocument=K2.isDocument;Ey.isMap=K2.isMap;Ey.isNode=K2.isNode;Ey.isPair=K2.isPair;Ey.isScalar=K2.isScalar;Ey.isSeq=K2.isSeq;Ey.Pair=zy.Pair;Ey.Scalar=Qy.Scalar;Ey.YAMLMap=Gy.YAMLMap;Ey.YAMLSeq=Ry.YAMLSeq;Ey.CST=Iy;Ey.Lexer=$y.Lexer;Ey.LineCounter=My.LineCounter;Ey.Parser=Ky.Parser;Ey.parse=r5.parse;Ey.parseAllDocuments=r5.parseAllDocuments;Ey.parseDocument=r5.parseDocument;Ey.stringify=r5.stringify;Ey.visit=nQ.visit;Ey.visitAsync=nQ.visitAsync});var $6={name:"@samarium.sdk/new",version:"0.22.0",main:"bin/samarium",type:"module",repository:{type:"git",url:"https://github.com/liontariai/samarium",directory:"packages/new"},keywords:["graphql","typescript","compiler","api","sdk","openapi","oas3","oas3.1","swagger","graphql-sdk","graphql-codegen"],homepage:"https://liontari.ai",bin:{samarium:"bin/samarium"},publishConfig:{access:"public"},files:["bin/**/*","README.md","package.json"],scripts:{prettier:"prettier --write .",bundle:"bun bundle.js",prepublishOnly:"bun run bundle",test:"bun test"},prettier:{tabWidth:4},devDependencies:{"bun-types":"^1.1.29","@samarium.sdk/make":"workspace:*"},peerDependencies:{typescript:"^5.0.0"},dependencies:{"@inquirer/prompts":"^5.0.5",commander:"^11.1.0","detect-indent":"^7.0.1",prettier:"^3.2.5",yaml:"^2.6.0"}};var XB=UD(qB(),1),{program:Hm,createCommand:Um,createArgument:Wm,createOption:Om,CommanderError:zm,InvalidArgumentError:Qm,InvalidOptionArgumentError:Gm,Command:JB,Argument:Rm,Option:Im,Help:$m}=XB.default;var RU=UD(u0(),1);var A3=UD(u0(),1);class Z2 extends Error{response;request;constructor(D,F){let P=`${Z2.extractMessage(D)}: ${JSON.stringify({response:D,request:F})}`;super(P);if(Object.setPrototypeOf(this,Z2.prototype),this.response=D,this.request=F,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,Z2)}static extractMessage(D){return D.errors?.[0]?.message??`GraphQL Error (Code: ${String(D.status)})`}}var C7=(D)=>D.toUpperCase(),R3=(D)=>{return typeof D==="function"?D():D},L7=(D,F)=>D.map((P,B)=>[P,F[B]]),v2=(D)=>{let F={};if(D instanceof Headers)F=oS(D);else if(Array.isArray(D))D.forEach(([P,B])=>{if(P&&B!==void 0)F[P]=B});else if(D)F=D;return F},oS=(D)=>{let F={};return D.forEach((P,B)=>{F[B]=P}),F},BU=(D)=>{try{let F=D();if(tS(F))return F.catch((P)=>{return PU(P)});return F}catch(F){return PU(F)}},PU=(D)=>{if(D instanceof Error)return D;return new Error(String(D))},tS=(D)=>{return typeof D==="object"&&D!==null&&"then"in D&&typeof D.then==="function"&&"catch"in D&&typeof D.catch==="function"&&"finally"in D&&typeof D.finally==="function"},I3=(D)=>{throw new Error(`Unhandled case: ${String(D)}`)},N1=(D)=>{return typeof D==="object"&&D!==null&&!Array.isArray(D)};var ZU=(D,F)=>{return D.documents?D:{documents:D,requestHeaders:F,signal:void 0}};var qU=(D,F,P)=>{return D.query?D:{query:D,variables:F,requestHeaders:P,signal:void 0}};var YU=UD(u0(),1);var w7="Accept",$3="Content-Type",u1="application/json",M3="application/graphql-response+json";var V7=(D)=>D.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),HU=(D)=>{let F=D.toLowerCase();return F.includes(M3)||F.includes(u1)},j7=(D)=>{try{if(Array.isArray(D))return{_tag:"Batch",executionResults:D.map(XU)};else if(N1(D))return{_tag:"Single",executionResult:XU(D)};else throw new Error(`Invalid execution result: result is not object or array.
358
358
  Got:
359
359
  ${String(D)}`)}catch(F){return F}},XU=(D)=>{if(typeof D!=="object"||D===null)throw new Error("Invalid execution result: result is not object");let F=void 0,P=void 0,B=void 0;if("errors"in D){if(!N1(D.errors)&&!Array.isArray(D.errors))throw new Error("Invalid execution result: errors is not plain object OR array");F=D.errors}if("data"in D){if(!N1(D.data)&&D.data!==null)throw new Error("Invalid execution result: data is not plain object");P=D.data}if("extensions"in D){if(!N1(D.extensions))throw new Error("Invalid execution result: extensions is not plain object");B=D.extensions}return{data:P,errors:F,extensions:B}},UU=(D)=>D._tag==="Batch"?D.executionResults.some(JU):JU(D.executionResult),JU=(D)=>Array.isArray(D.errors)?D.errors.length>0:Boolean(D.errors),b7=(D)=>{return typeof D==="object"&&D!==null&&"kind"in D&&D.kind===YU.Kind.OPERATION_DEFINITION};var WU=UD(u0(),1),OU=UD(u0(),1),zU=UD(u0(),1),eS=(D)=>{let F=void 0,P=D.definitions.filter(b7);if(P.length===1)F=P[0].name?.value;return F},DT=(D)=>{let F=!1,P=D.definitions.filter(b7);if(P.length===1)F=P[0].operation===WU.OperationTypeNode.MUTATION;return F},_1=(D,F)=>{let P=typeof D==="string"?D:zU.print(D),B=!1,Z=void 0;if(F)return{expression:P,isMutation:B,operationName:Z};let q=BU(()=>typeof D==="string"?OU.parse(D):D);if(q instanceof Error)return{expression:P,isMutation:B,operationName:Z};return Z=eS(q),B=DT(q),{expression:P,operationName:Z,isMutation:B}};var K3=JSON;var E3=async(D)=>{let F={...D,method:D.request._tag==="Single"?D.request.document.isMutation?"POST":C7(D.method??"post"):D.request.hasMutations?"POST":C7(D.method??"post"),fetchOptions:{...D.fetchOptions,errorPolicy:D.fetchOptions.errorPolicy??"none"}},B=await PT(F.method)(F);if(!B.ok)return new Z2({status:B.status,headers:B.headers},{query:D.request._tag==="Single"?D.request.document.expression:D.request.query,variables:D.request.variables});let Z=await FT(B,D.fetchOptions.jsonSerializer??K3);if(Z instanceof Error)throw Z;let q={status:B.status,headers:B.headers};if(UU(Z)&&F.fetchOptions.errorPolicy==="none"){let X=Z._tag==="Batch"?{...Z.executionResults,...q}:{...Z.executionResult,...q};return new Z2(X,{query:D.request._tag==="Single"?D.request.document.expression:D.request.query,variables:D.request.variables})}switch(Z._tag){case"Single":return{...q,...QU(F)(Z.executionResult)};case"Batch":return{...q,data:Z.executionResults.map(QU(F))};default:I3(Z)}},QU=(D)=>(F)=>{return{extensions:F.extensions,data:F.data,errors:D.fetchOptions.errorPolicy==="all"?F.errors:void 0}},FT=async(D,F)=>{let P=D.headers.get($3),B=await D.text();if(P&&HU(P))return j7(F.parse(B));else return j7(B)},PT=(D)=>async(F)=>{let P=new Headers(F.headers),B=null,Z=void 0;if(!P.has(w7))P.set(w7,[M3,u1].join(", "));if(D==="POST"){if(Z=(F.fetchOptions.jsonSerializer??K3).stringify(BT(F)),typeof Z==="string"&&!P.has($3))P.set($3,u1)}else B=ZT(F);let q={method:D,headers:P,body:Z,...F.fetchOptions},X=new URL(F.url),J=q;if(F.middleware){let H=await Promise.resolve(F.middleware({...q,url:F.url,operationName:F.request._tag==="Single"?F.request.document.operationName:void 0,variables:F.request.variables})),{url:W,...U}=H;X=new URL(W),J=U}if(B)B.forEach((H,W)=>{X.searchParams.append(W,H)});return await(F.fetch??fetch)(X,J)},BT=(D)=>{switch(D.request._tag){case"Single":return{query:D.request.document.expression,variables:D.request.variables,operationName:D.request.document.operationName};case"Batch":return L7(D.request.query,D.request.variables??[]).map(([F,P])=>({query:F,variables:P}));default:throw I3(D.request)}},ZT=(D)=>{let F=D.fetchOptions.jsonSerializer??K3,P=new URLSearchParams;switch(D.request._tag){case"Single":{if(P.append("query",V7(D.request.document.expression)),D.request.variables)P.append("variables",F.stringify(D.request.variables));if(D.request.document.operationName)P.append("operationName",D.request.document.operationName);return P}case"Batch":{let B=D.request.variables?.map((X)=>F.stringify(X))??[],Z=D.request.query.map(V7),q=L7(Z,B).map(([X,J])=>({query:X,variables:J}));return P.append("query",F.stringify(q)),P}default:throw I3(D.request)}};class g2{url;requestConfig;constructor(D,F={}){this.url=D,this.requestConfig=F}rawRequest=async(...D)=>{let[F,P,B]=D,Z=qU(F,P,B),{headers:q,fetch:X=globalThis.fetch,method:J="POST",requestMiddleware:Y,responseMiddleware:H,excludeOperationName:W,...U}=this.requestConfig,{url:O}=this;if(Z.signal!==void 0)U.signal=Z.signal;let z=_1(Z.query,W),I=await E3({url:O,request:{_tag:"Single",document:z,variables:Z.variables},headers:{...v2(R3(q)),...v2(Z.requestHeaders)},fetch:X,method:J,fetchOptions:U,middleware:Y});if(H)await H(I,{operationName:z.operationName,variables:P,url:this.url});if(I instanceof Error)throw I;return I};async request(D,...F){let[P,B]=F,Z=GU(D,P,B),{headers:q,fetch:X=globalThis.fetch,method:J="POST",requestMiddleware:Y,responseMiddleware:H,excludeOperationName:W,...U}=this.requestConfig,{url:O}=this;if(Z.signal!==void 0)U.signal=Z.signal;let z=_1(Z.document,W),I=await E3({url:O,request:{_tag:"Single",document:z,variables:Z.variables},headers:{...v2(R3(q)),...v2(Z.requestHeaders)},fetch:X,method:J,fetchOptions:U,middleware:Y});if(H)await H(I,{operationName:z.operationName,variables:Z.variables,url:this.url});if(I instanceof Error)throw I;return I.data}async batchRequests(D,F){let P=ZU(D,F),{headers:B,excludeOperationName:Z,...q}=this.requestConfig;if(P.signal!==void 0)q.signal=P.signal;let X=P.documents.map(({document:U})=>_1(U,Z)),J=X.map(({expression:U})=>U),Y=X.some(({isMutation:U})=>U),H=P.documents.map(({variables:U})=>U),W=await E3({url:this.url,request:{_tag:"Batch",operationName:void 0,query:J,hasMutations:Y,variables:H},headers:{...v2(R3(B)),...v2(P.requestHeaders)},fetch:this.requestConfig.fetch??globalThis.fetch,method:this.requestConfig.method||"POST",fetchOptions:q,middleware:this.requestConfig.requestMiddleware});if(this.requestConfig.responseMiddleware)await this.requestConfig.responseMiddleware(W,{operationName:void 0,variables:H,url:this.url});if(W instanceof Error)throw W;return W.data}setHeaders(D){return this.requestConfig.headers=D,this}setHeader(D,F){let{headers:P}=this.requestConfig;if(P)P[D]=F;else this.requestConfig.headers={[D]:F};return this}setEndpoint(D){return this.url=D,this}}var GU=(D,F,P)=>{return D.document?D:{document:D,variables:F,requestHeaders:P,signal:void 0}};async function y2(D,F){try{let B=await new g2(D).request(A3.getIntrospectionQuery(),void 0,new Headers(F?.map((q)=>q.split("="))));return A3.buildClientSchema(B)}catch(P){throw P}}import qT from"fs";var S7=async(D,F)=>{let P=await y2(D.url,D.headers),B=RU.printSchema(P);qT.writeFileSync(F,B)};var C3=UD(u0(),1),L3=UD(u0(),1),MD=UD(u0(),1),XT=Object.defineProperty,$U=(D,F)=>{for(var P in F)XT(D,P,{get:F[P],enumerable:!0,configurable:!0,set:(B)=>F[P]=()=>B})};class MU{collector;options;authConfig;static FieldValueWrapperType;static EnumTypesMapped;static HelperTypes;static HelperFunctions;typeMeta;typeName;originalFullTypeName;constructor(D,F,P,B){this.collector=F,this.options=P,this.authConfig=B,this.typeMeta=F.getType(D),this.originalFullTypeName=D,this.typeName=this.originalTypeNameToTypescriptFriendlyName(D)}originalTypeNameToTypescriptFriendlyName(D){return D.replaceAll("[","").replaceAll("]","Array").replaceAll("!","NotNull")}originalTypeNameToTypescriptTypeNameWithoutModifiers(D,F=""){return`${D.replaceAll("[","").replaceAll("]","").replaceAll("!","")}${F}`}originalTypeNameToTypescriptTypeName(D,F=""){return`${this.originalTypeNameToTypescriptTypeNameWithoutModifiers(D,F)}${Array.from({length:D.split("[").length-1}).fill("[]").join("")}`}static makeRootOperationFunction(D){throw new Error("Method not implemented.")}}var JT=`const Proxy = global.Proxy;
360
360
  Proxy.prototype = {};
@@ -417,6 +417,13 @@ export class RootOperation {
417
417
  input: string | URL | globalThis.Request,
418
418
  init?: RequestInit,
419
419
  ) => Promise<Response>,
420
+ sseFetchTransform: undefined as unknown as (
421
+ input: string | URL | globalThis.Request,
422
+ init?: RequestInit,
423
+ ) => Promise<
424
+ [string | URL | globalThis.Request, RequestInit | undefined]
425
+ >,
426
+
420
427
  _auth_fn: undefined as
421
428
  | (() => string | { [key: string]: string })
422
429
  | (() => Promise<string | { [key: string]: string }>)
@@ -500,6 +507,10 @@ export class RootOperation {
500
507
  (acc, [opName, { selection, rootSlw }]) => ({
501
508
  ...acc,
502
509
  [opName]: {
510
+ opType: rootSlw[SLW_IS_ROOT_TYPE]?.toLowerCase() as
511
+ | "subscription"
512
+ | "query"
513
+ | "mutation",
503
514
  query: \`\${rootSlw[SLW_IS_ROOT_TYPE]?.toLowerCase()} \${opName} \${
504
515
  selection.variableDefinitions.length
505
516
  ? \`(\${selection.variableDefinitions.join(", ")}) \`
@@ -512,13 +523,13 @@ export class RootOperation {
512
523
  {} as Record<
513
524
  string,
514
525
  {
526
+ opType: "subscription" | "query" | "mutation";
515
527
  query: string;
516
528
  variables: any;
517
529
  fragments: Map<string, string>;
518
530
  }
519
531
  >,
520
532
  );
521
- // const subscription = \`{\${subscriptions.join("")}}\`;
522
533
 
523
534
  const results = Object.fromEntries(
524
535
  await Promise.all([
@@ -526,7 +537,9 @@ export class RootOperation {
526
537
  async ([opName, op]) =>
527
538
  [
528
539
  opName,
529
- await this.executeOperation(op, headers),
540
+ op.opType === "subscription"
541
+ ? await this.subscribeOperation(op, headers)
542
+ : await this.executeOperation(op, headers),
530
543
  ] as const,
531
544
  ),
532
545
  ]),
@@ -535,8 +548,95 @@ export class RootOperation {
535
548
  return results;
536
549
  }
537
550
 
551
+ private async subscribeOperation(
552
+ query: {
553
+ opType: "subscription" | "query" | "mutation";
554
+ query: string;
555
+ variables: any;
556
+ fragments: Map<string, string>;
557
+ },
558
+ headers: Record<string, string> = {},
559
+ ): Promise<AsyncGenerator<any, void, unknown>> {
560
+ const that = this;
561
+ const generator = (async function* () {
562
+ const [url, options] = await (
563
+ RootOperation[OPTIONS].sseFetchTransform ??
564
+ ((url: string, options?: RequestInit) => [url, options])
565
+ )("http://localhost:4000/graphql", {
566
+ method: "POST",
567
+ headers: {
568
+ ...headers,
569
+ "Content-Type": "application/json",
570
+ Accept: "text/event-stream",
571
+ },
572
+ body: JSON.stringify({
573
+ query: \`\${[...query.fragments.values()].join("\\n")}\\n \${query.query}\`.trim(),
574
+ variables: query.variables,
575
+ }),
576
+ });
577
+ const response = await fetch(url, {
578
+ ...options,
579
+ headers: {
580
+ ...options?.headers,
581
+ "Content-Type": "application/json",
582
+ Accept: "text/event-stream",
583
+ },
584
+ });
585
+
586
+ const reader = response.body!.getReader();
587
+ const decoder = new TextDecoder();
588
+ let buffer = "";
589
+
590
+ while (true) {
591
+ const { done, value } = await reader.read();
592
+ if (done) break;
593
+
594
+ buffer += decoder.decode(value, { stream: true });
595
+ const events = buffer.split("\\n\\n");
596
+ buffer = events.pop() || "";
597
+
598
+ for (const event of events) {
599
+ if (event.trim()) {
600
+ const eventName = event.match(/^event: (.*)$/m)?.[1];
601
+ const rawdata = event.match(/^data: (.*)$/m)?.[1];
602
+
603
+ if ((eventName === null && rawdata === "") || !rawdata)
604
+ continue;
605
+ if (eventName === "complete" || done) break;
606
+
607
+ const parsed = JSON.parse(rawdata) as {
608
+ data: any;
609
+ errors: any[];
610
+ };
611
+ const { data, errors } = parsed ?? {};
612
+ if (errors?.length > 0) {
613
+ if (!data) {
614
+ const err = new Error(JSON.stringify(errors), {
615
+ cause: "Only errors were returned from the server.",
616
+ });
617
+ throw err;
618
+ }
619
+ for (const error of errors) {
620
+ if (error.path) {
621
+ that.utilSet(data, error.path, error);
622
+ }
623
+ }
624
+ }
625
+
626
+ yield data;
627
+ }
628
+ }
629
+ }
630
+
631
+ return;
632
+ })();
633
+
634
+ return generator;
635
+ }
636
+
538
637
  private async executeOperation(
539
638
  query: {
639
+ opType: "subscription" | "query" | "mutation";
540
640
  query: string;
541
641
  variables: any;
542
642
  fragments: Map<string, string>;
@@ -756,6 +856,7 @@ export class OperationSelectionCollector {
756
856
  public getOperationResultPath<T>(
757
857
  path: (string | number)[] = [],
758
858
  _type?: string,
859
+ opResultDataOverride?: any,
759
860
  ): T {
760
861
  if (!this.op) {
761
862
  throw new Error(
@@ -763,7 +864,7 @@ export class OperationSelectionCollector {
763
864
  );
764
865
  }
765
866
 
766
- let result = this.operationResult;
867
+ let result = opResultDataOverride ?? this.operationResult;
767
868
 
768
869
  if (path.length === 0) return result as T;
769
870
 
@@ -829,6 +930,10 @@ export const SLW_OP_PATH = Symbol("SLW_OP_PATH");
829
930
  export const SLW_REGISTER_PATH = Symbol("SLW_REGISTER_PATH");
830
931
  export const SLW_RENDER_WITH_ARGS = Symbol("SLW_RENDER_WITH_ARGS");
831
932
 
933
+ export const SLW_OP_RESULT_DATA_OVERRIDE = Symbol(
934
+ "SLW_OP_RESULT_DATA_OVERRIDE",
935
+ );
936
+
832
937
  export const SLW_RECREATE_VALUE_CALLBACK = Symbol(
833
938
  "SLW_RECREATE_VALUE_CALLBACK",
834
939
  );
@@ -851,6 +956,7 @@ export class SelectionWrapperImpl<
851
956
  [SLW_CLONE](
852
957
  overrides: {
853
958
  SLW_OP_PATH?: string;
959
+ OP_RESULT_DATA?: any;
854
960
  } = {},
855
961
  ) {
856
962
  const slw = new SelectionWrapper(
@@ -869,6 +975,11 @@ export class SelectionWrapperImpl<
869
975
  slw[SLW_IS_FRAGMENT] = this[SLW_IS_FRAGMENT];
870
976
  slw[SLW_PARENT_SLW] = this[SLW_PARENT_SLW];
871
977
  slw[SLW_OP_PATH] = overrides.SLW_OP_PATH ?? this[SLW_OP_PATH];
978
+
979
+ if (overrides.OP_RESULT_DATA) {
980
+ slw[SLW_OP_RESULT_DATA_OVERRIDE] = overrides.OP_RESULT_DATA;
981
+ }
982
+
872
983
  return slw;
873
984
  }
874
985
 
@@ -896,6 +1007,9 @@ export class SelectionWrapperImpl<
896
1007
  [SLW_LAZY_FLAG]?: boolean;
897
1008
 
898
1009
  [SLW_RECREATE_VALUE_CALLBACK]?: () => valueT;
1010
+
1011
+ [SLW_OP_RESULT_DATA_OVERRIDE]?: any;
1012
+
899
1013
  constructor(
900
1014
  fieldName?: fieldName,
901
1015
  typeNamePure?: typeNamePure,
@@ -1233,6 +1347,7 @@ export class SelectionWrapper<
1233
1347
  prop === SLW_REGISTER_PATH ||
1234
1348
  prop === SLW_RENDER_WITH_ARGS ||
1235
1349
  prop === SLW_RECREATE_VALUE_CALLBACK ||
1350
+ prop === SLW_OP_RESULT_DATA_OVERRIDE ||
1236
1351
  prop === SLW_CLONE
1237
1352
  ) {
1238
1353
  return target[
@@ -1264,18 +1379,48 @@ export class SelectionWrapper<
1264
1379
  valueT,
1265
1380
  argsT
1266
1381
  >,
1382
+ overrideOpPath?: string,
1267
1383
  ): valueT | undefined => {
1268
1384
  const data = t[
1269
1385
  ROOT_OP_COLLECTOR
1270
1386
  ]!.ref.getOperationResultPath<valueT>(
1271
- (t[SLW_OP_PATH]?.split(".") ?? []).map((p) =>
1272
- !isNaN(+p) ? +p : p,
1273
- ),
1387
+ (
1388
+ (overrideOpPath ?? t[SLW_OP_PATH])?.split(
1389
+ ".",
1390
+ ) ?? []
1391
+ ).map((p) => (!isNaN(+p) ? +p : p)),
1274
1392
  t[SLW_FIELD_TYPENAME],
1393
+ t[SLW_OP_RESULT_DATA_OVERRIDE],
1275
1394
  );
1276
1395
  return data;
1277
1396
  };
1278
1397
 
1398
+ if (prop === Symbol.asyncIterator) {
1399
+ const asyncGenRootPath =
1400
+ target[SLW_OP_PATH]?.split(".")?.[0];
1401
+ const asyncGen = getResultDataForTarget(
1402
+ target,
1403
+ asyncGenRootPath,
1404
+ ) as AsyncGenerator<valueT, any, any>;
1405
+
1406
+ return function () {
1407
+ return {
1408
+ next() {
1409
+ return asyncGen.next().then((val) => {
1410
+ return {
1411
+ done: val.done,
1412
+ value: target[SLW_CLONE]({
1413
+ SLW_OP_PATH:
1414
+ asyncGenRootPath,
1415
+ OP_RESULT_DATA: val.value,
1416
+ }),
1417
+ };
1418
+ });
1419
+ },
1420
+ };
1421
+ };
1422
+ }
1423
+
1279
1424
  if (!Object.hasOwn(slw_value ?? {}, String(prop))) {
1280
1425
  // check if the selected field is an array
1281
1426
  if (typeArrDepth) {
@@ -1285,6 +1430,8 @@ export class SelectionWrapper<
1285
1430
  target[SLW_OP_PATH] +
1286
1431
  "." +
1287
1432
  String(prop),
1433
+ OP_RESULT_DATA:
1434
+ target[SLW_OP_RESULT_DATA_OVERRIDE],
1288
1435
  });
1289
1436
  return elm;
1290
1437
  }
@@ -1303,6 +1450,10 @@ export class SelectionWrapper<
1303
1450
  target[SLW_OP_PATH] +
1304
1451
  "." +
1305
1452
  String(i),
1453
+ OP_RESULT_DATA:
1454
+ target[
1455
+ SLW_OP_RESULT_DATA_OVERRIDE
1456
+ ],
1306
1457
  }),
1307
1458
  );
1308
1459
 
@@ -1342,11 +1493,17 @@ export class SelectionWrapper<
1342
1493
  }
1343
1494
  }
1344
1495
 
1345
- if (slwOpPathIsIndexAccessOrInArray) {
1496
+ if (
1497
+ slwOpPathIsIndexAccessOrInArray ||
1498
+ (target[SLW_OP_RESULT_DATA_OVERRIDE] &&
1499
+ !slw[SLW_OP_RESULT_DATA_OVERRIDE])
1500
+ ) {
1346
1501
  // index access detected, cloning
1347
1502
  slw = slw[SLW_CLONE]({
1348
1503
  SLW_OP_PATH:
1349
1504
  target[SLW_OP_PATH] + "." + String(prop),
1505
+ OP_RESULT_DATA:
1506
+ target[SLW_OP_RESULT_DATA_OVERRIDE],
1350
1507
  });
1351
1508
  }
1352
1509
 
@@ -1483,6 +1640,7 @@ export class SelectionWrapper<
1483
1640
  ? T
1484
1641
  : ToTArrayWithDepth<T[], Prev[D]>;
1485
1642
  type ConvertToPromise<T, skip = 1> = skip extends 0 ? T : Promise<T>;
1643
+ type ConvertToAsyncIter<T, skip = 1> = skip extends 0 ? T : AsyncIterable<T>;
1486
1644
  type ReplacePlaceHoldersWithTNested<
1487
1645
  inferedResult,
1488
1646
  EE,
@@ -1512,6 +1670,7 @@ export class SelectionWrapper<
1512
1670
  E extends { [key: string | number | symbol]: any } = {},
1513
1671
  REP extends string | number | symbol = never,
1514
1672
  AS_PROMISE = 0,
1673
+ AS_ASYNC_ITER = 0,
1515
1674
  > = (
1516
1675
  makeSLFNInput: () => F,
1517
1676
  SLFN_name: N,
@@ -1535,12 +1694,17 @@ export class SelectionWrapper<
1535
1694
  >(
1536
1695
  this: any,
1537
1696
  s: (selection: FF) => TT,
1538
- ) => Prettify<ConvertToPromise<ToTArrayWithDepth<inferedResult, TAD>, AS_PROMISE> &
1539
- ReplacePlaceHoldersWithTNested<
1540
- ToTArrayWithDepth<inferedResult, TAD>,
1541
- EE,
1542
- REP
1543
- >>;
1697
+ ) => Prettify<
1698
+ ConvertToPromise<
1699
+ ConvertToAsyncIter<ToTArrayWithDepth<inferedResult, TAD>, AS_ASYNC_ITER>,
1700
+ AS_PROMISE
1701
+ > &
1702
+ ReplacePlaceHoldersWithTNested<
1703
+ ConvertToAsyncIter<ToTArrayWithDepth<inferedResult, TAD>, AS_ASYNC_ITER>,
1704
+ EE,
1705
+ REP
1706
+ >
1707
+ >;
1544
1708
  `;static HelperFunctions=`
1545
1709
  const selectScalars = <S>(selection: Record<string, any>) =>
1546
1710
  Object.fromEntries(
@@ -1653,16 +1817,16 @@ export class SelectionWrapper<
1653
1817
  ${this.typeMeta.isList??0},
1654
1818
  {},
1655
1819
  this
1656
- )`;let D=`${this.typeName}Selection`;if(this.collector.hasSelectionFunction(this.typeMeta))return D;else this.collector.addSelectionFunction(this.typeMeta,D);let F=this.typeMeta.fields.some((J)=>J.type.isScalar||J.type.isEnum),P=this.typeMeta.name===this.collector.QueryTypeName||this.typeMeta.name===this.collector.MutationTypeName||this.typeMeta.name===this.collector.SubscriptionTypeName,B="";if(this.typeMeta.isUnion)B=`
1820
+ )`;let D=`${this.typeName}Selection`;if(this.collector.hasSelectionFunction(this.typeMeta))return D;else this.collector.addSelectionFunction(this.typeMeta,D);let F=this.typeMeta.fields.some((Y)=>Y.type.isScalar||Y.type.isEnum),P=this.typeMeta.name===this.collector.QueryTypeName||this.typeMeta.name===this.collector.MutationTypeName||this.typeMeta.name===this.collector.SubscriptionTypeName,B=this.typeMeta.name===this.collector.SubscriptionTypeName,Z="";if(this.typeMeta.isUnion)Z=`
1657
1821
  $on: {
1658
- ${this.typeMeta.possibleTypes.map((J)=>`${J.name}: ${this.originalTypeNameToTypescriptFriendlyName(J.name)}Selection.bind({
1822
+ ${this.typeMeta.possibleTypes.map((Y)=>`${Y.name}: ${this.originalTypeNameToTypescriptFriendlyName(Y.name)}Selection.bind({
1659
1823
  collector: this,
1660
1824
  fieldName: "",
1661
- onTypeFragment: "${J.name}",
1825
+ onTypeFragment: "${Y.name}",
1662
1826
  }),`).join(`
1663
1827
  `)}
1664
1828
  }
1665
- `;else B=`
1829
+ `;else Z=`
1666
1830
  $fragment: <F extends (this: any, ...args: any[]) => any>(f: F) =>
1667
1831
  f.bind({
1668
1832
  collector: this,
@@ -1676,36 +1840,37 @@ export class SelectionWrapper<
1676
1840
  ) as SLWsFromSelection<
1677
1841
  ReturnType<typeof make${D}Input>
1678
1842
  >,
1679
- `:""}`;let Z=new Map,q=`
1843
+ `:""}`;let q=new Map,X=`
1680
1844
  export function make${D}Input(this: any) ${this.typeMeta.isUnion?"":`: ReturnTypeFrom${D}`} {
1681
1845
  return {
1682
- ${this.typeMeta.fields.map((J)=>[J,this.makeSelectionFunctionInputObjectValueForField(J,this.typeMeta.isInput?[]:[this.typeName])]).map(([J,Y])=>{let H=`
1846
+ ${this.typeMeta.fields.map((Y)=>[Y,this.makeSelectionFunctionInputObjectValueForField(Y,this.typeMeta.isInput?[]:[this.typeName])]).map(([Y,H])=>{let W=`
1683
1847
  $lazy: (
1684
- ${J.hasArgs?`args: ${this.typeName}${J.name.slice(0,1).toUpperCase()}${J.name.slice(1)}Args`:""}
1685
- ) => Promise<"T">`;return Z.set(J.name,[`${J.hasArgs?`(
1686
- args: ${this.typeName}${J.name.slice(0,1).toUpperCase()}${J.name.slice(1)}Args
1687
- ) =>`:""}`,`${J.type.isScalar||J.type.isEnum?`SelectionWrapperImpl<"${J.name}", "${J.type.name.replaceAll("[","").replaceAll("]","").replaceAll("!","")}${J.type.isNonNull?"!":""}", ${J.type.isList}, {}, ${J.hasArgs?`${this.typeName}${J.name.slice(0,1).toUpperCase()}${J.name.slice(1)}Args`:"undefined"}>`:`ReturnType<
1848
+ ${Y.hasArgs?`args: ${this.typeName}${Y.name.slice(0,1).toUpperCase()}${Y.name.slice(1)}Args`:""}
1849
+ ) => Promise<"T">`;return q.set(Y.name,[`${Y.hasArgs?`(
1850
+ args: ${this.typeName}${Y.name.slice(0,1).toUpperCase()}${Y.name.slice(1)}Args
1851
+ ) =>`:""}`,`${Y.type.isScalar||Y.type.isEnum?`SelectionWrapperImpl<"${Y.name}", "${Y.type.name.replaceAll("[","").replaceAll("]","").replaceAll("!","")}${Y.type.isNonNull?"!":""}", ${Y.type.isList}, {}, ${Y.hasArgs?`${this.typeName}${Y.name.slice(0,1).toUpperCase()}${Y.name.slice(1)}Args`:"undefined"}>`:`ReturnType<
1688
1852
  SLFN<
1689
1853
  {},
1690
- ReturnType<typeof make${super.originalTypeNameToTypescriptFriendlyName(J.type.name)}SelectionInput>,
1691
- "${super.originalTypeNameToTypescriptFriendlyName(J.type.name)}Selection",
1692
- "${super.originalTypeNameToTypescriptTypeNameWithoutModifiers(J.type.name)}",
1693
- ${J.type.isList??0}
1854
+ ReturnType<typeof make${super.originalTypeNameToTypescriptFriendlyName(Y.type.name)}SelectionInput>,
1855
+ "${super.originalTypeNameToTypescriptFriendlyName(Y.type.name)}Selection",
1856
+ "${super.originalTypeNameToTypescriptTypeNameWithoutModifiers(Y.type.name)}",
1857
+ ${Y.type.isList??0}
1694
1858
  ${P?`,
1695
1859
  {
1696
- ${H} ${this.authConfig?`& {
1860
+ ${W} ${this.authConfig?`& {
1697
1861
  auth: (auth: FnOrPromisOrPrimitive) => Promise<"T">;
1698
1862
  }`:""};
1699
- ${this.authConfig?`auth: (auth: FnOrPromisOrPrimitive) => Promise<"T"> & {${H}}`:""}
1863
+ ${this.authConfig?`auth: (auth: FnOrPromisOrPrimitive) => Promise<"T"> & {${W}}`:""}
1700
1864
  },
1701
1865
  "$lazy" ${this.authConfig?'| "auth"':""},
1702
1866
  AS_PROMISE
1867
+ ${B?", 1":""}
1703
1868
  `:""}
1704
1869
  >
1705
- >`}`]),`${Y},`}).join(`
1870
+ >`}`]),`${H},`}).join(`
1706
1871
  `)}
1707
1872
 
1708
- ${B}
1873
+ ${Z}
1709
1874
  } as const;
1710
1875
  };
1711
1876
  export const ${D} = makeSLFN(
@@ -1714,13 +1879,13 @@ export class SelectionWrapper<
1714
1879
  "${this.originalFullTypeName.replaceAll("[","").replaceAll("]","").replaceAll("!","")}",
1715
1880
  ${this.typeMeta.isList??0}
1716
1881
  );
1717
- `,X=this.typeMeta.isUnion?"":`
1882
+ `,J=this.typeMeta.isUnion?"":`
1718
1883
  type ReturnTypeFrom${D}RetTypes<AS_PROMISE = 0> = {
1719
- ${Array.from(Z).map(([J,[Y,H]])=>`${J}: ${H}`).join(`
1884
+ ${Array.from(q).map(([Y,[H,W]])=>`${Y}: ${W}`).join(`
1720
1885
  `)}
1721
1886
  }
1722
1887
  type ReturnTypeFrom${D} = {
1723
- ${Array.from(Z).map(([J,[Y,H]])=>`${J}: ${Y} ReturnTypeFrom${D}RetTypes["${J}"]`).join(`
1888
+ ${Array.from(q).map(([Y,[H,W]])=>`${Y}: ${H} ReturnTypeFrom${D}RetTypes["${Y}"]`).join(`
1724
1889
  `)}
1725
1890
  } & {
1726
1891
  $fragment: <F extends (this: any, ...args: any[]) => any>(
@@ -1731,8 +1896,8 @@ export class SelectionWrapper<
1731
1896
  ${F?`
1732
1897
  $scalars: () => SLWsFromSelection<ReturnType<typeof ${`make${D}Input`}>>;
1733
1898
  `:""}
1734
- };`;return this.collector.addSelectionFunction(this.typeMeta,`${X}
1735
- ${q}
1899
+ };`;return this.collector.addSelectionFunction(this.typeMeta,`${J}
1900
+ ${X}
1736
1901
  `),D}static makeRootOperationFunction(D,F){let{QueryTypeName:P,MutationTypeName:B,SubscriptionTypeName:Z}=D,q=[P,B,Z].filter(Boolean),X=[...D.types.values()].filter((Y)=>Y.isDirective?.locations.some((H)=>[C3.DirectiveLocation.FIELD,C3.DirectiveLocation.FRAGMENT_SPREAD,C3.DirectiveLocation.INLINE_FRAGMENT].includes(H))).map((Y)=>{return`"${Y.isDirective.name}": ${new m2(Y.name,D,{}).makeDirective()}`});return`
1737
1902
  ${X?.length?`export const $directives = {
1738
1903
  ${X.join(`,
@@ -1845,6 +2010,10 @@ export class SelectionWrapper<
1845
2010
  input: string | URL | globalThis.Request,
1846
2011
  init?: RequestInit,
1847
2012
  ) => Promise<Response>;
2013
+ sseFetchTransform?: (
2014
+ input: string | URL | globalThis.Request,
2015
+ init?: RequestInit,
2016
+ ) => Promise<[string | URL | globalThis.Request, RequestInit | undefined]>;
1848
2017
  scalars?: {
1849
2018
  [key in keyof ScalarTypeMapDefault]?: (
1850
2019
  v: string,
@@ -1877,6 +2046,9 @@ export class SelectionWrapper<
1877
2046
  if (options.fetcher) {
1878
2047
  RootOperation[OPTIONS].fetcher = options.fetcher;
1879
2048
  }
2049
+ if (options.sseFetchTransform) {
2050
+ RootOperation[OPTIONS].sseFetchTransform = options.sseFetchTransform;
2051
+ }
1880
2052
  if (options.scalars) {
1881
2053
  RootOperation[OPTIONS].scalars = {
1882
2054
  ...RootOperation[OPTIONS].scalars,
@@ -2145,7 +2317,7 @@ export class SelectionWrapper<
2145
2317
  export default __client__ as typeof __client__ & {
2146
2318
  init: typeof __init__;
2147
2319
  } & {
2148
- ${q.map((Y)=>`${Y?.toLowerCase()}: {
2320
+ ${q.map((Y)=>({op:Y,wrapForAsyncIter:(H)=>Y===Z?`AsyncIterable<${H}>`:H})).map(({op:Y,wrapForAsyncIter:H})=>`${Y?.toLowerCase()}: {
2149
2321
  [field in Exclude<
2150
2322
  keyof ReturnType<typeof make${Y}SelectionInput>,
2151
2323
  "$fragment" | "$scalars"
@@ -2158,20 +2330,20 @@ export class SelectionWrapper<
2158
2330
  infer VT,
2159
2331
  infer AT
2160
2332
  >
2161
- ? ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD> & {
2333
+ ? ${H("ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>")} & {
2162
2334
  $lazy: () => Promise<
2163
- ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
2335
+ ${H("ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>")}
2164
2336
  > ${F?`& {
2165
2337
  auth: (
2166
2338
  auth: FnOrPromisOrPrimitive,
2167
2339
  ) => Promise<
2168
- ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
2340
+ ${H("ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>")}
2169
2341
  >
2170
2342
  }
2171
2343
  `:""};
2172
2344
  ${F?`auth: (token: FnOrPromisOrPrimitive) => Promise<"T"> & {
2173
2345
  $lazy: () => Promise<
2174
- ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
2346
+ ${H("ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>")}
2175
2347
  >;
2176
2348
  };`:""}
2177
2349
  }
@@ -2188,23 +2360,20 @@ export class SelectionWrapper<
2188
2360
  infer _VT,
2189
2361
  infer _AT
2190
2362
  >
2191
- ? (args: _A) => ToTArrayWithDepth<
2192
- SLW_TPN_ToType<_TTNP>,
2193
- _TTAD
2194
- > & {
2363
+ ? (args: _A) => ${H("ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>,_TTAD>")} & {
2195
2364
  $lazy: (args: _A) => Promise<
2196
- ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>
2365
+ ${H("ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>")}
2197
2366
  > ${F?`& {
2198
2367
  auth: (
2199
2368
  auth: FnOrPromisOrPrimitive,
2200
2369
  ) => Promise<
2201
- ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>
2370
+ ${H("ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>")}
2202
2371
  >;
2203
2372
  }
2204
2373
  `:""};
2205
2374
  ${F?`auth: (token: FnOrPromisOrPrimitive) => Promise<"T"> & {
2206
2375
  $lazy: () => Promise<
2207
- ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>
2376
+ ${H("ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>")}
2208
2377
  >;
2209
2378
  };`:""}
2210
2379
  }
@@ -3834,12 +4003,12 @@ ${r2.default.green("Done! Alias added to 'tsconfig.json'.")}
3834
4003
  ${r2.default.green("Go ahead and import the generated file in your project:")}
3835
4004
 
3836
4005
  ${cD.import("import")} ${cD.name(B)} ${cD.from("from")} ${cD.string(`"${B}"`)};
3837
- `),P=!0}return P};var CF=async(D,F,P,B={})=>{let Z=!0;if(D.url=await X0("GraphQL",D.url,"The URL",Z),D.headers?.length)for(let Y of D.headers){let H=await X0("GraphQL",Y,"The header",Z);D.headers[D.headers.indexOf(Y)]=H}if(B.endpoint)B.endpoint=await X0("GraphQL",B.endpoint,"The endpoint",Z);if(B.authHeaderName)B.authHeaderName=await X0("GraphQL",B.authHeaderName,"The auth header name",Z);P=await X0("GraphQL",P,"The output file",Z);let q;try{q=await y2(D.url,D.headers)}catch(Y){if(Y.response?.status===401||Y.response?.status===403){console.error(`Introspection failed: HTTP ${Y.response.status} Unauthorized. Please check your headers.`);return}console.error("Failed to introspect schema",Y);return}let J=await new k1.Generator(X2.GraphQL[F]).generate({schema:q,options:{},authConfig:D.headers?{headerName:D.headers.length===1?D.headers[0].split("=")[0]:"Authorization"}:void 0});if(!P.endsWith(".ts"))P+=".ts";gO.mkdirSync(P.split("/").slice(0,-1).join("/"),{recursive:!0}),gO.writeFileSync(P,J.replace("[AUTH_HEADER_NAME]",B.authHeaderName??"Authorization").replace("[ENDPOINT]",B.endpoint??D.url))};var LF=UD(e3(),1);import tN from"fs";import yO from"path";var mO=async()=>{K8("GraphQL");let D=await D5("Enter the graphql endpoint url:"),F,P;try{F=await y2(D)}catch(X){if(X.response?.status===401||X.response?.status===403){let[J,Y]=await F5();try{F=await y2(D,[`${J}=${Y}`]),P=J}catch(H){console.error("Error: ",H.message);return}}else{console.error("Error: ",X.message),console.error("Failed to introspect schema");return}}if(!F){console.error("Failed to introspect schema");return}let B=await P5(["."]),Z=await B5("Enter the output filename:"),q=yO.resolve(...B,Z);try{let J=await new k1.Generator(X2.GraphQL.default).generate({schema:F,options:{},authConfig:P?{headerName:P}:void 0});tN.writeFileSync(q,J.replace("[ENDPOINT]",D))}catch(X){console.error("Error: ",X.message),console.error("Failed to generate code");return}if(!await Z5(Z,q))console.log(`
4006
+ `),P=!0}return P};var CF=async(D,F,P,B={})=>{let Z=!0;if(D.url=await X0("GraphQL",D.url,"The URL",Z),D.headers?.length)for(let Y of D.headers){let H=await X0("GraphQL",Y,"The header",Z);D.headers[D.headers.indexOf(Y)]=H}if(B.endpoint)B.endpoint=await X0("GraphQL",B.endpoint,"The endpoint",Z);if(B.authHeaderName)B.authHeaderName=await X0("GraphQL",B.authHeaderName,"The auth header name",Z);P=await X0("GraphQL",P,"The output file",Z);let q;try{q=await y2(D.url,D.headers)}catch(Y){if(Y.response?.status===401||Y.response?.status===403){console.error(`Introspection failed: HTTP ${Y.response.status} Unauthorized. Please check your headers.`);return}console.error("Failed to introspect schema",Y);return}let J=await new k1.Generator(X2.GraphQL[F]).generate({schema:q,options:{},authConfig:D.headers?{headerName:D.headers.length===1?D.headers[0].split("=")[0]:"Authorization"}:void 0});if(!P.endsWith(".ts"))P+=".ts";gO.mkdirSync(P.split("/").slice(0,-1).join("/"),{recursive:!0}),gO.writeFileSync(P,J.replaceAll("[AUTH_HEADER_NAME]",B.authHeaderName??"Authorization").replaceAll("[ENDPOINT]",B.endpoint??D.url))};var LF=UD(e3(),1);import tN from"fs";import yO from"path";var mO=async()=>{K8("GraphQL");let D=await D5("Enter the graphql endpoint url:"),F,P;try{F=await y2(D)}catch(X){if(X.response?.status===401||X.response?.status===403){let[J,Y]=await F5();try{F=await y2(D,[`${J}=${Y}`]),P=J}catch(H){console.error("Error: ",H.message);return}}else{console.error("Error: ",X.message),console.error("Failed to introspect schema");return}}if(!F){console.error("Failed to introspect schema");return}let B=await P5(["."]),Z=await B5("Enter the output filename:"),q=yO.resolve(...B,Z);try{let J=await new k1.Generator(X2.GraphQL.default).generate({schema:F,options:{},authConfig:P?{headerName:P}:void 0});tN.writeFileSync(q,J.replaceAll("[ENDPOINT]",D))}catch(X){console.error("Error: ",X.message),console.error("Failed to generate code");return}if(!await Z5(Z,q))console.log(`
3838
4007
  ${LF.default.green(`Done! Generated file saved at ${q}.`)}
3839
4008
  ${LF.default.green("Go ahead and import the generated file in your project:")}
3840
4009
 
3841
4010
  ${cD.import("import")} ${cD.name(Z.replace(".ts",""))} ${cD.from("from")} ${cD.string(`"./${yO.relative(process.cwd(),q.replace(".ts",""))}"`)};
3842
- `);console.log(" "),console.log("Please star the repo if you liked it! https://github.com/liontariai/samarium"),console.log(" ")};var oQ=UD(iQ(),1);async function F8(D,F){let B=await(await fetch(D,{headers:F?.map((Z)=>Z.split("="))})).text();try{return JSON.parse(B)}catch(Z){return oQ.default.parse(B)}}import oy from"fs";var fP=async(D,F)=>{let P=await F8(D.url,D.headers);oy.writeFileSync(F,JSON.stringify(P,null,2))};import tQ from"fs";var hP=async(D,F,P,B={})=>{let Z=!0;if(D.url=await X0("OpenAPI",D.url,"The URL",Z),D.headers?.length)for(let Y of D.headers){let H=await X0("OpenAPI",Y,"The header",Z);D.headers[D.headers.indexOf(Y)]=H}if(B.endpoint)B.endpoint=await X0("OpenAPI",B.endpoint,"The endpoint",Z);if(B.authHeaderName)B.authHeaderName=await X0("OpenAPI",B.authHeaderName,"The auth header name",Z);P=await X0("OpenAPI",P,"The output file",Z);let q;try{q=await F8(D.url,D.headers)}catch(Y){if(Y.response?.status===401||Y.response?.status===403){console.error(`Introspection failed: HTTP ${Y.response.status} Unauthorized. Please check your headers.`);return}console.error("Failed to introspect schema",Y);return}let J=await new f1.Generator(X2.OpenAPI[F]).generate({schema:q,options:{},authConfig:D.headers?{headerName:D.headers.length===1?D.headers[0].split("=")[0]:"Authorization"}:void 0});if(!P.endsWith(".ts"))P+=".ts";tQ.mkdirSync(P.split("/").slice(0,-1).join("/"),{recursive:!0}),tQ.writeFileSync(P,J.replace("[ENDPOINT]",B.endpoint??q.servers?.[0]?.url??D.url))};var vP=UD(e3(),1);import ty from"fs";import eQ from"path";var DG=async()=>{K8("OpenAPI");let D=await D5("Enter the url to the OpenAPI schema json or yaml file:"),F,P;try{F=await F8(D)}catch(X){if(X.response?.status===401||X.response?.status===403){let[J,Y]=await F5();try{F=await F8(D,[`${J}=${Y}`]),P=J}catch(H){console.error("Error: ",H.message);return}}else{console.error("Error: ",X.message),console.error("Failed to introspect schema");return}}if(!F){console.error("Failed to introspect schema");return}let B=await P5(["."]),Z=await B5("Enter the output filename:"),q=eQ.resolve(...B,Z);try{let J=await new f1.Generator(X2.OpenAPI.default).generate({schema:F,options:{},authConfig:P?{headerName:P}:void 0});ty.writeFileSync(q,J.replace("[ENDPOINT]",F.servers?.[0]?.url??D))}catch(X){console.error("Error: ",X.message),console.error("Failed to generate code");return}if(!await Z5(Z,q))console.log(`
4011
+ `);console.log(" "),console.log("Please star the repo if you liked it! https://github.com/liontariai/samarium"),console.log(" ")};var oQ=UD(iQ(),1);async function F8(D,F){let B=await(await fetch(D,{headers:F?.map((Z)=>Z.split("="))})).text();try{return JSON.parse(B)}catch(Z){return oQ.default.parse(B)}}import oy from"fs";var fP=async(D,F)=>{let P=await F8(D.url,D.headers);oy.writeFileSync(F,JSON.stringify(P,null,2))};import tQ from"fs";var hP=async(D,F,P,B={})=>{let Z=!0;if(D.url=await X0("OpenAPI",D.url,"The URL",Z),D.headers?.length)for(let Y of D.headers){let H=await X0("OpenAPI",Y,"The header",Z);D.headers[D.headers.indexOf(Y)]=H}if(B.endpoint)B.endpoint=await X0("OpenAPI",B.endpoint,"The endpoint",Z);if(B.authHeaderName)B.authHeaderName=await X0("OpenAPI",B.authHeaderName,"The auth header name",Z);P=await X0("OpenAPI",P,"The output file",Z);let q;try{q=await F8(D.url,D.headers)}catch(Y){if(Y.response?.status===401||Y.response?.status===403){console.error(`Introspection failed: HTTP ${Y.response.status} Unauthorized. Please check your headers.`);return}console.error("Failed to introspect schema",Y);return}let J=await new f1.Generator(X2.OpenAPI[F]).generate({schema:q,options:{},authConfig:D.headers?{headerName:D.headers.length===1?D.headers[0].split("=")[0]:"Authorization"}:void 0});if(!P.endsWith(".ts"))P+=".ts";tQ.mkdirSync(P.split("/").slice(0,-1).join("/"),{recursive:!0}),tQ.writeFileSync(P,J.replaceAll("[ENDPOINT]",B.endpoint??q.servers?.[0]?.url??D.url))};var vP=UD(e3(),1);import ty from"fs";import eQ from"path";var DG=async()=>{K8("OpenAPI");let D=await D5("Enter the url to the OpenAPI schema json or yaml file:"),F,P;try{F=await F8(D)}catch(X){if(X.response?.status===401||X.response?.status===403){let[J,Y]=await F5();try{F=await F8(D,[`${J}=${Y}`]),P=J}catch(H){console.error("Error: ",H.message);return}}else{console.error("Error: ",X.message),console.error("Failed to introspect schema");return}}if(!F){console.error("Failed to introspect schema");return}let B=await P5(["."]),Z=await B5("Enter the output filename:"),q=eQ.resolve(...B,Z);try{let J=await new f1.Generator(X2.OpenAPI.default).generate({schema:F,options:{},authConfig:P?{headerName:P}:void 0});ty.writeFileSync(q,J.replaceAll("[ENDPOINT]",F.servers?.[0]?.url??D))}catch(X){console.error("Error: ",X.message),console.error("Failed to generate code");return}if(!await Z5(Z,q))console.log(`
3843
4012
  ${vP.default.green(`Done! Generated file saved at ${q}.`)}
3844
4013
  ${vP.default.green("Go ahead and import the generated file in your project:")}
3845
4014
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@samarium.sdk/new",
3
- "version": "0.21.2",
3
+ "version": "0.22.0",
4
4
  "main": "bin/samarium",
5
5
  "type": "module",
6
6
  "repository": {
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "devDependencies": {
46
46
  "bun-types": "^1.1.29",
47
- "@samarium.sdk/make": "0.17.0"
47
+ "@samarium.sdk/make": "0.21.2"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "typescript": "^5.0.0"