modelence 0.26.0-nd.dev.2 → 0.26.0-nd.dev.4
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 +12 -11
- package/dist/bin/modelence.js.map +1 -1
- package/dist/{chunk-HFNAJCTD.js → chunk-FHOJ4TLI.js} +3 -3
- package/dist/{chunk-HFNAJCTD.js.map → chunk-FHOJ4TLI.js.map} +1 -1
- package/dist/{chunk-GMTUEWYF.js → chunk-KD6Y757U.js} +5 -5
- package/dist/{chunk-GMTUEWYF.js.map → chunk-KD6Y757U.js.map} +1 -1
- package/dist/{package-JPHG4QIF.js → package-7W265FW4.js} +2 -2
- package/dist/{package-JPHG4QIF.js.map → package-7W265FW4.js.map} +1 -1
- package/dist/server-UHDRSKRY.js +2 -0
- package/dist/{server-CYLJLPFN.js.map → server-UHDRSKRY.js.map} +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/server-CYLJLPFN.js +0 -2
package/dist/bin/modelence.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
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 ${
|
|
5
|
-
claude plugin install ${
|
|
6
|
-
Guide: ${
|
|
7
|
-
`),console.log(`Declared the Modelence Claude Code plugin in ${
|
|
8
|
-
`);if(await promises.writeFile(t,
|
|
9
|
-
`),console.log(`Successfully configured ${
|
|
2
|
+
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import q,{join,dirname,relative,sep}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import {execFile,execSync,spawnSync}from'child_process';import Ue 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 Ft from'archiver';import ft from'os';import {promisify}from'util';async function b(e,{pick:t,pickEnvironment:n=false,appId:o}={}){let r=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!r.ok)throw new Error("Failed to create CLI authentication code");let{code:i,verificationUrl:a}=await r.json(),s=new URL(a),c=t??(n?"environment":void 0);c&&s.searchParams.set("pick",c),o&&s.searchParams.set("appId",o),console.log(`Please visit ${s} to authenticate`),console.log(`Code: ${i}`);try{await Ue(s.toString());}catch{console.log("Could not open a browser automatically. Please open the URL above manually.");}return await Ve(e,i)}async function Ve(e,t){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await We(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 We(e,t){let n=await fetch(`${e}/api/cli/token?code=${t}`,{method:"GET"});if(!n.ok)throw new Error(`CLI token polling failed: ${n.statusText}`);let{token:o,expiresAt:r,target:i}=await n.json();return o?{token:o,expiresAt:r,target:i}:null}var D=".modelence",A="project.json";function re(e=process.cwd()){return join(e,D,A)}async function I(e=process.cwd()){try{let t=await promises.readFile(re(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return {}}}async function O(e,t=process.cwd()){let n=await I(t);await promises.mkdir(join(t,D),{recursive:true}),await promises.writeFile(re(t),JSON.stringify({...n,...e},null,2)+`
|
|
3
|
+
`);}var z=".modelence.env";async function Ke(e,t){let n="setupToken"in t?{"X-Modelence-Setup-Token":t.setupToken}:{Authorization:`Bearer ${t.cliToken}`},o=await fetch(`${e}/api/setup`,{method:"GET",headers:n});if(!o.ok){let r=await o.text();throw new Error(r||`Request failed with status ${o.status}`)}return o.json()}async function se(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(e,o=>{t.close(),n(o.trim());});})}async function Ye(){return (await se(`Warning: ${z} already exists. Do you want to overwrite it? (y/N) `)).toLowerCase()==="y"}function qe(e){return String(e).replace(/"/g,'\\"')}async function He(){let{appId:e}=await I();return typeof e=="string"&&e?e:void 0}async function Xe(e){await O({appId:e});}var ae=".claude",x=join(ae,"settings.json"),M="modelence@modelence",G="modelence/modelence",Ze={modelence:{source:{source:"github",repo:G}}},Qe="https://docs.modelence.com/ai-coding-agents",ie=`Install the Modelence plugin for Claude Code by hand:
|
|
4
|
+
claude plugin marketplace add ${G}
|
|
5
|
+
claude plugin install ${M} --scope project
|
|
6
|
+
Guide: ${Qe}`;async function et(){let e=join(process.cwd(),x),t;try{t=await promises.readFile(e,"utf8");}catch(o){if(o.code!=="ENOENT"){console.warn(`Could not read ${x}; leaving it unchanged.`);return}}let n={};if(t!==void 0)try{n=JSON.parse(t);}catch{console.warn(`Could not parse ${x}; leaving it unchanged.`);return}n.extraKnownMarketplaces={...n.extraKnownMarketplaces,...Ze},n.enabledPlugins?.[M]===void 0&&(n.enabledPlugins={...n.enabledPlugins,[M]:true});try{await promises.mkdir(join(process.cwd(),ae),{recursive:!0}),await promises.writeFile(e,JSON.stringify(n,null,2)+`
|
|
7
|
+
`),console.log(`Declared the Modelence Claude Code plugin in ${x}`);}catch(o){console.warn(`Failed to write ${x}:`,o);}}function J(e){return spawnSync("claude",e,{encoding:"utf8",shell:process.platform==="win32"})}async function tt(){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 n=J(["plugin","marketplace","add",G]),o=J(["plugin","install",M,"--scope","project"]);if(o.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=n.status!==0?n:o;console.warn(`Could not install the Modelence plugin: ${(r.stderr||r.stdout||"").trim()}`),console.warn(ie);}}async function nt(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(),z),n={},o=!1;try{let c=await promises.readFile(t,"utf8");n=parse(c),o=!0,await nt(t),await Ye()||(console.log("Setup canceled"),process.exit(0));}catch{}let r;if(e.token)r={setupToken:e.token};else {let{token:c}=await b(e.host,{pickEnvironment:!0,appId:await He()});r={cliToken:c};}console.log("Fetching service configuration...");let i=await Ke(e.host,r),a={...n,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"},s=Object.entries(a).map(([c,u])=>`${c}="${qe(u)}"`).join(`
|
|
8
|
+
`);if(await promises.writeFile(t,s.trim()+`
|
|
9
|
+
`),console.log(`Successfully configured ${z} file`),i.appId)try{await Xe(i.appId),console.log(`Recorded the app ID in ${D}/${A}`);}catch(c){console.warn(`Failed to record the app ID in ${D}/${A}:`,c);}await et(),!e.token&&process.stdin.isTTY&&await tt(),o&&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."),!o&&a.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
|
-
`);if(c=a.logCount,a.status!==s){s=a.status;let i=Rt(a);i&&console.log(i);}if(a.status==="deploy-completed"){a.siteUrl&&console.log(`Live at ${a.siteUrl}`);return}if(a.status==="build-failed"||a.status==="deploy-failed"){for(let i of a.errors)console.error(` ${i}`);process.exitCode=1;return}await new Promise(i=>setTimeout(i,Ie));}console.error("Timed out waiting for the deployment; check the dashboard for its status."),process.exitCode=1;}function Rt(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}}function jt(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}async function Lt(e){return process.env.MODELENCE_TOKEN?process.env.MODELENCE_TOKEN:await fe(e)}async function ke(e,t,n){if(n)try{await ge(e,t,n);}catch(o){console.warn("Could not save the login for next time:",o);}}async function X(e){let t={environmentId:e.environmentId,appAlias:e.appAlias,envAlias:e.envAlias};try{await S({deploy:t,..."appId"in e?{appId:e.appId}:{}});}catch(n){console.warn("Could not record the deploy target in .modelence/project.json:",n);}}async function Ft(e,t){if(e)return e.replace(/\/$/,"");if(process.env.MODELENCE_SERVICE_ENDPOINT)return process.env.MODELENCE_SERVICE_ENDPOINT.replace(/\/$/,"");try{let n=parse(await promises.readFile(join(t,".modelence.env"),"utf8"));if(n.MODELENCE_SERVICE_ENDPOINT)return n.MODELENCE_SERVICE_ENDPOINT.replace(/\/$/,"")}catch{}return At}function Bt(e){return {preset:e.preset,nodeVersion:e.nodeVersion,rootDirectory:e.rootDir,installCommand:e.installCommand,buildCommand:e.buildCommand,startCommand:e.startCommand,outputDirectory:e.outputDir}}function Q(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Ut(e,t){console.log("Build plan:"),console.log(` preset: ${e.preset??"node"}`),console.log(` node: ${e.nodeVersion??"default (22)"}`),e.rootDirectory&&console.log(` root: ${e.rootDirectory}`),console.log(` install: ${e.installCommand??"default"}`),console.log(` build: ${e.buildCommand||"(none)"}`),e.preset==="static"?console.log(` serve: ${e.outputDirectory??"dist"}/ (static site)`):console.log(` start: ${e.startCommand??"npm start"}`);for(let n of t)console.log(` note: ${n}`);}function Vt(e,t){if(!t)return;let n=[];e.preset&&t.preset&&e.preset!==t.preset&&n.push(`preset ${e.preset} (detected ${t.preset})`);for(let o of ["installCommand","buildCommand","startCommand"]){let r=t[o];r!==void 0&&e[o]!==void 0&&e[o]!==r&&n.push(`${o.replace("Command","")} "${e[o]}" (detected "${r}")`);}n.length>0&&(console.log("Using the environment's Build & Deploy settings: "+n.join(", ")),console.log("Edit them in the dashboard, or pass --preset/--*-command to change them."));}function xe(e){return `${(e/1024/1024).toFixed(2)} MB`}async function Jt(e){await promises.rm(e,{force:true}),console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),n=bt("zip",{zlib:{level:9}}),o=new Promise((a,i)=>{t.on("close",a),t.on("error",i),n.on("error",i);});n.pipe(t);let r=["package.json","package-lock.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server","scripts",join(".modelence","build"),".next"];for(let a of r)await De(y(a))&&n.file(y(a),{name:a});for(let a of s)await De(y(a))&&n.directory(y(a),a);await n.finalize(),await o;let c=await promises.stat(e);console.log(`Deployment bundle created (${xe(c.size)})`);}async function De(e){try{return await promises.access(e),!0}catch{return false}}function Ne(e={}){console.log("Starting Modelence dev server...");let t=w(),n=K.resolve("./node_modules/.bin/tsx");execSync(`"${n}" watch --ignore "vite.config.ts.timestamp-*" "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development",...e.takeover?{MODELENCE_TAKEOVER:"1"}:{}}});}function Ae(){console.log("Starting Modelence production server...");let e=w(),t=K.basename(e,K.extname(e)),n=$(`${t}.mjs`);execSync(`node "${n}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}async function Oe(e){await j(e.host),console.log(e.host?`Removed the saved login for ${e.host}.`:`Removed saved logins (${R()}).`);}var Qt=fileURLToPath(import.meta.url),Zt=dirname(Qt),en=JSON.parse(readFileSync(join(Zt,"../../package.json"),"utf-8")),g=new Command().name("modelence").description("Modelence CLI tool").version(en.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 re(e);});g.command("build").description("Build the application").action(async()=>{await v(),await _();});g.command("deploy").description("Deploy the current directory to Modelence Cloud (any Node.js app; 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)").option("--preset <preset>","Build preset: node, static or modelence (default: detected)").option("--node-version <version>","Node.js version for the container, e.g. 22").option("--root-dir <path>","Subdirectory containing the app (monorepos)").option("--install-command <command>","Override the detected install command").option("--build-command <command>",'Override the detected build command ("" to skip)').option("--start-command <command>","Override the detected start command").option("--output-dir <path>","Static sites: directory the build writes, e.g. dist").action(async e=>{try{await Te(e);}catch(t){console.error(`Deploy 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 Oe(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 v(),Ne(e);});g.command("start").description("Start production server").action(async()=>{await v(),Ae();});g.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
12
|
+
`));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var it=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"),n=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof n!="object")throw new Error("modelence.config.ts should export an object");return it.parse(n)}var de=null,K=null;function ue(){if(!K)throw new Error("Configuration not loaded");return K}function y(){let{serverDir:e,serverEntry:t}=ue();return join(e,t).replace(/\\/g,"/")}function pe(){return ue().postBuildCommand}function j(e){let t=Y("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function v(e){return join(process.cwd(),e).replace(/\\/g,"/")}function Y(e){let t=v(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function E(){try{K=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");de=parse(e);}catch(e){if(e.code==="ENOENT")de={};else throw e}}async function dt(){let e=pe();if(e){console.log("Running post-build command..."),execSync(e);return}await ut(),await pt();}async function ut(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:q.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function pt(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),n={build:{ssr:q.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:q.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},n,true));}async function mt(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[y()],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 _(){console.log("Building Modelence project...");try{let e=j();await me.rm(e,{recursive:!0,force:!0}),await mt(),await dt(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await me.access(Y());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}var ht="auth.json",wt=60*1e3;function L(){let e=process.env.MODELENCE_HOME||join(ft.homedir(),".modelence");return join(e,ht)}async function Z(){try{let e=JSON.parse(await promises.readFile(L(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}async function X(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 Z(),n=t[e];return !n?.token||!n.expiresAt||new Date(n.expiresAt).getTime()-wt<=Date.now()?null:n.token}async function ve(e,t,n){let o=await Z();await X({...o,hosts:{...o.hosts,[e]:{token:t,expiresAt:n}}});}async function F(e){if(!e){await X({});return}let t=await Z(),{[e]:n,...o}=t.hosts??{};await X({...t,hosts:o});}var Et={5:7,6:8,9:10};function ke(e){let t=/^lockfileVersion:\s*['"]?(\d+)(?:\.\d+)?['"]?\s*$/m.exec(e);if(t)return Et[t[1]]}function kt(e){let t=[],n=false;for(let o of e.split(`
|
|
14
|
+
`)){if(/^packages:\s*$/.test(o)){n=true;continue}if(!n)continue;let r=/^\s+-\s*['"]?([^'"#]+?)['"]?\s*(?:#.*)?$/.exec(o);r?t.push(r[1].trim()):o.trim()!==""&&!o.startsWith(" ")&&!o.startsWith(" ")&&(n=false);}return t}function Ct(e){let t=e.workspaces;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object"){let n=t.packages;return Array.isArray(n)?n.filter(o=>typeof o=="string"):[]}return []}function Ee(e){let n=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").map(o=>o==="**"?".*":o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")).join("/");return new RegExp(`^${n}$`)}async function Pt(e,t){let n=[];async function o(r,i){if(i>t)return;let a;try{a=await promises.readdir(r,{withFileTypes:!0});}catch{return}for(let s of a){if(!s.isDirectory()||s.name==="node_modules"||s.name.startsWith("."))continue;let c=join(r,s.name);n.push(c),await o(c,i+1);}}return await o(e,1),n}var bt=4;async function Dt(e,t){if(t.length===0)return [];let n=t.filter(a=>!a.startsWith("!")).map(Ee),o=t.filter(a=>a.startsWith("!")).map(a=>Ee(a.slice(1))),r=await Pt(e,bt),i=[];for(let a of r){let s=relative(e,a).split(sep).join("/");if(!n.some(u=>u.test(s))||o.some(u=>u.test(s)))continue;let c;try{c=JSON.parse(await promises.readFile(join(a,"package.json"),"utf8"));}catch{continue}typeof c.name=="string"&&i.push({name:c.name,dir:s,scripts:c.scripts??{}});}return i.sort((a,s)=>a.dir.localeCompare(s.dir))}function It(e,t){switch(e){case "pnpm":return `pnpm --filter ${t} start`;case "yarn":return `yarn workspace ${t} start`;default:return `npm start --workspace ${t}`}}async function Ce(e,t,n){let o=Ct(n);if(t==="pnpm")try{o=kt(await promises.readFile(join(e,"pnpm-workspace.yaml"),"utf8"));}catch{}let i=(await Dt(e,o)).filter(a=>a.scripts.start);if(i.length===1){let[a]=i;return {startCommand:It(t,a.name),note:`No root start script; the container starts the ${a.name} workspace package (${a.dir}/).`}}return i.length>1?{note:`Several workspace packages have a start script (${i.map(s=>s.name).join(", ")}); pass --start-command to choose one.`}:{}}var xt=18;async function f(e){try{return await promises.access(e),!0}catch{return false}}async function Pe(e){try{let t=JSON.parse(await promises.readFile(e,"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function Tt(e){if(typeof e!="string")return;let t=e.match(/(\d+)(?:\.\d+)?(?:\.\d+)?/);if(!t)return;let n=Number(t[1]);return n>=xt?String(n):void 0}function St(e){for(let t of e.split(/\r?\n/)){let n=t.match(/^\s*web\s*:\s*(.+?)\s*$/);if(n)return n[1]}}function Nt(e,t){let o=t.packages?.[""];if(!o)return true;for(let r of ["dependencies","devDependencies","optionalDependencies"]){let i=e[r]??{},a=o[r]??{},s=new Set([...Object.keys(i),...Object.keys(a)]);for(let c of s)if(i[c]!==a[c])return false}return true}function At(e,t){if(typeof e!="string")return;let n=/^([a-z]+)@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+.*)?$/.exec(e.trim());if(!(!n||n[1]!==t))return n[2]}function Ot(e,t,n){switch(e){case "pnpm":return {install:`npm install -g ${n?`pnpm@${n}`:"pnpm"} && pnpm install --frozen-lockfile`,run:r=>`pnpm run ${r}`,start:"pnpm start"};case "yarn":return {install:"yarn install --frozen-lockfile",run:o=>`yarn ${o}`,start:"yarn start"};default:return {install:t?"npm ci":"npm install",run:o=>`npm run ${o}`,start:"npm start"}}}async function be(e=process.cwd()){let t=[],n=await Pe(join(e,"package.json"));if(!n)throw new Error("No package.json found in the current directory");let o=n.scripts??{},r=n.engines??{},i=await f(join(e,"modelence.config.ts"))||await f(join(e,"modelence.config.js")),a="npm";await f(join(e,"pnpm-lock.yaml"))?a="pnpm":await f(join(e,"yarn.lock"))&&(a="yarn");let s=await f(join(e,"package-lock.json"));if(a==="npm"&&!s&&t.push("No package-lock.json found; dependencies are installed with `npm install`."),a==="npm"&&s){let m=await Pe(join(e,"package-lock.json"));m&&!Nt(n,m)&&(s=false,t.push("package-lock.json is out of date with package.json, so dependencies are installed with `npm install`. Run `npm install` locally and commit the lockfile to get reproducible `npm ci` installs."));}let c=At(n.packageManager,a);if(a==="pnpm"&&!c){let m=ke(await promises.readFile(join(e,"pnpm-lock.yaml"),"utf8"));m?c=String(m):t.push('Could not tell which pnpm version wrote pnpm-lock.yaml; the build installs the latest. Add e.g. "packageManager": "pnpm@10.4.1" to package.json to pin it.');}let u=Ot(a,s,c),l;o.build?l=u.run("build"):i||t.push("No `build` script found; the deploy skips the build step.");let d;try{d=St(await promises.readFile(join(e,"Procfile"),"utf8"));}catch{}if(!d&&o.start&&(d=u.start),!d&&!i){let m=await Ce(e,a,n);d=m.startCommand,m.note&&t.push(m.note);}let N=Tt(r.node),P=!i&&!d&&l?await $t(e,n):void 0;return P?(t.push(`No start script found; the site is served from ${P}/ with single-page app fallback.`),{preset:"static",packageManager:a,nodeVersion:N,installCommand:u.install,buildCommand:l,outputDirectory:P,notes:t}):(d||t.push("No `start` script or Procfile found; the container runs `npm start`. Pass --start-command to override."),{preset:i?"modelence":"node",packageManager:a,nodeVersion:N,installCommand:u.install,buildCommand:l,startCommand:d,notes:t})}async function $t(e,t){let n={...t.dependencies??{},...t.devDependencies??{}},o=await f(join(e,"vite.config.ts"))||await f(join(e,"vite.config.js"))||await f(join(e,"vite.config.mts"));if(n.vite||o)return "dist";if(n["react-scripts"])return "build";if(n["@angular/cli"]||n.astro||await f(join(e,"index.html")))return "dist"}var Ie=promisify(execFile),De=200*1024*1024,Bt=[".git","node_modules",".modelence/build",".modelence/tmp",".modelence/cache"],Ut=[/^\.modelence(\.[^/]+)?\.env$/];function xe(e){return e.split(sep).join("/")}function Te(e){let t=xe(e),n=t.split("/");for(let r of Bt)if(r.split("/").length===1){if(n.slice(0,-1).includes(r))return true}else if(t===r||t.startsWith(`${r}/`))return true;let o=n[n.length-1];return Ut.some(r=>r.test(o))}async function Vt(e){try{let{stdout:t}=await Ie("git",["rev-parse","--is-inside-work-tree"],{cwd:e});return t.trim()==="true"}catch{return false}}async function Wt(e){let{stdout:t}=await Ie("git",["ls-files","--cached","--others","--exclude-standard","-z"],{cwd:e,maxBuffer:67108864});return t.split("\0").filter(n=>n.length>0)}async function Se(e,t=""){let n=await promises.readdir(join(e,t),{withFileTypes:true}),o=[];for(let r of n){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?Te(`${i}/x`)||o.push(...await Se(e,i)):r.isFile()&&o.push(i);}return o}async function Jt(e=process.cwd()){let t=await Vt(e),n=t?await Wt(e):await Se(e),o=[];for(let r of n)if(!Te(r))try{(await promises.stat(join(e,r))).isFile()&&o.push(r);}catch{}return {files:o.sort(),usedGit:t}}async function Ne(e,t){let{files:n,usedGit:o}=await Jt(e);if(n.length===0)throw new Error("No files to upload");await promises.mkdir(join(t,".."),{recursive:true}),await promises.rm(t,{force:true});let r=createWriteStream(t),i=Ft("zip",{zlib:{level:6}}),a=new Promise((c,u)=>{r.on("close",c),r.on("error",u),i.on("error",u);});i.pipe(r);for(let c of n)i.file(join(e,c),{name:xe(relative("",c))});await i.finalize(),await a;let{size:s}=await promises.stat(t);if(s>De)throw await promises.rm(t,{force:true}),new Error(`Source is ${(s/1024/1024).toFixed(0)} MB compressed; the limit is ${De/1024/1024} MB. Add build output and large assets to .gitignore.`);return {fileCount:n.length,sizeBytes:s,usedGit:o}}var C=class extends Error{constructor(n,o){super(n);this.status=o;this.name="StudioApiError";}};async function S(e,t,{method:n="GET",token:o,body:r,query:i}={}){let a=new URL(t,e);for(let[u,l]of Object.entries(i??{}))a.searchParams.set(u,String(l));let s={};o&&(s.Authorization=`Bearer ${o}`),r!==void 0&&(s["Content-Type"]="application/json");let c=await fetch(a,{method:n,headers:s,body:r===void 0?void 0:JSON.stringify(r)});if(!c.ok){let u=await c.text(),l=u||c.statusText;try{let d=JSON.parse(u);l=d.error||d.message||l;}catch{}throw new C(l,c.status)}return await c.json()}var Yt="https://cloud.modelence.com",Me=3e3,qt=30*60*1e3,Ht=10*60*1e3;async function Re(e){let t=process.cwd(),n=await nn(e.host,t),o=e.prebuilt?"bundle":"source",r=on(e),i=await I(t),a,s=join(t,".modelence","tmp",`${o}.zip`);if(o==="bundle")await E(),await _(),await an(s);else {let l=await be(t);a={preset:l.preset,nodeVersion:l.nodeVersion,installCommand:l.installCommand,buildCommand:l.buildCommand,startCommand:l.startCommand,outputDirectory:l.outputDirectory},rn({...a,...ne(r)},l.notes);let{fileCount:d,sizeBytes:N,usedGit:P}=await Ne(t,s);console.log(`Packed ${d} files (${je(N)})`+(P?" from git":"; not a git repository, so only default exclusions applied"));}let c=en(e,i),u=await tn(n);if(!u||!c){let l=await b(n,{pick:"deploy",appId:i.appId});u=l.token,await Oe(n,l.token,l.expiresAt),l.target&&(c={environmentId:l.target.environmentId},await te(l.target));}if(!c)throw new Error("No deploy target selected. Run again and pick an environment in the browser, or pass --app and --env.");try{await Ae({host:n,token:u,target:c,kind:o,archivePath:s,overrides:r,detected:a,project:i});}catch(l){if(!(l instanceof C)||l.status!==401)throw l;await F(n),console.log("Your saved login has expired; please sign in again.");let d=await b(n,{pick:"deploy",appId:i.appId});await Oe(n,d.token,d.expiresAt),d.target&&(c={environmentId:d.target.environmentId},await te(d.target)),await Ae({host:n,token:d.token,target:c,kind:o,archivePath:s,overrides:r,detected:a,project:i});}finally{await promises.rm(s,{force:true});}}async function Ae({host:e,token:t,target:n,kind:o,archivePath:r,overrides:i,detected:a,project:s}){let c=await S(e,"/api/upload-bundle",{method:"POST",token:t,body:{...n,kind:o}});await Xt(e,t,c.environmentId),console.log(`Uploading to ${c.appAlias}/${c.envAlias}...`);let u=await promises.readFile(r),l=await fetch(c.uploadUrl,{method:"PUT",body:new Uint8Array(u),headers:{"Content-Type":"application/zip"}});if(!l.ok)throw new Error(`Failed to upload: ${l.statusText}`);let d=await S(e,"/api/deploy",{method:"POST",token:t,body:{environmentId:c.environmentId,bundleName:c.bundleName,kind:o,plan:ne(i),detected:a?ne(a):void 0}});(!s.deploy||s.deploy.environmentId!==d.environmentId)&&await te({environmentId:d.environmentId,appAlias:d.appAlias,envAlias:d.envAlias}),d.plan&&sn(d.plan,a),console.log(`Deployment started: ${d.deploymentUrl}`),d.buildId&&await Zt(e,t,d.environmentId,d.buildId);}async function Xt(e,t,n){let o=Date.now()+Ht,r=false;for(;Date.now()<o;){let i;try{({status:i}=await S(e,"/api/environment/status",{token:t,query:{environmentId:n}}));}catch(a){if(a instanceof C&&a.status===404)return;throw a}if(i==="ready")return;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(a=>setTimeout(a,Me));}throw new Error("Timed out waiting for the environment to be ready.")}async function Zt(e,t,n,o){let r=Date.now()+qt,i="",a=0;for(;Date.now()<r;){let s=await S(e,"/api/deploy/status",{token:t,query:{environmentId:n,buildId:o,logOffset:a}});for(let c of s.logs)process.stdout.write(` \u2502 ${c.replace(/\n$/,"")}
|
|
15
|
+
`);if(a=s.logCount,s.status!==i){i=s.status;let c=Qt(s);c&&console.log(c);}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 c of s.errors)console.error(` ${c}`);process.exitCode=1;return}await new Promise(c=>setTimeout(c,Me));}console.error("Timed out waiting for the deployment; check the dashboard for its status."),process.exitCode=1;}function Qt(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}}function en(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}async function tn(e){return process.env.MODELENCE_TOKEN?process.env.MODELENCE_TOKEN:await ye(e)}async function Oe(e,t,n){if(n)try{await ve(e,t,n);}catch(o){console.warn("Could not save the login for next time:",o);}}async function te(e){let t={environmentId:e.environmentId,appAlias:e.appAlias,envAlias:e.envAlias};try{await O({deploy:t,..."appId"in e?{appId:e.appId}:{}});}catch(n){console.warn("Could not record the deploy target in .modelence/project.json:",n);}}async function nn(e,t){if(e)return e.replace(/\/$/,"");if(process.env.MODELENCE_SERVICE_ENDPOINT)return process.env.MODELENCE_SERVICE_ENDPOINT.replace(/\/$/,"");try{let n=parse(await promises.readFile(join(t,".modelence.env"),"utf8"));if(n.MODELENCE_SERVICE_ENDPOINT)return n.MODELENCE_SERVICE_ENDPOINT.replace(/\/$/,"")}catch{}return Yt}function on(e){return {preset:e.preset,nodeVersion:e.nodeVersion,rootDirectory:e.rootDir,installCommand:e.installCommand,buildCommand:e.buildCommand,startCommand:e.startCommand,outputDirectory:e.outputDir}}function ne(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function rn(e,t){console.log("Build plan:"),console.log(` preset: ${e.preset??"node"}`),console.log(` node: ${e.nodeVersion??"default (22)"}`),e.rootDirectory&&console.log(` root: ${e.rootDirectory}`),console.log(` install: ${e.installCommand??"default"}`),console.log(` build: ${e.buildCommand||"(none)"}`),e.preset==="static"?console.log(` serve: ${e.outputDirectory??"dist"}/ (static site)`):console.log(` start: ${e.startCommand??"npm start"}`);for(let n of t)console.log(` note: ${n}`);}function sn(e,t){if(!t)return;let n=[];e.preset&&t.preset&&e.preset!==t.preset&&n.push(`preset ${e.preset} (detected ${t.preset})`);for(let o of ["installCommand","buildCommand","startCommand"]){let r=t[o];r!==void 0&&e[o]!==void 0&&e[o]!==r&&n.push(`${o.replace("Command","")} "${e[o]}" (detected "${r}")`);}n.length>0&&(console.log("Using the environment's Build & Deploy settings: "+n.join(", ")),console.log("Edit them in the dashboard, or pass --preset/--*-command to change them."));}function je(e){return `${(e/1024/1024).toFixed(2)} MB`}async function an(e){await promises.rm(e,{force:true}),console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),n=Ft("zip",{zlib:{level:9}}),o=new Promise((s,c)=>{t.on("close",s),t.on("error",c),n.on("error",c);});n.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 s of r)await $e(v(s))&&n.file(v(s),{name:s});for(let s of i)await $e(v(s))&&n.directory(v(s),s);await n.finalize(),await o;let a=await promises.stat(e);console.log(`Deployment bundle created (${je(a.size)})`);}async function $e(e){try{return await promises.access(e),!0}catch{return false}}function _e(e={}){console.log("Starting Modelence dev server...");let t=y(),n=q.resolve("./node_modules/.bin/tsx");execSync(`"${n}" watch --ignore "vite.config.ts.timestamp-*" "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development",...e.takeover?{MODELENCE_TAKEOVER:"1"}:{}}});}function Fe(){console.log("Starting Modelence production server...");let e=y(),t=q.basename(e,q.extname(e)),n=j(`${t}.mjs`);execSync(`node "${n}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}async function Be(e){await F(e.host),console.log(e.host?`Removed the saved login for ${e.host}.`:`Removed saved logins (${L()}).`);}var hn=fileURLToPath(import.meta.url),wn=dirname(hn),yn=JSON.parse(readFileSync(join(wn,"../../package.json"),"utf-8")),h=new Command().name("modelence").description("Modelence CLI tool").version(yn.version);h.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);});h.command("build").description("Build the application").action(async()=>{await E(),await _();});h.command("deploy").description("Deploy the current directory to Modelence Cloud (any Node.js app; 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)").option("--preset <preset>","Build preset: node, static or modelence (default: detected)").option("--node-version <version>","Node.js version for the container, e.g. 22").option("--root-dir <path>","Subdirectory containing the app (monorepos)").option("--install-command <command>","Override the detected install command").option("--build-command <command>",'Override the detected build command ("" to skip)').option("--start-command <command>","Override the detected start command").option("--output-dir <path>","Static sites: directory the build writes, e.g. dist").action(async e=>{try{await Re(e);}catch(t){console.error(`Deploy failed: ${t instanceof Error?t.message:String(t)}`),process.exit(1);}});h.command("logout").description("Forget the saved Modelence Cloud login").option("-h, --host <host>","Only forget the login for this host").action(async e=>{await Be(e);});h.command("dev").description("Start development server").option("--takeover","Disconnect any instance currently holding the environment and connect this one").action(async e=>{await E(),_e(e);});h.command("start").description("Start production server").action(async()=>{await E(),Fe();});h.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
15
16
|
//# sourceMappingURL=modelence.js.map
|