modelence 0.23.0-setup.dev.3 → 0.23.0-setup.dev.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/bin/modelence.js +4 -4
  2. package/dist/bin/modelence.js.map +1 -1
  3. package/dist/chunk-DYEQCKE3.js +37 -0
  4. package/dist/chunk-DYEQCKE3.js.map +1 -0
  5. package/dist/{chunk-JQ7HKLQZ.js → chunk-I7OPVKVV.js} +3 -3
  6. package/dist/chunk-I7OPVKVV.js.map +1 -0
  7. package/dist/{chunk-QMKQ7DUD.js → chunk-KDOTVIEY.js} +3 -3
  8. package/dist/{chunk-QMKQ7DUD.js.map → chunk-KDOTVIEY.js.map} +1 -1
  9. package/dist/{chunk-UHER7BLC.js → chunk-UJ2WYHH7.js} +2 -2
  10. package/dist/{chunk-UHER7BLC.js.map → chunk-UJ2WYHH7.js.map} +1 -1
  11. package/dist/chunk-UW37F3GV.js +2 -0
  12. package/dist/chunk-UW37F3GV.js.map +1 -0
  13. package/dist/{package-A4RGADVP.js → package-RDXN7Z54.js} +2 -2
  14. package/dist/{package-A4RGADVP.js.map → package-RDXN7Z54.js.map} +1 -1
  15. package/dist/{render-V4SWSKPW.js → render-FRLQDLXI.js} +2 -2
  16. package/dist/{render-V4SWSKPW.js.map → render-FRLQDLXI.js.map} +1 -1
  17. package/dist/server-BCMO6EDH.js +2 -0
  18. package/dist/{server-D7FBXWTW.js.map → server-BCMO6EDH.js.map} +1 -1
  19. package/dist/server.d.ts +50 -0
  20. package/dist/server.js +1 -1
  21. package/dist/telemetry.js +1 -1
  22. package/dist/transport-LWVQ4TUY.js +2 -0
  23. package/dist/{transport-OSL4EWWD.js.map → transport-LWVQ4TUY.js.map} +1 -1
  24. package/package.json +1 -3
  25. package/dist/chunk-7XZDALJZ.js +0 -37
  26. package/dist/chunk-7XZDALJZ.js.map +0 -1
  27. package/dist/chunk-B5WLEHNH.js +0 -3
  28. package/dist/chunk-B5WLEHNH.js.map +0 -1
  29. package/dist/chunk-JQ7HKLQZ.js.map +0 -1
  30. package/dist/server-D7FBXWTW.js +0 -2
  31. package/dist/transport-OSL4EWWD.js +0 -2
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
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 L 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 he 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:i}=await n.json(),a=new URLSearchParams({...t?{pick:"environment"}:{},...o?{appId:o}:{}}),r=a.size>0?`${i}&${a}`:i;return console.log(`Please visit ${r} to authenticate`),console.log(`Code: ${s}`),await G(r),{token:await W(e,s)}}async function W(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await K(e,t);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function K(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 D=".modelence.env",C=".modelence",b="project.json";async function H(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 Q(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${D} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function Z(e){return String(e).replace(/"/g,'\\"')}async function ee(){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 te(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 I=".claude",w=join(I,"settings.json"),x="modelence@modelence";async function oe(){let e=join(process.cwd(),w),t;try{t=await promises.readFile(e,"utf8");}catch{try{await promises.mkdir(join(process.cwd(),I),{recursive:!0}),await promises.writeFile(e,JSON.stringify({enabledPlugins:{[x]:!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?.[x];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 "${x}": true under "enabledPlugins".`);}catch{console.warn(`Could not parse ${w} to check the Modelence plugin status.`);}}async function ne(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 M(e){try{let t=join(process.cwd(),D),o={},n=!1;try{let c=await promises.readFile(t,"utf8");o=parse(c),n=!0,await ne(t),await Q()||(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 ee()});s={cliToken:c};}console.log("Fetching service configuration...");let i=await H(e.host,s),a={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:i.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:i.serviceToken,MODELENCE_CONTAINER_ID:i.containerId},r=Object.entries(a).map(([c,g])=>`${c}="${Z(g)}"`).join(`
2
+ import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import M,{join,dirname}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import K 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:i}=await n.json(),a=new URLSearchParams({...t?{pick:"environment"}:{},...o?{appId:o}:{}}),r=a.size>0?`${i}&${a}`:i;return console.log(`Please visit ${r} to authenticate`),console.log(`Code: ${s}`),await K(r),{token:await W(e,s)}}async function W(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let i=await X(e,t);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function 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 D=".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: ${D} 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 I=".claude",w=join(I,"settings.json"),x="modelence@modelence",O={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(),I),{recursive:!0}),await promises.writeFile(e,JSON.stringify({extraKnownMarketplaces:O,enabledPlugins:{[x]:!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?.[x];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 "${x}": true under "enabledPlugins", and declare the marketplace under "extraKnownMarketplaces": ${JSON.stringify(O)}.`);}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(),D),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 i=await Q(e.host,s),a={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:i.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:i.serviceToken,MODELENCE_CONTAINER_ID:i.containerId},r=Object.entries(a).map(([c,g])=>`${c}="${ee(g)}"`).join(`
5
5
  `);if(await promises.writeFile(t,r.trim()+`
6
- `),console.log(`Successfully configured ${D} file`),i.appId)try{await te(i.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 oe(),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.");}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var se=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()});async function j(){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 se.parse(o)}var S=null,T=null;function le(){if(!S)throw new Error("Environment variables not loaded");return S}function F(){if(!T)throw new Error("Configuration not loaded");return T}function _(e){return `${le().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function u(){let{serverDir:e,serverEntry:t}=F();return join(e,t).replace(/\\/g,"/")}function B(){return F().postBuildCommand}function N(e){let t=$("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function m(e){return join(process.cwd(),e).replace(/\\/g,"/")}function $(e){let t=m(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function E(){try{T=await j();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await L.readFile(join(process.cwd(),".modelence.env"),"utf-8");S=parse(e);}catch(e){if(e.code==="ENOENT")S={};else throw e}}async function ue(){let e=B();if(e){console.log("Running post-build command..."),execSync(e);return}await me(),await fe();}async function me(){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 fe(){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 ge(){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=N();await L.rm(e,{recursive:!0,force:!0}),await ge(),await ue(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await L.access($());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function V(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip"),s=e.host||_("");await P(),await Ee(n);let{token:i}=await y(s),{bundleName:a}=await ve(e.app,e.env,n,i,s);await promises.unlink(n),await ye(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function Ee(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(r){if(r.code!=="ENOENT")throw r}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=he("zip",{zlib:{level:9}});o.on("warning",r=>{if(r.code==="ENOENT")console.warn("Warning:",r);else throw r}),o.on("error",r=>{throw r});let n=new Promise((r,c)=>{t.on("close",r),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],i=["public","server",join(".modelence","build"),".next"];for(let r of s)await promises.access(m(r)).then(()=>true).catch(()=>false)&&o.file(m(r),{name:r});for(let r of i)await promises.access(m(r)).then(()=>true).catch(()=>false)&&o.directory(m(r),r);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 ve(e,t,o,n,s){let i=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:a,bundleName:r}=await i.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: ${r}`),{bundleName:r}}async function ye(e,t,o,n,s,i){let a=await fetch(`${i}/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:r}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${r}`);}function J(){console.log("Starting Modelence dev server...");let e=u(),t=O.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function q(){console.log("Starting Modelence production server...");let e=u(),t=O.basename(e,O.extname(e)),o=N(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Te=fileURLToPath(import.meta.url),$e=dirname(Te),Oe=JSON.parse(readFileSync(join($e,"../../package.json"),"utf-8")),f=new Command().name("modelence").description("Modelence CLI tool").version(Oe.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 M(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 V(e);});f.command("dev").description("Start development server").action(async()=>{await E(),J();});f.command("start").description("Start production server").action(async()=>{await E(),q();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
6
+ `),console.log(`Successfully configured ${D} file`),i.appId)try{await oe(i.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.");}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 F(){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 S=null,T=null;function de(){if(!S)throw new Error("Environment variables not loaded");return S}function _(){if(!T)throw new Error("Configuration not loaded");return T}function B(e){return `${de().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function u(){let{serverDir:e,serverEntry:t}=_();return join(e,t).replace(/\\/g,"/")}function L(){return _().postBuildCommand}function N(e){let t=$("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function m(e){return join(process.cwd(),e).replace(/\\/g,"/")}function $(e){let t=m(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function E(){try{T=await F();}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");S=parse(e);}catch(e){if(e.code==="ENOENT")S={};else throw e}}async function me(){let e=L();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:M.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:M.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:M.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=N();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($());}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||B("");await P(),await ve(n);let{token:i}=await y(s),{bundleName:a}=await ye(e.app,e.env,n,i,s);await promises.unlink(n),await Ce(e.app,e.env,a,join(".modelence","build","app.mjs"),i,s);}async function ve(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(r){if(r.code!=="ENOENT")throw r}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",r=>{if(r.code==="ENOENT")console.warn("Warning:",r);else throw r}),o.on("error",r=>{throw r});let n=new Promise((r,c)=>{t.on("close",r),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],i=["public","server",join(".modelence","build"),".next"];for(let r of s)await promises.access(m(r)).then(()=>true).catch(()=>false)&&o.file(m(r),{name:r});for(let r of i)await promises.access(m(r)).then(()=>true).catch(()=>false)&&o.directory(m(r),r);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 i=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:a,bundleName:r}=await i.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: ${r}`),{bundleName:r}}async function Ce(e,t,o,n,s,i){let a=await fetch(`${i}/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:r}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${r}`);}function z(){console.log("Starting Modelence dev server...");let e=u(),t=M.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function G(){console.log("Starting Modelence production server...");let e=u(),t=M.basename(e,M.extname(e)),o=N(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var $e=fileURLToPath(import.meta.url),Me=dirname($e),Oe=JSON.parse(readFileSync(join(Me,"../../package.json"),"utf-8")),f=new Command().name("modelence").description("Modelence CLI tool").version(Oe.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").action(async()=>{await E(),z();});f.command("start").description("Start production server").action(async()=>{await E(),G();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
7
7
  //# 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","appId","response","code","verificationUrl","hintParams","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","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":";wdAkBA,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,CAAa,IAAI,gBAAgB,CACrC,GAAIL,CAAAA,CAAkB,CAAE,IAAA,CAAM,aAAc,EAAI,EAAC,CACjD,GAAIC,CAAAA,CAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CAAC,CAAA,CACKK,CAAAA,CAAMD,CAAAA,CAAW,IAAA,CAAO,CAAA,CAAI,CAAA,EAAGD,CAAe,CAAA,CAAA,EAAIC,CAAU,CAAA,CAAA,CAAKD,EAEvE,OAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBE,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,QAAQ,GAAA,CAAI,CAAA,MAAA,EAASH,CAAI,CAAA,CAAE,CAAA,CAE3B,M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tB,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\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 hintParams = new URLSearchParams({\n ...(pickEnvironment ? { pick: 'environment' } : {}),\n ...(appId ? { appId } : {}),\n });\n const url = hintParams.size > 0 ? `${verificationUrl}&${hintParams}` : 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*/\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\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\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({ enabledPlugins: { [CLAUDE_PLUGIN_ID]: true } }, null, 2) + '\\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\".`\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 };\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 } 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","hintParams","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,CAAa,IAAI,gBAAgB,CACrC,GAAIL,CAAAA,CAAkB,CAAE,IAAA,CAAM,aAAc,EAAI,EAAC,CACjD,GAAIC,CAAAA,CAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CAAC,CAAA,CACKK,CAAAA,CAAMD,CAAAA,CAAW,IAAA,CAAO,CAAA,CAAI,CAAA,EAAGD,C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,EACf,WAAA,CAAY,uBAAuB,EACnC,MAAA,CAAO,SAAY,CAClB,MAAMrD,CAAAA,EAAQ,CACd,MAAMc,IACR,CAAC,EAEHuC,CAAAA,CACG,OAAA,CAAQ,QAAQ,CAAA,CAChB,WAAA,CAAY,2BAA2B,CAAA,CACvC,eAAe,iBAAA,CAAmB,mBAAmB,EACrD,cAAA,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\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 hintParams = new URLSearchParams({\n ...(pickEnvironment ? { pick: 'environment' } : {}),\n ...(appId ? { appId } : {}),\n });\n const url = hintParams.size > 0 ? `${verificationUrl}&${hintParams}` : 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*/\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\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 };\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 } 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"]}
@@ -0,0 +1,37 @@
1
+ import {t as t$1}from'./chunk-I7OPVKVV.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}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 ar from'dotenv';import Un from'fs/promises';import en 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}from'crypto';import oo from'bcrypt';import F,{z as z$1}from'zod';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import bn from'@vitejs/plugin-react';import Le from'fs';import B$1,{Router}from'express';import Ei from'cookie-parser';import bi 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 V=null;async function qt(){if(V)return V;let e=N();if(!e)throw new Error("MongoDB URI is not set");let t=le.getConfig("mongodbPoolSize");V=new MongoClient(e,{driverInfo:{name:"Modelence",version:t$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await V.connect(),await V.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),V}catch(o){throw console.error(o),V=null,o}}function N(){return le.getConfig("mongodbUri")||void 0}function ve(){return V}var de=null,vr="_modelenceSocketio",zt=60;async function Cr({httpServer:e,channels:t}){let o=ve(),r=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let n=null;if(r&&o){n=o.db().collection(vr);try{await n.createIndex({createdAt:1},{expireAfterSeconds:zt,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:zt,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(i,s));}),console.log("Socket.IO server initialized");}function kr({category:e,id:t,data:o}){de?.to(`${e}:${t}`).emit(e,o);}var Wt={init:Cr,broadcast:kr};async function Ce(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let o=t[1];return !!await r.findOne({domain:o})}var Jt={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 ke=3,z=50,Kt=8,Yt=128,Qt=254,Xt=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`}),Ve=e=>z$1.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),Sr=z$1.object({firstName:Ve({max:50}),lastName:Ve({max:50}),avatarUrl:Ve({max:400}),handle:Xt({min:ke,max:z})}).strict();function Se(e){let t=Sr.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 Ae(e){return z$1.string().min(Kt,{message:`Password must contain at least ${Kt} characters`}).max(Yt,{message:`Password must be at most ${Yt} characters`}).parse(e)}function O(e){return z$1.string().max(Qt,{message:`Email must be at most ${Qt} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function Zt(e){return Xt({min:ke,max:z}).parse(e)}function Re(e){return e instanceof MongoServerError&&e.code===11e3&&typeof e.keyPattern=="object"&&e.keyPattern!==null&&"emails.address"in e.keyPattern}function xe(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 eo(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=Zt(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 eo(n)}let r=t.split("@")[0].padEnd(ke,"_").slice(0,z);return eo(r)}var Fe=Object.freeze({});function Be(e){Fe=Object.freeze(Object.assign({},Fe,e));}function w(){return Fe}var qe=Object.freeze({});function to(e){qe=Object.freeze(Object.assign({},qe,e));}function y(){return qe}function _r(){return w()?.provider?!!a$2("_system.user.auth.email.verification"):false}var Lr=10,Tr=oo.hashSync(randomBytes(32).toString("hex"),Lr);async function ro(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||Tr,u=await oo.compare(a,d);if(!l||!u)throw Pr();if(!c.emails?.find(h=>h.address.toLowerCase()===s)?.verified&&_r())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 no(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 Pr(){return new Error("Incorrect email/password combination")}async function io(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 so(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await q.requireById(t.id),r=Se(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 ze=["google","github"];async function ao({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!ze.includes(e))throw new Error(`Invalid provider. Supported providers are: ${ze.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 We=[];function co(e){if(We.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");We=e;}async function k(e){let{bucket:t,type:o,value:r,message:n}=e,i=We.filter(a=>a.bucket===t&&a.type===o),s=n?()=>new d$1(n):void 0;for(let a of i)await Mr(a,r,s);}async function Mr(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?Ir(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 Ir(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 lo({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 Dr={locale:"en",strength:2};async function $r(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:Dr,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 uo(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 $r(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 Ke({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||lo)({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 Je={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function mo(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 Je;let n=r.emails?.find(i=>i.address.toLowerCase()===o);if(!n||n.verified)return Je;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 Ke({userId:r._id,email:o,baseUrl:t?.baseUrl}),Je}async function po(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=Ae(i.password),f=r?.ip;if(f&&await k({bucket:"signupAttempt",type:"ip",value:f}),!n.allowDisposableEmails&&await Ce(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=Se({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 P=await oo.hash(u,10),M;try{M=await q.insertOne({handle:C,status:"active",emails:[{address:d,verified:!1}],createdAt:new Date,authMethods:{password:{hash:P}},...E.firstName!==void 0&&{firstName:E.firstName},...E.lastName!==void 0&&{lastName:E.lastName},...E.avatarUrl!==void 0&&{avatarUrl:E.avatarUrl}});}catch(_){throw Re(_)?new Error(`User with email already exists: ${d}`):_}let S=await q.findOne({_id:M.insertedId},{readPreference:"primary"});if(!S)throw new Error("User not found");return await Ke({userId:M?.insertedId,email:d,baseUrl:r?.baseUrl}),n.onAfterSignup?.({provider:"email",user:S,session:o,connectionInfo:r}),n.signup?.onSuccess?.(S),M.insertedId}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:"email",error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}var Ye="resetPasswordToken",Vr="/api/_internal/",wo={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Vr};async function yo(e$1){return t.findOne({token:e(e$1)})}async function fo(e){return t.findOneAndDelete({_id:e})}function Fr({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 go={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Eo(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 go;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||Fr)({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}),go}async function bo(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=xe(t,w().passwordReset?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await yo(r);if(!n||n.expiresAt<new Date)throw new Error("This password reset link is invalid or has expired.");return e.res.cookie(Ye,r,{...wo,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 vo(e,t){let o=t.req?.cookies?.[Ye];!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=Ae(e.password),i=()=>{t.res?.clearCookie(Ye,wo);},s=await yo(r);if(!s)throw i(),new Error("Invalid or expired reset token");if(s.expiresAt<new Date)throw await fo(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 oo.hash(n,10);if(!await fo(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 Co({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 Ze="magicLinkToken",zr="/api/_internal/",So={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:zr},Ao=15,ko=6,Wr=5;function Oe(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 ot(){return !!y().magicLink?.enabled}function Ro(){return !!y().magicLink?.allowSignup}async function xo(e$1){return u.findOne({token:e(e$1)})}async function rt(e){return u.findOneAndDelete({_id:e})}async function Qe(e){try{await u.insertOne(e);}catch(t){console.error("Failed to restore a magic link token after a failed signup:",t);}}var Xe={success:true,message:"If this email can be used to sign in, a link has been sent"};async function Oo(e$1,{connectionInfo:t}){if(!ot())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 Ce(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&&!Ro())return Xe;let c=randomBytes(32).toString("hex"),l=randomInt(0,10**ko).toString().padStart(ko,"0"),d=Date.now(),u$1=new Date(d),f=new Date(d+a$1.minutes(Ao));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||Co)({email:o,magicLinkUrl:h,code:l,name:""}),P=z$2(C);return await n.sendEmail({to:o,from:i,subject:w()?.magicLink?.subject||"Your sign-in link",text:P,html:C}),Xe}async function _o(e){let t=a$2("_system.site.url")||"",o=xe(t,w().magicLink?.redirectUrl)||"/";try{let r=z$1.string().parse(e.query.token),n=await xo(r);if(!n||n.expiresAt<new Date)throw new Error("This sign-in link is invalid or has expired.");return e.res.cookie(Ze,r,{...So,maxAge:a$1.minutes(Ao)}),{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 et={locale:"en",strength:2};async function Lo(e){let{tokenDoc:t,session:o,connectionInfo:r,res:n$1,clearCookie:i}=e,s=t.email,a=y(),c=Ro(),l=false;try{let d=await rt(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:et})){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 Qe(d),S}let f;try{f=await Jr(s,u,c);}catch(S){throw await Qe(d),S}let{userDoc:h,isNew:E}=f;if(!h)throw await Qe(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,P=h.emails?.find(S=>S.address.toLowerCase()===s),M=!E&&!P?.verified;return M&&(C=await q.findOneAndUpdate({_id:h._id,"emails.address":s},{$set:{"emails.$.verified":!0}},{collation:et,returnDocument:"after"})??h),await j(o.authToken,C._id),n$1&&n(n$1,o.authToken),E?Oe("onAfterSignup",()=>a.onAfterSignup?.({provider:"magicLink",user:C,session:o,connectionInfo:r})):(M&&Oe("onAfterEmailVerification",()=>a.onAfterEmailVerification?.({provider:"magicLink",user:C,session:o,connectionInfo:r})),Oe("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;Oe(u,()=>f?.({provider:"magicLink",error:d,session:o,connectionInfo:r}));}throw d}}async function Jr(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:et});try{let{doc:i,isNew:s}=await n();return {userDoc:i,isNew:s}}catch(i){if(!Re(i))throw i;let{doc:s}=await n();return {userDoc:s,isNew:false}}}async function To(e,t){let{session:o,connectionInfo:r,res:n,req:i}=t;if(!o)throw new Error("Session is not initialized");if(!ot())throw new Error("Magic link authentication is not enabled");let s=z$1.string().parse(i?.cookies?.[Ze]),a=()=>{n?.clearCookie(Ze,So);},c=await xo(s);if(!c)throw a(),new Error("Invalid or expired code or magic link");if(c.expiresAt<new Date)throw await rt(c._id),a(),new Error("Code or magic link has expired");return Lo({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:a})}async function Po(e$1,t){let{session:o,connectionInfo:r,res:n}=t;if(!o)throw new Error("Session is not initialized");if(!ot())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:Wr}});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 rt(c._id),new Error("Code or magic link has expired");return Lo({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:()=>{}})}function Mo(e){return `${e.bucket}
23
+ ${e.type}
24
+ ${e.window}`}function Kr(){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 Yr(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 nt(e={}){let t=Kr(),o=Yr(e),r=new Map;for(let s of o)r.set(Mo(s),s);let n=[],i=new Set;for(let s of t){let a=Mo(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 it=new a("_system.user",{stores:[q,r,s,t,u],queries:{getOwnProfile:io},mutations:{signupWithPassword:po,loginWithPassword:ro,logout:no,resendEmailVerification:mo,sendResetPasswordToken:Eo,resetPassword:vo,sendMagicLink:Oo,loginWithMagicLink:To,loginWithOneTimeCode:Po,updateProfile:so,unlinkOAuthProvider:ao},cronJobs:{updateDisposableEmailList:Jt},rateLimits:nt(),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:uo}},{path:"/api/_internal/auth/reset-password",handlers:{get:bo}},{path:"/api/_internal/auth/magic-link",handlers:{get:_o}}]});var Qr={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 Xr(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 Zr(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:Xr(i,a)});}}return o}function _e(e,t="withoutRemoteServer"){let o=Qr[t];return Zr(o,e)}async function Io({configSchema:e,cronJobsMetadata:t,stores:o,roles:r}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=(o??[]).map(a=>({name:a.getName(),schema:a.getSerializedSchema(),collections:[a.getName()],version:2,indexes:a.getIndexes(),searchIndexes:a.getSearchIndexes(),indexCreationMode:a.getIndexCreationMode()})),s=await T("/api/connect","POST",{hostname:en.hostname(),containerId:n,dataModels:i,configSchema:e,cronJobsMetadata:t,roles:r});if(s.status==="error")throw new Error(s.error);return console.log("Successfully connected to Modelence Cloud"),s}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Uo(){return T("/api/configs","GET")}async function No(){return await T("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function T(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 st=false,tn=a$1.seconds(10);function Do(){setInterval(async()=>{if(!st){st=true;try{await No();}catch(e){console.error("Error syncing status",e);}try{await on();}catch(e){console.error("Error syncing config",e);}st=false;}},tn);}function at(e){c$2(e),c$2(_e(d$2(),"withRemoteServer"));}async function on(){let{configs:e}=await Uo();at(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={},$o=a$1.seconds(10),Vo=randomBytes(32).toString("base64url"),sn=a$1.seconds(30),te=new Map,ct=e=>e instanceof MongoError&&e.code===11e3,jo=(e,t)=>typeof e.keyPattern=="object"&&e.keyPattern!==null&&Object.prototype.hasOwnProperty.call(e.keyPattern,t),an=async({error:e,resource:t})=>{if(jo(e,"resource"))return true;if(jo(e,"_id"))return false;let o=await W.findOne({resource:t});return !!o&&o._id!==t},Ho=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},Fo=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},cn=e=>{let t=e,o=te.get(t);o&&(o.stopRequested=true,o.timer&&(clearTimeout(o.timer),o.timer=null),te.delete(t));},Go=({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=sn,successfulLockCacheDuration:o=$o,failedLockCacheDuration:r=$o,heartbeat:n,bypassCache:i,instanceId:s=Vo}={}){let a=Date.now();if(!i&&J[e]&&a<J[e].expiresAt)return J[e].value&&n&&Go({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 ln({resource:e,staleThresholdDate:c,instanceId:s});return J[e]={value:l,expiresAt:a+(l?o:r)},l?(n&&Go({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 ln=async({resource:e,staleThresholdDate:t,instanceId:o})=>{try{return await Ho({resource:e,staleThresholdDate:t,instanceId:o})}catch(r){if(ct(r)&&await an({error:r,resource:e})){if(!await Fo({resource:e,staleThresholdDate:t,instanceId:o}))return false;try{return await Ho({resource:e,staleThresholdDate:t,instanceId:o})}catch(i){if(ct(i))return false;throw i}}if(ct(r))return false;throw r}};async function pe(e,{instanceId:t=Vo}={}){cn(e);try{let o=await W.deleteOne({_id:e,instanceId:t});return o.deletedCount===0?await Fo({resource:e,instanceId:t}):o.deletedCount>0}catch{return false}finally{delete J[e];}}var Y={},lt=null,dt=new c("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function qo(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(lt)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 zo(){if(lt)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 dt.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);}),lt=setInterval(dn,a$1.seconds(1));}}async function dn(){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 un(o);});}async function un(e){let{alias:t,params:o,handler:r,state:n}=e;n.isRunning=true,n.startTs=Date.now(),await dt.upsertOne({alias:t},{$set:{lastStartDate:new Date(n.startTs)},$setOnInsert:{alias:t}});let i=n$1("cron",`cron:${t}`);try{await r(),Bo(n,o),i.end("success");}catch(s){Bo(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 Bo(e,t){e.scheduledRunTs=e.startTs?e.startTs+t.interval:Date.now(),e.startTs=void 0,e.isRunning=false;}function Wo(){return Object.values(Y).map(({alias:e,params:t})=>({alias:e,description:t.description,interval:t.interval,timeout:t.timeout}))}var Jo=new a("_system.cron",{stores:[dt]});function Ko(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 ut=new a("_system.lock",{stores:[W]});var fe=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 mt(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 fe.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)+`
25
+ [Output truncated - exceeded size limit]`:d;await fe.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 fe.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 pe("migrations");}}}function Yo(e){setTimeout(()=>{mt(e).catch(t=>{console.error("Error running migrations:",t);});},0);}var Qo=new a("_system.migration",{stores:[fe]});var Xo=new a("_system.rateLimit",{stores:[me]});async function mn({filePath:e,contentType:t,visibility:o}){return await T("/api/files/upload","POST",{filePath:e,contentType:t,visibility:o})}async function pn(e){await T("/api/files/delete","POST",{filePath:e});}async function fn(e){return await T("/api/files/download","POST",{filePath:e})}async function gn(e){return await T("/api/files/url","POST",{filePath:e})}var Zo=new a("_system.files",{});function pt(e){return e.replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}var ge="./.modelence/build/client".replace(/\\/g,"/"),tr="./.modelence/build/ssr".replace(/\\/g,"/"),or="/index.tsx",vn=/(<div\b[^>]*\bid\s*=\s*["']root["'][^>]*>)\s*<\/div>/i,Cn="</head>",ft=class{constructor(){this.ssrEnabled=false;this.ssrTransportInstalled=false;this.prodEntryLoaded=false;}enableSsr(){this.ssrEnabled=true;}async init({httpServer:t}){if(this.config=await _n(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(),tr,"index.mjs");if(!Le.existsSync(o))throw new Error(`Modelence: SSR is enabled (startApp({ ssr: true })) but the SSR bundle is missing at ${o}.
26
+
27
+ 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:
28
+ \u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
29
+ \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(ge,t)];return this.config?.publicDir&&o.push(B$1.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&kn(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-BCMO6EDH.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,o),l=this.collectCssAssets(a);Rn(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}=Sn(r),P=An(h,a.renderStylesheetLinks(l));o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200),o.write(P),o.write(`<script id="__MODELENCE_STATE__" type="application/json">${pt(d)}</script>`),o.write(E),await u(o),o.write("</div>"),o.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${pt(f())}</script>`),o.end(C);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,or):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(ge)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let o=Q.resolve(process.cwd(),"src/client/index.html"),r=Le.readFileSync(o,"utf-8");return this.viteServer&&(r=await this.viteServer.transformIndexHtml(t,r)),r}if(!this.prodTemplateCache){let o=Q.resolve(process.cwd(),ge,"index.html");this.prodTemplateCache=Le.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(or),t()}return this.prodEntryLoaded||(await import(Q.resolve(process.cwd(),tr,"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:ge});}isDev(){return process.env.NODE_ENV!=="production"}};function kn(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 Sn(e){let t=e.match(vn);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 An(e,t){if(!t)return e;let o=e.lastIndexOf(Cn);return o===-1?t+e:e.slice(0,o)+t+e.slice(o)}function Rn(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 xn(){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 On(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 _n(e,t={}){let o=process.cwd(),r=await xn(),n=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>Le.existsSync(Q.join(o,a))),i=[bn(),Ln()];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:ge,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 On(s,r)}function Ln(){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 Te=new ft;function Tn(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function Pn(e){if(e)return Array.isArray(e)?e:[e]}function Mn(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:Tn(e.from),replyTo:Pn(e.replyTo)}}function In(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 rr={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 T("/api/email/send","POST",Mn(e));}catch(t){throw In(t)}}};var gt=Object.freeze({});function nr(e){gt=Object.freeze(Object.assign({},gt,e));}function ir(){return gt}var ht=Object.freeze({});function sr(e){ht=Object.freeze(Object.assign({},ht,e));}function Pe(){return ht}async function $n({modules:e=[],roles:t={},defaultRoles:o={},server:r=Te,migrations:n=[],email:i$1={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&r===Te&&Te.enableSsr(),ar.config(),ar.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;Kn().then(()=>{}).catch(()=>{});for(let D of e)if(D.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${D.name}'
30
+
31
+ The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
32
+
33
+ Rename your module to something that does not start with '_system.'`);let u=[it,p,Jo,Qo,Xo,le,ut,Zo],f$1=[...u,...e];f(),Hn(u),jn(e),v$1(t,o);let h=zn(f$1);e$1(h);let E=Gn(f$1),C=Vn(f$1);Wn(f$1),it.rateLimits=nt(s.rateLimits);let P=Fn(f$1);co(P);let{storesToInit:M,effectiveStores:S}=Ko(E);if(d){let{configs:D,environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr}=await Io({configSchema:h,cronJobsMetadata:Wo(),stores:S,roles:t});at(D),g({environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr});}else c$2(_e(h));if(d&&!i$1.provider?Be({...i$1,provider:rr}):Be(i$1),to(s),nr(a),sr({...c,provider:c.provider||Wt}),N()){await qt();let D=[...new Set([...M,...S])];Jn(D),await qn(S,n);}else Yo(n);d&&(await i(),Do()),zo().catch(console.error),await cr(r,{combinedModules:f$1,channels:C});}function jn(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 Hn(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 Gn(e){return e.flatMap(t=>t.stores)}function Vn(e){return e.flatMap(t=>t.channels)}function Fn(e){return e.flatMap(t=>t.rateLimits)}function Bn(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var wt="migrations";async function qn(e,t){if(!await K(wt,{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 yt(a,"full");for(let a of n)await yt(a,"drop-only");}catch(a){throw await pe(wt),a}let i=(async()=>{for(let a of n)await yt(a,"create-only");})(),s=mt(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 pe(wt);});}async function yt(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){Bn(o,r);}}function zn(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 Wn(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))qo(`${t.name}.${o}`,r);}function Jn(e){let t=ve();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function Kn(){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 Yn(),n=await import('./package-RDXN7Z54.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:en.hostname(),environmentId:o})});}}async function Yn(){try{let e=Q.join(process.cwd(),"package.json"),t=await Un.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function lr(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 Xn(e){await lr(e),await q.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Zn(e){await lr(e),await q.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Et=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=Pe().provider;if(!r){m$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function ei(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 Me(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 bt(e,t){let{authToken:o}=await m(t);n(e,o),e.status(302),e.redirect("/");}async function oi(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 bt(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 ri(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 bt(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 ni(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 bt(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 Ie(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 oi(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?ri(t,o,s,n,i):ni(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 Ue(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 Ne(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 De(e){return !e||typeof e!="string"?null:e}async function ai(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 ci(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 li(e,t){let o=De(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ue(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 ai(o,s,a,c),d=await ci(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 Ne(e,t,u,i):await Ie(e,t,u);}catch(l){console.error("Google OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function di(){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 Me(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,li),e}var ur=di;async function pi(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 fi(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 gi(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 hi(e,t){return e.email?e.email:(await gi(t)).find(r=>r.primary&&r.verified)?.email??null}async function wi(e,t){let o=De(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ue(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 pi(o,s,a,c),d=await fi(l.access_token),u=await hi(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 Ne(e,t,C,i):await Ie(e,t,C);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function yi(){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 Me(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,wi),e}var mr=yi;function pr(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 vi(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 Ci(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=vi(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,pr(c,n,l));});}}async function cr(e,{combinedModules:t,channels:o}){let r=B$1();r.use(Ei()),r.use(Ai()),Ci(r,t),r.use(B$1.json({limit:"16mb"})),r.use(B$1.urlencoded({extended:true,limit:"16mb"})),r.use(ur()),r.use(mr()),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){ki(l,d,f);}});let n=bi.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=Pe()?.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")||`http://localhost:${a}`;console.log(`
34
+ Application started on ${c}
35
+ `),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=F.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(r?e.cookies.oauthLinkToken:null)||n.authToken),s=F.object({screenWidth:F.number(),screenHeight:F.number(),windowWidth:F.number(),windowHeight:F.number(),pixelRatio:F.number(),orientation:F.string().nullable()}).nullish().parse(n.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:xi(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:Ri(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 ki(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=Si(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 Si(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 Ai(){let{frameAncestors:e}=ir(),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 Ri(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 xi(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}
36
+ export{k as a,mn as b,pn as c,fn as d,gn as e,cr as f,ne as g,$n as h,Xn as i,Zn as j,Et as k,ei as l};//# sourceMappingURL=chunk-DYEQCKE3.js.map
37
+ //# sourceMappingURL=chunk-DYEQCKE3.js.map