modelence 0.23.0-setup.dev.1 → 0.23.0-setup.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.
Files changed (45) hide show
  1. package/dist/bin/modelence.js +8 -4
  2. package/dist/bin/modelence.js.map +1 -1
  3. package/dist/chunk-4EHMYUFO.js +41 -0
  4. package/dist/chunk-4EHMYUFO.js.map +1 -0
  5. package/dist/{chunk-VW6ML4HX.js → chunk-5DF3HHWJ.js} +2 -2
  6. package/dist/{chunk-VW6ML4HX.js.map → chunk-5DF3HHWJ.js.map} +1 -1
  7. package/dist/chunk-ILNPNRGJ.js +3 -0
  8. package/dist/chunk-ILNPNRGJ.js.map +1 -0
  9. package/dist/chunk-KDOTVIEY.js +4 -0
  10. package/dist/chunk-KDOTVIEY.js.map +1 -0
  11. package/dist/chunk-NCJCE4XN.js +3 -0
  12. package/dist/chunk-NCJCE4XN.js.map +1 -0
  13. package/dist/{chunk-SIKRUWRN.js → chunk-UJ2WYHH7.js} +2 -2
  14. package/dist/{chunk-SIKRUWRN.js.map → chunk-UJ2WYHH7.js.map} +1 -1
  15. package/dist/chunk-UW37F3GV.js +2 -0
  16. package/dist/chunk-UW37F3GV.js.map +1 -0
  17. package/dist/client.js +1 -1
  18. package/dist/package-4N23FMUL.js +2 -0
  19. package/dist/{package-XAQYEUWG.js.map → package-4N23FMUL.js.map} +1 -1
  20. package/dist/{render-RN75WGWX.js → render-FRLQDLXI.js} +2 -2
  21. package/dist/{render-RN75WGWX.js.map → render-FRLQDLXI.js.map} +1 -1
  22. package/dist/renderApp-YNRUDPRK.js +2 -0
  23. package/dist/{renderApp-DDIZBBPN.js.map → renderApp-YNRUDPRK.js.map} +1 -1
  24. package/dist/server-6OSZ242A.js +2 -0
  25. package/dist/{server-46L3FOLX.js.map → server-6OSZ242A.js.map} +1 -1
  26. package/dist/server.d.ts +50 -0
  27. package/dist/server.js +1 -1
  28. package/dist/telemetry.js +1 -1
  29. package/dist/transport-LWVQ4TUY.js +2 -0
  30. package/dist/{transport-JPOZOWQ6.js.map → transport-LWVQ4TUY.js.map} +1 -1
  31. package/package.json +4 -3
  32. package/dist/chunk-B5WLEHNH.js +0 -3
  33. package/dist/chunk-B5WLEHNH.js.map +0 -1
  34. package/dist/chunk-B7EXKTEZ.js +0 -3
  35. package/dist/chunk-B7EXKTEZ.js.map +0 -1
  36. package/dist/chunk-I25TKIJW.js +0 -37
  37. package/dist/chunk-I25TKIJW.js.map +0 -1
  38. package/dist/chunk-PGNYB3ZP.js +0 -3
  39. package/dist/chunk-PGNYB3ZP.js.map +0 -1
  40. package/dist/chunk-WHC2SP5P.js +0 -4
  41. package/dist/chunk-WHC2SP5P.js.map +0 -1
  42. package/dist/package-XAQYEUWG.js +0 -2
  43. package/dist/renderApp-DDIZBBPN.js +0 -2
  44. package/dist/server-46L3FOLX.js +0 -2
  45. package/dist/transport-JPOZOWQ6.js +0 -2
