modelence 0.26.0-nd.dev.1 → 0.26.0-nd.dev.10
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/bin/modelence.js +14 -10
- package/dist/bin/modelence.js.map +1 -1
- package/dist/chunk-52W7FC72.js +3 -0
- package/dist/chunk-52W7FC72.js.map +1 -0
- package/dist/{chunk-SLTP5FXB.js → chunk-IQOUXFAM.js} +5 -5
- package/dist/{chunk-SLTP5FXB.js.map → chunk-IQOUXFAM.js.map} +1 -1
- package/dist/{package-EUTX35CI.js → package-KS634H3H.js} +2 -2
- package/dist/{package-EUTX35CI.js.map → package-KS634H3H.js.map} +1 -1
- package/dist/server-I6C4KNMF.js +2 -0
- package/dist/{server-RC3UJPKA.js.map → server-I6C4KNMF.js.map} +1 -1
- package/dist/server.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-KJPTCTWA.js +0 -3
- package/dist/chunk-KJPTCTWA.js.map +0 -1
- package/dist/server-RC3UJPKA.js +0 -2
package/dist/bin/modelence.js
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import
|
|
3
|
-
`);}var
|
|
4
|
-
claude plugin marketplace add ${
|
|
2
|
+
import {Command}from'commander';import {readFileSync,promises,createWriteStream,openAsBlob}from'fs';import {fileURLToPath}from'url';import Y,{join,dirname,relative,isAbsolute,resolve,sep}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import {execFile,execSync,spawnSync}from'child_process';import Xe from'open';import me from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import Nt from'archiver';import Pt from'os';import {promisify}from'util';import {parse as parse$1,printParseErrorCode}from'jsonc-parser';async function C(e,{pick:t,purpose:o,pickEnvironment:n=false,appId:r}={}){let i=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!i.ok)throw new Error("Failed to create CLI authentication code");let{code:c,verificationUrl:l}=await i.json(),a=new URL(l),s=t??(n?"environment":void 0);s&&a.searchParams.set("pick",s),o&&a.searchParams.set("purpose",o),r&&a.searchParams.set("appId",r),console.log(`Please visit ${a} to authenticate`),console.log(`Code: ${c}`);try{await Xe(a.toString());}catch{console.log("Could not open a browser automatically. Please open the URL above manually.");}return await Ze(e,c)}async function Ze(e,t){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await Qe(e,t);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function Qe(e,t){let o=await fetch(`${e}/api/cli/token?code=${t}`,{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:n,expiresAt:r,target:i}=await o.json();return n?{token:n,expiresAt:r,target:i}:null}var S=".modelence",D="project.json";function re(e=process.cwd()){return join(e,S,D)}async function P(e=process.cwd()){try{let t=await promises.readFile(re(e),"utf8"),o=JSON.parse(t);return o&&typeof o=="object"?o:{}}catch{return {}}}async function _(e,t=process.cwd()){let o=await P(t);await promises.mkdir(join(t,S),{recursive:true}),await promises.writeFile(re(t),JSON.stringify({...o,...e},null,2)+`
|
|
3
|
+
`);}var K=".modelence.env";async function nt(e,t){let o="setupToken"in t?{"X-Modelence-Setup-Token":t.setupToken}:{Authorization:`Bearer ${t.cliToken}`},n=await fetch(`${e}/api/setup`,{method:"GET",headers:o});if(!n.ok){let r=await n.text();throw new Error(r||`Request failed with status ${n.status}`)}return n.json()}async function se(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{t.question(e,n=>{t.close(),o(n.trim());});})}async function rt(){return (await se(`Warning: ${K} already exists. Do you want to overwrite it? (y/N) `)).toLowerCase()==="y"}function it(e){return String(e).replace(/"/g,'\\"')}async function st(){let{appId:e}=await P();return typeof e=="string"&&e?e:void 0}async function at(e){await _({appId:e});}var ae=".claude",x=join(ae,"settings.json"),O="modelence@modelence",q="modelence/modelence",ct={modelence:{source:{source:"github",repo:q}}},lt="https://docs.modelence.com/ai-coding-agents",ie=`Install the Modelence plugin for Claude Code by hand:
|
|
4
|
+
claude plugin marketplace add ${q}
|
|
5
5
|
claude plugin install ${O} --scope project
|
|
6
|
-
Guide: ${
|
|
7
|
-
`),console.log(`Declared the Modelence Claude Code plugin in ${
|
|
8
|
-
`);if(await promises.writeFile(t,
|
|
9
|
-
`),console.log(`Successfully configured ${
|
|
6
|
+
Guide: ${lt}`;async function pt(){let e=join(process.cwd(),x),t;try{t=await promises.readFile(e,"utf8");}catch(n){if(n.code!=="ENOENT"){console.warn(`Could not read ${x}; leaving it unchanged.`);return}}let o={};if(t!==void 0)try{o=JSON.parse(t);}catch{console.warn(`Could not parse ${x}; leaving it unchanged.`);return}o.extraKnownMarketplaces={...o.extraKnownMarketplaces,...ct},o.enabledPlugins?.[O]===void 0&&(o.enabledPlugins={...o.enabledPlugins,[O]:true});try{await promises.mkdir(join(process.cwd(),ae),{recursive:!0}),await promises.writeFile(e,JSON.stringify(o,null,2)+`
|
|
7
|
+
`),console.log(`Declared the Modelence Claude Code plugin in ${x}`);}catch(n){console.warn(`Failed to write ${x}:`,n);}}function J(e){return spawnSync("claude",e,{encoding:"utf8",shell:process.platform==="win32"})}async function ut(){let e=J(["--version"]);if(e.error||e.status!==0){console.log(ie);return}let t=(await se("Install the Modelence plugin for Claude Code? (Y/n) ")).toLowerCase();if(t&&t!=="y"&&t!=="yes")return;let o=J(["plugin","marketplace","add",q]),n=J(["plugin","install",O,"--scope","project"]);if(n.status===0)console.log("Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: run /mcp, choose modelence, then Authenticate.");else {let r=o.status!==0?o:n;console.warn(`Could not install the Modelence plugin: ${(r.stderr||r.stdout||"").trim()}`),console.warn(ie);}}async function dt(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function ce(e){try{let t=join(process.cwd(),K),o={},n=!1;try{let a=await promises.readFile(t,"utf8");o=parse(a),n=!0,await dt(t),await rt()||(console.log("Setup canceled"),process.exit(0));}catch{}let r;if(e.token)r={setupToken:e.token};else {let{token:a}=await C(e.host,{pickEnvironment:!0,appId:await st()});r={cliToken:a};}console.log("Fetching service configuration...");let i=await nt(e.host,r),c={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:i.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:i.serviceToken,MODELENCE_CONTAINER_ID:i.containerId,MODELENCE_RUNTIME:process.env.MODELENCE_RUNTIME||"local"},l=Object.entries(c).map(([a,s])=>`${a}="${it(s)}"`).join(`
|
|
8
|
+
`);if(await promises.writeFile(t,l.trim()+`
|
|
9
|
+
`),console.log(`Successfully configured ${K} file`),i.appId)try{await at(i.appId),console.log(`Recorded the app ID in ${S}/${D}`);}catch(a){console.warn(`Failed to record the app ID in ${S}/${D}:`,a);}await pt(),!e.token&&process.stdin.isTTY&&await ut(),n&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, start a new session."),!n&&c.MODELENCE_RUNTIME==="local"&&(console.log(`
|
|
10
10
|
Next step \u2014 run the app on this machine:
|
|
11
11
|
`),console.log(" npm install (if you haven't already)"),console.log(` npm run dev (starts the app)
|
|
12
|
-
`));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var
|
|
13
|
-
`,{mode:384});}async function
|
|
14
|
-
`)
|
|
12
|
+
`));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var gt=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()});async function le(){let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");return gt.parse(o)}var pe=null,H=null;function ue(){if(!H)throw new Error("Configuration not loaded");return H}function E(){let{serverDir:e,serverEntry:t}=ue();return join(e,t).replace(/\\/g,"/")}function de(){return ue().postBuildCommand}function R(e){let t=W("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function v(e){return join(process.cwd(),e).replace(/\\/g,"/")}function W(e){let t=v(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function b(){try{H=await le();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await me.readFile(join(process.cwd(),".modelence.env"),"utf-8");pe=parse(e);}catch(e){if(e.code==="ENOENT")pe={};else throw e}}async function vt(){let e=de();if(e){console.log("Running post-build command..."),execSync(e);return}await bt(),await Ct();}async function bt(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:Y.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function Ct(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{ssr:Y.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:Y.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},o,true));}async function St(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[E()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function F(){console.log("Building Modelence project...");try{let e=R();await me.rm(e,{recursive:!0,force:!0}),await St(),await vt(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await me.access(W());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}var At="auth.json",Tt=60*1e3;function L(){let e=process.env.MODELENCE_HOME||join(Pt.homedir(),".modelence");return join(e,At)}async function j(){try{let e=JSON.parse(await promises.readFile(L(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}async function Z(e){let t=L();await promises.mkdir(dirname(t),{recursive:true,mode:448}),await promises.writeFile(t,JSON.stringify(e,null,2)+`
|
|
13
|
+
`,{mode:384});}async function ye(e){let{hosts:t={}}=await j(),o=t[e];return !o?.token||!o.expiresAt||new Date(o.expiresAt).getTime()-Tt<=Date.now()?null:o.token}async function Ee(e){let{hosts:t={}}=await j();return Object.entries(t).filter(([o,n])=>(!e||o===e)&&!!n?.token).map(([o,n])=>({host:o,token:n.token}))}async function ve(e,t,o){let n=await j();await Z({...n,hosts:{...n.hosts,[e]:{token:t,expiresAt:o}}});}async function U(e){if(!e){await Z({});return}let t=await j(),{[e]:o,...n}=t.hosts??{};await Z({...t,hosts:n});}var Ce=promisify(execFile),be=200*1024*1024,Ot=[".git","node_modules",".modelence/build",".modelence/tmp",".modelence/cache"],Mt=[/^\.modelence(\.[^/]+)?\.env$/];function Rt(e){return /^\.env(?:\.|$)/.test(e)&&!/\.(example|sample|template)$/.test(e)}function Ft(e){return e.split(/\r?\n/).some(t=>{if(/^\s*[#;]/.test(t))return false;let o=/https?:\/\/([^/\s]+)@/.exec(t)?.[1];if(o&&o.replace(/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,"").replace(/:/g,"")!=="")return true;let n=/^\s*[^=]*?(?:_authToken|_auth|_password|npmAuthToken|npmAuthIdent)["']?\s*[=:]\s*(.*?)\s*$/i.exec(t);if(!n)return false;let r=n[1].replace(/\s+#.*$/,"").replace(/^["']|["']$/g,"").trim();return r!==""&&!/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(r)})}function Se(e){return e.split(sep).join("/")}function Pe(e){let t=Se(e),o=t.split("/");for(let r of Ot)if(r.split("/").length===1){if(o.slice(0,-1).includes(r))return true}else if(t===r||t.startsWith(`${r}/`))return true;let n=o[o.length-1];return Rt(n)||Mt.some(r=>r.test(n))}async function Lt(e){try{let{stdout:t}=await Ce("git",["rev-parse","--is-inside-work-tree"],{cwd:e});return t.trim()==="true"}catch{return false}}async function jt(e){let{stdout:t}=await Ce("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:e,maxBuffer:67108864});return t.split("\0").filter(o=>o.length>0)}async function xe(e,t=""){let o=await promises.readdir(join(e,t),{withFileTypes:true}),n=[];for(let r of o){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?Pe(`${i}/x`)||n.push(...await xe(e,i)):r.isFile()&&n.push(i);}return n}async function Ut(e=process.cwd()){let t=await Lt(e),o=t?await jt(e):await xe(e),n=[],r=[];for(let i of o){if(Pe(i)){r.push(i);continue}try{if((await promises.lstat(join(e,i))).isFile()){if([".npmrc",".yarnrc.yml",".yarnrc"].includes(i.split("/").at(-1)??"")&&Ft(await promises.readFile(join(e,i),"utf8"))){r.push(i);continue}n.push(i);}}catch{}}return {files:n.sort(),usedGit:t,excludedFiles:r.sort()}}async function Ae(e,t){let{files:o,usedGit:n,excludedFiles:r}=await Ut(e);if(o.length===0)throw new Error("No files to upload");await promises.mkdir(join(t,".."),{recursive:true}),await promises.rm(t,{force:true});let i=createWriteStream(t),c=Nt("zip",{zlib:{level:6}}),l=new Promise((s,p)=>{i.on("close",s),i.on("error",p),c.on("error",p);});c.pipe(i);for(let s of o)c.file(join(e,s),{name:Se(relative("",s))});await c.finalize(),await l;let{size:a}=await promises.stat(t);if(a>be)throw await promises.rm(t,{force:true}),new Error(`Source is ${(a/1024/1024).toFixed(0)} MB compressed; the limit is ${be/1024/1024} MB. Add build output and large assets to .gitignore.`);return {fileCount:o.length,sizeBytes:a,usedGit:n,excludedFiles:r}}var m="modelence.json",k="https://docs.modelence.com/deploy/setup",B=`Use ${k}.md to set up Modelence deployment for this project`;function V(e=process.cwd()){return join(e,m)}async function Ie(e=process.cwd()){let t;try{t=await promises.readFile(V(e),"utf8");}catch{return null}let o=[],n=parse$1(t,o,{allowTrailingComma:true,disallowComments:false});if(o.length>0)throw new Error(`${m} is not valid JSON: ${Gt(t,o[0])}`);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${m} must contain a JSON object`);return n}function Gt(e,t){let o=e.slice(0,t.offset),n=o.split(`
|
|
14
|
+
`).length,r=t.offset-o.lastIndexOf(`
|
|
15
|
+
`);return `${printParseErrorCode(t.error)} at line ${n}, column ${r}`}async function $e(e,t=process.cwd()){await promises.writeFile(V(t),JSON.stringify(e,null,2)+`
|
|
16
|
+
`);}function De(e){let t=[];t.push(` runtime: ${e.runtime??"node"}`),t.push(` node: ${e.build?.node??"default (22)"}`),e.build?.root&&e.build.root!=="."&&t.push(` root: ${e.build.root}`),t.push(` install: ${e.build?.install??"default"}`),t.push(` build: ${Te(e.build?.command)}`);for(let[o,n]of Object.entries(e.build?.env??{}))t.push(` env: ${o}=${n}`);t.push(` start: ${Te(e.web?.start)}`);for(let o of e.web?.static??[])t.push(` static: ${o.path} -> ${o.dir}/`);return t}function Te(e){return e===void 0?"default":e===null||e===""?"(none)":e}async function Oe(e,t="."){if(typeof t!="string"||isAbsolute(t))throw new Error("build.root must be a relative directory inside the project.");let o=await promises.realpath(e),n=resolve(o,t);if(!_e(o,n))throw new Error("build.root must stay inside the project.");let r;try{r=await promises.realpath(n);}catch{throw new Error(`build.root "${t}" does not exist.`)}if(!_e(o,r)||!(await promises.stat(r)).isDirectory())throw new Error("build.root must be a directory inside the project.");return r}function _e(e,t){let o=relative(e,t);return o!==".."&&!o.startsWith(`..${sep}`)&&!isAbsolute(o)}var Me=["$schema","runtime","build","web"];async function Re(e){let t=await Ie(e);if(!t)throw new Error(Ht(e));Wt(t),t.build?.root!==void 0&&await Oe(e,t.build.root),console.log(`Build plan (${m}):`);for(let o of De(t))console.log(o);return t}function Ht(e){return [`${m} not found in ${e}.`,"Modelence Cloud builds and runs your app exactly as this file describes (install, build and start commands, Node.js version, static directories).","Ask your coding agent to create it with this prompt:","",` ${B}`,"",`Reference: ${k}`].join(`
|
|
17
|
+
`)}function Wt(e){let t=Object.keys(e).filter(o=>!Me.includes(o));if(t.length>0)throw new Error(`${m} has unknown key "${t[0]}" (allowed: ${Me.join(", ")}).`);for(let o of ["build","web"]){let n=e[o];if(n!==void 0&&(!n||typeof n!="object"||Array.isArray(n)))throw new Error(`${m}: "${o}" must be an object.`)}}function Fe(e,t){if(e.app&&e.env)return {appAlias:e.app,envAlias:e.env};if(e.env&&t.deploy?.appAlias)return {appAlias:t.deploy.appAlias,envAlias:e.env};if(e.env&&t.appId)return {appId:t.appId,envAlias:e.env};if(e.app||e.env)throw new Error("Pass both --app and --env, or neither to pick the target in the browser.");return t.deploy?.environmentId?{environmentId:t.deploy.environmentId}:null}var w=class extends Error{constructor(o,n){super(o);this.status=n;this.name="StudioApiError";}};async function f(e,t,{method:o="GET",token:n,body:r,query:i}={}){let c=new URL(t,e);for(let[s,p]of Object.entries(i??{}))c.searchParams.set(s,String(p));let l={};n&&(l.Authorization=`Bearer ${n}`),r!==void 0&&(l["Content-Type"]="application/json");let a=await fetch(c,{method:o,headers:l,body:r===void 0?void 0:JSON.stringify(r)});if(!a.ok){let s=await a.text(),p=s||a.statusText;try{let d=JSON.parse(s);p=d.error||d.message||p;}catch{}throw new w(p,a.status)}return await a.json()}var Qt="https://cloud.modelence.com";function z(e){return e instanceof w&&e.status===401}async function Le(e){return process.env.MODELENCE_TOKEN?process.env.MODELENCE_TOKEN:await ye(e)}async function ee(e,t,o){if(o)try{await ve(e,t,o);}catch(n){console.warn("Could not save the login for next time:",n);}}async function I(e){let t={environmentId:e.environmentId,appAlias:e.appAlias,envAlias:e.envAlias};try{await _({deploy:t,..."appId"in e?{appId:e.appId}:{}});}catch(o){console.warn("Could not record the deploy target in .modelence/project.json:",o);}}async function je(e,t){if(e)return e.replace(/\/$/,"");if(process.env.MODELENCE_SERVICE_ENDPOINT)return process.env.MODELENCE_SERVICE_ENDPOINT.replace(/\/$/,"");try{let o=parse(await promises.readFile(join(t,".modelence.env"),"utf8"));if(o.MODELENCE_SERVICE_ENDPOINT)return o.MODELENCE_SERVICE_ENDPOINT.replace(/\/$/,"")}catch{}return Qt}var Ue=3e3,eo=30*60*1e3,to=10*60*1e3;async function Be(e,t,o){let n=Date.now()+to,r=false;for(;Date.now()<n;){let i;try{({status:i}=await f(e,"/api/environment/status",{token:t,query:{environmentId:o}}));}catch(c){if(c instanceof w&&c.status===404)return false;throw c}if(i==="ready")return r;if(i==="failed")throw new Error("The environment failed to provision; check it in the dashboard.");r||(console.log("Waiting for the environment to finish provisioning..."),r=true),await new Promise(c=>setTimeout(c,Ue));}throw new Error("Timed out waiting for the environment to be ready.")}async function Ve(e,t,o,n){let r=Date.now()+eo,i="",c="",l=0,a=false;for(;Date.now()<r;){let s;try{s=await f(e.host,"/api/deploy/status",{token:e.token,query:{environmentId:o,buildId:n,logOffset:l}});}catch(p){if(!z(p)||a)throw p;a=true,await t();continue}for(let p of s.logs)process.stdout.write(` \u2502 ${p.replace(/\n$/,"")}
|
|
18
|
+
`);if(l=Math.max(l,s.logCount),s.status!==i){i=s.status;let p=oo(s);p&&p!==c&&(c=p,console.log(p));}if(s.status==="deploy-completed"){s.siteUrl&&console.log(`Live at ${s.siteUrl}`);return}if(s.status==="build-failed"||s.status==="deploy-failed"){for(let p of s.errors)console.error(` ${p}`);if(s.containerLogs&&s.containerLogs.length>0){console.error("Container output:");for(let p of s.containerLogs)console.error(` \u2502 ${p.replace(/\n$/,"")}`);}process.exitCode=1;return}await new Promise(p=>setTimeout(p,Ue));}console.error("Timed out waiting for the deployment; check the dashboard for its status."),process.exitCode=1;}function oo(e){switch(e.status){case "build-pending":return "Building image...";case "deploy-pending":case "deploying":return "Image built. Deploying containers...";case "rolling-out":return "Rolling out new containers...";case "deploy-completed":return "Deployed successfully.";case "build-failed":return "Build failed.";case "deploy-failed":return "Deployment failed.";default:return null}}async function te({session:e,target:t,kind:o,archivePath:n,spec:r,project:i}){let{host:c,token:l}=e,a=()=>f(c,"/api/upload-bundle",{method:"POST",token:l,body:{...t,kind:o}}),s=await a();await Be(c,l,s.environmentId)&&(s=await a()),console.log(`Uploading to ${s.appAlias}/${s.envAlias}...`);let p=await openAsBlob(n,{type:"application/zip"}),d=await fetch(s.uploadUrl,{method:"PUT",body:p,headers:{"Content-Type":"application/zip"}});if(!d.ok)throw new Error(`Failed to upload: ${await ro(d)}`);let u=await f(c,"/api/deploy",{method:"POST",token:l,body:{environmentId:s.environmentId,bundleName:s.bundleName,kind:o,spec:r}});return (!i.deploy||i.deploy.environmentId!==u.environmentId)&&await I({environmentId:u.environmentId,appAlias:u.appAlias,envAlias:u.envAlias}),console.log(`Deployment started: ${u.deploymentUrl}`),{environmentId:u.environmentId,buildId:u.buildId}}async function ro(e){let t=await e.text().catch(()=>""),o=t.match(/<Code>([^<]+)<\/Code>/)?.[1],n=t.match(/<Message>([^<]+)<\/Message>/)?.[1],r=e.statusText||`HTTP ${e.status}`;return o?`${r} (${o}${n?`: ${n}`:""})`:r}async function Ge(e){let t=process.cwd(),o=await je(e.host,t),n=e.prebuilt?"bundle":"source",r=await P(t),i=Fe(e,r),c,l=join(t,".modelence","tmp",`${n}.zip`);if(n==="bundle")await b(),await F(),await ao(l);else {c=await Re(t);let{fileCount:a,sizeBytes:s,usedGit:p,excludedFiles:d}=await Ae(t,l);console.log(`Packed ${a} files (${Je(s)})`+(p?" from git":"; not a git repository, so only default exclusions applied")),d.length>0&&console.log(`Excluded ${d.length} local or generated files from the upload. Store secrets in the target environment.`);}try{let a=await Le(o);if(!a||!i){let u=await C(o,{pick:i?void 0:"deploy",purpose:"deploy",appId:r.appId});a=u.token,await ee(o,u.token,u.expiresAt),u.target&&(i={environmentId:u.target.environmentId},await I(u.target));}if(!i)throw new Error("No deploy target selected. Run again and pick an environment in the browser, or pass --app and --env.");let s={host:o,token:a},p=async()=>{await U(o),console.log("Your saved login has expired; please sign in again.");let u=await C(o,{pick:i?void 0:"deploy",purpose:"deploy",appId:r.appId});await ee(o,u.token,u.expiresAt),u.target&&(i={environmentId:u.target.environmentId},await I(u.target)),s.token=u.token;},d;try{d=await te({session:s,target:i,kind:n,archivePath:l,spec:c,project:r});}catch(u){if(!z(u))throw u;await p(),d=await te({session:s,target:i,kind:n,archivePath:l,spec:c,project:r});}d.buildId&&await Ve(s,p,d.environmentId,d.buildId);}finally{await promises.rm(l,{force:true});}}function Je(e){return `${(e/1024/1024).toFixed(2)} MB`}async function ao(e){await promises.rm(e,{force:true}),console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=Nt("zip",{zlib:{level:9}}),n=new Promise((l,a)=>{t.on("close",l),t.on("error",a),o.on("error",a);});o.pipe(t);let r=["package.json","package-lock.json","next.config.js","next.config.ts","modelence.config.ts"],i=["public","server","scripts",join(".modelence","build"),".next"];for(let l of r)await ze(v(l))&&o.file(v(l),{name:l});for(let l of i)await ze(v(l))&&o.directory(v(l),l);await o.finalize(),await n;let c=await promises.stat(e);console.log(`Deployment bundle created (${Je(c.size)})`);}async function ze(e){try{return await promises.access(e),!0}catch{return false}}function Ke(e={}){console.log("Starting Modelence dev server...");let t=E(),o=Y.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development",...e.takeover?{MODELENCE_TAKEOVER:"1"}:{}}});}function He(){console.log("Starting Modelence production server...");let e=E(),t=Y.basename(e,Y.extname(e)),o=R(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}async function We(e){let t=await Ee(e.host);await Promise.all(t.map(({host:o,token:n})=>uo(o,n))),await U(e.host),console.log(e.host?`Removed the saved login for ${e.host}.`:`Removed saved logins (${L()}).`);}async function uo(e,t){try{await f(e,"/api/cli/logout",{method:"POST",token:t});}catch{}}var fo="https://cloud.modelence.com";async function Ye(e){let t=process.cwd(),o=V(t);if(!e.force&&await go(o))throw new Error(`${m} already exists; pass --force to overwrite it.`);let r={$schema:`${(e.host??fo).replace(/\/$/,"")}/schema/modelence.json`,build:{node:"22",install:"npm ci",command:null},web:{start:null,static:[]}};await $e(r,t),console.log(`Wrote a ${m} template.`),console.log("Ask your coding agent to fill it in with this prompt:"),console.log(""),console.log(` ${B}`),console.log(""),console.log(`Reference: ${k}`),console.log(`Once ${m} describes your app, run \`modelence deploy\`.`);}async function go(e){try{return await promises.access(e),!0}catch{return false}}var bo=fileURLToPath(import.meta.url),Co=dirname(bo),So=JSON.parse(readFileSync(join(Co,"../../package.json"),"utf-8")),g=new Command().name("modelence").description("Modelence CLI tool").version(So.version);g.command("setup").description("Setup Modelence environment variables").option("-t, --token <token>","Modelence setup token (omit to authorize in the browser)").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await ce(e);});g.command("build").description("Build the application").action(async()=>{await b(),await F();});g.command("deploy").description("Deploy the project described by modelence.json to Modelence Cloud (picks the target in the browser on first run)").option("-a, --app <app>","Application alias").option("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").option("--prebuilt","Build locally and upload the .modelence/build bundle (Modelence apps only)").action(async e=>{try{await Ge(e);}catch(t){console.error(`Deploy failed: ${t instanceof Error?t.message:String(t)}`),process.exit(1);}});g.command("init").description("Create a modelence.json template for this project").option("--force","Overwrite an existing modelence.json").option("-h, --host <host>","Modelence host used for the schema URL").action(async e=>{try{await Ye(e);}catch(t){console.error(`Init failed: ${t instanceof Error?t.message:String(t)}`),process.exit(1);}});g.command("logout").description("Forget the saved Modelence Cloud login").option("-h, --host <host>","Only forget the login for this host").action(async e=>{await We(e);});g.command("dev").description("Start development server").option("--takeover","Disconnect any instance currently holding the environment and connect this one").action(async e=>{await b(),Ke(e);});g.command("start").description("Start production server").action(async()=>{await b(),He();});g.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
15
19
|
//# sourceMappingURL=modelence.js.map
|