@flexkit/cli 0.0.8 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -174,7 +174,7 @@ ${A.stack??""}`);return}this.output.debug(`Retrying (attempt ${t.toString()}): $
|
|
|
174
174
|
`,loader:"js"})),n.onLoad({filter:/.*/,namespace:"node-builtin"},s=>({contents:`
|
|
175
175
|
export default globalThis.__require('${s.path}');
|
|
176
176
|
export * from '${s.path}';
|
|
177
|
-
`,loader:"js"}));}},{name:"handle-css",setup(n){n.onResolve({filter:/\.css$/},()=>({path:"empty-css",namespace:"css-stub"})),n.onLoad({filter:/.*/,namespace:"css-stub"},()=>({contents:"export default {};",loader:"js"}));}}],external:["/node_modules/*","tty","os","path","fs","util","stream","events","assert","process"],mainFields:["module","main"],logLevel:"warning"});let i=await import(t);RA__default.default.unlinkSync(t);let g=i.default;return A4(g)}catch(i){let g=i instanceof Error?i:new Error(i);return t&&RA__default.default.unlinkSync(t),new eg(g.message,e)}}function A4(e){let A=t=>{if(Array.isArray(t))return t;let{title:i,projectId:g,schema:r,scopes:n,basePath:
|
|
177
|
+
`,loader:"js"}));}},{name:"handle-css",setup(n){n.onResolve({filter:/\.css$/},()=>({path:"empty-css",namespace:"css-stub"})),n.onLoad({filter:/.*/,namespace:"css-stub"},()=>({contents:"export default {};",loader:"js"}));}}],external:["/node_modules/*","tty","os","path","fs","util","stream","events","assert","process"],mainFields:["module","main"],logLevel:"warning"});let i=await import(t);RA__default.default.unlinkSync(t);let g=i.default;return A4(g)}catch(i){let g=i instanceof Error?i:new Error(i);return t&&RA__default.default.unlinkSync(t),new eg(g.message,e)}}function A4(e){let A=t=>{if(Array.isArray(t))return t;let{title:i,projectId:g,schema:r,scopes:n,spaces:s,basePath:o=""}=t;return {title:i,projectId:g,schema:r,scopes:n,spaces:s,basePath:o}};return Array.isArray(e)?e.map(A):A(e)}function e4(e=8){let A="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let i=0;i<e;i++)t+=A.charAt(Math.floor(Math.random()*A.length));return t}var WM=QA(kk());var pg=QA(bt()),rQ=QA(Sl());var dM=QA(Sl()),fM={"padding-left":0,"padding-right":2},Rl={top:"","top-mid":"","top-left":"","top-right":"",bottom:"","bottom-mid":"","bottom-left":"","bottom-right":"",left:"","left-mid":"",mid:"","mid-mid":"",right:"","right-mid":"",middle:""},x4={l:"left",c:"center",r:"right"};function ur(e,A){let t=new dM.default({style:{...fM,"padding-right":fM["padding-right"]},chars:Rl});return t.push(...e.map(i=>i.map((g,r)=>({content:g,hAlign:x4["l"]})))),t.toString()}var Xe=" ".repeat(2),zt=`
|
|
178
178
|
`,v4="\u{1D5EB}",Ml={chars:Rl,style:{"padding-left":0,"padding-right":0}},J4=[{name:"help",shorthand:"h",type:String,description:"Output usage information",deprecated:false},{name:"version",shorthand:"v",type:String,description:"Output the version number",deprecated:false},{name:"cwd",shorthand:null,type:String,argument:"DIR",description:"Sets the current working directory for a single run of a command",deprecated:false},{name:"local-config",shorthand:"A",type:String,argument:"FILE",description:"Path to the local `flexkit.config.ts` file of your project",deprecated:false},{name:"global-config",shorthand:"Q",type:String,argument:"DIR",description:"Path to the global configuration directory",deprecated:false},{name:"debug",shorthand:"d",type:String,description:"Debug mode (default off)",deprecated:false},{name:"no-color",shorthand:null,type:String,description:"No color mode (default off)",deprecated:false},{name:"scope",shorthand:"S",type:String,description:"Set a custom scope",deprecated:false},{name:"token",shorthand:"t",type:String,argument:"TOKEN",description:"Login token",deprecated:false}];function K4(e,A){let t={...Ml,colWidths:[A],style:{"padding-left":Xe.length}},i=new rQ.default(t);return i.push([{content:e,wordWrap:true}]),i.toString()}function kl(e){let A="";for(let t=0;t<e.length;t++)if(t===e.length-1)A+=e[t];else {let i=e[t],g=e[t+1];A+=i,i.trim()!==""&&g.trim()!==""&&(A+=" ");}return A}function wM(e){return e.filter(A=>A!==null).join(zt)}function H4(e){let A=[Xe,v4,pg.default.bold("flexkit"),pg.default.bold(e.name)];if(e.arguments.length>0)for(let t of e.arguments)A.push(t.required?t.name:`[${t.name}]`);return e.options.length>0&&A.push("[options]"),A.push(zt),kl(A)}function pM(e,A,t){if(e.length===0)return null;let i=e.filter(o=>!o.deprecated&&o.description!==void 0);i.sort((o,a)=>o.name<a.name?-1:o.name>a.name?1:0);let g=0,r=[];for(let o of i){let a=o.shorthand?`${Xe}-${o.shorthand},`:"",B=`${Xe}--${o.name}`;o.argument&&(B+=` <${o.argument}>`),B+=Xe;let u=a.length+B.length;g=Math.max(u,g),r.push([a,B,{content:o.description,wordWrap:true}]);}let n=A.columns-g,s=new rQ.default({...Ml,colWidths:[null,null,n]});return s.push(...r),[`${Xe}${pg.default.dim(t)}:`,zt,zt,s.toString(),zt,zt].join("")}function Y4(e,A){if(!e)return null;let t=0,i=[];for(let s of e){let o=`${Xe}${s.name}`,a=Xe;a+=s.arguments.map(u=>u.required?u.name:`[${u.name}]`).join(" "),a+=Xe;let B=o.length+a.length;t=Math.max(B,t),i.push([o,a,{content:s.description,wordWrap:true}]);}let g=Xe.repeat(4).length,r=A.columns-t-g,n=new rQ.default({...Ml,colWidths:[null,null,r]});return n.push(...i),[`${Xe}${pg.default.dim("Commands")}:`,zt,zt,n.toString(),zt,zt].join("")}function T4(e){let A=[`${Xe}${pg.default.dim("Examples:")}`,""];for(let t of e.examples){let i=[Xe];i.push(pg.default.gray("-")),i.push(t.name),A.push(kl(i)),A.push("");let g=r=>kl([Xe,Xe,pg.default.cyan(`$ ${r}`)]);if(Array.isArray(t.value))for(let r of t.value)A.push(g(r));else A.push(g(t.value));A.push("");}return wM(A)}function P4(e,A){return `${K4(e.description,A.columns)}${zt}`}function O4(e,A){let t=["",H4(e),P4(e,A),Y4(e.subcommands,A),pM(e.options,A,"Options"),pM(J4,A,"Global Options"),T4(e),""];return wM(t)}function ie(e,A){return O4(e,{columns:A.columns??80})}var FM=QA(Ds());function yM(e){let A=0;for(let t of e.split(`
|
|
179
179
|
`)){let i=(0, FM.default)(t);i.length>A&&(A=i.length);}return A}async function Nl(e,{message:A="the question",choices:t=[{name:`something
|
|
180
180
|
description
|
|
@@ -183,10 +183,10 @@ etc`,value:"something unique",short:"generally the first line of `name`"}],pageS
|
|
|
183
183
|
`),i.spinner("Waiting for your confirmation");let g;for(;!g;)try{await Jt(2e3),g=await q4(e,A,t);}catch(r){if(!$e(r)||r.serverMessage!=="Confirmation incomplete")return i.error(Ie(r)),1}return "error"in g?(i.error(g.error.message),1):(i.success(`Email authentication complete for ${A}`),{sid:g.sid,email:A})}async function _4(e,A){try{let t=new URL("/auth/login/otp",e.authUrl);return await e.fetch(t.href,{method:"POST",body:{email:A}})}catch(t){if($e(t)){if(t.code==="not_exists")throw new QC(A,"Please sign up: https://flexkit.io/signup");if(t.code==="invalid_email")throw new EC(A,t.message)}throw new Error(`Unexpected error: ${Ie(t)}`)}}async function q4(e,A,t){let i=new URL("/auth/confirm-otp-login",e.authUrl);return i.searchParams.set("email",A),i.searchParams.set("token",t),await e.fetch(i.href)}var PM=QA(KM()),OM=QA(YM()),_M=QA(nQ());function Kl(e,A,t){let i=new url.URL("/api/auth/login/session",e.authUrl);i.searchParams.set("code",A);let g=/-/g,r=wk.hostname().replace(g," ").replace(".local",""),n=`${RS()} on ${r} via ${t}`;return i.searchParams.set("tokenName",n),e.fetch(i.href)}async function oQ(e,A){let t;for(;!t;)try{t=await e.input.text({message:A});}catch(i){if(e.output.print(`
|
|
184
184
|
`),i.isTtyError)throw new Error(ae(`Interactive mode not supported \u2013 please run ${bA("login you@domain.com")}`))}return t}async function cr(e,A,t,i=QP()){let r=await(i?BP:oP)(e,A,t);if(typeof r=="number")return r;if(!("verificationToken"in r))return 1;let{output:n}=e;n.spinner("Verifying authentication token");let s=await Kl(e,r.verificationToken,t);return n.success(`${t} authentication complete for ${Lt(s.email)}`),s}async function oP(e,A,t){let{output:i}=e,g=CP__default.default.createServer(),{port:r}=await(0, OM.listen)(g,0,"127.0.0.1");A.searchParams.set("origin",`http://localhost:${r}`),i.log("Please visit the following URL in your web browser:"),i.log(Hn(A.href)),i.spinner(`Waiting for ${t} authentication to be completed`);try{let[n]=await Promise.all([new Promise((a,B)=>{g.once("request",(u,Q)=>{Q.setHeader("connection","close");let I=new url.URL(u.url??"/","http://localhost").searchParams;a(I);let C=new url.URL("https://flexkit.io/notifications/cli-login-"),E=I.get("loginError");if(E)C.pathname+="failed",C.searchParams.set("loginError",E);else {C.pathname+="success";let c=I.get("email");c&&C.searchParams.set("email",c);}Q.statusCode=302,Q.setHeader("location",C.href),Q.end();}),g.once("error",B);}),(0,PM.default)(A.href)]);i.stopSpinner(),i.print(li(3));let s=n.get("loginError");if(s){let a=JSON.parse(s);return i.prettyError(a),1}let o=n.get("code");return o?{verificationToken:o}:(i.error("Verification token was not provided. Please contact support."),1)}finally{g.close();}}async function BP(e,A){let{output:t}=e;A.searchParams.set("mode","oob"),t.log("Please visit the following URL in your web browser:"),t.log(Hn(A.href)),t.print(`
|
|
185
185
|
`),t.log("After login is complete, enter the verification code printed in your browser.");let i=await oQ(e,"Verification code:");return t.print(li(6)),{verificationToken:i}}function QP(){return (0, _M.default)()||EP()}function EP(){return !!(process.env.SSH_CLIENT??process.env.SSH_TTY)}function Ms(e,A){let t=new url.URL("/auth/login/github",e.authUrl);return cr(e,t,"GitHub",A)}function Ns(e,A){let t=new url.URL("/auth/login/google",e.authUrl);return cr(e,t,"Google",A)}function Gs(e,A){let t=new url.URL("/auth/login/bitbucket",e.authUrl);return cr(e,t,"Bitbucket",A)}async function Us(e,A){let t=1,g=await Nl(e,{message:"Log in to Flexkit",choices:[{name:"Continue with GitHub",value:"github",short:"github"},{name:"Continue with Google",value:"google",short:"google"},{name:"Continue with Bitbucket",value:"bitbucket",short:"bitbucket"},{name:"Continue with Email",value:"email",short:"email"}]});if(g==="github")t=await Ms(e,A);else if(g==="google")t=await Ns(e,A);else if(g==="bitbucket")t=await Gs(e,A);else if(g==="email"){let r=await oQ(e,"Enter your email address:");t=await Gl(e,r);}return t}var qM={name:"login",description:"Authenticate using your email or team id.",arguments:[{name:"email or project id",required:false}],options:[{name:"github",description:"Log in with GitHub",shorthand:null,type:String,deprecated:false},{name:"google",description:"Log in with Google",shorthand:null,type:String,deprecated:false},{name:"bitbucket",description:"Log in with Bitbucket",shorthand:null,type:String,deprecated:false},{name:"oob",description:'Log in with "out of band" authentication',shorthand:null,type:String,deprecated:false}],examples:[{name:"Log into the Flexkit platform",value:"flexkit login"},{name:"Log in using a specific email address",value:"flexkit login username@example.com"},{name:'Log in using a specific team "slug" for SAML Single Sign-On',value:"flexkit login acme"},{name:'Log in using GitHub in "out-of-band" mode',value:"flexkit login --github --oob"}]};async function Hl(e){let{output:A}=e,t=te(e.argv.slice(2),{"--oob":Boolean,"--github":Boolean,"--google":Boolean,"--bitbucket":Boolean,"--help":Boolean,"-h":"--help"});if(t.flags["--help"])return A.print(ie(qM,{columns:e.stderr.columns})),2;let[,i]=t.args,g=1;return i?WM.validate(i):t.flags["--github"]?g=await Ms(e,t.flags["--oob"]):t.flags["--google"]?g=await Ns(e,t.flags["--oob"]):t.flags["--bitbucket"]?g=await Gs(e,t.flags["--oob"]):g=await Us(e,t.flags["--oob"]),typeof g=="number"?g:(e.authConfig.token=g.sid,sr(e.authConfig),A.debug(`Saved credentials in "${ot(ir())}"`),A.congratulations("You are now logged in."),A.print(`${Im(`Check out the CLI docs at https://flexkit.io/docs/cli or run ${bA("--help")} for a list of available commands.`,nm("tip"))}
|
|
186
|
-
`),0)}var ZM=QA(Yl());function gt(e,{debug:A=false}={}){let t=e;typeof t=="string"&&(t=new Error(t));let i=t,{message:g,stack:r,status:n,code:s,sizeLimit:o}=i;A&&console.error(`> [debug] handling error: ${r??""}`),g!=="User force closed the prompt with 0 null"&&(n===403?console.error(ae(g||`Authentication error. Run ${bA("login")} to log-in again.`)):n===429?console.error(ae(g)):s==="size_limit_exceeded"?console.error(ae(`File size limit exceeded (${(0, ZM.default)(o)}).`)):g?console.error(ae(g)):n===500?console.error(ae("Unexpected server error. Please retry.")):s==="USER_ABORT"?yS("Canceled"):console.error(ae(`Unexpected error. Please try again later. (${g})`)));}var XM={name:"logout",description:"Logout the current authenticated user.",arguments:[],options:[],examples:[{name:"Logout from the CLI",value:"flexkit logout"}]};async function Tl(e){let A,{authConfig:t,output:i}=e,g=new URL("/api/auth/logout",e.authUrl);try{A=te(e.argv.slice(2),{"--help":Boolean,"-h":"--help"});}catch(n){return gt(n),1}if(A.flags["--help"])return i.print(ie(XM,{columns:e.stderr.columns})),2;if(!t.token)return i.note(`Not currently logged in, so ${bA("logout")} did nothing`),0;i.spinner("Logging out\u2026",200);let r=0;try{await e.fetch(g.href,{method:"POST"});}catch(n){$e(n)&&(n.status===403?i.debug("Token is invalid so it cannot be revoked"):n.status!==200&&(i.debug(n.message),r=1));}delete t.token;try{sr(t),i.debug("Configuration has been deleted");}catch(n){i.debug(Ie(n)),r=1;}return r===0?i.log("Logged out!"):i.error("Failed during logout"),r}var zM={name:"deploy",description:"Deploy the current schema and observe job progress in real time.",arguments:[],options:[{name:"allow-breaking-changes",shorthand:null,type:Boolean,description:"Allow intentional entity and attribute removals",deprecated:false},{name:"force",shorthand:null,type:String,description:"Force deployment when the schema has not changed",deprecated:false}],examples:[{name:"Deploy the current project schema",value:"flexkit deploy"},{name:"Force deployment when the schema has not changed",value:"flexkit deploy --force"},{name:"Deploy intentional entity or attribute removals",value:"flexkit deploy --allow-breaking-changes"}]};var dP=["queued","validating","building","uploading","activating","completed","failed"],pP=["completed","failed"],$M=1500,wP=8e3,yP=5;function eN(e){return typeof e=="string"&&dP.includes(e)}function FP(e){return Dt(e)&&e.hasChanges===false&&typeof e.message=="string"&&typeof e.schemaHash=="string"}function Ol(e){return pP.includes(e)}function AN(e){let A=encodeURIComponent(e);return {poll:`/deploy/jobs/${A}`,sse:`/deploy/jobs/${A}/events`}}function mP(e,A,t,i){i.has(t)||(i.add(t),e.log(`[${A}] ${t}`));}function SP(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="number")return `${e.toString()}%`;if(Dt(e)){if(typeof e.message=="string"&&e.message.trim().length>0)return e.message.trim();if(typeof e.percent=="number")return `${e.percent.toString()}%`}}function QQ(e){if(Array.isArray(e))return e.flatMap(r=>QQ(r));if(typeof e=="string")return [{message:e}];if(!Dt(e))return [{message:"Deploy failed with an unknown error."}];let A=Array.isArray(e.errors)?e.errors:void 0;if(!A&&Array.isArray(e.details)&&(A=e.details),A&&A.length>0){let r=A.flatMap(n=>QQ(n));if(r.length>0)return r}let i={message:typeof e.message=="string"&&e.message.trim().length>0?e.message:"Deploy failed."};typeof e.code=="string"&&e.code.length>0&&(i.code=e.code);let g=RP(e.path);return g&&(i.path=g),typeof e.hint=="string"&&e.hint.length>0&&(i.hint=e.hint),typeof e.helpUrl=="string"&&e.helpUrl.length>0&&(i.helpUrl=e.helpUrl),[i]}function RP(e){if(typeof e=="string"&&e.length>0)return e;if(!Array.isArray(e)||e.length===0)return;let A="";for(let t of e){if(typeof t=="number"){A+=`[${t.toString()}]`;continue}if(typeof t!="string")return;A+=A.length>0?`.${t}`:t;}return A}function tN(e,A,t){for(let i of t){let g=i.code??"unknown",r=i.path??"-",n=i.hint?` hint=${i.hint}`:"";e.error(`[${A}] code=${g} path=${r} message=${i.message}${n}`),i.helpUrl&&e.log(`[${A}] Learn more: ${i.helpUrl}`);}}function _l(e,A,t,i,g){mP(e,A,t.state,i);let r=SP(t.progress);!r||g.lastProgress===r||(g.lastProgress=r,e.dim(`[${A}] ${r}`));}function Pl(e){let A=e.length===1?e[0]:e.join(", "),t=e.length===1?"project":"projects";return {projectsLabel:A,projectWord:t}}async function kP(e,A,t,i,g,r){try{let
|
|
186
|
+
`),0)}var ZM=QA(Yl());function gt(e,{debug:A=false}={}){let t=e;typeof t=="string"&&(t=new Error(t));let i=t,{message:g,stack:r,status:n,code:s,sizeLimit:o}=i;A&&console.error(`> [debug] handling error: ${r??""}`),g!=="User force closed the prompt with 0 null"&&(n===403?console.error(ae(g||`Authentication error. Run ${bA("login")} to log-in again.`)):n===429?console.error(ae(g)):s==="size_limit_exceeded"?console.error(ae(`File size limit exceeded (${(0, ZM.default)(o)}).`)):g?console.error(ae(g)):n===500?console.error(ae("Unexpected server error. Please retry.")):s==="USER_ABORT"?yS("Canceled"):console.error(ae(`Unexpected error. Please try again later. (${g})`)));}var XM={name:"logout",description:"Logout the current authenticated user.",arguments:[],options:[],examples:[{name:"Logout from the CLI",value:"flexkit logout"}]};async function Tl(e){let A,{authConfig:t,output:i}=e,g=new URL("/api/auth/logout",e.authUrl);try{A=te(e.argv.slice(2),{"--help":Boolean,"-h":"--help"});}catch(n){return gt(n),1}if(A.flags["--help"])return i.print(ie(XM,{columns:e.stderr.columns})),2;if(!t.token)return i.note(`Not currently logged in, so ${bA("logout")} did nothing`),0;i.spinner("Logging out\u2026",200);let r=0;try{await e.fetch(g.href,{method:"POST"});}catch(n){$e(n)&&(n.status===403?i.debug("Token is invalid so it cannot be revoked"):n.status!==200&&(i.debug(n.message),r=1));}delete t.token;try{sr(t),i.debug("Configuration has been deleted");}catch(n){i.debug(Ie(n)),r=1;}return r===0?i.log("Logged out!"):i.error("Failed during logout"),r}var zM={name:"deploy",description:"Deploy the current schema and observe job progress in real time.",arguments:[],options:[{name:"allow-breaking-changes",shorthand:null,type:Boolean,description:"Allow intentional entity and attribute removals",deprecated:false},{name:"force",shorthand:null,type:String,description:"Force deployment when the schema has not changed",deprecated:false}],examples:[{name:"Deploy the current project schema",value:"flexkit deploy"},{name:"Force deployment when the schema has not changed",value:"flexkit deploy --force"},{name:"Deploy intentional entity or attribute removals",value:"flexkit deploy --allow-breaking-changes"}]};var dP=["queued","validating","building","uploading","activating","completed","failed"],pP=["completed","failed"],$M=1500,wP=8e3,yP=5;function eN(e){return typeof e=="string"&&dP.includes(e)}function FP(e){return Dt(e)&&e.hasChanges===false&&typeof e.message=="string"&&typeof e.schemaHash=="string"}function Ol(e){return pP.includes(e)}function AN(e){let A=encodeURIComponent(e);return {poll:`/deploy/jobs/${A}`,sse:`/deploy/jobs/${A}/events`}}function mP(e,A,t,i){i.has(t)||(i.add(t),e.log(`[${A}] ${t}`));}function SP(e){if(typeof e=="string"&&e.trim().length>0)return e.trim();if(typeof e=="number")return `${e.toString()}%`;if(Dt(e)){if(typeof e.message=="string"&&e.message.trim().length>0)return e.message.trim();if(typeof e.percent=="number")return `${e.percent.toString()}%`}}function QQ(e){if(Array.isArray(e))return e.flatMap(r=>QQ(r));if(typeof e=="string")return [{message:e}];if(!Dt(e))return [{message:"Deploy failed with an unknown error."}];let A=Array.isArray(e.errors)?e.errors:void 0;if(!A&&Array.isArray(e.details)&&(A=e.details),A&&A.length>0){let r=A.flatMap(n=>QQ(n));if(r.length>0)return r}let i={message:typeof e.message=="string"&&e.message.trim().length>0?e.message:"Deploy failed."};typeof e.code=="string"&&e.code.length>0&&(i.code=e.code);let g=RP(e.path);return g&&(i.path=g),typeof e.hint=="string"&&e.hint.length>0&&(i.hint=e.hint),typeof e.helpUrl=="string"&&e.helpUrl.length>0&&(i.helpUrl=e.helpUrl),[i]}function RP(e){if(typeof e=="string"&&e.length>0)return e;if(!Array.isArray(e)||e.length===0)return;let A="";for(let t of e){if(typeof t=="number"){A+=`[${t.toString()}]`;continue}if(typeof t!="string")return;A+=A.length>0?`.${t}`:t;}return A}function tN(e,A,t){for(let i of t){let g=i.code??"unknown",r=i.path??"-",n=i.hint?` hint=${i.hint}`:"";e.error(`[${A}] code=${g} path=${r} message=${i.message}${n}`),i.helpUrl&&e.log(`[${A}] Learn more: ${i.helpUrl}`);}}function _l(e,A,t,i,g){mP(e,A,t.state,i);let r=SP(t.progress);!r||g.lastProgress===r||(g.lastProgress=r,e.dim(`[${A}] ${r}`));}function Pl(e){let A=e.length===1?e[0]:e.join(", "),t=e.length===1?"project":"projects";return {projectsLabel:A,projectWord:t}}async function kP(e,A,t,i,g,r,n){try{let s=await e.fetch("/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schema:t,scopes:i,spaces:g,...n?{allowBreakingChanges:!0}:{},...r?{forceDeploy:!0}:{}}),projectId:A,retry:{retries:3}});if(FP(s))return {hasChanges:!1,message:s.message,schemaHash:s.schemaHash};let o=s;return {hasChanges:!0,jobId:o.jobId,state:o.state,observe:AN(o.jobId)}}catch(s){if($e(s)&&s.status===409&&typeof s.jobId=="string"){let o=eN(s.state)?s.state:"queued",a=AN(s.jobId);return e.output.warn(`[${A}] Another deploy is already running. Attaching to job ${s.jobId}.`),{hasChanges:true,jobId:s.jobId,state:o,observe:a}}throw s}}function MP(e){let A=e.split(/\r?\n/),t=[];for(let g of A)g.startsWith("data:")&&t.push(g.slice(5).trim());if(t.length===0)return null;let i=t.join(`
|
|
187
187
|
`);if(i.length===0)return null;try{let g=JSON.parse(i);if(!Dt(g)||!eN(g.state))return null;let r={state:g.state,progress:g.progress,error:g.error};return typeof g.jobId=="string"&&(r.jobId=g.jobId),r}catch{return null}}async function NP(e,A,t,i,g,r){let n=new AbortController,s=setTimeout(()=>{n.abort();},wP),o;try{o=await e.fetch(t.sse,{json:!1,projectId:A,signal:n.signal,retry:{retries:2}});}finally{clearTimeout(s);}if(!o.body)throw new Error("SSE stream is unavailable.");let a=o.body.getReader(),B=new TextDecoder,u="";for(;;){if(r())throw new Error("Deploy observation was canceled.");let Q=await a.read();if(Q.done)throw new Error("SSE stream ended before deploy completed.");u+=B.decode(Q.value,{stream:true});let I=u.split(`
|
|
188
188
|
|
|
189
|
-
`);u=I.pop()??"";for(let C of I){let E=MP(C);if(E&&(_l(e.output,A,E,i,g),!!Ol(E.state)))return E}}}async function GP(e,A,t,i,g,r){let n=0;for(;;){if(r())throw new Error("Deploy observation was canceled.");try{let s=await e.fetch(t.poll,{projectId:A,retry:{retries:3}});if(_l(e.output,A,s,i,g),Ol(s.state))return s;n=0,await Jt($M);continue}catch(s){if(n+=1,n>yP)throw s;let o=Math.min($M*n,5e3);e.output.debug(`[${A}] polling retry in ${o.toString()}ms: ${Ie(s)}`),await Jt(o);}}}async function UP(e,A,t,i,g){let r=new Set,n={};if(_l(e.output,A,{state:i},r,n),Ol(i))return {state:i};try{return await NP(e,A,t,r,n,g)}catch(s){return e.output.debug(`[${A}] SSE observation unavailable, falling back to polling: ${Ie(s)}`),GP(e,A,t,r,n,g)}}function bP(e,A,t){let i=QQ(t.error);tN(e,A,i);}function LP(e){return Array.isArray(e.errors)&&e.errors.length>0}function xP(e,A,t){if(!$e(t)){e.output.error(`[${A}] ${Ie(t)}`);return}if(t.status===401){e.output.log(`[${A}] You are not logged in. Please log in first by running ${bA("login")}`);return}if(t.status===409&&typeof t.jobId=="string"){e.output.warn(`[${A}] Deploy lock is active for job ${t.jobId}.`);return}if(t.status===400||LP(t)){tN(e.output,A,QQ(t));return}e.output.error(`[${A}] ${t.serverMessage}`);}async function ql(e){let A,{output:t}=e;try{A=te(e.argv.slice(2),{"--allow-breaking-changes":Boolean,"--help":Boolean,"-h":"--help","--force":Boolean});}catch(a){return gt(a),1}if(A.flags["--help"])return t.print(ie(zM,{columns:e.stderr.columns})),2;if(e.flexkitConfig===void 0)return t.error(`No Flexkit configuration file found in the current directory. Please ensure you are executing the command from the correct folder, or run ${bA("init")} to create a new Flexkit project in this directory.`),1;let i=[],g=[],r=[],{projects:n}=e.flexkitConfig,s=false,o=()=>{s=true,t.warn("Received Ctrl+C. Stopping deploy command.");};process.once("SIGINT",o);try{t.spinner("Deploying schema",200);for(let a of n){if(s)break;let B=a.schema??[],u=a.scopes??[];try{let Q=await kP(e,a.projectId,B,u,A.flags["--force"]??!1,A.flags["--allow-breaking-changes"]??!1);if(!Q.hasChanges){g.push(a.projectId),t.log(`[${a.projectId}] ${Q.message}`),t.dim(`[${a.projectId}] schemaHash=${Q.schemaHash}`);continue}let I=await UP(e,a.projectId,Q.observe,Q.state,()=>s);if(I.state==="completed"){i.push(a.projectId);continue}r.push(a.projectId),bP(t,a.projectId,I);}catch(Q){r.push(a.projectId),xP(e,a.projectId,Q);}}}finally{process.off("SIGINT",o),t.stopSpinner();}if(s)return 1;if(i.length>0){let{projectsLabel:a,projectWord:B}=Pl(i);t.success(`Deploy completed for ${B} ${a}.`);}if(g.length>0){let{projectsLabel:a,projectWord:B}=Pl(g);t.log(`No changes to deploy for ${B} ${a}.`);}if(r.length>0){let{projectsLabel:a,projectWord:B}=Pl(r);return t.error(`Deploy failed for ${B} ${a}.`),1}return 0}var Wl={name:"ls",description:"List projects, or get a single project by name or id.",arguments:[{name:"nameOrId",required:false}],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"List projects",value:"flexkit project ls"},{name:"List projects in a specific team scope",value:"flexkit project ls --scope my-team"},{name:"Get a single project by id or name",value:"flexkit project ls my-project"}]},jl={name:"add",description:"Create a project.",arguments:[{name:"name",required:true}],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"Create a project",value:"flexkit project add my-project"},{name:"Create a project in a specific team scope",value:"flexkit project add my-project --scope team-id-or-name"}]},Vl={name:"rm",description:"Remove a project by id or name.",arguments:[{name:"nameOrId",required:true}],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"Remove a project",value:"flexkit project rm my-project"},{name:"Remove a project from a specific team scope",value:"flexkit project rm my-project --scope team-id-or-name"}]},iN={name:"project",description:"Manage projects.",arguments:[],subcommands:[Wl,jl,Vl],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"List projects",value:"flexkit project ls"},{name:"Create a new project",value:"flexkit project add my-project"},{name:"Remove a project",value:"flexkit project rm my-project-id"}]};function gN(e,A){let t="/api/projects";if(e&&(t+=`/${encodeURIComponent(e)}`),A){let i=new URLSearchParams({scope:A});t+=`?${i.toString()}`;}return t}function vP(e){return "project"in e}function JP(e,A){if(e.log(`Team: ${A.team.name} (${A.team.id})`),A.projects.length===0){e.log("No projects found.");return}let t=[["ID","Name","Created At"],...A.projects.map(i=>[i.id,i.name,i.createdAt??""])];e.print(ur(t));}function KP(e,A){e.log(`Team: ${A.team.name} (${A.team.id})`),e.print(ur([["ID",A.project.id],["Name",A.project.name],["Created At",A.project.createdAt??""]]));}function Zl(e,A){e.print(JSON.stringify(A,null,2));}function HP(e){return $e(e)?Dt(e)&&typeof e.error=="string"?e.error:typeof e.serverMessage=="string"&&e.serverMessage!=="Response Error"?e.serverMessage:e.message:e.message}function YP(e){if(!$e(e))return [];if(!Dt(e)||!Array.isArray(e.matches))return [];let A=[];for(let t of e.matches){if(!Dt(t)||typeof t.id!="string"||typeof t.name!="string")continue;let i={id:t.id,name:t.name};typeof t.createdAt=="string"&&(i.createdAt=t.createdAt),A.push(i);}return A}function TP(e,A){if(A.length===0){e.error("Project name is ambiguous. Retry with the project id.");return}e.error("Project name is ambiguous. Use one of the following project ids:");let t=[["ID","Name","Created At"],...A.map(i=>[i.id,i.name,i.createdAt??""])];e.print(ur(t));}function PP(e,A,t){let{output:i}=e;return $e(A)?A.status===401?(i.log(`You are not logged in. Please log in first by running ${bA("login")}`),1):A.status===409&&(t==="ls"||t==="rm")?(TP(i,YP(A)),1):(i.error(HP(A)),1):(i.debug(String(A)),1)}async function OP(e,A,t,i){let g=await e.fetch(gN(A,t));return i?(Zl(e.output,g),0):vP(g)?(KP(e.output,g),0):(JP(e.output,g),0)}async function _P(e,A,t,i){let g={name:A};t&&(g.scope=t);let r=await e.fetch("/api/projects",{method:"POST",body:g});return i?(Zl(e.output,r),0):(e.output.log(`Created project "${r.project.name}" (${r.project.id}) in team "${r.team.name}" (${r.team.id}).`),0)}async function qP(e,A,t,i){let g=gN(A,t),r=await e.fetch(g);if(!await e.input.confirm({message:`Delete project "${r.project.name}" (${r.project.id}) from team "${r.team.name}"?`,default:false}))return e.output.log("Canceled."),0;let s=await e.fetch(g,{method:"DELETE"});return i?(Zl(e.output,s),0):(e.output.log(`Deleted project "${s.project.name}" (${s.project.id}).`),0)}function WP(e,A){let{columns:t}=e.stderr;return A?A==="ls"?(e.output.print(ie(Wl,{columns:t})),2):A==="add"?(e.output.print(ie(jl,{columns:t})),2):A==="rm"?(e.output.print(ie(Vl,{columns:t})),2):(e.output.error(`The ${A} subcommand does not exist`),1):(e.output.print(ie(iN,{columns:t})),2)}async function Xl(e){let A;try{A=te(e.argv.slice(2),{"--help":Boolean,"-h":"--help","--json":Boolean});}catch(n){return gt(n),1}let[,t,i]=A.args,g=A.flags["--scope"],r=A.flags["--json"]??false;if(A.flags["--help"])return WP(e,t);if(!t)return e.output.error(`No subcommand provided. Use ${bA("project --help")} to see available project subcommands.`),1;try{return t==="ls"?await OP(e,i,g,r):t==="add"?i?await _P(e,i,g,r):(e.output.error(`Missing required project name. Usage: ${bA("project add <name>")}`),1):t==="rm"?i?await qP(e,i,g,r):(e.output.error(`Missing required project id or name. Usage: ${bA("project rm <nameOrId>")}`),1):(e.output.error(`The ${t} subcommand does not exist`),1)}catch(n){return t==="ls"||t==="add"||t==="rm"?PP(e,n,t):(e.output.debug(String(n)),1)}}var rN={name:"whoami",description:"Shows the username or email of the currently logged-in user.",arguments:[],options:[],examples:[{name:"Print current user name or email",value:"flexkit whoami"}]};async function zl(e){let A,{output:t}=e;try{A=te(e.argv.slice(2),{"--help":Boolean,"-h":"--help"});}catch(g){return gt(g),1}if(A.flags["--help"])return t.print(ie(rN,{columns:e.stderr.columns})),2;let i=new URL("/api/auth/user",e.authUrl);try{t.spinner("");let g=await e.fetch(i.href);t.stopSpinner();let r=g.display_name?.trim()??g.email?.trim()??"";return r?(t.log(r),0):(t.error("No user information available."),1)}catch(g){return t.stopSpinner(),$e(g)?g.status===401?(t.log(`You are not logged in. Please log in first by running ${bA("login")}`),1):(t.debug(g.message),1):(t.debug(Ie(g)),1)}}function nI(e,A){let{output:t}=e,i=e.flexkitConfig?.projects??[];if(i.length===0)return t.error(`No project configuration found. Run this command from a directory with a flexkit.config file or pass --local-config. See ${bA("--help")}.`),null;if(A){let g=i.find(r=>r.projectId===A);return g||(t.error(`Project "${A}" is not defined in the local config. Available projects: ${i.map(r=>r.projectId).join(", ")}`),null)}return i.length>1?(t.error(`Multiple projects found in the local config. Pass --project <projectId> to select one of: ${i.map(g=>g.projectId).join(", ")}`),null):i[0]}var $l={name:"upload",description:"Upload files or URLs as project assets. Identical files are deduplicated by content hash.",arguments:[{name:"path|url",required:true}],options:[{name:"project",shorthand:null,type:String,argument:"ID",description:"Project id (required when the local config defines several projects)",deprecated:false},{name:"concurrency",shorthand:null,type:Number,argument:"N",description:"Number of parallel uploads (default 5)",deprecated:false},{name:"id-from",shorthand:null,type:String,argument:"STRATEGY",description:'Derive deterministic asset _ids: "filename" or "hash"',deprecated:false},{name:"tag",shorthand:null,type:String,argument:"NAME",description:"Tag every uploaded asset with the given tag (created if missing)",deprecated:false},{name:"json",shorthand:null,type:String,description:"Output created assets as NDJSON on stdout",deprecated:false}],examples:[{name:"Upload a folder of images",value:"flexkit assets upload ./images"},{name:"Upload files and a remote URL with a tag",value:"flexkit assets upload hero.png https://example.com/logo.svg --tag branding"},{name:"Upload with deterministic ids derived from filenames",value:"flexkit assets upload ./icons --id-from filename"}]},Ah={name:"export",description:"Export all project assets (files + metadata) into a tarball that can be re-imported.",arguments:[{name:"dest.tar.gz",required:false}],options:[{name:"project",shorthand:null,type:String,argument:"ID",description:"Project id (required when the local config defines several projects)",deprecated:false},{name:"tag",shorthand:null,type:String,argument:"NAME",description:"Only export assets with the given tag",deprecated:false},{name:"concurrency",shorthand:null,type:Number,argument:"N",description:"Number of parallel downloads (default 5)",deprecated:false},{name:"overwrite",shorthand:null,type:String,description:"Overwrite the destination file if it exists",deprecated:false}],examples:[{name:"Export all assets",value:"flexkit assets export"},{name:"Export assets with a tag to a specific file",value:"flexkit assets export branding.tar.gz --tag branding"}]},nN={name:"assets",description:"Manage project assets.",arguments:[],subcommands:[$l,Ah],options:[],examples:[{name:"Upload a folder of images",value:"flexkit assets upload ./images"},{name:"Export all assets to a tarball",value:"flexkit assets export"}]};var EN=QA(Yl());async function yg(e,A,t){let i=new Array(e.length),g=0;async function r(){for(;g<e.length;){let s=g;g+=1;let o=e[s];try{i[s]={item:o,result:await t(o,s)};}catch(a){i[s]={item:o,error:a instanceof Error?a:new Error(String(a))};}}}let n=Math.max(1,Math.min(A,e.length));return await Promise.all(Array.from({length:n},()=>r())),i}var eh=3,jP=1e3;function VP(e){if(!(e instanceof Error))return false;let A=e.message.toLowerCase();return A.includes("fetch failed")||A.includes("network")||A.includes("econnreset")||A.includes("etimedout")||A.includes("socket")}function th(e,A){return e.apiUrl.replace("https://",`https://${A}.`)}async function Et(e,A,t,i={}){let g=`${th(e,A)}/graphql`,r;for(let n=1;n<=eh;n+=1)try{let s=await fetch(g,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.authConfig.token??""},body:JSON.stringify({query:t,variables:i})}),o=await s.text(),a;try{a=JSON.parse(o);}catch{throw new Error(`GraphQL HTTP ${s.status}: ${o.slice(0,500)}`)}if(!s.ok&&!a.errors?.length)throw new Error(`GraphQL HTTP ${s.status}: ${o.slice(0,500)}`);return a}catch(s){if(r=s,n<eh&&VP(s)){e.output.debug(`GraphQL request failed (attempt ${n}/${eh}): ${s instanceof Error?s.message:String(s)}. Retrying...`),await Jt(jP*n);continue}throw s}throw r instanceof Error?r:new Error(String(r))}function at(e){return (e??[]).map(A=>A.message).join("; ")}function IN(e){return e.toLowerCase().includes("constraint")}var ZP={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",ico:"image/vnd.microsoft.icon",bmp:"image/bmp",gif:"image/gif",tif:"image/tiff",tiff:"image/tiff",svg:"image/svg+xml",avif:"image/avif",heic:"image/heic",heif:"image/heif",apng:"image/apng",aac:"audio/aac",mp3:"audio/mpeg",wav:"audio/wav",midi:"audio/midi",oga:"audio/ogg",avi:"video/x-msvideo",mp4:"video/mp4",mpeg:"video/mpeg",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg",ts:"video/mp2t","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed",zip:"application/zip",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",epub:"application/epub+zip",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",gz:"application/gzip",jar:"application/java-archive",json:"application/json",jsonld:"application/ld+json",mjs:"text/javascript",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",tar:"application/x-tar",vsd:"application/vnd.visio",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",txt:"text/plain",csv:"text/csv",md:"text/markdown"};function ih(e){let A=e.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase()??"";return ZP[A]??"application/octet-stream"}function sN(e,A){let t=e?.split(";")[0]?.trim()??"";return t&&t!=="application/octet-stream"?t:ih(A)}function zP(e){return e.startsWith("http://")||e.startsWith("https://")}async function BN(e){let A=await RA.promises.readdir(e,{withFileTypes:true}),t=[];for(let i of A){let g=ue__default.default.join(e,i.name);if(!i.name.startsWith(".")){if(i.isDirectory()){t.push(...await BN(g));continue}i.isFile()&&t.push(g);}}return t}async function QN(e,A){let t=[];for(let i of e){if(zP(i)){let{pathname:n}=new URL(i),s=decodeURIComponent(n.split("/").pop()||"file.bin");t.push({source:i,isUrl:true,filename:s});continue}let g=ue__default.default.resolve(A,i);if((await RA.promises.stat(g)).isDirectory()){let n=await BN(g);for(let s of n)t.push({source:s,isUrl:false,filename:ue__default.default.basename(s)});continue}t.push({source:g,isUrl:false,filename:ue__default.default.basename(g)});}return t}async function $P(e){if(!e.isUrl)return {buffer:await RA.promises.readFile(e.source),mimeType:ih(e.filename)};let A=await fetch(e.source);if(!A.ok)throw new Error(`Failed to download ${e.source} (HTTP ${A.status})`);let t=Buffer.from(await A.arrayBuffer()),i=sN(A.headers.get("content-type"),e.filename);return {buffer:t,mimeType:i}}function AO(e,A,t){if(e==="filename")return A.filename.replace(/\.[A-Za-z0-9]+$/,"");if(e==="hash")return crypto.createHash("sha256").update(t).digest("hex")}var CN=5,oN=120;function eO(e){let A=Number(e.headers.get("Retry-After"));if(Number.isFinite(A)&&A>0)return Math.min(A,oN)*1e3;let t=Number(e.headers.get("X-RateLimit-Reset"));return Number.isFinite(t)&&t>Date.now()?Math.min(t-Date.now(),oN*1e3):5e3}async function tO(e,A,t,i){let g=new URLSearchParams({filename:i.filename});i.assetId&&g.set("assetId",i.assetId);let r=`${th(e,A)}/assets?${g.toString()}`;for(let n=1;;n+=1){let s=await fetch(r,{method:"POST",headers:{"Content-Type":i.mimeType,Authorization:e.authConfig.token??""},body:new Uint8Array(t)}),o=await s.text();if(s.status===429&&n<=CN){let a=eO(s);e.output.debug(`Rate limited uploading ${i.filename} (attempt ${n}/${CN}). Waiting ${Math.ceil(a/1e3)}s...`),await Jt(a);continue}if(!s.ok)throw new Error(`Asset upload failed for ${i.filename} (HTTP ${s.status}): ${o.slice(0,300)}`);return JSON.parse(o)}}async function aQ(e,A,t,i={}){let{buffer:g,mimeType:r}=await $P(t),n=i.assetId??AO(i.idStrategy??"random",t,g);return tO(e,A,g,{mimeType:r,filename:t.filename,assetId:n})}async function gO(e,A,t){let i=await Et(e,A,`query FindTag($where: _tagWhere) {
|
|
189
|
+
`);u=I.pop()??"";for(let C of I){let E=MP(C);if(E&&(_l(e.output,A,E,i,g),!!Ol(E.state)))return E}}}async function GP(e,A,t,i,g,r){let n=0;for(;;){if(r())throw new Error("Deploy observation was canceled.");try{let s=await e.fetch(t.poll,{projectId:A,retry:{retries:3}});if(_l(e.output,A,s,i,g),Ol(s.state))return s;n=0,await Jt($M);continue}catch(s){if(n+=1,n>yP)throw s;let o=Math.min($M*n,5e3);e.output.debug(`[${A}] polling retry in ${o.toString()}ms: ${Ie(s)}`),await Jt(o);}}}async function UP(e,A,t,i,g){let r=new Set,n={};if(_l(e.output,A,{state:i},r,n),Ol(i))return {state:i};try{return await NP(e,A,t,r,n,g)}catch(s){return e.output.debug(`[${A}] SSE observation unavailable, falling back to polling: ${Ie(s)}`),GP(e,A,t,r,n,g)}}function bP(e,A,t){let i=QQ(t.error);tN(e,A,i);}function LP(e){return Array.isArray(e.errors)&&e.errors.length>0}function xP(e,A,t){if(!$e(t)){e.output.error(`[${A}] ${Ie(t)}`);return}if(t.status===401){e.output.log(`[${A}] You are not logged in. Please log in first by running ${bA("login")}`);return}if(t.status===409&&typeof t.jobId=="string"){e.output.warn(`[${A}] Deploy lock is active for job ${t.jobId}.`);return}if(t.status===400||LP(t)){tN(e.output,A,QQ(t));return}e.output.error(`[${A}] ${t.serverMessage}`);}async function ql(e){let A,{output:t}=e;try{A=te(e.argv.slice(2),{"--allow-breaking-changes":Boolean,"--help":Boolean,"-h":"--help","--force":Boolean});}catch(a){return gt(a),1}if(A.flags["--help"])return t.print(ie(zM,{columns:e.stderr.columns})),2;if(e.flexkitConfig===void 0)return t.error(`No Flexkit configuration file found in the current directory. Please ensure you are executing the command from the correct folder, or run ${bA("init")} to create a new Flexkit project in this directory.`),1;let i=[],g=[],r=[],{projects:n}=e.flexkitConfig,s=false,o=()=>{s=true,t.warn("Received Ctrl+C. Stopping deploy command.");};process.once("SIGINT",o);try{t.spinner("Deploying schema",200);for(let a of n){if(s)break;let B=a.schema??[],u=a.scopes??[],Q=a.spaces??[];try{let I=await kP(e,a.projectId,B,u,Q,A.flags["--force"]??!1,A.flags["--allow-breaking-changes"]??!1);if(!I.hasChanges){g.push(a.projectId),t.log(`[${a.projectId}] ${I.message}`),t.dim(`[${a.projectId}] schemaHash=${I.schemaHash}`);continue}let C=await UP(e,a.projectId,I.observe,I.state,()=>s);if(C.state==="completed"){i.push(a.projectId);continue}r.push(a.projectId),bP(t,a.projectId,C);}catch(I){r.push(a.projectId),xP(e,a.projectId,I);}}}finally{process.off("SIGINT",o),t.stopSpinner();}if(s)return 1;if(i.length>0){let{projectsLabel:a,projectWord:B}=Pl(i);t.success(`Deploy completed for ${B} ${a}.`);}if(g.length>0){let{projectsLabel:a,projectWord:B}=Pl(g);t.log(`No changes to deploy for ${B} ${a}.`);}if(r.length>0){let{projectsLabel:a,projectWord:B}=Pl(r);return t.error(`Deploy failed for ${B} ${a}.`),1}return 0}var Wl={name:"ls",description:"List projects, or get a single project by name or id.",arguments:[{name:"nameOrId",required:false}],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"List projects",value:"flexkit project ls"},{name:"List projects in a specific team scope",value:"flexkit project ls --scope my-team"},{name:"Get a single project by id or name",value:"flexkit project ls my-project"}]},jl={name:"add",description:"Create a project.",arguments:[{name:"name",required:true}],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"Create a project",value:"flexkit project add my-project"},{name:"Create a project in a specific team scope",value:"flexkit project add my-project --scope team-id-or-name"}]},Vl={name:"rm",description:"Remove a project by id or name.",arguments:[{name:"nameOrId",required:true}],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"Remove a project",value:"flexkit project rm my-project"},{name:"Remove a project from a specific team scope",value:"flexkit project rm my-project --scope team-id-or-name"}]},iN={name:"project",description:"Manage projects.",arguments:[],subcommands:[Wl,jl,Vl],options:[{name:"json",shorthand:null,type:String,description:"Output response as JSON",deprecated:false}],examples:[{name:"List projects",value:"flexkit project ls"},{name:"Create a new project",value:"flexkit project add my-project"},{name:"Remove a project",value:"flexkit project rm my-project-id"}]};function gN(e,A){let t="/api/projects";if(e&&(t+=`/${encodeURIComponent(e)}`),A){let i=new URLSearchParams({scope:A});t+=`?${i.toString()}`;}return t}function vP(e){return "project"in e}function JP(e,A){if(e.log(`Team: ${A.team.name} (${A.team.id})`),A.projects.length===0){e.log("No projects found.");return}let t=[["ID","Name","Created At"],...A.projects.map(i=>[i.id,i.name,i.createdAt??""])];e.print(ur(t));}function KP(e,A){e.log(`Team: ${A.team.name} (${A.team.id})`),e.print(ur([["ID",A.project.id],["Name",A.project.name],["Created At",A.project.createdAt??""]]));}function Zl(e,A){e.print(JSON.stringify(A,null,2));}function HP(e){return $e(e)?Dt(e)&&typeof e.error=="string"?e.error:typeof e.serverMessage=="string"&&e.serverMessage!=="Response Error"?e.serverMessage:e.message:e.message}function YP(e){if(!$e(e))return [];if(!Dt(e)||!Array.isArray(e.matches))return [];let A=[];for(let t of e.matches){if(!Dt(t)||typeof t.id!="string"||typeof t.name!="string")continue;let i={id:t.id,name:t.name};typeof t.createdAt=="string"&&(i.createdAt=t.createdAt),A.push(i);}return A}function TP(e,A){if(A.length===0){e.error("Project name is ambiguous. Retry with the project id.");return}e.error("Project name is ambiguous. Use one of the following project ids:");let t=[["ID","Name","Created At"],...A.map(i=>[i.id,i.name,i.createdAt??""])];e.print(ur(t));}function PP(e,A,t){let{output:i}=e;return $e(A)?A.status===401?(i.log(`You are not logged in. Please log in first by running ${bA("login")}`),1):A.status===409&&(t==="ls"||t==="rm")?(TP(i,YP(A)),1):(i.error(HP(A)),1):(i.debug(String(A)),1)}async function OP(e,A,t,i){let g=await e.fetch(gN(A,t));return i?(Zl(e.output,g),0):vP(g)?(KP(e.output,g),0):(JP(e.output,g),0)}async function _P(e,A,t,i){let g={name:A};t&&(g.scope=t);let r=await e.fetch("/api/projects",{method:"POST",body:g});return i?(Zl(e.output,r),0):(e.output.log(`Created project "${r.project.name}" (${r.project.id}) in team "${r.team.name}" (${r.team.id}).`),0)}async function qP(e,A,t,i){let g=gN(A,t),r=await e.fetch(g);if(!await e.input.confirm({message:`Delete project "${r.project.name}" (${r.project.id}) from team "${r.team.name}"?`,default:false}))return e.output.log("Canceled."),0;let s=await e.fetch(g,{method:"DELETE"});return i?(Zl(e.output,s),0):(e.output.log(`Deleted project "${s.project.name}" (${s.project.id}).`),0)}function WP(e,A){let{columns:t}=e.stderr;return A?A==="ls"?(e.output.print(ie(Wl,{columns:t})),2):A==="add"?(e.output.print(ie(jl,{columns:t})),2):A==="rm"?(e.output.print(ie(Vl,{columns:t})),2):(e.output.error(`The ${A} subcommand does not exist`),1):(e.output.print(ie(iN,{columns:t})),2)}async function Xl(e){let A;try{A=te(e.argv.slice(2),{"--help":Boolean,"-h":"--help","--json":Boolean});}catch(n){return gt(n),1}let[,t,i]=A.args,g=A.flags["--scope"],r=A.flags["--json"]??false;if(A.flags["--help"])return WP(e,t);if(!t)return e.output.error(`No subcommand provided. Use ${bA("project --help")} to see available project subcommands.`),1;try{return t==="ls"?await OP(e,i,g,r):t==="add"?i?await _P(e,i,g,r):(e.output.error(`Missing required project name. Usage: ${bA("project add <name>")}`),1):t==="rm"?i?await qP(e,i,g,r):(e.output.error(`Missing required project id or name. Usage: ${bA("project rm <nameOrId>")}`),1):(e.output.error(`The ${t} subcommand does not exist`),1)}catch(n){return t==="ls"||t==="add"||t==="rm"?PP(e,n,t):(e.output.debug(String(n)),1)}}var rN={name:"whoami",description:"Shows the username or email of the currently logged-in user.",arguments:[],options:[],examples:[{name:"Print current user name or email",value:"flexkit whoami"}]};async function zl(e){let A,{output:t}=e;try{A=te(e.argv.slice(2),{"--help":Boolean,"-h":"--help"});}catch(g){return gt(g),1}if(A.flags["--help"])return t.print(ie(rN,{columns:e.stderr.columns})),2;let i=new URL("/api/auth/user",e.authUrl);try{t.spinner("");let g=await e.fetch(i.href);t.stopSpinner();let r=g.display_name?.trim()??g.email?.trim()??"";return r?(t.log(r),0):(t.error("No user information available."),1)}catch(g){return t.stopSpinner(),$e(g)?g.status===401?(t.log(`You are not logged in. Please log in first by running ${bA("login")}`),1):(t.debug(g.message),1):(t.debug(Ie(g)),1)}}function nI(e,A){let{output:t}=e,i=e.flexkitConfig?.projects??[];if(i.length===0)return t.error(`No project configuration found. Run this command from a directory with a flexkit.config file or pass --local-config. See ${bA("--help")}.`),null;if(A){let g=i.find(r=>r.projectId===A);return g||(t.error(`Project "${A}" is not defined in the local config. Available projects: ${i.map(r=>r.projectId).join(", ")}`),null)}return i.length>1?(t.error(`Multiple projects found in the local config. Pass --project <projectId> to select one of: ${i.map(g=>g.projectId).join(", ")}`),null):i[0]}var $l={name:"upload",description:"Upload files or URLs as project assets. Identical files are deduplicated by content hash.",arguments:[{name:"path|url",required:true}],options:[{name:"project",shorthand:null,type:String,argument:"ID",description:"Project id (required when the local config defines several projects)",deprecated:false},{name:"concurrency",shorthand:null,type:Number,argument:"N",description:"Number of parallel uploads (default 5)",deprecated:false},{name:"id-from",shorthand:null,type:String,argument:"STRATEGY",description:'Derive deterministic asset _ids: "filename" or "hash"',deprecated:false},{name:"tag",shorthand:null,type:String,argument:"NAME",description:"Tag every uploaded asset with the given tag (created if missing)",deprecated:false},{name:"json",shorthand:null,type:String,description:"Output created assets as NDJSON on stdout",deprecated:false}],examples:[{name:"Upload a folder of images",value:"flexkit assets upload ./images"},{name:"Upload files and a remote URL with a tag",value:"flexkit assets upload hero.png https://example.com/logo.svg --tag branding"},{name:"Upload with deterministic ids derived from filenames",value:"flexkit assets upload ./icons --id-from filename"}]},Ah={name:"export",description:"Export all project assets (files + metadata) into a tarball that can be re-imported.",arguments:[{name:"dest.tar.gz",required:false}],options:[{name:"project",shorthand:null,type:String,argument:"ID",description:"Project id (required when the local config defines several projects)",deprecated:false},{name:"tag",shorthand:null,type:String,argument:"NAME",description:"Only export assets with the given tag",deprecated:false},{name:"concurrency",shorthand:null,type:Number,argument:"N",description:"Number of parallel downloads (default 5)",deprecated:false},{name:"overwrite",shorthand:null,type:String,description:"Overwrite the destination file if it exists",deprecated:false}],examples:[{name:"Export all assets",value:"flexkit assets export"},{name:"Export assets with a tag to a specific file",value:"flexkit assets export branding.tar.gz --tag branding"}]},nN={name:"assets",description:"Manage project assets.",arguments:[],subcommands:[$l,Ah],options:[],examples:[{name:"Upload a folder of images",value:"flexkit assets upload ./images"},{name:"Export all assets to a tarball",value:"flexkit assets export"}]};var EN=QA(Yl());async function yg(e,A,t){let i=new Array(e.length),g=0;async function r(){for(;g<e.length;){let s=g;g+=1;let o=e[s];try{i[s]={item:o,result:await t(o,s)};}catch(a){i[s]={item:o,error:a instanceof Error?a:new Error(String(a))};}}}let n=Math.max(1,Math.min(A,e.length));return await Promise.all(Array.from({length:n},()=>r())),i}var eh=3,jP=1e3;function VP(e){if(!(e instanceof Error))return false;let A=e.message.toLowerCase();return A.includes("fetch failed")||A.includes("network")||A.includes("econnreset")||A.includes("etimedout")||A.includes("socket")}function th(e,A){return e.apiUrl.replace("https://",`https://${A}.`)}async function Et(e,A,t,i={}){let g=`${th(e,A)}/graphql`,r;for(let n=1;n<=eh;n+=1)try{let s=await fetch(g,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e.authConfig.token??""},body:JSON.stringify({query:t,variables:i})}),o=await s.text(),a;try{a=JSON.parse(o);}catch{throw new Error(`GraphQL HTTP ${s.status}: ${o.slice(0,500)}`)}if(!s.ok&&!a.errors?.length)throw new Error(`GraphQL HTTP ${s.status}: ${o.slice(0,500)}`);return a}catch(s){if(r=s,n<eh&&VP(s)){e.output.debug(`GraphQL request failed (attempt ${n}/${eh}): ${s instanceof Error?s.message:String(s)}. Retrying...`),await Jt(jP*n);continue}throw s}throw r instanceof Error?r:new Error(String(r))}function at(e){return (e??[]).map(A=>A.message).join("; ")}function IN(e){return e.toLowerCase().includes("constraint")}var ZP={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",ico:"image/vnd.microsoft.icon",bmp:"image/bmp",gif:"image/gif",tif:"image/tiff",tiff:"image/tiff",svg:"image/svg+xml",avif:"image/avif",heic:"image/heic",heif:"image/heif",apng:"image/apng",aac:"audio/aac",mp3:"audio/mpeg",wav:"audio/wav",midi:"audio/midi",oga:"audio/ogg",avi:"video/x-msvideo",mp4:"video/mp4",mpeg:"video/mpeg",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg",ts:"video/mp2t","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed",zip:"application/zip",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",epub:"application/epub+zip",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",gz:"application/gzip",jar:"application/java-archive",json:"application/json",jsonld:"application/ld+json",mjs:"text/javascript",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",ogg:"application/ogg",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",tar:"application/x-tar",vsd:"application/vnd.visio",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",txt:"text/plain",csv:"text/csv",md:"text/markdown"};function ih(e){let A=e.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase()??"";return ZP[A]??"application/octet-stream"}function sN(e,A){let t=e?.split(";")[0]?.trim()??"";return t&&t!=="application/octet-stream"?t:ih(A)}function zP(e){return e.startsWith("http://")||e.startsWith("https://")}async function BN(e){let A=await RA.promises.readdir(e,{withFileTypes:true}),t=[];for(let i of A){let g=ue__default.default.join(e,i.name);if(!i.name.startsWith(".")){if(i.isDirectory()){t.push(...await BN(g));continue}i.isFile()&&t.push(g);}}return t}async function QN(e,A){let t=[];for(let i of e){if(zP(i)){let{pathname:n}=new URL(i),s=decodeURIComponent(n.split("/").pop()||"file.bin");t.push({source:i,isUrl:true,filename:s});continue}let g=ue__default.default.resolve(A,i);if((await RA.promises.stat(g)).isDirectory()){let n=await BN(g);for(let s of n)t.push({source:s,isUrl:false,filename:ue__default.default.basename(s)});continue}t.push({source:g,isUrl:false,filename:ue__default.default.basename(g)});}return t}async function $P(e){if(!e.isUrl)return {buffer:await RA.promises.readFile(e.source),mimeType:ih(e.filename)};let A=await fetch(e.source);if(!A.ok)throw new Error(`Failed to download ${e.source} (HTTP ${A.status})`);let t=Buffer.from(await A.arrayBuffer()),i=sN(A.headers.get("content-type"),e.filename);return {buffer:t,mimeType:i}}function AO(e,A,t){if(e==="filename")return A.filename.replace(/\.[A-Za-z0-9]+$/,"");if(e==="hash")return crypto.createHash("sha256").update(t).digest("hex")}var CN=5,oN=120;function eO(e){let A=Number(e.headers.get("Retry-After"));if(Number.isFinite(A)&&A>0)return Math.min(A,oN)*1e3;let t=Number(e.headers.get("X-RateLimit-Reset"));return Number.isFinite(t)&&t>Date.now()?Math.min(t-Date.now(),oN*1e3):5e3}async function tO(e,A,t,i){let g=new URLSearchParams({filename:i.filename});i.assetId&&g.set("assetId",i.assetId);let r=`${th(e,A)}/assets?${g.toString()}`;for(let n=1;;n+=1){let s=await fetch(r,{method:"POST",headers:{"Content-Type":i.mimeType,Authorization:e.authConfig.token??""},body:new Uint8Array(t)}),o=await s.text();if(s.status===429&&n<=CN){let a=eO(s);e.output.debug(`Rate limited uploading ${i.filename} (attempt ${n}/${CN}). Waiting ${Math.ceil(a/1e3)}s...`),await Jt(a);continue}if(!s.ok)throw new Error(`Asset upload failed for ${i.filename} (HTTP ${s.status}): ${o.slice(0,300)}`);return JSON.parse(o)}}async function aQ(e,A,t,i={}){let{buffer:g,mimeType:r}=await $P(t),n=i.assetId??AO(i.idStrategy??"random",t,g);return tO(e,A,g,{mimeType:r,filename:t.filename,assetId:n})}async function gO(e,A,t){let i=await Et(e,A,`query FindTag($where: _tagWhere) {
|
|
190
190
|
_tags(where: $where) {
|
|
191
191
|
_id
|
|
192
192
|
}
|