@@ -1,6 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import P,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import z$1 from'open';import B from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ue from'archiver';async function E(e,{pickEnvironment:o=false}={}){let t=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!t.ok)throw new Error("Failed to create CLI authentication code");let{code:r,verificationUrl:s}=await t.json(),n=o?`${s}&pick=environment`:s;return console.log(`Please visit ${n} to authenticate`),console.log(`Code: ${r}`),await z$1(n),{token:await J(e,r)}}async function J(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let n=await q(e,o);if(n)return n}catch(n){console.error("Error polling for CLI token:",n);}await new Promise(n=>setTimeout(n,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function q(e,o){let t=await fetch(`${e}/api/cli/token?code=${o}`,{method:"GET"});if(!t.ok)throw new Error(`CLI token polling failed: ${t.statusText}`);let{token:r}=await t.json();return r}var S=".modelence.env",x=".modelence",N="project.json";async function K(e,o){let t="setupToken"in o?{"X-Modelence-Setup-Token":o.setupToken}:{Authorization:`Bearer ${o.cliToken}`},r=await fetch(`${e}/api/setup`,{method:"GET",headers:t});if(!r.ok){let s=await r.text();throw new Error(s||`Request failed with status ${r.status}`)}return r.json()}async function X(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${S} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function Y(e){return String(e).replace(/"/g,'\\"')}async function H(e){let o=join(process.cwd(),x),t=join(o,N),r={};try{r=JSON.parse(await promises.readFile(t,"utf8"));}catch{}await promises.mkdir(o,{recursive:true}),await promises.writeFile(t,JSON.stringify({...r,appId:e},null,2)+`
3
- `);}async function Q(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function O(e){try{let o=join(process.cwd(),S),t={},r=!1;try{let a=await promises.readFile(o,"utf8");t=parse(a),r=!0,await Q(o),await X()||(console.log("Setup canceled"),process.exit(0));}catch{}let s;if(e.token)s={setupToken:e.token};else {let{token:a}=await E(e.host,{pickEnvironment:!0});s={cliToken:a};}console.log("Fetching service configuration...");let n=await K(e.host,s),c={...t,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:n.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:n.serviceToken,MODELENCE_CONTAINER_ID:n.containerId},i=Object.entries(c).map(([a,f])=>`${a}="${Y(f)}"`).join(`
4
- `);if(await promises.writeFile(o,i.trim()+`
5
- `),console.log(`Successfully configured ${S} file`),n.appId)try{await H(n.appId),console.log(`Recorded the app ID in ${x}/${N}`);}catch(a){console.warn(`Failed to record the app ID in ${x}/${N}:`,a);}r&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.");}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var oe=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()});async function $(){let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");return oe.parse(t)}var y=null,T=null;function re(){if(!y)throw new Error("Environment variables not loaded");return y}function M(){if(!T)throw new Error("Configuration not loaded");return T}function j(e){return `${re().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:o}=M();return join(e,o).replace(/\\/g,"/")}function I(){return M().postBuildCommand}function C(e){let o=D("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function u(e){return join(process.cwd(),e).replace(/\\/g,"/")}function D(e){let o=u(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function w(){try{T=await $();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await B.readFile(join(process.cwd(),".modelence.env"),"utf-8");y=parse(e);}catch(e){if(e.code==="ENOENT")y={};else throw e}}async function ce(){let e=I();if(e){console.log("Running post-build command..."),execSync(e);return}await ae(),await le();}async function ae(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:P.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function le(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{ssr:P.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:P.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},t,true));}async function de(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[p()],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 b(){console.log("Building Modelence project...");try{let e=C();await B.rm(e,{recursive:!0,force:!0}),await de(),await ce(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await B.access(D());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function L(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||j("");await b(),await me(r);let{token:n}=await E(s),{bundleName:c}=await fe(e.app,e.env,r,n,s);await promises.unlink(r),await ge(e.app,e.env,c,join(".modelence","build","app.mjs"),n,s);}async function me(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=ue("zip",{zlib:{level:9}});t.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),t.on("error",i=>{throw i});let r=new Promise((i,a)=>{o.on("close",i),o.on("error",a),t.on("error",a);});t.pipe(o);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],n=["public","server",join(".modelence","build"),".next"];for(let i of s)await promises.access(u(i)).then(()=>true).catch(()=>false)&&t.file(u(i),{name:i});for(let i of n)await promises.access(u(i)).then(()=>true).catch(()=>false)&&t.directory(u(i),i);await t.finalize(),await r;let c=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(c.size/1024/1024).toFixed(2)} MB)`);}async function fe(e,o,t,r,s){let n=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!n.ok)throw console.error(await n.text()),new Error(`Failed to create upload URL: ${n.statusText}`);let{uploadUrl:c,bundleName:i}=await n.json(),a=await promises.readFile(t),f=await fetch(c,{method:"PUT",body:new Uint8Array(a),headers:{"Content-Type":"application/zip"}});if(!f.ok)throw new Error(`Failed to upload bundle: ${f.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${i}`),{bundleName:i}}async function ge(e,o,t,r,s,n){let c=await fetch(`${n}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!c.ok)throw new Error(`Failed to trigger deployment: ${c.statusText}`);let{deploymentUrl:i}=await c.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${i}`);}function V(){console.log("Starting Modelence dev server...");let e=p(),o=P.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function A(){console.log("Starting Modelence production server...");let e=p(),o=P.basename(e,P.extname(e)),t=C(`${o}.mjs`);execSync(`node "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Se=fileURLToPath(import.meta.url),xe=dirname(Se),Ne=JSON.parse(readFileSync(join(xe,"../../package.json"),"utf-8")),m=new Command().name("modelence").description("Modelence CLI tool").version(Ne.version);m.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 O(e);});m.command("build").description("Build the application").action(async()=>{await w(),await b();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await w(),await L(e);});m.command("dev").description("Start development server").action(async()=>{await w(),V();});m.command("start").description("Start production server").action(async()=>{await w(),A();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
2
+ import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import O,{join,dirname}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import G from'open';import R 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 {execSync}from'child_process';import Ee from'archiver';async function y(e,{pickEnvironment:t=false,appId:o}={}){let n=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!n.ok)throw new Error("Failed to create CLI authentication code");let{code:s,verificationUrl:r}=await n.json(),a=new URL(r);t&&a.searchParams.set("pick","environment"),o&&a.searchParams.set("appId",o),console.log(`Please visit ${a} to authenticate`),console.log(`Code: ${s}`);try{await G(a.toString());}catch{console.log("Could not open a browser automatically. Please open the URL above manually.");}return {token:await W(e,s)}}async function W(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let r=await X(e,t);if(r)return r}catch(r){console.error("Error polling for CLI token:",r);}await new Promise(r=>setTimeout(r,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function X(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}=await o.json();return n}var x=".modelence.env",C=".modelence",b="project.json";async function Q(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 s=await n.text();throw new Error(s||`Request failed with status ${n.status}`)}return n.json()}async function Z(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${x} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function ee(e){return String(e).replace(/"/g,'\\"')}async function te(){try{let e=await promises.readFile(join(process.cwd(),C,b),"utf8"),{appId:t}=JSON.parse(e);return typeof t=="string"&&t?t:void 0}catch{return}}async function oe(e){let t=join(process.cwd(),C),o=join(t,b),n={};try{n=JSON.parse(await promises.readFile(o,"utf8"));}catch{}await promises.mkdir(t,{recursive:true}),await promises.writeFile(o,JSON.stringify({...n,appId:e},null,2)+`
3
+ `);}var $=".claude",w=join($,"settings.json"),D="modelence@modelence",I={modelence:{source:{source:"github",repo:"modelence/modelence"}}};async function ne(){let e=join(process.cwd(),w),t;try{t=await promises.readFile(e,"utf8");}catch{try{await promises.mkdir(join(process.cwd(),$),{recursive:!0}),await promises.writeFile(e,JSON.stringify({extraKnownMarketplaces:I,enabledPlugins:{[D]:!0}},null,2)+`
4
+ `),console.log(`Enabled the Modelence Claude Code plugin in ${w}`);}catch(o){console.warn(`Failed to create ${w}:`,o);}return}try{let n=JSON.parse(t)?.enabledPlugins?.[D];n!==!0&&console.warn(`Note: the Modelence plugin is ${n===!1?"disabled":"not enabled"} in ${w}. To get Modelence tools and docs in Claude Code, add "${D}": true under "enabledPlugins", and declare the marketplace under "extraKnownMarketplaces": ${JSON.stringify(I)}.`);}catch{console.warn(`Could not parse ${w} to check the Modelence plugin status.`);}}async function re(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 j(e){try{let t=join(process.cwd(),x),o={},n=!1;try{let c=await promises.readFile(t,"utf8");o=parse(c),n=!0,await re(t),await Z()||(console.log("Setup canceled"),process.exit(0));}catch{}let s;if(e.token)s={setupToken:e.token};else {let{token:c}=await y(e.host,{pickEnvironment:!0,appId:await te()});s={cliToken:c};}console.log("Fetching service configuration...");let r=await Q(e.host,s),a={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId,MODELENCE_RUNTIME:process.env.MODELENCE_RUNTIME||"local"},i=Object.entries(a).map(([c,g])=>`${c}="${ee(g)}"`).join(`
5
+ `);if(await promises.writeFile(t,i.trim()+`
6
+ `),console.log(`Successfully configured ${x} file`),r.appId)try{await oe(r.appId),console.log(`Recorded the app ID in ${C}/${b}`);}catch(c){console.warn(`Failed to record the app ID in ${C}/${b}:`,c);}await ne(),n&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session."),a.MODELENCE_RUNTIME==="local"&&(console.log(`
7
+ Next step \u2014 run the app on this machine:
8
+ `),console.log(" npm install (if you haven't already)"),console.log(` npm run dev (starts the app)
9
+ `));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var ae=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()});async function _(){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 ae.parse(o)}var N=null,T=null;function de(){if(!N)throw new Error("Environment variables not loaded");return N}function L(){if(!T)throw new Error("Configuration not loaded");return T}function F(e){return `${de().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function u(){let{serverDir:e,serverEntry:t}=L();return join(e,t).replace(/\\/g,"/")}function B(){return L().postBuildCommand}function S(e){let t=M("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function m(e){return join(process.cwd(),e).replace(/\\/g,"/")}function M(e){let t=m(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function E(){try{T=await _();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await R.readFile(join(process.cwd(),".modelence.env"),"utf-8");N=parse(e);}catch(e){if(e.code==="ENOENT")N={};else throw e}}async function me(){let e=B();if(e){console.log("Running post-build command..."),execSync(e);return}await fe(),await ge();}async function fe(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:O.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function ge(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{ssr:O.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:O.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 we(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[u()],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 P(){console.log("Building Modelence project...");try{let e=S();await R.rm(e,{recursive:!0,force:!0}),await we(),await me(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await R.access(M());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function J(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip"),s=e.host||F("");await P(),await ve(n);let{token:r}=await y(s),{bundleName:a}=await ye(e.app,e.env,n,r,s);await promises.unlink(n),await Ce(e.app,e.env,a,join(".modelence","build","app.mjs"),r,s);}async function ve(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=Ee("zip",{zlib:{level:9}});o.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),o.on("error",i=>{throw i});let n=new Promise((i,c)=>{t.on("close",i),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],r=["public","server",join(".modelence","build"),".next"];for(let i of s)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.file(m(i),{name:i});for(let i of r)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.directory(m(i),i);await o.finalize(),await n;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ye(e,t,o,n,s){let r=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:a,bundleName:i}=await r.json(),c=await promises.readFile(o),g=await fetch(a,{method:"PUT",body:new Uint8Array(c),headers:{"Content-Type":"application/zip"}});if(!g.ok)throw new Error(`Failed to upload bundle: ${g.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${i}`),{bundleName:i}}async function Ce(e,t,o,n,s,r){let a=await fetch(`${r}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:t,bundleName:o,entryPoint:n})});if(!a.ok)throw new Error(`Failed to trigger deployment: ${a.statusText}`);let{deploymentUrl:i}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${i}`);}function z(e={}){console.log("Starting Modelence dev server...");let t=u(),o=O.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 K(){console.log("Starting Modelence production server...");let e=u(),t=O.basename(e,O.extname(e)),o=S(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Me=fileURLToPath(import.meta.url),Oe=dirname(Me),Ie=JSON.parse(readFileSync(join(Oe,"../../package.json"),"utf-8")),f=new Command().name("modelence").description("Modelence CLI tool").version(Ie.version);f.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 j(e);});f.command("build").description("Build the application").action(async()=>{await E(),await P();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await E(),await J(e);});f.command("dev").description("Start development server").option("--takeover","Disconnect any instance currently holding the environment and connect this one").action(async e=>{await E(),z(e);});f.command("start").description("Start production server").action(async()=>{await E(),K();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
6
10
  //# sourceMappingURL=modelence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","confirmOverwrite","rl","createInterface","answer","escapeEnvValue","value","recordProjectAppId","appId","dirPath","join","projectPath","existing","fs","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";0dAaA,eAAsBA,EACpBC,CAAAA,CACA,CAAE,gBAAAC,CAAAA,CAAkB,KAAM,EAAmC,EAAC,CAClC,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGF,CAAI,CAAA,aAAA,CAAA,CAAiB,CACnD,OAAQ,MACV,CAAC,EAED,GAAI,CAACE,EAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,KAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,CAAA,CAAI,MAAMF,EAAS,IAAA,EAAK,CAChDG,EAAMJ,CAAAA,CAAkB,CAAA,EAAGG,CAAe,CAAA,iBAAA,CAAA,CAAsBA,CAAAA,CAEtE,eAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBC,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,OAAA,CAAQ,GAAA,CAAI,CAAA,MAAA,EAASF,CAAI,EAAE,CAAA,CAE3B,MAAMG,IAAKD,CAAG,CAAA,CAIP,CAAE,KAAA,CAFK,MAAME,EAAYP,CAAAA,CAAMG,CAAI,CAE3B,CACjB,CAEA,eAAeI,CAAAA,CAAYP,CAAAA,CAAcG,EAA+B,CAGtE,IAAMK,EAAe,IAAA,CAAK,GAAA,GAAQ,GAAA,CAClC,KAAO,KAAK,GAAA,EAAI,CAAIA,G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AA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,MAAA,CAAO,mBAAA,CAAqB,gBAAgB,EAC5C,MAAA,CAAO,MAAOnF,GAAY,CACzB,MAAM8B,GAAQ,CACd,MAAMe,CAAAA,CAAO7C,CAAO,EACtB,CAAC,CAAA,CAEHmF,EACG,OAAA,CAAQ,KAAK,EACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAMrD,GAAQ,CACdyC,CAAAA,GACF,CAAC,CAAA,CAEHY,CAAAA,CACG,OAAA,CAAQ,OAAO,CAAA,CACf,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CAAO,SAAY,CAClB,MAAMrD,CAAAA,EAAQ,CACd4C,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization. The returned token is short-lived and\n user-scoped; commands re-authorize on every run, so no credential is ever\n stored on disk.\n\n With `pickEnvironment`, the approval page also asks the user to choose an\n environment. The choice never travels back through the CLI — the server\n stamps it on the token itself, and /api/setup derives the target from\n there, so the authorization is only good for the environment the user\n approved.\n*/\nexport async function authenticateCli(\n host: string,\n { pickEnvironment = false }: { pickEnvironment?: boolean } = {}\n): Promise<{ token: string }> {\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n const url = pickEnvironment ? `${verificationUrl}&pick=environment` : verificationUrl;\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(url);\n\n const token = await waitForAuth(host, code);\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like cache/ are\n temporary), so the whole team gets it. It's a hint in the git-remote sense —\n connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, { pickEnvironment: true });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n if (fileExisted) {\n // Anything that read the old file holds stale credentials: the dev\n // server loads it at boot, and MCP connections send its token per\n // connection.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.'\n );\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
1
+ {"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","confirmOverwrite","rl","createInterface","answer","escapeEnvValue","value","readProjectAppId","content","fs","join","recordProjectAppId","dirPath","projectPath","existing","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACES","ensureClaudePluginEnabled","settingsPath","enabled","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";+dAkBA,eAAsBA,CAAAA,CACpBC,CAAAA,CACA,CAAE,gBAAAC,CAAAA,CAAkB,KAAA,CAAO,KAAA,CAAAC,CAAM,CAAA,CAAmD,EAAC,CACzD,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGH,CAAI,gBAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,CAAA,CAED,GAAI,CAACG,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,EAAI,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAChDG,CAAAA,CAAM,IAAI,IAAID,CAAe,CAAA,CAC/BJ,CAAAA,EACFK,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,OAAQ,aAAa,CAAA,CAExCJ,CAAAA,EACFI,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,QAASJ,CAAK,CAAA,CAGrC,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBI,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,OAAA,CAAQ,GAAA,CAAI,CAAA,MAAA,EAASF,CAAI,CAAA,CAAE,CAAA,CAE3B,GAAI,CACF,MAAMG,CAAAA,CAAKD,CAAAA,CAAI,QAAA,EAAU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modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization. The returned token is short-lived and\n user-scoped; commands re-authorize on every run, so no credential is ever\n stored on disk.\n\n With `pickEnvironment`, the approval page also asks the user to choose an\n environment. The choice never travels back through the CLI — the server\n stamps it on the token itself, and /api/setup derives the target from\n there, so the authorization is only good for the environment the user\n approved.\n\n `appId` is the hint from .modelence/project.json: the approval page uses it\n to preselect the app this project was last connected to. Purely a\n convenience for the picker — the user can still choose any app, and an\n unresolvable ID is simply ignored.\n*/\nexport async function authenticateCli(\n host: string,\n { pickEnvironment = false, appId }: { pickEnvironment?: boolean; appId?: string } = {}\n): Promise<{ token: string }> {\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n const url = new URL(verificationUrl);\n if (pickEnvironment) {\n url.searchParams.set('pick', 'environment');\n }\n if (appId) {\n url.searchParams.set('appId', appId);\n }\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n try {\n await open(url.toString());\n } catch {\n // Headless/SSH/container — no browser to open. The URL and code above\n // are already printed, so authentication can proceed manually.\n console.log('Could not open a browser automatically. Please open the URL above manually.');\n }\n\n const token = await waitForAuth(host, code);\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n try {\n const content = await fs.readFile(join(process.cwd(), MODELENCE_DIR, PROJECT_FILE), 'utf8');\n const { appId } = JSON.parse(content);\n return typeof appId === 'string' && appId ? appId : undefined;\n } catch {\n return undefined;\n }\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like build/, cache/ and\n tmp/ are temporary), so the whole team gets it. It's a hint in the git-remote\n sense — connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\n}\n\nconst CLAUDE_DIR = '.claude';\nconst CLAUDE_SETTINGS_FILE = join(CLAUDE_DIR, 'settings.json');\nconst CLAUDE_PLUGIN_ID = 'modelence@modelence';\n// Without the marketplace declared alongside enabledPlugins, Claude Code\n// can't resolve the plugin unless the user already ran\n// `claude plugin marketplace add` themselves.\nconst CLAUDE_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: 'modelence/modelence' } },\n};\n\n/*\n Makes the Modelence Claude Code plugin available in connected projects that\n didn't start from the template (which ships this file). Only ever creates\n the file: an existing settings.json is the user's own — a missing or\n explicitly disabled plugin entry there gets a hint, not an edit, so a\n deliberate opt-out is never flipped back on. The file is inert for people\n who don't use Claude Code, and like the project file, failing to write it\n doesn't fail the setup.\n*/\nasync function ensureClaudePluginEnabled(): Promise<void> {\n const settingsPath = join(process.cwd(), CLAUDE_SETTINGS_FILE);\n\n let content: string;\n try {\n content = await fs.readFile(settingsPath, 'utf8');\n } catch {\n // Missing — create it with just the plugin enabled.\n try {\n await fs.mkdir(join(process.cwd(), CLAUDE_DIR), { recursive: true });\n await fs.writeFile(\n settingsPath,\n JSON.stringify(\n {\n extraKnownMarketplaces: CLAUDE_MARKETPLACES,\n enabledPlugins: { [CLAUDE_PLUGIN_ID]: true },\n },\n null,\n 2\n ) + '\\n'\n );\n console.log(`Enabled the Modelence Claude Code plugin in ${CLAUDE_SETTINGS_FILE}`);\n } catch (error) {\n console.warn(`Failed to create ${CLAUDE_SETTINGS_FILE}:`, error);\n }\n return;\n }\n\n try {\n const settings = JSON.parse(content);\n const enabled = settings?.enabledPlugins?.[CLAUDE_PLUGIN_ID];\n if (enabled !== true) {\n console.warn(\n `Note: the Modelence plugin is ${enabled === false ? 'disabled' : 'not enabled'} in ` +\n `${CLAUDE_SETTINGS_FILE}. To get Modelence tools and docs in Claude Code, add ` +\n `\"${CLAUDE_PLUGIN_ID}\": true under \"enabledPlugins\", and declare the marketplace under ` +\n `\"extraKnownMarketplaces\": ${JSON.stringify(CLAUDE_MARKETPLACES)}.`\n );\n }\n } catch {\n console.warn(`Could not parse ${CLAUDE_SETTINGS_FILE} to check the Modelence plugin status.`);\n }\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n // Where this working copy runs; Studio sandboxes pre-set \"sandbox\".\n MODELENCE_RUNTIME: process.env.MODELENCE_RUNTIME || 'local',\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n await ensureClaudePluginEnabled();\n\n if (fileExisted) {\n // Anything that read the old file holds stale credentials: the dev\n // server loads it at boot, and MCP connections send its token per\n // connection.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.'\n );\n }\n\n if (newEnv.MODELENCE_RUNTIME === 'local') {\n console.log('\\nNext step — run the app on this machine:\\n');\n console.log(\" npm install (if you haven't already)\");\n console.log(' npm run dev (starts the app)\\n');\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(options: { takeover?: boolean } = {}) {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: {\n ...process.env,\n NODE_ENV: 'development',\n ...(options.takeover ? { MODELENCE_TAKEOVER: '1' } : {}),\n },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .option(\n '--takeover',\n 'Disconnect any instance currently holding the environment and connect this one'\n )\n .action(async (options) => {\n await loadEnv();\n dev(options);\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
@@ -0,0 +1,41 @@
1
+ import {t as t$1}from'./chunk-ILNPNRGJ.js';import {a,b,c,d,q,r,s,t,u,m,n,e,z as z$2,l,k as k$1,o,j,p,v as v$1,A,B,C,D,f as f$1,E,x as x$1,w as w$1,g as g$1,H,F as F$1,G as G$1}from'./chunk-KDOTVIEY.js';import {c as c$1,b as b$1,d as d$1,a as a$4}from'./chunk-VYR7VQMQ.js';import {a as a$2,f,e as e$1,g,c as c$2,i,m as m$1,l as l$1,d as d$2,k as k$2,n as n$1,j as j$1,o as o$1}from'./chunk-UW37F3GV.js';import {a as a$3,b as b$2}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import gr from'dotenv';import Wn from'fs/promises';import Ho from'os';import Q from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoServerError,MongoClient,MongoError,ObjectId}from'mongodb';export{ObjectId as m}from'mongodb';import {randomBytes,randomInt,randomUUID,createHash}from'crypto';import co from'bcrypt';import G,{z as z$1}from'zod';import Pe from'fs';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Tn from'@vitejs/plugin-react';import B$1,{Router}from'express';import Mi from'cookie-parser';import Ti from'http';var le=new a("_system",{queries:{setupStatus:async()=>({setupRequired:b()})},configSchema:{mongodbUri:{type:"secret",isPublic:false,default:""},mongodbPoolSize:{type:"number",isPublic:false,default:10},"env.type":{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""},multiInstance:{type:"boolean",isPublic:false,default:false}}});var F=null;async function Qt(){if(F)return F;let e=N();if(!e)throw new Error("MongoDB URI is not set");let t=le.getConfig("mongodbPoolSize");F=new MongoClient(e,{driverInfo:{name:"Modelence",version:t$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await F.connect(),await F.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),F}catch(o){throw console.error(o),F=null,o}}function N(){return le.getConfig("mongodbUri")||void 0}function ke(){return F}var de=null,_r="_modelenceSocketio",Xt=60;async function Lr({httpServer:e,channels:t}){let o=ke(),r=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let n=null;if(r&&o){n=o.db().collection(_r);try{await n.createIndex({createdAt:1},{expireAfterSeconds:Xt,background:!0});}catch(i){if(i instanceof Error&&"code"in i&&i.code===85)try{await n.dropIndex("createdAt_1"),await n.createIndex({createdAt:1},{expireAfterSeconds:Xt,background:!0});}catch(s){console.error("Failed to recreate index on MongoDB collection for Socket.IO:",s);}else console.error("Failed to create index on MongoDB collection for Socket.IO:",i);}}de=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["websocket"],perMessageDeflate:false}),de.on("error",i=>{console.error("Socket.IO error:",i);}),de.use(async(i,s)=>{let a=i.handshake.auth.token;try{i.data=await x$1(a),s();}catch(c){s(c instanceof Error?c:new Error(String(c)));}}),de.on("connection",i=>{i.on("disconnect",()=>{H(i);}),i.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(i.data))&&(i.join(s),c=true,i.emit("joinedChannel",s));break}c||i.emit("joinError",{channel:s,error:"Access denied"});}),i.on("leaveChannel",s=>{i.leave(s),console.log(`User ${i.id} left channel ${s}`),i.emit("leftChannel",s);}),i.on("subscribeLiveQuery",s=>F$1(i,s)),i.on("unsubscribeLiveQuery",s=>G$1(i,s));}),console.log("Socket.IO server initialized");}function Mr({category:e,id:t,data:o}){de?.to(`${e}:${t}`).emit(e,o);}var Zt={init:Lr,broadcast:Mr};async function Se(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let o=t[1];return !!await r.findOne({domain:o})}var eo={interval:a$1.days(1),async handler(){let e=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let o=(await e.text()).split(`
2
+ `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),r$1=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await r.insertMany(s.map(a=>({domain:a,addedAt:r$1})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var Ae=3,z=50,to=8,oo=128,ro=254,no=e=>z$1.string().trim().min(e.min??1,{message:`must be at least ${e.min??1} characters`}).max(e.max,{message:`must be at most ${e.max} characters`}),qe=e=>z$1.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),Tr=z$1.object({firstName:qe({max:50}),lastName:qe({max:50}),avatarUrl:qe({max:400}),handle:no({min:Ae,max:z})}).strict();function Re(e){let t=Tr.partial().safeParse(e);if(!t.success){let o=t.error.issues[0],r=o.path.join("."),n=r?`${r}: ${o.message}`:o.message;throw new Error(n)}return t.data}function xe(e){return z$1.string().min(to,{message:`Password must contain at least ${to} characters`}).max(oo,{message:`Password must be at most ${oo} characters`}).parse(e)}function O(e){return z$1.string().max(ro,{message:`Email must be at most ${ro} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function io(e){return no({min:Ae,max:z}).parse(e)}function Oe(e){return e instanceof MongoServerError&&e.code===11e3&&typeof e.keyPattern=="object"&&e.keyPattern!==null&&"emails.address"in e.keyPattern}function _e(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function ee(e){return {id:e._id,handle:e.handle,roles:e.roles||[],firstName:e.firstName??void 0,lastName:e.lastName??void 0,avatarUrl:e.avatarUrl??void 0}}async function so(e){let t=e.slice(0,z);try{if(!await q.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(n){throw new Error(`Database error while checking handle availability: ${n}`)}let o=51;for(let n=2;n<=o;n++){let i=`_${n}`,s=`${t.slice(0,z-i.length)}${i}`;try{if(!await q.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}let r=10;for(let n=0;n<r;n++){let i=`_${randomBytes(3).toString("hex")}`,s=`${t.slice(0,z-i.length)}${i}`;try{if(!await q.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}throw new Error(`Could not generate a unique handle for base "${e}" after exhausting all attempts.`)}async function L(e,t,{throwOnConflict:o=true}={}){if(e!=null&&String(e).trim()!==""){let n=io(String(e).trim());if(o){if(await q.findOne({handle:n},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return n}return so(n)}let r=t.split("@")[0].padEnd(Ae,"_").slice(0,z);return so(r)}var ze=Object.freeze({});function We(e){ze=Object.freeze(Object.assign({},ze,e));}function w(){return ze}var Je=Object.freeze({});function ao(e){Je=Object.freeze(Object.assign({},Je,e));}function y(){return Je}function Dr(){return w()?.provider?!!a$2("_system.user.auth.email.verification"):false}var $r=10,jr=co.hashSync(randomBytes(32).toString("hex"),$r);async function lo(e,{user:t,session:o,connectionInfo:r,res:n$1}){try{if(!o)throw new Error("Session is not initialized");if(t)throw new c$1("User is already authenticated","ALREADY_AUTHENTICATED");let i=r?.ip;i&&await k({bucket:"signin",type:"ip",value:i});let s=O(e.email),a=z$1.string().parse(e.password),c=await q.findOne({"emails.address":s,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l=c?.authMethods?.password?.hash,d=l||jr,u=await co.compare(a,d);if(!l||!u)throw Hr();if(!c.emails?.find(h=>h.address.toLowerCase()===s)?.verified&&Dr())throw new b$1("Your email address hasn't been verified yet. Please check your inbox for the verification email.","EMAIL_NOT_VERIFIED");return await j(o.authToken,c._id),n$1&&n(n$1,o.authToken),y().onAfterLogin?.({provider:"email",user:c,session:o,connectionInfo:r}),y().login?.onSuccess?.(c),{user:ee(c),session:{authToken:o.authToken}}}catch(i){throw i instanceof Error&&(y().onLoginError?.({provider:"email",error:i,session:o,connectionInfo:r}),y().login?.onError?.(i)),i}}async function uo(e,{session:t,res:o$1}){if(!t)throw new Error("Session is not initialized");await k$1(t.authToken),o$1&&o(o$1);}function Hr(){return new Error("Incorrect email/password combination")}async function mo(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await q.requireById(t.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{}),firstName:o.firstName??void 0,lastName:o.lastName??void 0,avatarUrl:o.avatarUrl??void 0}}async function po(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await q.requireById(t.id),r=Re(e);if(await y().validateProfileUpdate?.(r),"handle"in r&&r.handle!==void 0&&await q.findOne({handle:r.handle,_id:{$ne:o._id}},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");if(Object.keys(r).length>0){let n={},i={};for(let[a,c]of Object.entries(r))c===void 0?i[a]="":n[a]=c;let s={};Object.keys(n).length>0&&(s.$set=n),Object.keys(i).length>0&&(s.$unset=i);try{await q.updateOne({_id:o._id},s);let a=Object.fromEntries(Object.keys(i).map(c=>[c,void 0]));o={...o,...n,...a};}catch(a){throw a instanceof Error&&"code"in a&&a.code===11e3?new Error("Handle already taken."):a}}return {user:ee(o)}}var Ke=["google","github"];async function fo({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!Ke.includes(e))throw new Error(`Invalid provider. Supported providers are: ${Ke.join(", ")}.`);let o=await q.requireById(t.id),r=o.authMethods??{};if(!r[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(r).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s=Object.keys(r).filter(l=>l!==e&&r[l]),a=s.length>0?{$or:s.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await q.updateOne({_id:o._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}var me=new c("_modelenceRateLimits",{schema:{bucket:d.string(),type:d.enum(["ip","user","email"]),value:d.string(),windowMs:d.number(),windowStart:d.date(),windowCount:d.number(),prevWindowCount:d.number(),expiresAt:d.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Ye=[];function go(e){if(Ye.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Ye=e;}async function k(e){let{bucket:t,type:o,value:r,message:n}=e,i=Ye.filter(a=>a.bucket===t&&a.type===o),s=n?()=>new d$1(n):void 0;for(let a of i)await Vr(a,r,s);}async function Vr(e,t,o){let r=()=>o?o():new d$1(`Rate limit exceeded for ${e.bucket}`),n=await me.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),i=Date.now(),s=Math.floor(i/e.window)*e.window,{count:a,modifier:c}=n?Fr(n,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+e.window+e.window)}}};if(a>=e.limit)throw r();await me.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function Fr(e,t,o){let r=t-e.windowMs;if(e.windowStart.getTime()===t){let n=e.windowCount,i=e.prevWindowCount,s=1-(o-t)/e.windowMs;return {count:Math.round(n+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===r){let n=1-(o-t)/e.windowMs;return {count:Math.round(e.windowCount*n),modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:e.windowCount,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}function ho({name:e,email:t,verificationUrl:o}){return `
3
+ <p>Hi${e?` ${e}`:""},</p>
4
+ <p>Please verify your email address ${t} by clicking the link below:</p>
5
+ <p><a href="${o}">${o}</a></p>
6
+ <p>If you did not request this, please ignore this email.</p>
7
+ `}var qr={locale:"en",strength:2};async function zr(e){let t=await s.findOne({token:e,expiresAt:{$gt:new Date}});if(!t)throw new Error("Invalid or expired verification token");let o=await q.findOne({_id:t.userId,status:{$nin:["deleted","disabled"]}});if(!o)throw new Error("User not found");let r=t.email;if(!r)throw new Error("Email not found in token");let n=await q.findOneAndUpdate({_id:t.userId,status:{$nin:["deleted","disabled"]},emails:{$elemMatch:{address:r,verified:{$ne:true}}}},{$set:{"emails.$.verified":true}},{collation:qr,returnDocument:"after"});if(await s.deleteOne({_id:t._id}),!n){let i=o.emails?.find(s=>s.address.toLowerCase()===r);throw i?i.verified?new Error("Email is already verified"):new Error("Unable to verify email address"):new Error("Email address not found for this user")}return {userDoc:n,email:r}}async function wo(e){let t=a$2("_system.site.url"),o=w().verification?.redirectUrl||w().emailVerifiedRedirectUrl||t||"/";try{let r=z$1.string().parse(e.query.token),{userDoc:n$1}=await zr(r);y().onAfterEmailVerification?.({provider:"email",user:n$1,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}});let{authToken:s}=await m(n$1._id);return n(e.res,s),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=verified`}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return r instanceof Error&&(y().onEmailVerificationError?.({provider:"email",error:r,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}}),console.error("Error verifying email:",r)),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent(n)}`}}}async function Xe({userId:e,email:t,baseUrl:o}){let r=a$2("_system.site.url")||o;if(w().provider){let n=w().provider,i=randomBytes(32).toString("hex"),s$1=new Date(Date.now()+a$1.hours(24));await s.insertOne({userId:e,email:t,token:i,createdAt:new Date,expiresAt:s$1});let a=`${r}/api/_internal/auth/verify-email?token=${i}`,l=(w()?.verification?.template||ho)({name:"",email:t,verificationUrl:a}),d=z$2(l);await n?.sendEmail({to:t,from:w()?.from||"noreply@modelence.com",subject:w()?.verification?.subject||"Verify your email address",text:d,html:l});}}var Qe={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function yo(e,{connectionInfo:t}){let o=O(e.email),r=await q.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r)return Qe;let n=r.emails?.find(i=>i.address.toLowerCase()===o);if(!n||n.verified)return Qe;if(!w().provider)throw new Error("Email provider is not configured");return await k({bucket:"verification",type:"user",value:r._id.toString(),message:"Please wait at least 60 seconds before requesting another verification email"}),await Xe({userId:r._id,email:o,baseUrl:t?.baseUrl}),Qe}async function Eo(e,{user:t,session:o,connectionInfo:r}){let n=y();try{if(t)throw new c$1("User is already authenticated","ALREADY_AUTHENTICATED");let i=e,{firstName:s,lastName:a,avatarUrl:c,handle:l}=i,d=O(i.email),u=xe(i.password),f=r?.ip;if(f&&await k({bucket:"signupAttempt",type:"ip",value:f}),!n.allowDisposableEmails&&await Se(d))throw new Error("Please use a permanent email address");let h=await q.findOne({"emails.address":d},{collation:{locale:"en",strength:2}});if(h){let _=h.emails?.find(D=>D.address.toLowerCase()===d);throw h.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${_?.address}`)}await n.onBeforeSignup?.({email:d,firstName:s,lastName:a,handle:l,provider:"email",connectionInfo:r}),f&&await k({bucket:"signup",type:"ip",value:f});let E=Re({firstName:s,lastName:a,avatarUrl:c,handle:l});await n.validateSignup?.({email:d,password:u,...E}),await n.validatePassword?.({password:u,email:d,context:"signup"});let C;if(E.handle)C=await L(E.handle,d);else if(n.generateHandle){let _=await n.generateHandle({email:d,firstName:E.firstName,lastName:E.lastName});C=await L(_,d,{throwOnConflict:!1});}else C=await L(void 0,d);let T=await co.hash(u,10),P;try{P=await q.insertOne({handle:C,status:"active",emails:[{address:d,verified:!1}],createdAt:new Date,authMethods:{password:{hash:T}},...E.firstName!==void 0&&{firstName:E.firstName},...E.lastName!==void 0&&{lastName:E.lastName},...E.avatarUrl!==void 0&&{avatarUrl:E.avatarUrl}});}catch(_){throw Oe(_)?new Error(`User with email already exists: ${d}`):_}let S=await q.findOne({_id:P.insertedId},{readPreference:"primary"});if(!S)throw new Error("User not found");return await Xe({userId:P?.insertedId,email:d,baseUrl:r?.baseUrl}),n.onAfterSignup?.({provider:"email",user:S,session:o,connectionInfo:r}),n.signup?.onSuccess?.(S),P.insertedId}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:"email",error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}var Ze="resetPasswordToken",Yr="/api/_internal/",ko={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Yr};async function So(e$1){return t.findOne({token:e(e$1)})}async function bo(e){return t.findOneAndDelete({_id:e})}function Qr({email:e,resetUrl:t}){return `
8
+ <p>Hi,</p>
9
+ <p>We received a request to reset your password for ${e}.</p>
10
+ <p>Click the link below to reset your password:</p>
11
+ <p><a href="${t}">${t}</a></p>
12
+ <p>This link will expire in 1 hour.</p>
13
+ <p>If you did not request this password reset, please ignore this email.</p>
14
+ `}var vo={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Ao(e$1,{connectionInfo:t$1}){let o=O(e$1.email),r=t$1?.ip;r&&await k({bucket:"passwordReset",type:"ip",value:r}),await k({bucket:"passwordReset",type:"email",value:o});let n=await q.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n)return vo;let i=w().provider;if(!i)throw new Error("Email provider is not configured");let s=randomBytes(32).toString("hex"),a=Date.now(),c=new Date(a),l=new Date(a+a$1.hours(1));await t.insertOne({userId:n._id,email:o,token:e(s),createdAt:c,expiresAt:l});let d=a$2("_system.site.url")||t$1?.baseUrl;if(!d)throw new Error("Unable to build password reset link: set _system.site.url (MODELENCE_SITE_URL)");let u=`${d}/api/_internal/auth/reset-password?token=${s}`,h=(w()?.passwordReset?.template||Qr)({email:o,resetUrl:u,name:""}),E=z$2(h);return await i.sendEmail({to:o,from:w()?.from||"noreply@modelence.com",subject:w()?.passwordReset?.subject||"Reset your password",text:E,html:h}),vo}async function Ro(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=_e(t,w().passwordReset?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await So(r);if(!n||n.expiresAt<new Date)throw new Error("This password reset link is invalid or has expired.");return e.res.cookie(Ze,r,{...ko,maxAge:a$1.hours(1)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling password reset landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This password reset link is invalid or has expired.")}`}}}async function xo(e,t){let o=t.req?.cookies?.[Ze];!o&&e.token&&console.warn("[modelence] resetPassword received a token via request args instead of the httpOnly cookie. This path is deprecated and will be removed; ensure password reset emails link to /api/_internal/auth/reset-password so the token is exchanged server-side.");let r=z$1.string().parse(o??e.token),n=xe(e.password),i=()=>{t.res?.clearCookie(Ze,ko);},s=await So(r);if(!s)throw i(),new Error("Invalid or expired reset token");if(s.expiresAt<new Date)throw await bo(s._id),i(),new Error("Reset token has expired");let a=await q.findOne({_id:s.userId});if(!a)throw new Error("User not found");await y().validatePassword?.({password:n,email:s.email??a.emails?.[0]?.address?.toLowerCase()??"",context:"reset"});let c=await co.hash(n,10);if(!await bo(s._id))throw i(),new Error("Invalid or expired reset token");await q.updateOne({_id:a._id},{$set:{"authMethods.password.hash":c}}),s.email&&await q.updateOne({_id:a._id,"emails.address":s.email},{$set:{"emails.$.verified":true}},{collation:{locale:"en",strength:2}}),await l(a._id);let d=Array.from(new Set((a.emails??[]).map(u=>u.address?.toLowerCase()).filter(u=>!!u)));return d.length>0&&await u.deleteMany({email:{$in:d}}),i(),{success:true,message:"Password has been reset successfully"}}function Oo({name:e,email:t,magicLinkUrl:o,code:r}){return `
15
+ <p>Hi${e?` ${e}`:""},</p>
16
+ <p>Click the link below to sign in as ${t}:</p>
17
+ <p><a href="${o}">${o}</a></p>
18
+ <p>Or enter this one-time code in the app:</p>
19
+ <p><strong style="font-size: 24px; letter-spacing: 4px;">${r}</strong></p>
20
+ <p>The link and code can only be used once and will expire in 15 minutes.</p>
21
+ <p>If you did not request this, please ignore this email.</p>
22
+ `}var ot="magicLinkToken",en="/api/_internal/",Lo={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:en},Mo=15,_o=6,tn=5;function Le(e,t){try{Promise.resolve(t?.()).catch(o=>{console.error(`Error in ${e} hook:`,o);});}catch(o){console.error(`Error in ${e} hook:`,o);}}function it(){return !!y().magicLink?.enabled}function To(){return !!y().magicLink?.allowSignup}async function Po(e$1){return u.findOne({token:e(e$1)})}async function st(e){return u.findOneAndDelete({_id:e})}async function et(e){try{await u.insertOne(e);}catch(t){console.error("Failed to restore a magic link token after a failed signup:",t);}}var tt={success:true,message:"If this email can be used to sign in, a link has been sent"};async function Io(e$1,{connectionInfo:t}){if(!it())throw new Error("Magic link authentication is not enabled");let o=O(e$1.email),r=t?.ip;r&&await k({bucket:"magicLink",type:"ip",value:r}),await k({bucket:"magicLink",type:"email",value:o});let n=w().provider;if(!n)throw new Error("Email provider is not configured");let i=w().from;if(!i)throw new Error("Email `from` address is not configured");let s=a$2("_system.site.url");if(!s)throw new Error("Unable to build magic link: set _system.site.url (MODELENCE_SITE_URL)");if(!y().allowDisposableEmails&&await Se(o))throw new Error("Please use a permanent email address");let a=await q.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(a&&(a.status==="disabled"||a.status==="deleted")||!a&&!To())return tt;let c=randomBytes(32).toString("hex"),l=randomInt(0,10**_o).toString().padStart(_o,"0"),d=Date.now(),u$1=new Date(d),f=new Date(d+a$1.minutes(Mo));await u.insertOne({email:o,token:e(c),code:e(l),attempts:0,createdAt:u$1,expiresAt:f});let h=`${s}/api/_internal/auth/magic-link?token=${c}`,C=(w()?.magicLink?.template||Oo)({email:o,magicLinkUrl:h,code:l,name:""}),T=z$2(C);return await n.sendEmail({to:o,from:i,subject:w()?.magicLink?.subject||"Your sign-in link",text:T,html:C}),tt}async function Uo(e){let t=a$2("_system.site.url")||"",o=_e(t,w().magicLink?.redirectUrl)||"/";try{let r=z$1.string().parse(e.query.token),n=await Po(r);if(!n||n.expiresAt<new Date)throw new Error("This sign-in link is invalid or has expired.");return e.res.cookie(ot,r,{...Lo,maxAge:a$1.minutes(Mo)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling magic link landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This sign-in link is invalid or has expired.")}`}}}var rt={locale:"en",strength:2};async function No(e){let{tokenDoc:t,session:o,connectionInfo:r,res:n$1,clearCookie:i}=e,s=t.email,a=y(),c=To(),l=false;try{let d=await st(t._id);if(!d)throw i(),new Error("Invalid or expired code or magic link");let u;if(c)try{if(!await q.findOne({"emails.address":s},{collation:rt})){l=!0,await a.onBeforeSignup?.({email:s,provider:"magicLink",connectionInfo:r});let _=r?.ip;_&&await k({bucket:"signup",type:"ip",value:_}),u=a.generateHandle?await L(await a.generateHandle({email:s}),s,{throwOnConflict:!1}):await L(void 0,s);}}catch(S){throw await et(d),S}let f;try{f=await on(s,u,c);}catch(S){throw await et(d),S}let{userDoc:h,isNew:E}=f;if(!h)throw await et(d),i(),c&&!l?new Error("User account is not active"):(l=!0,new Error("Sign up with magic link is not enabled"));if(l=E,h.status==="disabled"||h.status==="deleted")throw i(),new Error("User account is not active");let C=h,T=h.emails?.find(S=>S.address.toLowerCase()===s),P=!E&&!T?.verified;return P&&(C=await q.findOneAndUpdate({_id:h._id,"emails.address":s},{$set:{"emails.$.verified":!0}},{collation:rt,returnDocument:"after"})??h),await j(o.authToken,C._id),n$1&&n(n$1,o.authToken),E?Le("onAfterSignup",()=>a.onAfterSignup?.({provider:"magicLink",user:C,session:o,connectionInfo:r})):(P&&Le("onAfterEmailVerification",()=>a.onAfterEmailVerification?.({provider:"magicLink",user:C,session:o,connectionInfo:r})),Le("onAfterLogin",()=>a.onAfterLogin?.({provider:"magicLink",user:C,session:o,connectionInfo:r}))),i(),{user:ee(C),session:{authToken:o.authToken}}}catch(d){if(d instanceof Error){let u=l?"onSignupError":"onLoginError",f=l?a.onSignupError:a.onLoginError;Le(u,()=>f?.({provider:"magicLink",error:d,session:o,connectionInfo:r}));}throw d}}async function on(e,t,o){let r=o&&t!==void 0,n=()=>q.findOneAndUpsert({emails:{$elemMatch:{address:e}}},{$setOnInsert:{handle:t,status:"active",emails:[{address:e,verified:true}],createdAt:new Date,authMethods:{}}},{upsert:r,collation:rt});try{let{doc:i,isNew:s}=await n();return {userDoc:i,isNew:s}}catch(i){if(!Oe(i))throw i;let{doc:s}=await n();return {userDoc:s,isNew:false}}}async function Do(e,t){let{session:o,connectionInfo:r,res:n,req:i}=t;if(!o)throw new Error("Session is not initialized");if(!it())throw new Error("Magic link authentication is not enabled");let s=z$1.string().parse(i?.cookies?.[ot]),a=()=>{n?.clearCookie(ot,Lo);},c=await Po(s);if(!c)throw a(),new Error("Invalid or expired code or magic link");if(c.expiresAt<new Date)throw await st(c._id),a(),new Error("Code or magic link has expired");return No({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:a})}async function $o(e$1,t){let{session:o,connectionInfo:r,res:n}=t;if(!o)throw new Error("Session is not initialized");if(!it())throw new Error("Magic link authentication is not enabled");let i=O(e$1.email),s=z$1.string().parse(e$1.code).replace(/[\s-]/g,""),a=r?.ip;a&&await k({bucket:"oneTimeCode",type:"ip",value:a}),await k({bucket:"oneTimeCode",type:"email",value:i});let c=await u.findOne({email:i,code:e(s),attempts:{$lt:tn}});if(!c)throw await u.updateMany({email:i},{$inc:{attempts:1}}),new Error("Invalid or expired code or magic link");if(c.expiresAt<new Date)throw await st(c._id),new Error("Code or magic link has expired");return No({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:()=>{}})}function jo(e){return `${e.bucket}
23
+ ${e.type}
24
+ ${e.window}`}function rn(){return [{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.seconds(60),limit:1},{bucket:"verification",type:"user",window:a$1.days(1),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.days(1),limit:100},{bucket:"passwordReset",type:"email",window:a$1.hours(1),limit:5},{bucket:"passwordReset",type:"email",window:a$1.days(1),limit:10},{bucket:"magicLink",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"magicLink",type:"ip",window:a$1.days(1),limit:100},{bucket:"magicLink",type:"email",window:a$1.hours(1),limit:5},{bucket:"magicLink",type:"email",window:a$1.days(1),limit:10},{bucket:"oneTimeCode",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"oneTimeCode",type:"ip",window:a$1.days(1),limit:100},{bucket:"oneTimeCode",type:"email",window:a$1.hours(1),limit:10},{bucket:"oneTimeCode",type:"email",window:a$1.days(1),limit:20}]}function nn(e){let t=[],o=["signup","signupAttempt","signin","verification","passwordReset","magicLink","oneTimeCode"];for(let r of o){let n=e[r];if(n!==void 0)for(let i of n)t.push({bucket:r,...i});}return t}function at(e={}){let t=rn(),o=nn(e),r=new Map;for(let s of o)r.set(jo(s),s);let n=[],i=new Set;for(let s of t){let a=jo(s),c=r.get(a);c!==void 0?(n.push(c),i.add(a)):n.push(s);}for(let[s,a]of r)i.has(s)||n.push(a);return n}var ct=new a("_system.user",{stores:[q,r,s,t,u],queries:{getOwnProfile:mo},mutations:{signupWithPassword:Eo,loginWithPassword:lo,logout:uo,resendEmailVerification:yo,sendResetPasswordToken:Ao,resetPassword:xo,sendMagicLink:Io,loginWithMagicLink:Do,loginWithOneTimeCode:$o,updateProfile:po,unlinkOAuthProvider:fo},cronJobs:{updateDisposableEmailList:eo},rateLimits:at(),configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:true},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:wo}},{path:"/api/_internal/auth/reset-password",handlers:{get:Ro}},{path:"/api/_internal/auth/magic-link",handlers:{get:Uo}}]});var sn={withoutRemoteServer:{MONGODB_URI:"_system.mongodbUri",MONGODB_POOL_SIZE:"_system.mongodbPoolSize",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV_TYPE:"_system.env.type",MODELENCE_MULTI_INSTANCE:"_system.multiInstance",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"},withRemoteServer:{MODELENCE_SITE_URL:"_system.site.url"}};function an(e,t){if(t==="number"){let o=Number(e);if(isNaN(o))throw new Error(`Invalid number value for config: ${e}`);return o}if(t==="boolean"){if(e.toLowerCase()==="true")return true;if(e.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${e}`)}return e}function cn(e,t){let o=[];for(let[r,n]of Object.entries(e)){let i=process.env[r],s=t[n];if(i){let a=s?.type??"string";o.push({key:n,type:a,value:an(i,a)});}}return o}function pe(){let e=process.env.MODELENCE_PORT||process.env.PORT||3e3;return process.env.MODELENCE_SITE_URL||`http://localhost:${e}`}function Me(e,t="withoutRemoteServer"){let o=sn[t],r=cn(o,e);return t==="withRemoteServer"&&process.env.MODELENCE_RUNTIME==="local"&&!r.some(({key:n})=>n==="_system.site.url")&&r.push({key:"_system.site.url",type:"string",value:pe()}),r}var dt;function un(){try{let e=Q.join(Ho.homedir(),".modelence"),t=Q.join(e,"machine-id");try{let r=Pe.readFileSync(t,"utf8").trim();if(r)return r}catch{}let o=randomUUID();return Pe.mkdirSync(e,{recursive:!0}),Pe.writeFileSync(t,o+`
25
+ `),o}catch{return Ho.hostname()}}function mn(){return dt||(dt=createHash("sha256").update(`${un()}
26
+ ${process.cwd()}
27
+ ${process.env.MODELENCE_ENVIRONMENT_ID||""}`).digest("hex").slice(0,32)),dt}function fe(){let e=process.env.MODELENCE_RUNTIME;return e==="local"||e==="sandbox"}function Te(){return process.env.MODELENCE_RUNTIME==="local"}function ut(){return fe()?mn():process.env.MODELENCE_CONTAINER_ID}async function Fo({configSchema:e,cronJobsMetadata:t,stores:o,roles:r}){let n=ut();if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");let i=Te()&&process.env.MODELENCE_TAKEOVER==="1";try{let s=(o??[]).map(c=>({name:c.getName(),schema:c.getSerializedSchema(),collections:[c.getName()],version:2,indexes:c.getIndexes(),searchIndexes:c.getSearchIndexes(),indexCreationMode:c.getIndexCreationMode()})),a=await M("/api/connect","POST",{hostname:Ho.hostname(),runtime:process.env.MODELENCE_RUNTIME,containerId:n,...Te()?{localSiteUrl:pe()}:{},...i?{force:!0}:{},dataModels:s,configSchema:e,cronJobsMetadata:t,roles:r});if(a.status==="error")throw Object.assign(new Error(`Unable to connect to Modelence Cloud: ${a.error}`),{responseBody:a});return console.log("Successfully connected to Modelence Cloud"),a}catch(s){let a=s;if(Te()&&a?.status===409&&!i){let c=a.responseBody?.error??a.message;console.error(`${c}
28
+ Re-run with the --takeover flag (e.g. npm run dev -- --takeover) to disconnect it and connect this instance instead.`),process.exit(1);}throw fe()&&(a?.status??a?.responseBody)!==void 0&&(console.error(a.message),process.exit(1)),console.error("Unable to connect to Modelence Cloud:",s),s}}async function Go(){return M("/api/configs","GET")}async function Bo(){return await M("/api/sync","POST",{containerId:ut()})}async function M(e,t,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${e}`,{method:t,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text(),a,c=s;try{a=JSON.parse(s);let d=a.error;if(typeof d=="string")c=d;else if(d&&typeof d=="object"){let u=d.message;typeof u=="string"&&(c=u);}}catch{}let l=new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${c}`);throw a!==void 0&&(l.responseBody=a),l.status=i.status,l}if(!(i.status===204||i.headers?.get("content-length")==="0"))return await i.json()}var mt=false,fn=a$1.seconds(10);function qo(){setInterval(async()=>{if(!mt){mt=true;try{let e=await Bo();e?.status==="detached"&&fe()&&(console.error(`Detached from Modelence Cloud: ${e.message??"this environment is now connected from another instance."}`),process.exit(1));}catch(e){console.error("Error syncing status",e);}try{await gn();}catch(e){console.error("Error syncing config",e);}mt=false;}},fn);}function pt(e){c$2(e),c$2(Me(d$2(),"withRemoteServer"));}async function gn(){let{configs:e}=await Go();pt(e);}var W=new c("_modelenceLocks",{schema:{_id:d.string(),instanceId:d.string(),acquiredAt:d.date(),resource:d.string()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}],indexCreationMode:"blocking"});var J={},zo=a$1.seconds(10),Yo=randomBytes(32).toString("base64url"),yn=a$1.seconds(30),te=new Map,ft=e=>e instanceof MongoError&&e.code===11e3,Wo=(e,t)=>typeof e.keyPattern=="object"&&e.keyPattern!==null&&Object.prototype.hasOwnProperty.call(e.keyPattern,t),En=async({error:e,resource:t})=>{if(Wo(e,"resource"))return true;if(Wo(e,"_id"))return false;let o=await W.findOne({resource:t});return !!o&&o._id!==t},Jo=async({resource:e,staleThresholdDate:t,instanceId:o})=>{let r=await W.upsertOne({_id:e,$or:[{instanceId:o},{acquiredAt:{$lt:t}}]},{$set:{resource:e,instanceId:o,acquiredAt:new Date},$setOnInsert:{_id:e}});return r.upsertedCount>0||r.modifiedCount>0},Qo=async({resource:e,instanceId:t,staleThresholdDate:o})=>{let r=o?{resource:e,_id:{$ne:e},$or:[{instanceId:t},{acquiredAt:{$lt:o}}]}:{resource:e,instanceId:t};return (await W.deleteOne(r)).deletedCount>0},bn=e=>{let t=e,o=te.get(t);o&&(o.stopRequested=true,o.timer&&(clearTimeout(o.timer),o.timer=null),te.delete(t));},Ko=({resource:e,lockDuration:t,instanceId:o})=>{let r=Math.floor(t/3),n=e,i=te.get(n);if(i&&!i.stopRequested&&i.heartbeatInterval===r&&i.lockDuration===t)return;i&&(i.stopRequested=true,i.timer&&(clearTimeout(i.timer),i.timer=null),te.delete(n));let s={timer:null,stopRequested:false,lockDuration:t,heartbeatInterval:r},a=()=>{s.timer=setTimeout(()=>{K(e,{lockDuration:t,bypassCache:true,instanceId:o}).then(c=>{c||(s.stopRequested=true,k$2(`Lost lock while refreshing heartbeat: ${e}`,{source:"lock",resource:e,instanceId:o}));}).finally(()=>{if(s.stopRequested){te.delete(n);return}a();});},r);};te.set(n,s),a();};async function K(e,{lockDuration:t=yn,successfulLockCacheDuration:o=zo,failedLockCacheDuration:r=zo,heartbeat:n,bypassCache:i,instanceId:s=Yo}={}){let a=Date.now();if(!i&&J[e]&&a<J[e].expiresAt)return J[e].value&&n&&Ko({resource:e,lockDuration:t,instanceId:s}),J[e].value;let c=new Date(a-t);k$2(`Attempting to acquire lock: ${e}`,{source:"lock",resource:e,instanceId:s});try{let l=await vn({resource:e,staleThresholdDate:c,instanceId:s});return J[e]={value:l,expiresAt:a+(l?o:r)},l?(n&&Ko({resource:e,lockDuration:t,instanceId:s}),k$2(`Lock acquired: ${e}`,{source:"lock",resource:e,instanceId:s})):k$2(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),l}catch{return J[e]={value:false,expiresAt:a+r},k$2(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),false}}var vn=async({resource:e,staleThresholdDate:t,instanceId:o})=>{try{return await Jo({resource:e,staleThresholdDate:t,instanceId:o})}catch(r){if(ft(r)&&await En({error:r,resource:e})){if(!await Qo({resource:e,staleThresholdDate:t,instanceId:o}))return false;try{return await Jo({resource:e,staleThresholdDate:t,instanceId:o})}catch(i){if(ft(i))return false;throw i}}if(ft(r))return false;throw r}};async function ge(e,{instanceId:t=Yo}={}){bn(e);try{let o=await W.deleteOne({_id:e,instanceId:t});return o.deletedCount===0?await Qo({resource:e,instanceId:t}):o.deletedCount>0}catch{return false}finally{delete J[e];}}var Y={},gt=null,ht=new c("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Zo(e,{description:t="",interval:o,timeout:r=Math.min(Math.max(o,a$1.minutes(1)),a$1.days(1)),handler:n}){if(Y[e])throw new Error(`Duplicate cron job declaration: '${e}' already exists`);if(gt)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${e}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${e}]`);if(r>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${e}]`);Y[e]={alias:e,params:{description:t,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function er(){if(gt)throw new Error("Cron jobs already started");let e=Object.keys(Y);if(e.length>0){if(!N()){console.log("MongoDB URI is not configured. Skipping cron jobs.");return}let t={alias:{$in:e}},o=await ht.fetch(t),r=Date.now();o.forEach(n=>{let i=Y[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values(Y).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),gt=setInterval(Cn,a$1.seconds(1));}}async function Cn(){let e=Date.now();await K("cron",{successfulLockCacheDuration:a$1.seconds(10),failedLockCacheDuration:a$1.seconds(30)})&&Object.values(Y).forEach(async o=>{let{params:r,state:n}=o;if(n.isRunning){n.startTs&&n.startTs+r.timeout<e&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=e&&await kn(o);});}async function kn(e){let{alias:t,params:o,handler:r,state:n}=e;n.isRunning=true,n.startTs=Date.now(),await ht.upsertOne({alias:t},{$set:{lastStartDate:new Date(n.startTs)},$setOnInsert:{alias:t}});let i=n$1("cron",`cron:${t}`);try{await r(),Xo(n,o),i.end("success");}catch(s){Xo(n,o);let a=s instanceof Error?s:new Error(String(s));o$1(a),i.end("error"),console.error(`Error in cron job '${t}':`,s);}}function Xo(e,t){e.scheduledRunTs=e.startTs?e.startTs+t.interval:Date.now(),e.startTs=void 0,e.isRunning=false;}function tr(){return Object.values(Y).map(({alias:e,params:t})=>({alias:e,description:t.description,interval:t.interval,timeout:t.timeout}))}var or=new a("_system.cron",{stores:[ht]});function rr(e){let t=[...new Set(e)],o=new Map;for(let i of t){let s=i.getChainRoot();o.set(s,s.getChainTail());}let r=[...new Set(o.values())],n=new Map;for(let[i,s]of o){let a=s.getName(),c=n.get(a);if(c!==void 0&&c!==i)throw new Error(`Store collision: multiple unrelated stores use collection name '${a}'. Use .extend() to create a single extension chain instead of independent stores.`);n.set(a,i);}return {storesToInit:t,effectiveStores:r}}var wt=new a("_system.lock",{stores:[W]});var he=new c("_modelenceMigrations",{schema:{version:d.number(),status:d.enum(["completed","failed"]),description:d.string().optional(),output:d.string().optional(),appliedAt:d.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function yt(e,{lockMode:t="acquire"}={}){if(e.length!==0){if(t==="acquire"&&!await K("migrations")){l$1("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}try{let o=e.map(({version:s})=>s),r=await he.fetch({version:{$in:o}}),n=new Set(r.map(({version:s})=>s)),i=e.filter(({version:s})=>!n.has(s));if(i.length===0)return;l$1(`Running migrations (${i.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i){l$1(`Running migration v${s}: ${a}`,{source:"migrations"});try{let d=(await c()||"").toString().trim(),u=15*1024*1024,f=d.length>u?d.slice(0,u)+`
29
+ [Output truncated - exceeded size limit]`:d;await he.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:f,appliedAt:new Date}}),l$1(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await he.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),l$1(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}}finally{t==="acquire"&&await ge("migrations");}}}function nr(e){setTimeout(()=>{yt(e).catch(t=>{console.error("Error running migrations:",t);});},0);}var ir=new a("_system.migration",{stores:[he]});var sr=new a("_system.rateLimit",{stores:[me]});async function Sn({filePath:e,contentType:t,visibility:o}){return await M("/api/files/upload","POST",{filePath:e,contentType:t,visibility:o})}async function An(e){await M("/api/files/delete","POST",{filePath:e});}async function Rn(e){return await M("/api/files/download","POST",{filePath:e})}async function xn(e){return await M("/api/files/url","POST",{filePath:e})}var ar=new a("_system.files",{});function Et(e){return e.replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}var we="./.modelence/build/client".replace(/\\/g,"/"),lr="./.modelence/build/ssr".replace(/\\/g,"/"),dr="/index.tsx",Pn=/(<div\b[^>]*\bid\s*=\s*["']root["'][^>]*>)\s*<\/div>/i,In="</head>",bt=class{constructor(){this.ssrEnabled=false;this.ssrTransportInstalled=false;this.prodEntryLoaded=false;}enableSsr(){this.ssrEnabled=true;}async init({httpServer:t}){if(this.config=await Vn(this.isDev()?t:void 0,{ssr:this.ssrEnabled}),this.isDev())console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config);else if(this.ssrEnabled){let o=Q.resolve(process.cwd(),lr,"index.mjs");if(!Pe.existsSync(o))throw new Error(`Modelence: SSR is enabled (startApp({ ssr: true })) but the SSR bundle is missing at ${o}.
30
+
31
+ This usually means \`postBuildCommand\` is set in modelence.config.ts, which replaces the default Vite client build (and the SSR build along with it). Either:
32
+ \u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
33
+ \u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:o}=await import('./transport-LWVQ4TUY.js');o(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,o=[B$1.static(we,t)];return this.config?.publicDir&&o.push(B$1.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&Un(t)){if(t.method==="HEAD"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200).end();return}try{await this.handleSsr(t,o);}catch(r){if(this.isDev()&&this.viteServer&&r instanceof Error&&this.viteServer.ssrFixStacktrace(r),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:r}),o.headersSent){o.end();return}this.serveStaticShell(o);}return}if(this.ssrEnabled){o.status(404).end();return}this.serveStaticShell(o);}async handleSsr(t,o){let r=await this.getTemplate(t.originalUrl),n=await this.captureSsrSnapshot();if(!n)throw new Error("Modelence SSR is enabled but no SSR snapshot was captured. Make sure 'src/client/index.tsx' calls renderApp(...) from 'modelence/client'.");let[{renderSsrTreeStream:i},{getCallContext:s},a]=await Promise.all([import('./render-FRLQDLXI.js'),import('./server-6OSZ242A.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,o),l=this.collectCssAssets(a);$n(o,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:u,getQueryState:f}=await i({callContext:c,loadingElement:n.loadingElement,routesElement:n.routesElement,router:n.router,location:t.originalUrl}),{prelude:h,rootOpenTag:E,epilogue:C}=Nn(r),T=Dn(h,a.renderStylesheetLinks(l));o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200),o.write(T),o.write(`<script id="__MODELENCE_STATE__" type="application/json">${Et(d)}</script>`),o.write(E),await u(o),o.write("</div>"),o.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${Et(f())}</script>`),o.end(C);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,dr):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(we)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let o=Q.resolve(process.cwd(),"src/client/index.html"),r=Pe.readFileSync(o,"utf-8");return this.viteServer&&(r=await this.viteServer.transformIndexHtml(t,r)),r}if(!this.prodTemplateCache){let o=Q.resolve(process.cwd(),we,"index.html");this.prodTemplateCache=Pe.readFileSync(o,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-YNRUDPRK.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(dr),t()}return this.prodEntryLoaded||(await import(Q.resolve(process.cwd(),lr,"index.mjs")),this.prodEntryLoaded=true),t()}serveStaticShell(t){if(this.isDev())try{t.setHeader("Cache-Control","no-store"),t.sendFile("index.html",{root:"./src/client"});}catch(o){console.error("Error serving index.html:",o),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:we});}isDev(){return process.env.NODE_ENV!=="production"}};function Un(e){if(e.method!=="GET"&&e.method!=="HEAD")return false;let t=e.get("accept")??"";if(t&&!t.includes("text/html")&&!t.includes("*/*"))return false;let o=(e.path??e.url??"").split("?")[0];if(o.startsWith("/api/"))return false;let r=o.split("/").pop()??"",n=r.lastIndexOf(".");if(n>0){let i=r.slice(n).toLowerCase();if(i!==".html"&&i!==".htm")return false}return true}function Nn(e){let t=e.match(Pn);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let o=e.slice(0,t.index),r=e.slice(t.index+t[0].length);return {prelude:o,rootOpenTag:t[1],epilogue:r}}function Dn(e,t){if(!t)return e;let o=e.lastIndexOf(In);return o===-1?t+e:e.slice(0,o)+t+e.slice(o)}function $n(e,t){if(t.length===0)return;let o=e;if(typeof o.writeEarlyHints=="function")try{o.writeEarlyHints({link:t});}catch(r){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",r);}}async function jn(){let e=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,e))?.config||{}}catch(t){return console.warn("Could not load vite config:",t),{}}}function Hn(e,t){let o=mergeConfig(e,t);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Vn(e,t={}){let o=process.cwd(),r=await jn(),n=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>Pe.existsSync(Q.join(o,a))),i=[Tn(),Fn()];if(n){let a=(await import('vite-plugin-eslint')).default;i.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:o,overrideConfigFile:Q.resolve(o,n)}));}let s=defineConfig({plugins:i,build:{outDir:we,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":Q.resolve(o,"src").replace(/\\/g,"/")}}});return Hn(s,r)}function Fn(){return {name:"modelence-asset-handler",async transform(e,t){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(t))return process.env.NODE_ENV==="development",e}}}var Ie=new bt;function Gn(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function Bn(e){if(e)return Array.isArray(e)?e:[e]}function qn(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:Gn(e.from),replyTo:Bn(e.replyTo)}}function zn(e){if(!(e instanceof Error))return new Error("Managed email send failed");let t=e.responseBody,o=t?.error?.code,r=t?.error?.message;return o&&r?new Error(`Managed email rejected (${o}): ${r}`):e}var ur={async sendEmail(e){if(e.cc||e.bcc||e.attachments||e.headers)throw new Error("Modelence managed email does not support cc, bcc, attachments, or custom headers in v1. Configure your own provider (Resend, SES, SMTP) to use these features. See https://docs.modelence.com/email/managed.");try{await M("/api/email/send","POST",qn(e));}catch(t){throw zn(t)}}};var vt=Object.freeze({});function mr(e){vt=Object.freeze(Object.assign({},vt,e));}function pr(){return vt}var Ct=Object.freeze({});function fr(e){Ct=Object.freeze(Object.assign({},Ct,e));}function Ue(){return Ct}async function Yn({modules:e=[],roles:t={},defaultRoles:o={},server:r=Ie,migrations:n=[],email:i$1={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&r===Ie&&Ie.enableSsr(),gr.config(),gr.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;ai().then(()=>{}).catch(()=>{});for(let D of e)if(D.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${D.name}'
34
+
35
+ The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
36
+
37
+ Rename your module to something that does not start with '_system.'`);let u=[ct,p,or,ir,sr,le,wt,ar],f$1=[...u,...e];f(),Xn(u),Qn(e),v$1(t,o);let h=ni(f$1);e$1(h);let E=Zn(f$1),C=ei(f$1);ii(f$1),ct.rateLimits=at(s.rateLimits);let T=ti(f$1);go(T);let{storesToInit:P,effectiveStores:S}=rr(E);if(d){let{configs:D,environmentId:Cr,appAlias:kr,environmentAlias:Sr,telemetry:Ar}=await Fo({configSchema:h,cronJobsMetadata:tr(),stores:S,roles:t});pt(D),g({environmentId:Cr,appAlias:kr,environmentAlias:Sr,telemetry:Ar});}else c$2(Me(h));if(d&&!i$1.provider?We({...i$1,provider:ur}):We(i$1),ao(s),mr(a),fr({...c,provider:c.provider||Zt}),N()){await Qt();let D=[...new Set([...P,...S])];si(D),await ri(S,n);}else nr(n);d&&(await i(),qo()),er().catch(console.error),await hr(r,{combinedModules:f$1,channels:C});}function Qn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))A(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))B(`${t.name}.${o}`,r);}}function Xn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))C(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))D(`${t.name}.${o}`,r);}}function Zn(e){return e.flatMap(t=>t.stores)}function ei(e){return e.flatMap(t=>t.channels)}function ti(e){return e.flatMap(t=>t.rateLimits)}function oi(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var kt="migrations";async function ri(e,t){if(!await K(kt,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let r,n;try{r=e.filter(a=>a.getIndexCreationMode()==="blocking"),n=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of r)await St(a,"full");for(let a of n)await St(a,"drop-only");}catch(a){throw await ge(kt),a}let i=(async()=>{for(let a of n)await St(a,"create-only");})(),s=yt(t,{lockMode:"skip"});Promise.allSettled([i,s]).then(([a,c])=>{a.status==="rejected"&&console.error("Error creating background indexes:",a.reason),c.status==="rejected"&&console.error("Error running migrations:",c.reason);}).finally(async()=>{await ge(kt);});}async function St(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){oi(o,r);}}function ni(e){let t={};for(let o of e)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in t)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);t[i]=n;}return t}function ii(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))Zo(`${t.name}.${o}`,r);}function si(e){let t=ke();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function ai(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await ci(),n=await import('./package-4N23FMUL.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Ho.hostname(),environmentId:o})});}}async function ci(){try{let e=Q.join(process.cwd(),"package.json"),t=await Wn.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function wr(e){await s.deleteMany({userId:e}),await t.deleteMany({userId:e});let t$1=await q.findOne({_id:e}),o=Array.from(new Set((t$1?.emails??[]).map(r=>r.address?.toLowerCase()).filter(r=>!!r)));o.length>0&&await u.deleteMany({email:{$in:o}});}async function di(e){await wr(e),await q.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function ui(e){await wr(e),await q.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var At=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=Ue().provider;if(!r){m$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function mi(e){if(!w().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return w().provider?.sendEmail(e)}async function Ne(e){return !e||typeof e!="string"?null:g$1(e)}function v(e,t,o){let r=y(),n=e.status(t);if(r.errorComponent)try{let i=r.errorComponent({error:o,statusCode:t});if(i)return n.send(i)}catch(i){console.error("Unhandled error in authConfig.errorComponent:",i);}return n.json({error:o})}async function Rt(e,t){let{authToken:o}=await m(t);n(e,o),e.status(302),e.redirect("/");}async function fi(e,t,o,r,n){let i=y();try{if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}let s={};o.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),o.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),o.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=o;Object.keys(s).length>0&&(await q.updateOne({_id:o._id},{$set:s}),a={...o,...s}),await Rt(e,o._id),i.onAfterLogin?.({provider:t.providerName,user:a,session:r,connectionInfo:n}),i.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(i.login?.onError?.(s),i.onLoginError?.({provider:t.providerName,error:s,session:r,connectionInfo:n})),s}}async function gi(e,t,o,r,n){let i=y();if((i.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}if(!o.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){v(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...o.firstName===void 0&&t.firstName&&{firstName:t.firstName},...o.lastName===void 0&&t.lastName&&{lastName:t.lastName},...o.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await q.updateOne({_id:o._id,status:{$nin:["deleted","disabled"]},$or:[{[`authMethods.${t.providerName}.id`]:{$exists:!1}},{[`authMethods.${t.providerName}.id`]:t.id}]},{$set:{[`authMethods.${t.providerName}.id`]:t.id,...c}})).matchedCount>0)){v(e,400,"User with this email already exists. Please log in instead.");return}await Rt(e,o._id);let u={...o,...c,authMethods:{...o.authMethods,[t.providerName]:{id:t.id}}};i.onAfterLogin?.({provider:t.providerName,user:u,session:r,connectionInfo:n}),i.login?.onSuccess?.(u);return}catch(c){throw c instanceof Error&&(i.login?.onError?.(c),i.onLoginError?.({provider:t.providerName,error:c,session:r,connectionInfo:n})),c}}v(e,400,"User with this email already exists. Please log in instead.");}async function hi(e,t,o,r){let n=y();try{let i;if(n.generateHandle){let l=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});i=await L(l,t.email,{throwOnConflict:!1});}else i=await L(void 0,t.email);let s={handle:i,status:"active",emails:[{address:t.email,verified:t.emailVerified}],createdAt:new Date,authMethods:{[t.providerName]:{id:t.id}},...t.firstName!==void 0&&{firstName:t.firstName},...t.lastName!==void 0&&{lastName:t.lastName},...t.avatarUrl!==void 0&&{avatarUrl:t.avatarUrl}},a=await q.insertOne(s);await Rt(e,a.insertedId);let c=await q.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(n.onAfterSignup?.({provider:t.providerName,user:c,session:o,connectionInfo:r}),n.signup?.onSuccess?.(c));}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}function re(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function De(e,t,o){let r=await q.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await ne(e,t);if(r)return fi(t,o,r,n,i);if(!o.email){v(t,400,`Email address is required for ${o.providerName} authentication.`);return}let s;try{s=await q.findOne({"emails.address":o.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=y();c.onSignupError?.({provider:o.providerName,error:a,session:n,connectionInfo:i}),c.signup?.onError?.(a);}throw a}return s?gi(t,o,s,n,i):hi(t,o,n,i)}function x(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function oe(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function $e(e,t,o){let r=e.query.state,n=e.cookies[o],[i,s,a]=(n||"").split(":");return !r||!n||r!==i?(v(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(o),{mode:s||"login",...a?{linkedUserId:a}:{}})}async function je(e,t,o,r){let n=y(),{session:i,connectionInfo:s}=await ne(e,t),a=null;if(r){if(!ObjectId.isValid(r)){x(t),v(t,400,"Invalid OAuth linking state.");return}a=new ObjectId(r);}else a=i?.userId??null;if(!a){x(t),v(t,401,"You must be signed in to link a provider.");return}let c=a;try{let l=`authMethods.${o.providerName}.id`;if((await q.updateOne({_id:c,status:{$nin:["deleted","disabled"]},$or:[{[l]:{$exists:!1}},{[l]:o.id}]},{$set:{[l]:o.id}})).matchedCount===0){let f=await q.findOne({_id:c});if(!f||f.status==="deleted"||f.status==="disabled"){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:s})),x(t),v(t,400,"User account is not active.");return}let h=f?.authMethods?.[o.providerName]?.id;if(h&&h!==o.id){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`User already has a different ${o.providerName} account linked`),session:i,connectionInfo:s})),x(t),v(t,400,`You have already linked a different ${o.providerName} account.`);return}oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`Unexpected OAuth linking state for ${o.providerName}`),session:i,connectionInfo:s})),x(t),v(t,400,`Unable to link ${o.providerName} account.`);return}let u=await q.findOne({_id:c},{readPreference:"primary"});u&&oe(()=>n.onAfterOAuthLink?.({provider:o.providerName,user:u,session:i,connectionInfo:s})),x(t),t.status(302).redirect("/");}catch(l){if(l instanceof MongoServerError&&l.code===11e3){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),v(t,400,`This ${o.providerName} account is already linked to a different user.`);return}if(l instanceof Error&&oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),!t.headersSent)throw l}}function He(e){return !e||typeof e!="string"?null:e}async function Ei(e,t,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function bi(e){let t=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function vi(e,t){let o=He(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=$e(e,t,"authStateGoogle");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret")),c=re("google");try{let l=await Ei(o,s,a,c),d=await bi(l.access_token),u={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google",firstName:d.given_name||void 0,lastName:d.family_name||void 0,avatarUrl:d.picture||void 0};n==="link"?await je(e,t,u,i):await De(e,t,u);}catch(l){console.error("Google OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function Ci(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.google.enabled"),s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret"));if(!i||!s||!a){v(r,503,"Google authentication is not configured");return}n();};return e.get("/api/_internal/auth/google",t,async(o,r)=>{let n=String(a$2("_system.user.auth.google.clientId")),i=re("google"),s=randomBytes(32).toString("hex"),a=o.query.mode==="link"?"link":"login",c=null;if(a==="link"&&o.query.linkNonce&&(c=await Ne(o.query.linkNonce),!c)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let l=c?`${s}:${a}:${c}`:`${s}:${a}`;r.cookie("authStateGoogle",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.append("client_id",n),d.searchParams.append("redirect_uri",i),d.searchParams.append("response_type","code"),d.searchParams.append("scope","profile email"),d.searchParams.append("access_type","online"),d.searchParams.append("state",s),r.redirect(d.toString());}),e.get("/api/_internal/auth/google/callback",t,vi),e}var Er=Ci;async function Ai(e,t,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:o,code:e,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function Ri(e){let t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function xi(e){let t=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user emails: ${t.statusText}`);return t.json()}async function Oi(e,t){return e.email?e.email:(await xi(t)).find(r=>r.primary&&r.verified)?.email??null}async function _i(e,t){let o=He(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=$e(e,t,"authStateGithub");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret")),c=re("github");try{let l=await Ai(o,s,a,c),d=await Ri(l.access_token),u=await Oi(d,l.access_token);if(!u){n==="link"&&x(t),v(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.");return}let f=d.name?d.name.trim().split(/\s+/):[],h=f[0]||void 0,E=f.length>1?f.slice(1).join(" "):void 0,C={id:String(d.id),email:u,emailVerified:!0,providerName:"github",firstName:h,lastName:E,avatarUrl:d.avatar_url||void 0};n==="link"?await je(e,t,C,i):await De(e,t,C);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function Li(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.github.enabled"),s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret"));if(!i||!s||!a){v(r,503,"GitHub authentication is not configured");return}n();};return e.get("/api/_internal/auth/github",t,async(o,r)=>{let n=String(a$2("_system.user.auth.github.clientId")),i=re("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(h=>h.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=o.query.mode==="link"?"link":"login",d=null;if(l==="link"&&o.query.linkNonce&&(d=await Ne(o.query.linkNonce),!d)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let u=d?`${c}:${l}:${d}`:`${c}:${l}`;r.cookie("authStateGithub",u,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let f=new URL("https://github.com/login/oauth/authorize");f.searchParams.append("client_id",n),f.searchParams.append("redirect_uri",i),f.searchParams.append("scope",a),f.searchParams.append("state",c),r.redirect(f.toString());}),e.get("/api/_internal/auth/github/callback",t,_i),e}var br=Li;function vr(e,t,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&N())try{let{session:l,user:d}=await x$1(s);a={session:l,user:d};}catch{}let c=n$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:j$1(r.query),body:j$1(r.body),params:j$1(r.params)});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.contentType&&n.setHeader("Content-Type",l.contentType),l.headers&&Object.entries(l.headers).forEach(([d,u])=>{n.setHeader(d,u);}),l.redirect?n.redirect(l.redirect):n.send(l.data));}catch(l){c.end("error"),l instanceof a$4?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}function Pi(e){let t=[];if(!e)return t.push(B$1.json({limit:"16mb"})),t.push(B$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let o=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(B$1.json(o));}if(e.urlencoded!==false){let o=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(B$1.urlencoded(o));}if(e.raw){let o=typeof e.raw=="object"?e.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};t.push(B$1.raw(r));}return t}function Ii(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=Pi(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,vr(c,n,l));});}}async function hr(e,{combinedModules:t,channels:o}){let r=B$1();r.use(Mi()),r.use(Di()),Ii(r,t),r.use(B$1.json({limit:"16mb"})),r.use(B$1.urlencoded({extended:true,limit:"16mb"})),r.use(Er()),r.use(br()),r.post("/api/_internal/auth/set-link-cookie",async(c,l)=>{let{session:d}=await ne(c,l);if(!d?.userId){l.status(401).json({error:"Not authenticated"});return}l.cookie("oauthLinkToken",d.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),l.json({ok:true});}),r.post("/api/_internal/auth/issue-link-nonce",async(c,l)=>{let{session:d}=await ne(c,l);if(!d?.userId){l.status(401).json({error:"Not authenticated"});return}let u=await f$1(String(d.userId));l.json({nonce:u});}),r.post("/api/_internal/method/:methodName(*)",async(c,l)=>{let d=c.params.methodName,u=await ne(c,l);try{let f=a$3(await E(d,c.body.args,u));l.json({data:f,typeMap:b$2(f)});}catch(f){Ui(l,d,f);}});let n=Ti.createServer(r),i=Number(process.env.MODELENCE_KEEP_ALIVE_TIMEOUT_MS)||65e3;n.keepAliveTimeout=i,n.headersTimeout=i+5e3,await e.init({httpServer:n}),e.middlewares&&r.use(e.middlewares()),r.all("*",(c,l,d)=>{Promise.resolve(e.handler(c,l)).catch(d);}),process.on("unhandledRejection",(c,l)=>{console.error("Unhandled Promise Rejection:"),console.error(c instanceof Error?c.stack:c),console.error("Promise:",l);}),process.on("uncaughtException",c=>{console.error("Uncaught Exception:"),console.error(c.stack),console.trace("Full application stack:");});let s=Ue()?.provider;s&&s.init({httpServer:n,channels:o});let a=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(a,()=>{l$1("Application started",{source:"app"});let c=a$2("_system.site.url")||pe();console.log(`
38
+ Application started on ${c}
39
+ `),b()&&console.log("This project is not connected to a backend yet, so the app serves setup instructions instead of its UI.\nTo connect it to Modelence Cloud, run `npx modelence setup` and restart the dev server.\n");});}async function ne(e,t=null){let o=(e.path??e.url??"").split("?")[0],r=o.startsWith("/api/_internal/auth/")&&o.endsWith("/callback"),n=e.body??{},i=G.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(r?e.cookies.oauthLinkToken:null)||n.authToken),s=G.object({screenWidth:G.number(),screenHeight:G.number(),windowWidth:G.number(),windowHeight:G.number(),pixelRatio:G.number(),orientation:G.string().nullable()}).nullish().parse(n.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:ji(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:$i(e)};if(!!N()){let{session:l,user:d,roles:u}=await x$1(i);return {clientInfo:s,connectionInfo:a,session:l,user:d,roles:u,req:e,res:t}}return {clientInfo:s,connectionInfo:a,session:null,user:null,roles:w$1(),req:e,res:t}}function Ui(e,t,o){if(o instanceof a$4){o.status>=500&&o.status<600&&console.error(`Error calling ${t}:`,o),o.code&&e.setHeader("X-Modelence-Error-Code",o.code),e.status(o.status).send(o.message);return}if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r="";try{r=Ni(o);}catch(n){console.error(`Error parsing Zod error in ${t}:`,n),r="Validation failed";}e.status(400).send(r);return}console.error(`Error calling ${t}:`,o),e.status(500).send(o instanceof Error?o.message:String(o));}function Ni(e){let t=e.flatten(),o=Object.entries(t.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),r=t.formErrors;return [...o,...r].filter(Boolean).join("; ")}function Di(){let{frameAncestors:e}=pr(),t=e&&e.length>0,o=t?["'self'",...e].join(" "):"'self'";return (r,n,i)=>{n.setHeader("Content-Security-Policy",`frame-ancestors ${o}`),t||n.setHeader("X-Frame-Options","SAMEORIGIN"),i();}}function $i(e){let t=e.headers["x-forwarded-host"],o=(Array.isArray(t)?t[0]:t?.split(",")[0])?.trim()||e.get("host"),r=e.headers["x-forwarded-proto"];return `${(Array.isArray(r)?r[0]:r?.split(",")[0])?.trim()||e.protocol}://${o}`}function ji(e){let t=e.headers["x-forwarded-for"];if(t)return (Array.isArray(t)?t[0]:t.split(",")[0]).trim();let o=e.ip||e.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}
40
+ export{k as a,Sn as b,An as c,Rn as d,xn as e,hr as f,ne as g,Yn as h,di as i,ui as j,At as k,mi as l};//# sourceMappingURL=chunk-4EHMYUFO.js.map
41
+ //# sourceMappingURL=chunk-4EHMYUFO.js.map