modelence 0.24.0-mcp-oauth.dev.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/modelence.js +5 -8
- package/dist/bin/modelence.js.map +1 -1
- package/dist/{chunk-ECEYGWUJ.js → chunk-6FAEWW7A.js} +6 -6
- package/dist/{chunk-ECEYGWUJ.js.map → chunk-6FAEWW7A.js.map} +1 -1
- package/dist/chunk-DKK3TACA.js +3 -0
- package/dist/chunk-DKK3TACA.js.map +1 -0
- package/dist/{chunk-NM66FFLD.js → chunk-LR6IBZVP.js} +2 -2
- package/dist/{chunk-NM66FFLD.js.map → chunk-LR6IBZVP.js.map} +1 -1
- package/dist/chunk-V3EQDOEU.js +3 -0
- package/dist/chunk-V3EQDOEU.js.map +1 -0
- package/dist/client.js +1 -1
- package/dist/{package-QH4HNRJF.js → package-PLJALKWH.js} +2 -2
- package/dist/{package-QH4HNRJF.js.map → package-PLJALKWH.js.map} +1 -1
- package/dist/{render-BBAPNCBO.js → render-RQCPSN7B.js} +2 -2
- package/dist/{render-BBAPNCBO.js.map → render-RQCPSN7B.js.map} +1 -1
- package/dist/renderApp-UF5FLZHD.js +2 -0
- package/dist/{renderApp-7DU7K73A.js.map → renderApp-UF5FLZHD.js.map} +1 -1
- package/dist/server-GF7ON6QY.js +2 -0
- package/dist/{server-FJI3WKY4.js.map → server-GF7ON6QY.js.map} +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-47CQLENF.js +0 -3
- package/dist/chunk-47CQLENF.js.map +0 -1
- package/dist/chunk-E6YINTUD.js +0 -3
- package/dist/chunk-E6YINTUD.js.map +0 -1
- package/dist/renderApp-7DU7K73A.js +0 -2
- package/dist/server-FJI3WKY4.js +0 -2
package/dist/bin/modelence.js
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import
|
|
3
|
-
`);}var
|
|
4
|
-
|
|
5
|
-
claude plugin install ${h}
|
|
6
|
-
Guide: ${ce}`;async function le(){let e=join(process.cwd(),w),t;try{t=await promises.readFile(e,"utf8");}catch{try{await promises.mkdir(join(process.cwd(),R),{recursive:!0}),await promises.writeFile(e,JSON.stringify({extraKnownMarketplaces:L,enabledPlugins:{[h]:!0}},null,2)+`
|
|
7
|
-
`),console.log(`Declared the Modelence Claude Code plugin in ${w}`);}catch(o){console.warn(`Failed to create ${w}:`,o);}return}try{let n=JSON.parse(t)?.enabledPlugins?.[h];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 "${h}": true under "enabledPlugins", and declare the marketplace under "extraKnownMarketplaces": ${JSON.stringify(L)}.`);}catch{console.warn(`Could not parse ${w} to check the Modelence plugin status.`);}}function T(e){return spawnSync("claude",e,{encoding:"utf8",shell:process.platform==="win32"})}async function de(){let e=T(["--version"]);if(e.error||e.status!==0){console.log(_);return}let t=await j("Install the Modelence plugin for Claude Code? (Y/n) ");if(t&&t.toLowerCase()!=="y")return;T(["plugin","marketplace","add",x]);let o=T(["plugin","install",h,"--scope","project"]);o.status===0?console.log("Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: run /mcp, choose modelence, then Authenticate."):(console.warn(`Could not install the Modelence plugin: ${(o.stderr||o.stdout||"").trim()}`),console.warn(_));}async function ue(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 F(e){try{let t=join(process.cwd(),M),o={},n=!1;try{let c=await promises.readFile(t,"utf8");o=parse(c),n=!0,await ue(t),await re()||(console.log("Setup canceled"),process.exit(0));}catch{}let s;if(e.token)s={setupToken:e.token};else {let{token:c}=await C(e.host,{pickEnvironment:!0,appId:await se()});s={cliToken:c};}console.log("Fetching service configuration...");let r=await ne(e.host,s),a={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId,MODELENCE_RUNTIME:process.env.MODELENCE_RUNTIME||"local"},i=Object.entries(a).map(([c,g])=>`${c}="${ie(g)}"`).join(`
|
|
2
|
+
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import O,{join,dirname}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import G from'open';import R from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import Ee from'archiver';async function y(e,{pickEnvironment:t=false,appId:o}={}){let n=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!n.ok)throw new Error("Failed to create CLI authentication code");let{code:s,verificationUrl:r}=await n.json(),a=new URL(r);t&&a.searchParams.set("pick","environment"),o&&a.searchParams.set("appId",o),console.log(`Please visit ${a} to authenticate`),console.log(`Code: ${s}`);try{await G(a.toString());}catch{console.log("Could not open a browser automatically. Please open the URL above manually.");}return {token:await W(e,s)}}async function W(e,t){let s=Date.now()+6e5;for(;Date.now()<s;){try{let r=await X(e,t);if(r)return r}catch(r){console.error("Error polling for CLI token:",r);}await new Promise(r=>setTimeout(r,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function X(e,t){let o=await fetch(`${e}/api/cli/token?code=${t}`,{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:n}=await o.json();return n}var x=".modelence.env",C=".modelence",b="project.json";async function Q(e,t){let o="setupToken"in t?{"X-Modelence-Setup-Token":t.setupToken}:{Authorization:`Bearer ${t.cliToken}`},n=await fetch(`${e}/api/setup`,{method:"GET",headers:o});if(!n.ok){let s=await n.text();throw new Error(s||`Request failed with status ${n.status}`)}return n.json()}async function Z(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${x} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function ee(e){return String(e).replace(/"/g,'\\"')}async function te(){try{let e=await promises.readFile(join(process.cwd(),C,b),"utf8"),{appId:t}=JSON.parse(e);return typeof t=="string"&&t?t:void 0}catch{return}}async function oe(e){let t=join(process.cwd(),C),o=join(t,b),n={};try{n=JSON.parse(await promises.readFile(o,"utf8"));}catch{}await promises.mkdir(t,{recursive:true}),await promises.writeFile(o,JSON.stringify({...n,appId:e},null,2)+`
|
|
3
|
+
`);}var $=".claude",w=join($,"settings.json"),D="modelence@modelence",I={modelence:{source:{source:"github",repo:"modelence/modelence"}}};async function ne(){let e=join(process.cwd(),w),t;try{t=await promises.readFile(e,"utf8");}catch{try{await promises.mkdir(join(process.cwd(),$),{recursive:!0}),await promises.writeFile(e,JSON.stringify({extraKnownMarketplaces:I,enabledPlugins:{[D]:!0}},null,2)+`
|
|
4
|
+
`),console.log(`Enabled the Modelence Claude Code plugin in ${w}`);}catch(o){console.warn(`Failed to create ${w}:`,o);}return}try{let n=JSON.parse(t)?.enabledPlugins?.[D];n!==!0&&console.warn(`Note: the Modelence plugin is ${n===!1?"disabled":"not enabled"} in ${w}. To get Modelence tools and docs in Claude Code, add "${D}": true under "enabledPlugins", and declare the marketplace under "extraKnownMarketplaces": ${JSON.stringify(I)}.`);}catch{console.warn(`Could not parse ${w} to check the Modelence plugin status.`);}}async function re(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function j(e){try{let t=join(process.cwd(),x),o={},n=!1;try{let c=await promises.readFile(t,"utf8");o=parse(c),n=!0,await re(t),await Z()||(console.log("Setup canceled"),process.exit(0));}catch{}let s;if(e.token)s={setupToken:e.token};else {let{token:c}=await y(e.host,{pickEnvironment:!0,appId:await te()});s={cliToken:c};}console.log("Fetching service configuration...");let r=await Q(e.host,s),a={...o,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId,MODELENCE_RUNTIME:process.env.MODELENCE_RUNTIME||"local"},i=Object.entries(a).map(([c,g])=>`${c}="${ee(g)}"`).join(`
|
|
8
5
|
`);if(await promises.writeFile(t,i.trim()+`
|
|
9
|
-
`),console.log(`Successfully configured ${
|
|
6
|
+
`),console.log(`Successfully configured ${x} file`),r.appId)try{await oe(r.appId),console.log(`Recorded the app ID in ${C}/${b}`);}catch(c){console.warn(`Failed to record the app ID in ${C}/${b}:`,c);}await ne(),n&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session."),!n&&a.MODELENCE_RUNTIME==="local"&&(console.log(`
|
|
10
7
|
Next step \u2014 run the app on this machine:
|
|
11
8
|
`),console.log(" npm install (if you haven't already)"),console.log(` npm run dev (starts the app)
|
|
12
|
-
`));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var
|
|
9
|
+
`));}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var ae=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()});async function _(){let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");return ae.parse(o)}var N=null,T=null;function de(){if(!N)throw new Error("Environment variables not loaded");return N}function L(){if(!T)throw new Error("Configuration not loaded");return T}function F(e){return `${de().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function u(){let{serverDir:e,serverEntry:t}=L();return join(e,t).replace(/\\/g,"/")}function B(){return L().postBuildCommand}function S(e){let t=M("build");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}function m(e){return join(process.cwd(),e).replace(/\\/g,"/")}function M(e){let t=m(".modelence");return e?join(t,e).replace(/\\/g,"/"):t.replace(/\\/g,"/")}async function E(){try{T=await _();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await R.readFile(join(process.cwd(),".modelence.env"),"utf-8");N=parse(e);}catch(e){if(e.code==="ENOENT")N={};else throw e}}async function me(){let e=B();if(e){console.log("Running post-build command..."),execSync(e);return}await fe(),await ge();}async function fe(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:O.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function ge(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{ssr:O.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:O.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},o,true));}async function we(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[u()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function P(){console.log("Building Modelence project...");try{let e=S();await R.rm(e,{recursive:!0,force:!0}),await we(),await me(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await R.access(M());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function J(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip"),s=e.host||F("");await P(),await ve(n);let{token:r}=await y(s),{bundleName:a}=await ye(e.app,e.env,n,r,s);await promises.unlink(n),await Ce(e.app,e.env,a,join(".modelence","build","app.mjs"),r,s);}async function ve(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=Ee("zip",{zlib:{level:9}});o.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),o.on("error",i=>{throw i});let n=new Promise((i,c)=>{t.on("close",i),t.on("error",c),o.on("error",c);});o.pipe(t);let s=["package.json","package-lock.json","next.config.js","next.config.ts","modelence.config.ts"],r=["public","server",join(".modelence","build"),".next"];for(let i of s)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.file(m(i),{name:i});for(let i of r)await promises.access(m(i)).then(()=>true).catch(()=>false)&&o.directory(m(i),i);await o.finalize(),await n;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ye(e,t,o,n,s){let r=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({appAlias:e,envAlias:t})});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:a,bundleName:i}=await r.json(),c=await promises.readFile(o),g=await fetch(a,{method:"PUT",body:new Uint8Array(c),headers:{"Content-Type":"application/zip"}});if(!g.ok)throw new Error(`Failed to upload bundle: ${g.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${i}`),{bundleName:i}}async function Ce(e,t,o,n,s,r){let a=await fetch(`${r}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:t,bundleName:o,entryPoint:n})});if(!a.ok)throw new Error(`Failed to trigger deployment: ${a.statusText}`);let{deploymentUrl:i}=await a.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${i}`);}function z(e={}){console.log("Starting Modelence dev server...");let t=u(),o=O.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development",...e.takeover?{MODELENCE_TAKEOVER:"1"}:{}}});}function K(){console.log("Starting Modelence production server...");let e=u(),t=O.basename(e,O.extname(e)),o=S(`${t}.mjs`);execSync(`node "${o}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Me=fileURLToPath(import.meta.url),Oe=dirname(Me),Ie=JSON.parse(readFileSync(join(Oe,"../../package.json"),"utf-8")),f=new Command().name("modelence").description("Modelence CLI tool").version(Ie.version);f.command("setup").description("Setup Modelence environment variables").option("-t, --token <token>","Modelence setup token (omit to authorize in the browser)").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await j(e);});f.command("build").description("Build the application").action(async()=>{await E(),await P();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await E(),await J(e);});f.command("dev").description("Start development server").option("--takeover","Disconnect any instance currently holding the environment and connect this one").action(async e=>{await E(),z(e);});f.command("start").description("Start production server").action(async()=>{await E(),K();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
13
10
|
//# sourceMappingURL=modelence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","ask","question","rl","createInterface","answer","confirmOverwrite","escapeEnvValue","value","readProjectAppId","content","fs","join","recordProjectAppId","dirPath","projectPath","existing","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACE_REPO","CLAUDE_MARKETPLACES","CLAUDE_PLUGIN_DOCS_URL","CLAUDE_PLUGIN_INSTALL_HINT","ensureClaudePluginEnabled","settingsPath","enabled","runClaude","args","spawnSync","offerClaudePluginInstall","probe","install","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":";keAkBA,eAAsBA,CAAAA,CACpBC,EACA,CAAE,eAAA,CAAAC,CAAAA,CAAkB,KAAA,CAAO,KAAA,CAAAC,CAAM,CAAA,CAAmD,EAAC,CACzD,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,GAAGH,CAAI,CAAA,aAAA,CAAA,CAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,EAED,GAAI,CAACG,CAAAA,CAAS,EAAA,CACZ,MAAM,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AmB,EACrD,MAAA,CAAO,mBAAA,CAAqB,gBAAgB,CAAA,CAC5C,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACN,MAAMe,CAAAA,CAAO7C,CAAO,EACtB,CAAC,EAEHmF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,YAAY,0BAA0B,CAAA,CACtC,MAAA,CACC,YAAA,CACA,gFACF,CAAA,CACC,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACNyC,CAAAA,CAAIvE,CAAO,EACb,CAAC,CAAA,CAEHmF,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 url = new URL(verificationUrl);\n if (pickEnvironment) {\n url.searchParams.set('pick', 'environment');\n }\n if (appId) {\n url.searchParams.set('appId', appId);\n }\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n try {\n await open(url.toString());\n } catch {\n // Headless/SSH/container — no browser to open. The URL and code above\n // are already printed, so authentication can proceed manually.\n console.log('Could not open a browser automatically. Please open the URL above manually.');\n }\n\n const token = await waitForAuth(host, code);\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { spawnSync } from 'child_process';\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 ask(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const answer = await ask(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `\n );\n return answer.toLowerCase() === 'y';\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n try {\n const content = await fs.readFile(join(process.cwd(), MODELENCE_DIR, PROJECT_FILE), 'utf8');\n const { appId } = JSON.parse(content);\n return typeof appId === 'string' && appId ? appId : undefined;\n } catch {\n return undefined;\n }\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like build/, cache/ and\n tmp/ are temporary), so the whole team gets it. It's a hint in the git-remote\n sense — connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\n}\n\nconst CLAUDE_DIR = '.claude';\nconst CLAUDE_SETTINGS_FILE = join(CLAUDE_DIR, 'settings.json');\nconst CLAUDE_PLUGIN_ID = 'modelence@modelence';\n// Without the marketplace declared alongside enabledPlugins, Claude Code\n// can't resolve the plugin unless the user already ran\n// `claude plugin marketplace add` themselves.\nconst CLAUDE_MARKETPLACE_REPO = 'modelence/modelence';\nconst CLAUDE_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: CLAUDE_MARKETPLACE_REPO } },\n};\nconst CLAUDE_PLUGIN_DOCS_URL = 'https://docs.modelence.com/ai-coding-agents';\nconst CLAUDE_PLUGIN_INSTALL_HINT =\n 'Install the Modelence plugin for Claude Code by hand:\\n' +\n ` claude plugin marketplace add ${CLAUDE_MARKETPLACE_REPO}\\n` +\n ` claude plugin install ${CLAUDE_PLUGIN_ID}\\n` +\n `Guide: ${CLAUDE_PLUGIN_DOCS_URL}`;\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(`Declared 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\nfunction runClaude(args: string[]) {\n return spawnSync('claude', args, { encoding: 'utf8', shell: process.platform === 'win32' });\n}\n\n/*\n Installs the plugin through the Claude Code CLI — the one install path that\n behaves the same for the terminal, the IDE extensions and the desktop app,\n which all read the same plugin state. Touches the user's machine-wide Claude\n config, so it asks first, and it never fails the setup: without the CLI on\n PATH it prints the commands to run by hand.\n*/\nasync function offerClaudePluginInstall(): Promise<void> {\n const probe = runClaude(['--version']);\n if (probe.error || probe.status !== 0) {\n console.log(CLAUDE_PLUGIN_INSTALL_HINT);\n return;\n }\n\n const answer = await ask('Install the Modelence plugin for Claude Code? (Y/n) ');\n if (answer && answer.toLowerCase() !== 'y') {\n return;\n }\n\n // Idempotent, and makes the install work before Claude Code has picked up\n // the marketplace declared in .claude/settings.json.\n runClaude(['plugin', 'marketplace', 'add', CLAUDE_MARKETPLACE_REPO]);\n const install = runClaude(['plugin', 'install', CLAUDE_PLUGIN_ID, '--scope', 'project']);\n if (install.status === 0) {\n console.log(\n 'Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: ' +\n 'run /mcp, choose modelence, then Authenticate.'\n );\n } else {\n console.warn(\n `Could not install the Modelence plugin: ${(install.stderr || install.stdout || '').trim()}`\n );\n console.warn(CLAUDE_PLUGIN_INSTALL_HINT);\n }\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n // Where this working copy runs; Studio sandboxes pre-set \"sandbox\".\n MODELENCE_RUNTIME: process.env.MODELENCE_RUNTIME || 'local',\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n await ensureClaudePluginEnabled();\n // Interactive runs only: with --token (CI) or without a terminal there is\n // nobody to ask, and no Claude Code to set up.\n if (!options.token && process.stdin.isTTY) {\n await offerClaudePluginInstall();\n }\n\n if (fileExisted) {\n // The dev server reads the file at boot, and an open agent session may\n // still hold the old environment id in its context.\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, start a new session.'\n );\n }\n\n // Only for a first-time setup: re-running it on an existing file already\n // told them to restart the dev server they're running.\n if (!fileExisted && newEnv.MODELENCE_RUNTIME === 'local') {\n console.log('\\nNext step — run the app on this machine:\\n');\n console.log(\" npm install (if you haven't already)\");\n console.log(' npm run dev (starts the app)\\n');\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(options: { takeover?: boolean } = {}) {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: {\n ...process.env,\n NODE_ENV: 'development',\n ...(options.takeover ? { MODELENCE_TAKEOVER: '1' } : {}),\n },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .option(\n '--takeover',\n 'Disconnect any instance currently holding the environment and connect this one'\n )\n .action(async (options) => {\n await loadEnv();\n dev(options);\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","appId","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","confirmOverwrite","rl","createInterface","answer","escapeEnvValue","value","readProjectAppId","content","fs","join","recordProjectAppId","dirPath","projectPath","existing","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACES","ensureClaudePluginEnabled","settingsPath","enabled","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";+dAkBA,eAAsBA,CAAAA,CACpBC,CAAAA,CACA,CAAE,gBAAAC,CAAAA,CAAkB,KAAA,CAAO,KAAA,CAAAC,CAAM,CAAA,CAAmD,EAAC,CACzD,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGH,CAAI,gBAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,CAAA,CAED,GAAI,CAACG,CAAAA,CAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,EAAI,MAAMF,CAAAA,CAAS,IAAA,EAAK,CAChDG,CAAAA,CAAM,IAAI,IAAID,CAAe,CAAA,CAC/BJ,CAAAA,EACFK,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,OAAQ,aAAa,CAAA,CAExCJ,CAAAA,EACFI,CAAAA,CAAI,YAAA,CAAa,GAAA,CAAI,QAASJ,CAAK,CAAA,CAGrC,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBI,CAAG,CAAA,gBAAA,CAAkB,CAAA,CACjD,OAAA,CAAQ,GAAA,CAAI,CAAA,MAAA,EAASF,CAAI,CAAA,CAAE,CAAA,CAE3B,GAAI,CACF,MAAMG,CAAAA,CAAKD,CAAAA,CAAI,QAAA,EAAU,EAC3B,CAAA,KAAQ,CAGN,OAAA,CAAQ,GAAA,CAAI,6EAA6E,EAC3F,CAIA,OAAO,CAAE,KAAA,CAFK,MAA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,CAAY,oBAAoB,CAAA,CAChC,OAAA,CAAQH,EAAAA,CAAY,OAAO,EAE9BE,CAAAA,CACG,OAAA,CAAQ,OAAO,CAAA,CACf,YAAY,uCAAuC,CAAA,CACnD,OAAO,qBAAA,CAAuB,0DAA0D,EACxF,MAAA,CAAO,mBAAA,CAAqB,gBAAA,CAAkB,6BAA6B,EAC3E,MAAA,CAAO,MAAOnF,GAAY,CACzB,MAAMD,EAAMC,CAAO,EACrB,CAAC,CAAA,CAEHmF,EACG,OAAA,CAAQ,OAAO,EACf,WAAA,CAAY,uBAAuB,EACnC,MAAA,CAAO,SAAY,CAClB,MAAMrD,GAAQ,CACd,MAAMc,CAAAA,GACR,CAAC,CAAA,CAEHuC,CAAAA,CACG,OAAA,CAAQ,QAAQ,EAChB,WAAA,CAAY,2BAA2B,EACvC,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,EACrD,MAAA,CAAO,mBAAA,CAAqB,gBAAgB,CAAA,CAC5C,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACN,MAAMe,CAAAA,CAAO7C,CAAO,EACtB,CAAC,EAEHmF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,YAAY,0BAA0B,CAAA,CACtC,MAAA,CACC,YAAA,CACA,gFACF,CAAA,CACC,MAAA,CAAO,MAAOnF,CAAAA,EAAY,CACzB,MAAM8B,CAAAA,GACNyC,CAAAA,CAAIvE,CAAO,EACb,CAAC,CAAA,CAEHmF,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 url = new URL(verificationUrl);\n if (pickEnvironment) {\n url.searchParams.set('pick', 'environment');\n }\n if (appId) {\n url.searchParams.set('appId', appId);\n }\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n try {\n await open(url.toString());\n } catch {\n // Headless/SSH/container — no browser to open. The URL and code above\n // are already printed, so authentication can proceed manually.\n console.log('Could not open a browser automatically. Please open the URL above manually.');\n }\n\n const token = await waitForAuth(host, code);\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n try {\n const content = await fs.readFile(join(process.cwd(), MODELENCE_DIR, PROJECT_FILE), 'utf8');\n const { appId } = JSON.parse(content);\n return typeof appId === 'string' && appId ? appId : undefined;\n } catch {\n return undefined;\n }\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like build/, cache/ and\n tmp/ are temporary), so the whole team gets it. It's a hint in the git-remote\n sense — connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\n}\n\nconst CLAUDE_DIR = '.claude';\nconst CLAUDE_SETTINGS_FILE = join(CLAUDE_DIR, 'settings.json');\nconst CLAUDE_PLUGIN_ID = 'modelence@modelence';\n// Without the marketplace declared alongside enabledPlugins, Claude Code\n// can't resolve the plugin unless the user already ran\n// `claude plugin marketplace add` themselves.\nconst CLAUDE_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: 'modelence/modelence' } },\n};\n\n/*\n Makes the Modelence Claude Code plugin available in connected projects that\n didn't start from the template (which ships this file). Only ever creates\n the file: an existing settings.json is the user's own — a missing or\n explicitly disabled plugin entry there gets a hint, not an edit, so a\n deliberate opt-out is never flipped back on. The file is inert for people\n who don't use Claude Code, and like the project file, failing to write it\n doesn't fail the setup.\n*/\nasync function ensureClaudePluginEnabled(): Promise<void> {\n const settingsPath = join(process.cwd(), CLAUDE_SETTINGS_FILE);\n\n let content: string;\n try {\n content = await fs.readFile(settingsPath, 'utf8');\n } catch {\n // Missing — create it with just the plugin enabled.\n try {\n await fs.mkdir(join(process.cwd(), CLAUDE_DIR), { recursive: true });\n await fs.writeFile(\n settingsPath,\n JSON.stringify(\n {\n extraKnownMarketplaces: CLAUDE_MARKETPLACES,\n enabledPlugins: { [CLAUDE_PLUGIN_ID]: true },\n },\n null,\n 2\n ) + '\\n'\n );\n console.log(`Enabled the Modelence Claude Code plugin in ${CLAUDE_SETTINGS_FILE}`);\n } catch (error) {\n console.warn(`Failed to create ${CLAUDE_SETTINGS_FILE}:`, error);\n }\n return;\n }\n\n try {\n const settings = JSON.parse(content);\n const enabled = settings?.enabledPlugins?.[CLAUDE_PLUGIN_ID];\n if (enabled !== true) {\n console.warn(\n `Note: the Modelence plugin is ${enabled === false ? 'disabled' : 'not enabled'} in ` +\n `${CLAUDE_SETTINGS_FILE}. To get Modelence tools and docs in Claude Code, add ` +\n `\"${CLAUDE_PLUGIN_ID}\": true under \"enabledPlugins\", and declare the marketplace under ` +\n `\"extraKnownMarketplaces\": ${JSON.stringify(CLAUDE_MARKETPLACES)}.`\n );\n }\n } catch {\n console.warn(`Could not parse ${CLAUDE_SETTINGS_FILE} to check the Modelence plugin status.`);\n }\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n // Where this working copy runs; Studio sandboxes pre-set \"sandbox\".\n MODELENCE_RUNTIME: process.env.MODELENCE_RUNTIME || 'local',\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n await ensureClaudePluginEnabled();\n\n if (fileExisted) {\n // Anything that read the old file holds stale credentials: the dev\n // server loads it at boot, and MCP connections send its token per\n // connection.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.'\n );\n }\n\n // Only for a first-time setup: re-running it on an existing file already\n // told them to restart the dev server they're running.\n if (!fileExisted && newEnv.MODELENCE_RUNTIME === 'local') {\n console.log('\\nNext step — run the app on this machine:\\n');\n console.log(\" npm install (if you haven't already)\");\n console.log(' npm run dev (starts the app)\\n');\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'package-lock.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(options: { takeover?: boolean } = {}) {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: {\n ...process.env,\n NODE_ENV: 'development',\n ...(options.takeover ? { MODELENCE_TAKEOVER: '1' } : {}),\n },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .option(\n '--takeover',\n 'Disconnect any instance currently holding the environment and connect this one'\n )\n .action(async (options) => {\n await loadEnv();\n dev(options);\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {t as t$1}from'./chunk-
|
|
1
|
+
import {t as t$1}from'./chunk-V3EQDOEU.js';import {a,b as b$1,c,d,s,t,u,v,w as w$1,o,p,i,l,e,B,n,m,q,r,x,C,D,E as E$1,F,f as f$1,G as G$1,z as z$2,y,g as g$1,h,J,H,I}from'./chunk-63RBLFRJ.js';import {b as b$2,c as c$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 as i$1,m as m$1,l as l$1,d as d$2,k as k$1,o as o$1,n as n$1,j}from'./chunk-UW37F3GV.js';import {a as a$3,b as b$3}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import Ro from'dotenv';import gi from'fs/promises';import Xr from'os';import Z from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {ObjectId,MongoServerError,MongoClient,MongoError}from'mongodb';export{ObjectId as m}from'mongodb';import {randomBytes,randomInt,randomUUID,createHash}from'crypto';import hr from'bcrypt';import F$1,{z}from'zod';import Te from'fs';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import ei from'@vitejs/plugin-react';import z$1,{Router}from'express';import ns from'cookie-parser';import is from'http';var ue=new a("_system",{queries:{setupStatus:async()=>({setupRequired:b$1()})},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 ir(){if(V)return V;let e=N();if(!e)throw new Error("MongoDB URI is not set");let t=ue.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(r){throw console.error(r),V=null,r}}function N(){return ue.getConfig("mongodbUri")||void 0}function Se(){return V}var me=null,Ko="_modelenceSocketio",sr=60;async function Yo({httpServer:e,channels:t}){let r=Se(),o=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let i=null;if(o&&r){i=r.db().collection(Ko);try{await i.createIndex({createdAt:1},{expireAfterSeconds:sr,background:!0});}catch(n){if(n instanceof Error&&"code"in n&&n.code===85)try{await i.dropIndex("createdAt_1"),await i.createIndex({createdAt:1},{expireAfterSeconds:sr,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:",n);}}me=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:i?createAdapter(i):void 0,transports:["websocket"],perMessageDeflate:false}),me.on("error",n=>{console.error("Socket.IO error:",n);}),me.use(async(n,s)=>{let a=n.handshake.auth.token;try{n.data=await z$2(a),s();}catch(c){s(c instanceof Error?c:new Error(String(c)));}}),me.on("connection",n=>{n.on("disconnect",()=>{J(n);}),n.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(n.data))&&(n.join(s),c=true,n.emit("joinedChannel",s));break}c||n.emit("joinError",{channel:s,error:"Access denied"});}),n.on("leaveChannel",s=>{n.leave(s),console.log(`User ${n.id} left channel ${s}`),n.emit("leftChannel",s);}),n.on("subscribeLiveQuery",s=>H(n,s)),n.on("unsubscribeLiveQuery",s=>I(n,s));}),console.log("Socket.IO server initialized");}function Xo({category:e,id:t,data:r}){me?.to(`${e}:${t}`).emit(e,r);}var ar={init:Yo,broadcast:Xo};async function Ae(e){let t$1=e.toLowerCase().trim().split("@");if(t$1.length!==2)return false;let r=t$1[1];return !!await t.findOne({domain:r})}var cr={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 r=(await e.text()).split(`
|
|
2
2
|
`).map(n=>n.trim().toLowerCase()).filter(n=>n.length>0),o=new Date,i=500;for(let n=0;n<r.length;n+=i){let s=r.slice(n,n+i);try{await t.insertMany(s.map(a=>({domain:a,addedAt:o})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var Qe=3,oe=50,Qo=/^[a-zA-Z0-9_-]+$/,lr=8,dr=128,ur=254,Zo=e=>z.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`}),Xe=e=>z.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),mr=Zo({min:Qe,max:oe}).regex(Qo,{message:"must contain only letters, numbers, underscores, and hyphens"}),en=z.object({firstName:Xe({max:50}),lastName:Xe({max:50}),avatarUrl:Xe({max:400}),handle:mr}).strict();function Re(e){let t=en.partial().safeParse(e);if(!t.success){let r=t.error.issues[0],o=r.path.join("."),i=o?`${o}: ${r.message}`:r.message;throw new c$1(i)}return t.data}function Oe(e){return z.string().min(lr,{message:`Password must contain at least ${lr} characters`}).max(dr,{message:`Password must be at most ${dr} characters`}).parse(e)}function L(e){return z.string().max(ur,{message:`Email must be at most ${ur} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function pr(e){return mr.parse(e)}function xe(e){return e instanceof MongoServerError&&e.code===11e3&&typeof e.keyPattern=="object"&&e.keyPattern!==null&&"emails.address"in e.keyPattern}function _e(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function G(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 fr(e){let t=e.slice(0,oe);try{if(!await s.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(i){throw new Error(`Database error while checking handle availability: ${i}`)}let r=51;for(let i=2;i<=r;i++){let n=`_${i}`,s$1=`${t.slice(0,oe-n.length)}${n}`;try{if(!await s.findOne({handle:s$1},{collation:{locale:"en",strength:2}}))return s$1}catch(a){throw new Error(`Database error while checking handle "${s$1}": ${a}`)}}let o=10;for(let i=0;i<o;i++){let n=`_${randomBytes(3).toString("hex")}`,s$1=`${t.slice(0,oe-n.length)}${n}`;try{if(!await s.findOne({handle:s$1},{collation:{locale:"en",strength:2}}))return s$1}catch(a){throw new Error(`Database error while checking handle "${s$1}": ${a}`)}}throw new Error(`Could not generate a unique handle for base "${e}" after exhausting all attempts.`)}async function U(e,t,{throwOnConflict:r=true}={}){if(e!=null&&String(e).trim()!==""){let n=pr(String(e).trim());if(r){if(await s.findOne({handle:n},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return n}return fr(n)}let i=t.split("@")[0].replace(/[^a-zA-Z0-9_-]/g,"_").padEnd(Qe,"_").slice(0,oe);return fr(i)}var Ze=Object.freeze({});function et(e){Ze=Object.freeze(Object.assign({},Ze,e));}function b(){return Ze}var tt=Object.freeze({});function gr(e){tt=Object.freeze(Object.assign({},tt,e));}function w(){return tt}function sn(){return b()?.provider?!!a$2("_system.user.auth.email.verification"):false}var an=10,cn=hr.hashSync(randomBytes(32).toString("hex"),an);async function wr(e,{user:t,session:r,connectionInfo:o,res:i}){try{if(!r)throw new Error("Session is not initialized");if(t)throw new c$1("User is already authenticated","ALREADY_AUTHENTICATED");let n=o?.ip;n&&await k({bucket:"signin",type:"ip",value:n});let s$1=L(e.email),a=z.string().parse(e.password),c=await s.findOne({"emails.address":s$1,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l$1=c?.authMethods?.password?.hash,d=l$1||cn,u=await hr.compare(a,d);if(!l$1||!u)throw ln();if(!c.emails?.find(g=>g.address.toLowerCase()===s$1)?.verified&&sn())throw new b$2("Your email address hasn't been verified yet. Please check your inbox for the verification email.","EMAIL_NOT_VERIFIED");return await l(r.authToken,c._id),i&&p(i,r.authToken),w().onAfterLogin?.({provider:"email",user:c,session:r,connectionInfo:o}),w().login?.onSuccess?.(c),{user:G(c),session:{authToken:r.authToken}}}catch(n){throw n instanceof Error&&(w().onLoginError?.({provider:"email",error:n,session:r,connectionInfo:o}),w().login?.onError?.(n)),n}}async function yr(e,{session:t,res:r}){if(!t)throw new Error("Session is not initialized");await m(t.authToken),r&&q(r);}function ln(){return new Error("Incorrect email/password combination")}var fe=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 rt=[];function Er(e){if(rt.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");rt=e;}async function k(e){let{bucket:t,type:r,value:o,message:i}=e,n=rt.filter(a=>a.bucket===t&&a.type===r),s=i?()=>new d$1(i):void 0;for(let a of n)await dn(a,o,s);}async function dn(e,t,r){let o=()=>r?r():new d$1(`Rate limit exceeded for ${e.bucket}`),i=await fe.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),n=Date.now(),s=Math.floor(n/e.window)*e.window,{count:a,modifier:c}=i?un(i,s,n):{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 o();await fe.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function un(e,t,r){let o=t-e.windowMs;if(e.windowStart.getTime()===t){let i=e.windowCount,n=e.prevWindowCount,s=1-(r-t)/e.windowMs;return {count:Math.round(i+n*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===o){let i=1-(r-t)/e.windowMs;return {count:Math.round(e.windowCount*i),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)}}}}async function br(e,{user:t}){if(!t)throw new b$2("Not authenticated");let r=await s.requireById(t.id);return {handle:r.handle,emails:r.emails,authMethods:Object.keys(r.authMethods||{}),firstName:r.firstName??void 0,lastName:r.lastName??void 0,avatarUrl:r.avatarUrl??void 0}}async function vr(e,{user:t}){if(!t)throw new b$2("Not authenticated");let r=await s.requireById(t.id),o=e,i=typeof o.handle=="string"&&o.handle.trim()===r.handle,{handle:n,...s$1}=o,a=Re(i?s$1:o);if(await w().validateProfileUpdate?.(a),"handle"in a&&a.handle!==void 0&&await s.findOne({handle:a.handle,_id:{$ne:r._id}},{collation:{locale:"en",strength:2}}))throw new c$1("Handle already taken.");if(Object.keys(a).length>0){await k({bucket:"updateProfile",type:"user",value:t.id});let c={},l={};for(let[u,m]of Object.entries(a))m===void 0?l[u]="":c[u]=m;let d={};Object.keys(c).length>0&&(d.$set=c),Object.keys(l).length>0&&(d.$unset=l);try{await s.updateOne({_id:r._id},d);let u=Object.fromEntries(Object.keys(l).map(m=>[m,void 0]));r={...r,...c,...u};}catch(u){throw u instanceof Error&&"code"in u&&u.code===11e3?new c$1("Handle already taken."):u}}return {user:G(r)}}var ot=["google","github"];async function Cr({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!ot.includes(e))throw new Error(`Invalid provider. Supported providers are: ${ot.join(", ")}.`);let r=await s.requireById(t.id),o=r.authMethods??{};if(!o[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(o).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s$1=Object.keys(o).filter(l=>l!==e&&o[l]),a=s$1.length>0?{$or:s$1.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await s.updateOne({_id:r._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}function kr({name:e,email:t,verificationUrl:r}){return `
|
|
3
3
|
<p>Hi${e?` ${e}`:""},</p>
|
|
4
4
|
<p>Please verify your email address ${t} by clicking the link below:</p>
|
|
@@ -30,12 +30,12 @@ Re-run with the --takeover flag (e.g. npm run dev -- --takeover) to disconnect i
|
|
|
30
30
|
|
|
31
31
|
This usually means \`postBuildCommand\` is set in modelence.config.ts, which replaces the default Vite client build (and the SSR build along with it). Either:
|
|
32
32
|
\u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
|
|
33
|
-
\u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:r}=await import('./transport-3V4KGAAU.js');r(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,r=[z$1.static(Ee,t)];return this.config?.publicDir&&r.push(z$1.static(this.config.publicDir,t)),r}async handler(t,r){if(this.ssrEnabled&&oi(t)){if(t.method==="HEAD"){r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.status(200).end();return}try{await this.handleSsr(t,r);}catch(o){if(this.isDev()&&this.viteServer&&o instanceof Error&&this.viteServer.ssrFixStacktrace(o),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:o}),r.headersSent){r.end();return}this.serveStaticShell(r);}return}if(this.ssrEnabled){r.status(404).end();return}this.serveStaticShell(r);}async handleSsr(t,r){let o=await this.getTemplate(t.originalUrl),i=await this.captureSsrSnapshot();if(!i)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:n},{getCallContext:s},a]=await Promise.all([import('./render-
|
|
33
|
+
\u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:r}=await import('./transport-3V4KGAAU.js');r(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,r=[z$1.static(Ee,t)];return this.config?.publicDir&&r.push(z$1.static(this.config.publicDir,t)),r}async handler(t,r){if(this.ssrEnabled&&oi(t)){if(t.method==="HEAD"){r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.status(200).end();return}try{await this.handleSsr(t,r);}catch(o){if(this.isDev()&&this.viteServer&&o instanceof Error&&this.viteServer.ssrFixStacktrace(o),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:o}),r.headersSent){r.end();return}this.serveStaticShell(r);}return}if(this.ssrEnabled){r.status(404).end();return}this.serveStaticShell(r);}async handleSsr(t,r){let o=await this.getTemplate(t.originalUrl),i=await this.captureSsrSnapshot();if(!i)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:n},{getCallContext:s},a]=await Promise.all([import('./render-RQCPSN7B.js'),import('./server-GF7ON6QY.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,r),l=this.collectCssAssets(a);si(r,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:u,getQueryState:m}=await n({callContext:c,loadingElement:i.loadingElement,routesElement:i.routesElement,router:i.router,location:t.originalUrl}),{prelude:g,rootOpenTag:y,epilogue:v}=ni(o),x=ii(g,a.renderStylesheetLinks(l));r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.status(200),r.write(x),r.write(`<script id="__MODELENCE_STATE__" type="application/json">${Rt(d)}</script>`),r.write(y),await u(r),r.write("</div>"),r.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${Rt(m())}</script>`),r.end(v);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,Co):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(Ee)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let r=Z.resolve(process.cwd(),"src/client/index.html"),o=Te.readFileSync(r,"utf-8");return this.viteServer&&(o=await this.viteServer.transformIndexHtml(t,o)),o}if(!this.prodTemplateCache){let r=Z.resolve(process.cwd(),Ee,"index.html");this.prodTemplateCache=Te.readFileSync(r,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-UF5FLZHD.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(Co),t()}return this.prodEntryLoaded||(await import(Z.resolve(process.cwd(),vo,"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(r){console.error("Error serving index.html:",r),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:Ee});}isDev(){return process.env.NODE_ENV!=="production"}};function oi(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 r=(e.path??e.url??"").split("?")[0];if(r.startsWith("/api/"))return false;let o=r.split("/").pop()??"",i=o.lastIndexOf(".");if(i>0){let n=o.slice(i).toLowerCase();if(n!==".html"&&n!==".htm")return false}return true}function ni(e){let t=e.match(ti);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let r=e.slice(0,t.index),o=e.slice(t.index+t[0].length);return {prelude:r,rootOpenTag:t[1],epilogue:o}}function ii(e,t){if(!t)return e;let r=e.lastIndexOf(ri);return r===-1?t+e:e.slice(0,r)+t+e.slice(r)}function si(e,t){if(t.length===0)return;let r=e;if(typeof r.writeEarlyHints=="function")try{r.writeEarlyHints({link:t});}catch(o){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",o);}}async function ai(){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 ci(e,t){let r=mergeConfig(e,t);if(r.plugins&&Array.isArray(r.plugins)){let o=new Set;r.plugins=r.plugins.flat().filter(i=>{if(!i||typeof i!="object"||Array.isArray(i))return true;let n=i.name;return !n||o.has(n)?false:(o.add(n),true)}).reverse(),r.plugins.reverse();}return r}async function li(e,t={}){let r=process.cwd(),o=await ai(),i=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>Te.existsSync(Z.join(r,a))),n=[ei(),di()];if(i){let a=(await import('vite-plugin-eslint')).default;n.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:r,overrideConfigFile:Z.resolve(r,i)}));}let s=defineConfig({plugins:n,build:{outDir:Ee,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":Z.resolve(r,"src").replace(/\\/g,"/")}}});return ci(s,o)}function di(){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 Me=new Ot;function ui(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function mi(e){if(e)return Array.isArray(e)?e:[e]}function pi(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:ui(e.from),replyTo:mi(e.replyTo)}}function fi(e){if(!(e instanceof Error))return new Error("Managed email send failed");let t=e.responseBody,r=t?.error?.code,o=t?.error?.message;return r&&o?new Error(`Managed email rejected (${r}): ${o}`):e}var ko={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 P("/api/email/send","POST",pi(e));}catch(t){throw fi(t)}}};var xt=Object.freeze({});function So(e){xt=Object.freeze(Object.assign({},xt,e));}function Ie(){return xt}var _t=Object.freeze({});function Ao(e){_t=Object.freeze(Object.assign({},_t,e));}function Ne(){return _t}async function yi({modules:e=[],roles:t={},defaultRoles:r$1={},server:o=Me,migrations:i=[],email:n={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&o===Me&&Me.enableSsr(),Ro.config(),Ro.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;_i().then(()=>{}).catch(()=>{});for(let ee of e)if(ee.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${ee.name}'
|
|
34
34
|
|
|
35
35
|
The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
|
|
36
36
|
|
|
37
|
-
Rename your module to something that does not start with '_system.'`);let u=[gt,r,fo,wo,yo,ue,St,Eo],m=[...u,...e];f(),bi(u),Ei(e),x(t,r$1);let g$1=Ri(m);e$1(g$1);let y=vi(m),v=Ci(m);Oi(m),gt.rateLimits=ft(s.rateLimits);let x$1=ki(m);Er(x$1);let{storesToInit:T,effectiveStores:S}=go(y);if(d){let{configs:ee,environmentId:Vo,appAlias:Go,environmentAlias:Fo,telemetry:zo}=await Zr({configSchema:g$1,cronJobsMetadata:po(),stores:S,roles:t});bt(ee),g({environmentId:Vo,appAlias:Go,environmentAlias:Fo,telemetry:zo});}else c$2(Ue(g$1));if(d&&!n.provider?et({...n,provider:ko}):et(n),gr(s),So(a),Ao({...c,provider:c.provider||ar}),N()){await ir();let ee=[...new Set([...T,...S])];xi(ee),await Ai(S,i);}else ho(i);d&&(await i$1(),ro()),mo().catch(console.error),await Oo(o,{combinedModules:m,channels:v});}function Ei(e){for(let t of e){for(let[r,o]of Object.entries(t.queries))C(`${t.name}.${r}`,o);for(let[r,o]of Object.entries(t.mutations))D(`${t.name}.${r}`,o);}}function bi(e){for(let t of e){for(let[r,o]of Object.entries(t.queries))E$1(`${t.name}.${r}`,o);for(let[r,o]of Object.entries(t.mutations))F(`${t.name}.${r}`,o);}}function vi(e){return e.flatMap(t=>t.stores)}function Ci(e){return e.flatMap(t=>t.channels)}function ki(e){return e.flatMap(t=>t.rateLimits)}function Si(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var Lt="migrations";async function Ai(e,t){if(!await X(Lt,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let o,i;try{o=e.filter(a=>a.getIndexCreationMode()==="blocking"),i=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of o)await Ut(a,"full");for(let a of i)await Ut(a,"drop-only");}catch(a){throw await we(Lt),a}let n=(async()=>{for(let a of i)await Ut(a,"create-only");})(),s=At(t,{lockMode:"skip"});Promise.allSettled([n,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 we(Lt);});}async function Ut(e,t="full"){let r=e.getName();try{await e.createIndexes(t);}catch(o){Si(r,o);}}function Ri(e){let t={};for(let r of e)for(let[o,i]of Object.entries(r.configSchema)){let n=`${r.name}.${o}`;if(n in t)throw new Error(`Duplicate config schema key: ${n} (${r.name})`);t[n]=i;}return t}function Oi(e){for(let t of e)for(let[r,o]of Object.entries(t.cronJobs))uo(`${t.name}.${r}`,o);}function xi(e){let t=Se();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let r of e)r.init(t);}async function _i(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",r=process.env.MODELENCE_ENVIRONMENT_ID,o=await Li(),i=await import('./package-QH4HNRJF.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:o.name,version:i.default.version,localHostname:Xr.hostname(),environmentId:r})});}}async function Li(){try{let e=Z.join(process.cwd(),"package.json"),t=await gi.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function xo(e){await u.deleteMany({userId:e}),await v.deleteMany({userId:e});let t=await s.findOne({_id:e}),r=Array.from(new Set((t?.emails??[]).map(o=>o.address?.toLowerCase()).filter(o=>!!o)));r.length>0&&await w$1.deleteMany({email:{$in:r}});}async function Pi(e){await xo(e),await s.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Ti(e){await xo(e),await s.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Pt=class{constructor(t,r){this.category=t,this.canAccessChannel=r||null;}broadcast(t,r){let o=Ne().provider;if(!o){m$1("Websockets provider should be added to startApp",{});return}o.broadcast({category:this.category,id:t,data:r});}};function Mi(e){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(e)}var _o=new Set(["javascript:","data:","file:","vbscript:","blob:"]);function Lo(e){try{return new URL(e)}catch{return null}}function De(){let e=String(a$2("_system.user.auth.mobile.redirectUrls")??"").split(/[\n,]/).map(r=>r.trim()).filter(Boolean),t=(w().mobile?.redirectUrls??[]).map(r=>String(r).trim()).filter(Boolean);return [...new Set([...e,...t])]}function Tt(e){if(!e||typeof e!="string")return false;let t=Lo(e);return !t||_o.has(t.protocol.toLowerCase())||Uo(t)?false:De().some(r=>{let o=Lo(r);return !o||_o.has(o.protocol.toLowerCase())||Uo(o)?false:t.protocol.toLowerCase()===o.protocol.toLowerCase()&&t.host.toLowerCase()===o.host.toLowerCase()&&Po(t.pathname)===Po(o.pathname)})}function Uo(e){return e.username!==""||e.password!==""}function Po(e){let t=e.replace(/\/+$/,"");return t===""?"/":t}var Ii=["code","error","errorCode","linked"];function $e(e,t){let r=new URL(e);for(let o of Ii)r.searchParams.delete(o);for(let[o,i]of Object.entries(t))r.searchParams.set(o,i);return r.toString()}function je(e){return e.platform==="mobile"&&e.redirectUri?{platform:"mobile",redirectUri:e.redirectUri,...e.codeChallenge?{codeChallenge:e.codeChallenge}:{}}:{platform:"web"}}function $i(e){return e.platform==="mobile"&&typeof e.codeChallenge=="string"}function Mo(e){return e.platform!=="mobile"}async function ji(e){return !e||typeof e!="string"?null:g$1(e)}function E(e,t,r,o={platform:"web"},i="oauth_failed"){if(o.platform==="mobile")return e.set("Referrer-Policy","no-referrer"),e.redirect($e(o.redirectUri,{error:r,errorCode:i}));let n=w(),s=e.status(t);if(n.errorComponent)try{let a=n.errorComponent({error:r,statusCode:t});if(a)return s.send(a)}catch(a){console.error("Unhandled error in authConfig.errorComponent:",a);}return s.json({error:r})}async function Mt(e,t,r,o$1={platform:"web"}){if(o$1.platform==="mobile"){if(!$i(o$1)){E(e,400,"This sign-in could not be completed. Please try signing in again.",o$1,"invalid_state");return}let n=await h(t.toString(),r,o$1.codeChallenge);e.set("Referrer-Policy","no-referrer"),e.redirect($e(o$1.redirectUri,{code:n}));return}let{authToken:i}=await o(t);p(e,i),e.redirect("/");}async function Hi(e,t,r,o,i,n){let s$1=w();try{if(r.status==="disabled"||r.status==="deleted"){E(e,400,"User account is not active.",n);return}let a={};r.firstName===void 0&&t.firstName&&(a.firstName=t.firstName),r.lastName===void 0&&t.lastName&&(a.lastName=t.lastName),r.avatarUrl===void 0&&t.avatarUrl&&(a.avatarUrl=t.avatarUrl);let c=r;Object.keys(a).length>0&&(await s.updateOne({_id:r._id},{$set:a}),c={...r,...a}),await Mt(e,r._id,t.providerName,n),Mo(n)&&(s$1.onAfterLogin?.({provider:t.providerName,user:c,session:o,connectionInfo:i}),s$1.login?.onSuccess?.(c));}catch(a){throw a instanceof Error&&(s$1.login?.onError?.(a),s$1.onLoginError?.({provider:t.providerName,error:a,session:o,connectionInfo:i})),a}}async function Bi(e,t,r,o,i,n){let s$1=w();if((s$1.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(r.status==="disabled"||r.status==="deleted"){E(e,400,"User account is not active.",n);return}if(!r.emails?.find(l=>l.address.toLowerCase()===t.email.toLowerCase())?.verified){E(e,400,"User with this email already exists. Please log in instead.",n);return}try{let l={...r.firstName===void 0&&t.firstName&&{firstName:t.firstName},...r.lastName===void 0&&t.lastName&&{lastName:t.lastName},...r.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await s.updateOne({_id:r._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,...l}})).matchedCount>0)){E(e,400,"User with this email already exists. Please log in instead.",n);return}await Mt(e,r._id,t.providerName,n);let m={...r,...l,authMethods:{...r.authMethods,[t.providerName]:{id:t.id}}};Mo(n)&&(s$1.onAfterLogin?.({provider:t.providerName,user:m,session:o,connectionInfo:i}),s$1.login?.onSuccess?.(m));return}catch(l){throw l instanceof Error&&(s$1.login?.onError?.(l),s$1.onLoginError?.({provider:t.providerName,error:l,session:o,connectionInfo:i})),l}}E(e,400,"User with this email already exists. Please log in instead.",n);}async function Vi(e,t,r,o,i){let n=w();try{let s$1;if(n.generateHandle){let d=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});s$1=await U(d,t.email,{throwOnConflict:!1});}else s$1=await U(void 0,t.email);let a={handle:s$1,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}},c=await s.insertOne(a);await Mt(e,c.insertedId,t.providerName,i);let l=await s.findOne({_id:c.insertedId},{readPreference:"primary"});l&&(n.onAfterSignup?.({provider:t.providerName,user:l,session:r,connectionInfo:o}),n.signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:s,session:r,connectionInfo:o}),n.signup?.onError?.(s)),s}}function se(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function He(e,t,r,o={platform:"web"}){let i=await s.findOne({[`authMethods.${r.providerName}.id`]:r.id}),{session:n,connectionInfo:s$1}=await ae(e,t);if(i)return Hi(t,r,i,n,s$1,o);if(!r.email){E(t,400,`Email address is required for ${r.providerName} authentication.`,o);return}let a;try{a=await s.findOne({"emails.address":r.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(c){if(c instanceof Error){let l=w();l.onSignupError?.({provider:r.providerName,error:c,session:n,connectionInfo:s$1}),l.signup?.onError?.(c);}throw c}return a?Bi(t,r,a,n,s$1,o):Vi(t,r,n,s$1,o)}function O(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function ie(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Gi(e){let{state:t,mode:r,linkedUserId:o,platform:i="web",redirectUri:n,codeChallenge:s}=e,a=[t,r,o??""];return (i!=="web"||n)&&(a.push(i),a.push(n?Buffer.from(n,"utf8").toString("base64url"):""),a.push(s??"")),a.join(":")}function Io(e){let[t,r,o,i,n,s]=(e||"").split(":"),a=n&&Buffer.from(n,"base64url").toString("utf8")||void 0;return {stateValue:t,mode:r||"login",...o?{linkedUserId:o}:{},platform:i==="mobile"?"mobile":"web",...a?{redirectUri:a}:{},...s?{codeChallenge:s}:{}}}function Be(e,t,r){let o=e.query.state,i=e.cookies[r],n=Io(i||""),s=No(n);return !o||!i||o!==n.stateValue?(E(t,400,"Invalid OAuth state - possible CSRF attack",s??{platform:"web"},"invalid_state"),null):(t.clearCookie(r),n.platform==="mobile"&&!s?(E(t,400,"Invalid OAuth redirect target.",{platform:"web"},"invalid_redirect"),null):{mode:n.mode,...n.linkedUserId?{linkedUserId:n.linkedUserId}:{},platform:n.platform,...n.redirectUri?{redirectUri:n.redirectUri}:{},...n.codeChallenge?{codeChallenge:n.codeChallenge}:{}})}function No(e){return e.platform!=="mobile"||!e.redirectUri||!Tt(e.redirectUri)?null:{platform:"mobile",redirectUri:e.redirectUri}}function Ve(e,t){return No(Io(e.cookies?.[t]||""))}function Fi(e){if(De().length===0)return "Mobile sign-in is not configured: auth.mobile.redirectUrls is empty. Add your app's deep link (e.g. 'myapp://auth') to enable it.";let r;try{r=new URL(e).protocol.toLowerCase();}catch{return "This redirectUri is not a valid URL. Pass your app's deep link, e.g. 'myapp://auth', and list it in auth.mobile.redirectUrls."}return r==="http:"||r==="https:"||r==="exp:"?"This redirectUri is not in auth.mobile.redirectUrls. Add it verbatim. Note that Linking.createURL returns a different value per build target \u2014 your app's scheme in a native build, an https URL on Expo Web, an exp:// URL in Expo Go \u2014 so each one you test needs its own entry.":"This redirectUri is not in auth.mobile.redirectUrls. Add it verbatim \u2014 entries match on scheme, host and path, so a differing path or port is a different target."}function zi(e,t,r){if(e.query.platform!=="mobile")return {ok:true,redirectUri:null,codeChallenge:null};let o=typeof e.query.redirectUri=="string"?e.query.redirectUri:"";if(!o)return E(t,400,"A redirectUri is required for mobile authentication."),{ok:false};if(!Tt(o))return console.error(`[modelence] Rejected mobile OAuth redirectUri: ${JSON.stringify(o)}. Allowed: ${JSON.stringify(De())}`),E(t,400,Fi(o),void 0,"invalid_redirect"),{ok:false};let i=typeof e.query.codeChallenge=="string"?e.query.codeChallenge:"",n=/^[A-Za-z0-9._~-]{16,256}$/.test(i);return r!=="link"&&!n?(E(t,400,"This sign-in request is missing a valid codeChallenge. Update the Modelence client package \u2014 signInWithOAuth generates it automatically."),{ok:false}):{ok:true,redirectUri:o,codeChallenge:n?i:null}}async function Ge(e,t,r){let o=randomBytes(32).toString("hex"),i=e.query.mode==="link"?"link":"login",n=zi(e,t,i);if(!n.ok)return null;let{redirectUri:s,codeChallenge:a}=n,c=null;if(i==="link"&&e.query.linkNonce&&(c=await ji(e.query.linkNonce),!c))return E(t,401,"Invalid or expired link nonce for OAuth linking.",s?{platform:"mobile",redirectUri:s}:void 0,"invalid_link_nonce"),null;let l=Gi({state:o,mode:i,linkedUserId:c,platform:s?"mobile":"web",redirectUri:s,codeChallenge:a});return t.cookie(r,l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)}),{state:o,mode:i}}async function Fe(e,t,r,o,i={platform:"web"}){let n=w(),{session:s$1,connectionInfo:a}=await ae(e,t),c=null;if(o){if(!ObjectId.isValid(o)){O(t),E(t,400,"Invalid OAuth linking state.",i);return}c=new ObjectId(o);}else c=s$1?.userId??null;if(!c){O(t),E(t,401,"You must be signed in to link a provider.",i);return}let l=c;try{let d=`authMethods.${r.providerName}.id`;if((await s.updateOne({_id:l,status:{$nin:["deleted","disabled"]},$or:[{[d]:{$exists:!1}},{[d]:r.id}]},{$set:{[d]:r.id}})).matchedCount===0){let g=await s.findOne({_id:l});if(!g||g.status==="deleted"||g.status==="disabled"){ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:new Error("User account not found or not active"),session:s$1,connectionInfo:a})),O(t),E(t,400,"User account is not active.",i);return}let y=g?.authMethods?.[r.providerName]?.id;if(y&&y!==r.id){ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:new Error(`User already has a different ${r.providerName} account linked`),session:s$1,connectionInfo:a})),O(t),E(t,400,`You have already linked a different ${r.providerName} account.`,i);return}ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:new Error(`Unexpected OAuth linking state for ${r.providerName}`),session:s$1,connectionInfo:a})),O(t),E(t,400,`Unable to link ${r.providerName} account.`,i);return}let m=await s.findOne({_id:l},{readPreference:"primary"});if(m&&ie(()=>n.onAfterOAuthLink?.({provider:r.providerName,user:m,session:s$1,connectionInfo:a})),O(t),i.platform==="mobile"){t.set("Referrer-Policy","no-referrer"),t.redirect($e(i.redirectUri,{linked:r.providerName}));return}t.redirect("/");}catch(d){if(d instanceof MongoServerError&&d.code===11e3){ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:d,session:s$1,connectionInfo:a})),O(t),E(t,400,`This ${r.providerName} account is already linked to a different user.`,i);return}if(d instanceof Error&&ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:d,session:s$1,connectionInfo:a})),O(t),!t.headersSent)throw d}}function ze(e){return !e||typeof e!="string"?null:e}async function Wi(e,t,r,o){let i=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:r,redirect_uri:o,grant_type:"authorization_code"})});if(!i.ok)throw new Error(`Failed to exchange code for token: ${i.statusText}`);return i.json()}async function Ji(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 Ki(e,t){let r=ze(e.query.code);if(!r){E(t,400,"Missing authorization code",Ve(e,"authStateGoogle")??void 0,"missing_code");return}let o=Be(e,t,"authStateGoogle");if(!o)return;let{mode:i,linkedUserId:n}=o,s=je(o),a=String(a$2("_system.user.auth.google.clientId")),c=String(a$2("_system.user.auth.google.clientSecret")),l=se("google");try{let d=await Wi(r,a,c,l),u=await Ji(d.access_token),m={id:u.id,email:u.email,emailVerified:u.verified_email,providerName:"google",firstName:u.given_name||void 0,lastName:u.family_name||void 0,avatarUrl:u.picture||void 0};i==="link"?await Fe(e,t,m,n,s):await He(e,t,m,s);}catch(d){console.error("Google OAuth error:",d),i==="link"&&O(t),E(t,500,"Authentication failed",s);}}function Yi(){let e=Router(),t=(r,o,i)=>{let n=!!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(!n||!s||!a){E(o,503,"Google authentication is not configured");return}i();};return e.get("/api/_internal/auth/google",t,async(r,o)=>{let i=String(a$2("_system.user.auth.google.clientId")),n=se("google"),s=await Ge(r,o,"authStateGoogle");if(!s)return;let{state:a}=s,c=new URL("https://accounts.google.com/o/oauth2/v2/auth");c.searchParams.append("client_id",i),c.searchParams.append("redirect_uri",n),c.searchParams.append("response_type","code"),c.searchParams.append("scope","profile email"),c.searchParams.append("access_type","online"),c.searchParams.append("state",a),o.redirect(c.toString());}),e.get("/api/_internal/auth/google/callback",t,Ki),e}var Do=Yi;async function Qi(e,t,r,o){let i=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:r,code:e,redirect_uri:o})});if(!i.ok)throw new Error(`Failed to exchange code for token: ${i.statusText}`);return i.json()}async function Zi(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 es(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 ts(e,t){return e.email?e.email:(await es(t)).find(o=>o.primary&&o.verified)?.email??null}async function rs(e,t){let r=ze(e.query.code);if(!r){E(t,400,"Missing authorization code",Ve(e,"authStateGithub")??void 0,"missing_code");return}let o=Be(e,t,"authStateGithub");if(!o)return;let{mode:i,linkedUserId:n}=o,s=je(o),a=String(a$2("_system.user.auth.github.clientId")),c=String(a$2("_system.user.auth.github.clientSecret")),l=se("github");try{let d=await Qi(r,a,c,l),u=await Zi(d.access_token),m=await ts(u,d.access_token);if(!m){i==="link"&&O(t),E(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.",s);return}let g=u.name?u.name.trim().split(/\s+/):[],y=g[0]||void 0,v=g.length>1?g.slice(1).join(" "):void 0,x={id:String(u.id),email:m,emailVerified:!0,providerName:"github",firstName:y,lastName:v,avatarUrl:u.avatar_url||void 0};i==="link"?await Fe(e,t,x,n,s):await He(e,t,x,s);}catch(d){console.error("GitHub OAuth error:",d),i==="link"&&O(t),E(t,500,"Authentication failed",s);}}function os(){let e=Router(),t=(r,o,i)=>{let n=!!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(!n||!s||!a){E(o,503,"GitHub authentication is not configured");return}i();};return e.get("/api/_internal/auth/github",t,async(r,o)=>{let i=String(a$2("_system.user.auth.github.clientId")),n=se("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(u=>u.trim()).join(" "):"user:email",c=await Ge(r,o,"authStateGithub");if(!c)return;let{state:l}=c,d=new URL("https://github.com/login/oauth/authorize");d.searchParams.append("client_id",i),d.searchParams.append("redirect_uri",n),d.searchParams.append("scope",a),d.searchParams.append("state",l),o.redirect(d.toString());}),e.get("/api/_internal/auth/github/callback",t,rs),e}var $o=os;function jo(e,t,r){return async(o,i,n)=>{let s=o.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&N())try{let{session:l,user:d}=await z$2(s);a={session:l,user:d};}catch{}let c=n$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:j(o.query),body:j(o.body),params:j(o.params)});try{let l=await r({query:o.query,body:o.body,params:o.params,headers:o.headers,cookies:o.cookies,rawBody:Buffer.isBuffer(o.body)?o.body:void 0,req:o,res:i,next:n},a);c.end(),l&&(i.status(l.status||200),l.contentType&&i.setHeader("Content-Type",l.contentType),l.headers&&Object.entries(l.headers).forEach(([d,u])=>{i.setHeader(d,u);}),l.redirect?i.redirect(l.redirect):i.send(l.data));}catch(l){c.end("error"),l instanceof a$4?i.status(l.status).send(l.message):(console.error(`Error in route handler: ${o.path}`),console.error(l),i.status(500).send(String(l)));}}}function ss(e){let t=[];if(!e)return t.push(z$1.json({limit:"16mb"})),t.push(z$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let r=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(z$1.json(r));}if(e.urlencoded!==false){let r=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(z$1.urlencoded(r));}if(e.raw){let r=typeof e.raw=="object"?e.raw:{},o={limit:r.limit||"16mb",type:r.type||"*/*"};t.push(z$1.raw(o));}return t}function as(e,t){for(let r of t)for(let o of r.routes){let{path:i,handlers:n,body:s}=o,a=ss(s);Object.entries(n).forEach(([c,l])=>{e[c](i,...a,jo(c,i,l));});}}var Ho=false;async function Oo(e,{combinedModules:t,channels:r}){let o=z$1(),{trustedProxies:i}=Ie(),s=ms(process.env.MODELENCE_TRUSTED_PROXIES)??i;o.set("trust proxy",s===void 0?true:s),o.use(ns()),o.use(ds()),as(o,t),o.use(z$1.json({limit:"16mb"})),o.use(z$1.urlencoded({extended:true,limit:"16mb"})),o.use(Do()),o.use($o()),o.post("/api/_internal/auth/set-link-cookie",async(u,m)=>{let{session:g}=await ae(u,m);if(!g?.userId){m.status(401).json({error:"Not authenticated"});return}m.cookie("oauthLinkToken",g.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),m.json({ok:true});}),o.post("/api/_internal/auth/issue-link-nonce",async(u,m)=>{let{session:g}=await ae(u,m);if(!g?.userId){m.status(401).json({error:"Not authenticated"});return}let y=await f$1(String(g.userId));m.json({nonce:y});}),o.post("/api/_internal/method/:methodName(*)",async(u,m)=>{let g=u.params.methodName,y=await ae(u,m);try{let v=a$3(await G$1(g,u.body.args,y));m.json({data:v,typeMap:b$3(v)});}catch(v){cs(m,g,v);}});let a=is.createServer(o),c=Number(process.env.MODELENCE_KEEP_ALIVE_TIMEOUT_MS)||65e3;a.keepAliveTimeout=c,a.headersTimeout=c+5e3,await e.init({httpServer:a}),e.middlewares&&o.use(e.middlewares()),o.all("*",(u,m,g)=>{Promise.resolve(e.handler(u,m)).catch(g);}),Ho||(Ho=true,process.on("unhandledRejection",(u,m)=>{console.error("Unhandled Promise Rejection:"),console.error(u instanceof Error?u.stack:u),console.error("Promise:",m);}),process.on("uncaughtException",u=>{console.error("Uncaught Exception:"),console.error(u.stack),console.trace("Full application stack:");}));let l=Ne()?.provider;l&&l.init({httpServer:a,channels:r});let d=process.env.MODELENCE_PORT||process.env.PORT||3e3;a.listen(d,()=>{l$1("Application started",{source:"app"});let u=a$2("_system.site.url")||ge();console.log(`
|
|
37
|
+
Rename your module to something that does not start with '_system.'`);let u=[gt,r,fo,wo,yo,ue,St,Eo],m=[...u,...e];f(),bi(u),Ei(e),x(t,r$1);let g$1=Ri(m);e$1(g$1);let y=vi(m),v=Ci(m);Oi(m),gt.rateLimits=ft(s.rateLimits);let x$1=ki(m);Er(x$1);let{storesToInit:T,effectiveStores:S}=go(y);if(d){let{configs:ee,environmentId:Vo,appAlias:Go,environmentAlias:Fo,telemetry:zo}=await Zr({configSchema:g$1,cronJobsMetadata:po(),stores:S,roles:t});bt(ee),g({environmentId:Vo,appAlias:Go,environmentAlias:Fo,telemetry:zo});}else c$2(Ue(g$1));if(d&&!n.provider?et({...n,provider:ko}):et(n),gr(s),So(a),Ao({...c,provider:c.provider||ar}),N()){await ir();let ee=[...new Set([...T,...S])];xi(ee),await Ai(S,i);}else ho(i);d&&(await i$1(),ro()),mo().catch(console.error),await Oo(o,{combinedModules:m,channels:v});}function Ei(e){for(let t of e){for(let[r,o]of Object.entries(t.queries))C(`${t.name}.${r}`,o);for(let[r,o]of Object.entries(t.mutations))D(`${t.name}.${r}`,o);}}function bi(e){for(let t of e){for(let[r,o]of Object.entries(t.queries))E$1(`${t.name}.${r}`,o);for(let[r,o]of Object.entries(t.mutations))F(`${t.name}.${r}`,o);}}function vi(e){return e.flatMap(t=>t.stores)}function Ci(e){return e.flatMap(t=>t.channels)}function ki(e){return e.flatMap(t=>t.rateLimits)}function Si(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var Lt="migrations";async function Ai(e,t){if(!await X(Lt,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let o,i;try{o=e.filter(a=>a.getIndexCreationMode()==="blocking"),i=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of o)await Ut(a,"full");for(let a of i)await Ut(a,"drop-only");}catch(a){throw await we(Lt),a}let n=(async()=>{for(let a of i)await Ut(a,"create-only");})(),s=At(t,{lockMode:"skip"});Promise.allSettled([n,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 we(Lt);});}async function Ut(e,t="full"){let r=e.getName();try{await e.createIndexes(t);}catch(o){Si(r,o);}}function Ri(e){let t={};for(let r of e)for(let[o,i]of Object.entries(r.configSchema)){let n=`${r.name}.${o}`;if(n in t)throw new Error(`Duplicate config schema key: ${n} (${r.name})`);t[n]=i;}return t}function Oi(e){for(let t of e)for(let[r,o]of Object.entries(t.cronJobs))uo(`${t.name}.${r}`,o);}function xi(e){let t=Se();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let r of e)r.init(t);}async function _i(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",r=process.env.MODELENCE_ENVIRONMENT_ID,o=await Li(),i=await import('./package-PLJALKWH.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:o.name,version:i.default.version,localHostname:Xr.hostname(),environmentId:r})});}}async function Li(){try{let e=Z.join(process.cwd(),"package.json"),t=await gi.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function xo(e){await u.deleteMany({userId:e}),await v.deleteMany({userId:e});let t=await s.findOne({_id:e}),r=Array.from(new Set((t?.emails??[]).map(o=>o.address?.toLowerCase()).filter(o=>!!o)));r.length>0&&await w$1.deleteMany({email:{$in:r}});}async function Pi(e){await xo(e),await s.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Ti(e){await xo(e),await s.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Pt=class{constructor(t,r){this.category=t,this.canAccessChannel=r||null;}broadcast(t,r){let o=Ne().provider;if(!o){m$1("Websockets provider should be added to startApp",{});return}o.broadcast({category:this.category,id:t,data:r});}};function Mi(e){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(e)}var _o=new Set(["javascript:","data:","file:","vbscript:","blob:"]);function Lo(e){try{return new URL(e)}catch{return null}}function De(){let e=String(a$2("_system.user.auth.mobile.redirectUrls")??"").split(/[\n,]/).map(r=>r.trim()).filter(Boolean),t=(w().mobile?.redirectUrls??[]).map(r=>String(r).trim()).filter(Boolean);return [...new Set([...e,...t])]}function Tt(e){if(!e||typeof e!="string")return false;let t=Lo(e);return !t||_o.has(t.protocol.toLowerCase())||Uo(t)?false:De().some(r=>{let o=Lo(r);return !o||_o.has(o.protocol.toLowerCase())||Uo(o)?false:t.protocol.toLowerCase()===o.protocol.toLowerCase()&&t.host.toLowerCase()===o.host.toLowerCase()&&Po(t.pathname)===Po(o.pathname)})}function Uo(e){return e.username!==""||e.password!==""}function Po(e){let t=e.replace(/\/+$/,"");return t===""?"/":t}var Ii=["code","error","errorCode","linked"];function $e(e,t){let r=new URL(e);for(let o of Ii)r.searchParams.delete(o);for(let[o,i]of Object.entries(t))r.searchParams.set(o,i);return r.toString()}function je(e){return e.platform==="mobile"&&e.redirectUri?{platform:"mobile",redirectUri:e.redirectUri,...e.codeChallenge?{codeChallenge:e.codeChallenge}:{}}:{platform:"web"}}function $i(e){return e.platform==="mobile"&&typeof e.codeChallenge=="string"}function Mo(e){return e.platform!=="mobile"}async function ji(e){return !e||typeof e!="string"?null:g$1(e)}function E(e,t,r,o={platform:"web"},i="oauth_failed"){if(o.platform==="mobile")return e.set("Referrer-Policy","no-referrer"),e.redirect($e(o.redirectUri,{error:r,errorCode:i}));let n=w(),s=e.status(t);if(n.errorComponent)try{let a=n.errorComponent({error:r,statusCode:t});if(a)return s.send(a)}catch(a){console.error("Unhandled error in authConfig.errorComponent:",a);}return s.json({error:r})}async function Mt(e,t,r,o$1={platform:"web"}){if(o$1.platform==="mobile"){if(!$i(o$1)){E(e,400,"This sign-in could not be completed. Please try signing in again.",o$1,"invalid_state");return}let n=await h(t.toString(),r,o$1.codeChallenge);e.set("Referrer-Policy","no-referrer"),e.redirect($e(o$1.redirectUri,{code:n}));return}let{authToken:i}=await o(t);p(e,i),e.redirect("/");}async function Hi(e,t,r,o,i,n){let s$1=w();try{if(r.status==="disabled"||r.status==="deleted"){E(e,400,"User account is not active.",n);return}let a={};r.firstName===void 0&&t.firstName&&(a.firstName=t.firstName),r.lastName===void 0&&t.lastName&&(a.lastName=t.lastName),r.avatarUrl===void 0&&t.avatarUrl&&(a.avatarUrl=t.avatarUrl);let c=r;Object.keys(a).length>0&&(await s.updateOne({_id:r._id},{$set:a}),c={...r,...a}),await Mt(e,r._id,t.providerName,n),Mo(n)&&(s$1.onAfterLogin?.({provider:t.providerName,user:c,session:o,connectionInfo:i}),s$1.login?.onSuccess?.(c));}catch(a){throw a instanceof Error&&(s$1.login?.onError?.(a),s$1.onLoginError?.({provider:t.providerName,error:a,session:o,connectionInfo:i})),a}}async function Bi(e,t,r,o,i,n){let s$1=w();if((s$1.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(r.status==="disabled"||r.status==="deleted"){E(e,400,"User account is not active.",n);return}if(!r.emails?.find(l=>l.address.toLowerCase()===t.email.toLowerCase())?.verified){E(e,400,"User with this email already exists. Please log in instead.",n);return}try{let l={...r.firstName===void 0&&t.firstName&&{firstName:t.firstName},...r.lastName===void 0&&t.lastName&&{lastName:t.lastName},...r.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await s.updateOne({_id:r._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,...l}})).matchedCount>0)){E(e,400,"User with this email already exists. Please log in instead.",n);return}await Mt(e,r._id,t.providerName,n);let m={...r,...l,authMethods:{...r.authMethods,[t.providerName]:{id:t.id}}};Mo(n)&&(s$1.onAfterLogin?.({provider:t.providerName,user:m,session:o,connectionInfo:i}),s$1.login?.onSuccess?.(m));return}catch(l){throw l instanceof Error&&(s$1.login?.onError?.(l),s$1.onLoginError?.({provider:t.providerName,error:l,session:o,connectionInfo:i})),l}}E(e,400,"User with this email already exists. Please log in instead.",n);}async function Vi(e,t,r,o,i){let n=w();try{let s$1;if(n.generateHandle){let d=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});s$1=await U(d,t.email,{throwOnConflict:!1});}else s$1=await U(void 0,t.email);let a={handle:s$1,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}},c=await s.insertOne(a);await Mt(e,c.insertedId,t.providerName,i);let l=await s.findOne({_id:c.insertedId},{readPreference:"primary"});l&&(n.onAfterSignup?.({provider:t.providerName,user:l,session:r,connectionInfo:o}),n.signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:s,session:r,connectionInfo:o}),n.signup?.onError?.(s)),s}}function se(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function He(e,t,r,o={platform:"web"}){let i=await s.findOne({[`authMethods.${r.providerName}.id`]:r.id}),{session:n,connectionInfo:s$1}=await ae(e,t);if(i)return Hi(t,r,i,n,s$1,o);if(!r.email){E(t,400,`Email address is required for ${r.providerName} authentication.`,o);return}let a;try{a=await s.findOne({"emails.address":r.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(c){if(c instanceof Error){let l=w();l.onSignupError?.({provider:r.providerName,error:c,session:n,connectionInfo:s$1}),l.signup?.onError?.(c);}throw c}return a?Bi(t,r,a,n,s$1,o):Vi(t,r,n,s$1,o)}function O(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function ie(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Gi(e){let{state:t,mode:r,linkedUserId:o,platform:i="web",redirectUri:n,codeChallenge:s}=e,a=[t,r,o??""];return (i!=="web"||n)&&(a.push(i),a.push(n?Buffer.from(n,"utf8").toString("base64url"):""),a.push(s??"")),a.join(":")}function Io(e){let[t,r,o,i,n,s]=(e||"").split(":"),a=n&&Buffer.from(n,"base64url").toString("utf8")||void 0;return {stateValue:t,mode:r||"login",...o?{linkedUserId:o}:{},platform:i==="mobile"?"mobile":"web",...a?{redirectUri:a}:{},...s?{codeChallenge:s}:{}}}function Be(e,t,r){let o=e.query.state,i=e.cookies[r],n=Io(i||""),s=No(n);return !o||!i||o!==n.stateValue?(E(t,400,"Invalid OAuth state - possible CSRF attack",s??{platform:"web"},"invalid_state"),null):(t.clearCookie(r),n.platform==="mobile"&&!s?(E(t,400,"Invalid OAuth redirect target.",{platform:"web"},"invalid_redirect"),null):{mode:n.mode,...n.linkedUserId?{linkedUserId:n.linkedUserId}:{},platform:n.platform,...n.redirectUri?{redirectUri:n.redirectUri}:{},...n.codeChallenge?{codeChallenge:n.codeChallenge}:{}})}function No(e){return e.platform!=="mobile"||!e.redirectUri||!Tt(e.redirectUri)?null:{platform:"mobile",redirectUri:e.redirectUri}}function Ve(e,t){return No(Io(e.cookies?.[t]||""))}function Fi(e){if(De().length===0)return "Mobile sign-in is not configured: auth.mobile.redirectUrls is empty. Add your app's deep link (e.g. 'myapp://auth') to enable it.";let r;try{r=new URL(e).protocol.toLowerCase();}catch{return "This redirectUri is not a valid URL. Pass your app's deep link, e.g. 'myapp://auth', and list it in auth.mobile.redirectUrls."}return r==="http:"||r==="https:"||r==="exp:"?"This redirectUri is not in auth.mobile.redirectUrls. Add it verbatim. Note that Linking.createURL returns a different value per build target \u2014 your app's scheme in a native build, an https URL on Expo Web, an exp:// URL in Expo Go \u2014 so each one you test needs its own entry.":"This redirectUri is not in auth.mobile.redirectUrls. Add it verbatim \u2014 entries match on scheme, host and path, so a differing path or port is a different target."}function zi(e,t,r){if(e.query.platform!=="mobile")return {ok:true,redirectUri:null,codeChallenge:null};let o=typeof e.query.redirectUri=="string"?e.query.redirectUri:"";if(!o)return E(t,400,"A redirectUri is required for mobile authentication."),{ok:false};if(!Tt(o))return console.error(`[modelence] Rejected mobile OAuth redirectUri: ${JSON.stringify(o)}. Allowed: ${JSON.stringify(De())}`),E(t,400,Fi(o),void 0,"invalid_redirect"),{ok:false};let i=typeof e.query.codeChallenge=="string"?e.query.codeChallenge:"",n=/^[A-Za-z0-9._~-]{16,256}$/.test(i);return r!=="link"&&!n?(E(t,400,"This sign-in request is missing a valid codeChallenge. Update the Modelence client package \u2014 signInWithOAuth generates it automatically."),{ok:false}):{ok:true,redirectUri:o,codeChallenge:n?i:null}}async function Ge(e,t,r){let o=randomBytes(32).toString("hex"),i=e.query.mode==="link"?"link":"login",n=zi(e,t,i);if(!n.ok)return null;let{redirectUri:s,codeChallenge:a}=n,c=null;if(i==="link"&&e.query.linkNonce&&(c=await ji(e.query.linkNonce),!c))return E(t,401,"Invalid or expired link nonce for OAuth linking.",s?{platform:"mobile",redirectUri:s}:void 0,"invalid_link_nonce"),null;let l=Gi({state:o,mode:i,linkedUserId:c,platform:s?"mobile":"web",redirectUri:s,codeChallenge:a});return t.cookie(r,l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)}),{state:o,mode:i}}async function Fe(e,t,r,o,i={platform:"web"}){let n=w(),{session:s$1,connectionInfo:a}=await ae(e,t),c=null;if(o){if(!ObjectId.isValid(o)){O(t),E(t,400,"Invalid OAuth linking state.",i);return}c=new ObjectId(o);}else c=s$1?.userId??null;if(!c){O(t),E(t,401,"You must be signed in to link a provider.",i);return}let l=c;try{let d=`authMethods.${r.providerName}.id`;if((await s.updateOne({_id:l,status:{$nin:["deleted","disabled"]},$or:[{[d]:{$exists:!1}},{[d]:r.id}]},{$set:{[d]:r.id}})).matchedCount===0){let g=await s.findOne({_id:l});if(!g||g.status==="deleted"||g.status==="disabled"){ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:new Error("User account not found or not active"),session:s$1,connectionInfo:a})),O(t),E(t,400,"User account is not active.",i);return}let y=g?.authMethods?.[r.providerName]?.id;if(y&&y!==r.id){ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:new Error(`User already has a different ${r.providerName} account linked`),session:s$1,connectionInfo:a})),O(t),E(t,400,`You have already linked a different ${r.providerName} account.`,i);return}ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:new Error(`Unexpected OAuth linking state for ${r.providerName}`),session:s$1,connectionInfo:a})),O(t),E(t,400,`Unable to link ${r.providerName} account.`,i);return}let m=await s.findOne({_id:l},{readPreference:"primary"});if(m&&ie(()=>n.onAfterOAuthLink?.({provider:r.providerName,user:m,session:s$1,connectionInfo:a})),O(t),i.platform==="mobile"){t.set("Referrer-Policy","no-referrer"),t.redirect($e(i.redirectUri,{linked:r.providerName}));return}t.redirect("/");}catch(d){if(d instanceof MongoServerError&&d.code===11e3){ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:d,session:s$1,connectionInfo:a})),O(t),E(t,400,`This ${r.providerName} account is already linked to a different user.`,i);return}if(d instanceof Error&&ie(()=>n.onOAuthLinkError?.({provider:r.providerName,error:d,session:s$1,connectionInfo:a})),O(t),!t.headersSent)throw d}}function ze(e){return !e||typeof e!="string"?null:e}async function Wi(e,t,r,o){let i=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:r,redirect_uri:o,grant_type:"authorization_code"})});if(!i.ok)throw new Error(`Failed to exchange code for token: ${i.statusText}`);return i.json()}async function Ji(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 Ki(e,t){let r=ze(e.query.code);if(!r){E(t,400,"Missing authorization code",Ve(e,"authStateGoogle")??void 0,"missing_code");return}let o=Be(e,t,"authStateGoogle");if(!o)return;let{mode:i,linkedUserId:n}=o,s=je(o),a=String(a$2("_system.user.auth.google.clientId")),c=String(a$2("_system.user.auth.google.clientSecret")),l=se("google");try{let d=await Wi(r,a,c,l),u=await Ji(d.access_token),m={id:u.id,email:u.email,emailVerified:u.verified_email,providerName:"google",firstName:u.given_name||void 0,lastName:u.family_name||void 0,avatarUrl:u.picture||void 0};i==="link"?await Fe(e,t,m,n,s):await He(e,t,m,s);}catch(d){console.error("Google OAuth error:",d),i==="link"&&O(t),E(t,500,"Authentication failed",s);}}function Yi(){let e=Router(),t=(r,o,i)=>{let n=!!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(!n||!s||!a){E(o,503,"Google authentication is not configured");return}i();};return e.get("/api/_internal/auth/google",t,async(r,o)=>{let i=String(a$2("_system.user.auth.google.clientId")),n=se("google"),s=await Ge(r,o,"authStateGoogle");if(!s)return;let{state:a}=s,c=new URL("https://accounts.google.com/o/oauth2/v2/auth");c.searchParams.append("client_id",i),c.searchParams.append("redirect_uri",n),c.searchParams.append("response_type","code"),c.searchParams.append("scope","profile email"),c.searchParams.append("access_type","online"),c.searchParams.append("state",a),o.redirect(c.toString());}),e.get("/api/_internal/auth/google/callback",t,Ki),e}var Do=Yi;async function Qi(e,t,r,o){let i=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:r,code:e,redirect_uri:o})});if(!i.ok)throw new Error(`Failed to exchange code for token: ${i.statusText}`);return i.json()}async function Zi(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 es(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 ts(e,t){return e.email?e.email:(await es(t)).find(o=>o.primary&&o.verified)?.email??null}async function rs(e,t){let r=ze(e.query.code);if(!r){E(t,400,"Missing authorization code",Ve(e,"authStateGithub")??void 0,"missing_code");return}let o=Be(e,t,"authStateGithub");if(!o)return;let{mode:i,linkedUserId:n}=o,s=je(o),a=String(a$2("_system.user.auth.github.clientId")),c=String(a$2("_system.user.auth.github.clientSecret")),l=se("github");try{let d=await Qi(r,a,c,l),u=await Zi(d.access_token),m=await ts(u,d.access_token);if(!m){i==="link"&&O(t),E(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.",s);return}let g=u.name?u.name.trim().split(/\s+/):[],y=g[0]||void 0,v=g.length>1?g.slice(1).join(" "):void 0,x={id:String(u.id),email:m,emailVerified:!0,providerName:"github",firstName:y,lastName:v,avatarUrl:u.avatar_url||void 0};i==="link"?await Fe(e,t,x,n,s):await He(e,t,x,s);}catch(d){console.error("GitHub OAuth error:",d),i==="link"&&O(t),E(t,500,"Authentication failed",s);}}function os(){let e=Router(),t=(r,o,i)=>{let n=!!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(!n||!s||!a){E(o,503,"GitHub authentication is not configured");return}i();};return e.get("/api/_internal/auth/github",t,async(r,o)=>{let i=String(a$2("_system.user.auth.github.clientId")),n=se("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(u=>u.trim()).join(" "):"user:email",c=await Ge(r,o,"authStateGithub");if(!c)return;let{state:l}=c,d=new URL("https://github.com/login/oauth/authorize");d.searchParams.append("client_id",i),d.searchParams.append("redirect_uri",n),d.searchParams.append("scope",a),d.searchParams.append("state",l),o.redirect(d.toString());}),e.get("/api/_internal/auth/github/callback",t,rs),e}var $o=os;function jo(e,t,r){return async(o,i,n)=>{let s=o.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&N())try{let{session:l,user:d}=await z$2(s);a={session:l,user:d};}catch{}let c=n$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:j(o.query),body:j(o.body),params:j(o.params)});try{let l=await r({query:o.query,body:o.body,params:o.params,headers:o.headers,cookies:o.cookies,rawBody:Buffer.isBuffer(o.body)?o.body:void 0,req:o,res:i,next:n},a);c.end(),l&&(i.status(l.status||200),l.contentType&&i.setHeader("Content-Type",l.contentType),l.headers&&Object.entries(l.headers).forEach(([d,u])=>{i.setHeader(d,u);}),l.redirect?i.redirect(l.redirect):i.send(l.data));}catch(l){c.end("error"),l instanceof a$4?i.status(l.status).send(l.message):(console.error(`Error in route handler: ${o.path}`),console.error(l),i.status(500).send(String(l)));}}}function ss(e){let t=[];if(!e)return t.push(z$1.json({limit:"16mb"})),t.push(z$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let r=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(z$1.json(r));}if(e.urlencoded!==false){let r=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(z$1.urlencoded(r));}if(e.raw){let r=typeof e.raw=="object"?e.raw:{},o={limit:r.limit||"16mb",type:r.type||"*/*"};t.push(z$1.raw(o));}return t}function as(e,t){for(let r of t)for(let o of r.routes){let{path:i,handlers:n,body:s}=o,a=ss(s);Object.entries(n).forEach(([c,l])=>{e[c](i,...a,jo(c,i,l));});}}var Ho=false;async function Oo(e,{combinedModules:t,channels:r}){let o=z$1(),{trustedProxies:i}=Ie(),s=ms(process.env.MODELENCE_TRUSTED_PROXIES)??i;o.set("trust proxy",s===void 0?true:s),o.use(ns()),o.use(ds()),as(o,t),o.use(z$1.json({limit:"16mb"})),o.use(z$1.urlencoded({extended:true,limit:"16mb"})),o.use(Do()),o.use($o()),o.post("/api/_internal/auth/set-link-cookie",async(u,m)=>{let{session:g}=await ae(u,m);if(!g?.userId){m.status(401).json({error:"Not authenticated"});return}m.cookie("oauthLinkToken",g.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),m.json({ok:true});}),o.post("/api/_internal/auth/issue-link-nonce",async(u,m)=>{let{session:g}=await ae(u,m);if(!g?.userId){m.status(401).json({error:"Not authenticated"});return}let y=await f$1(String(g.userId));m.json({nonce:y});}),o.post("/api/_internal/method/:methodName(*)",async(u,m)=>{let g=u.params.methodName,y=await ae(u,m);try{let v=a$3(await G$1(g,u.body.args,y));m.json({data:v,typeMap:b$3(v)});}catch(v){cs(m,g,v);}});let a=is.createServer(o),c=Number(process.env.MODELENCE_KEEP_ALIVE_TIMEOUT_MS)||65e3;a.keepAliveTimeout=c,a.headersTimeout=c+5e3,await e.init({httpServer:a}),e.middlewares&&o.use(e.middlewares()),o.all("*",(u,m,g)=>{Promise.resolve(e.handler(u,m)).catch(g);}),Ho||(Ho=true,process.on("unhandledRejection",(u,m)=>{console.error("Unhandled Promise Rejection:"),console.error(u instanceof Error?u.stack:u),console.error("Promise:",m);}),process.on("uncaughtException",u=>{console.error("Uncaught Exception:"),console.error(u.stack),console.trace("Full application stack:");}));let l=Ne()?.provider;l&&l.init({httpServer:a,channels:r});let d=process.env.MODELENCE_PORT||process.env.PORT||3e3;a.listen(d,()=>{l$1("Application started",{source:"app"});let u=a$2("_system.site.url")||ge();console.log(`
|
|
38
38
|
Application started on ${u}
|
|
39
|
-
`),b$1()&&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
|
|
40
|
-
export{k as a,qn as b,Wn as c,Jn as d,Kn as e,Oo as f,ae as g,yi as h,Pi as i,Ti as j,Pt as k,Mi as l};//# sourceMappingURL=chunk-
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
39
|
+
`),b$1()&&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 ae(e,t=null){let r=(e.path??e.url??"").split("?")[0],o=r.startsWith("/api/_internal/auth/")&&r.endsWith("/callback"),i=e.body??{},n=F$1.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(o?e.cookies.oauthLinkToken:null)||i.authToken),s=F$1.object({screenWidth:F$1.number(),screenHeight:F$1.number(),windowWidth:F$1.number(),windowHeight:F$1.number(),pixelRatio:F$1.number(),orientation:F$1.string().nullable()}).nullish().parse(i.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:fs(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:us(e)};if(!!N()){let{session:l,user:d,roles:u}=await z$2(n);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:y(),req:e,res:t}}function cs(e,t,r){if(r instanceof a$4){r.status>=500&&r.status<600&&console.error(`Error calling ${t}:`,r),r.code&&e.setHeader("X-Modelence-Error-Code",r.code),e.status(r.status).send(r.message);return}if(r instanceof Error&&r?.constructor?.name==="ZodError"&&"errors"in r){let o="";try{o=ls(r);}catch(i){console.error(`Error parsing Zod error in ${t}:`,i),o="Validation failed";}e.status(400).send(o);return}console.error(`Error calling ${t}:`,r),e.status(500).send(r instanceof Error?r.message:String(r));}function ls(e){let t=e.flatten(),r=Object.entries(t.fieldErrors).map(([n,s])=>`${n}: ${(s??[]).join(", ")}`),o=t.formErrors;return [...r,...o].filter(Boolean).join("; ")}function ds(){let{frameAncestors:e}=Ie(),t=e&&e.length>0,r=t?["'self'",...e].join(" "):"'self'";return (o,i,n)=>{i.setHeader("Content-Security-Policy",`frame-ancestors ${r}`),t||i.setHeader("X-Frame-Options","SAMEORIGIN"),n();}}function us(e){let t=e.headers["x-forwarded-host"],r=(Array.isArray(t)?t[0]:t?.split(",")[0])?.trim()||e.get("host");return `${e.protocol}://${r}`}function ms(e){let t=e?.split(",").map(r=>r.trim()).filter(r=>r.length>0);return t?.length?t:void 0}function ps(e){let t=e.socket?.remoteAddress;if(!t)return false;let r=e.app?.get?.("trust proxy fn");return typeof r!="function"?e.app?.get?.("trust proxy")!==false:!!r(t,0)}function fs(e){let{clientIpHeader:t}=Ie();if(t&&ps(e)){let o=e.headers[t.toLowerCase()],i=(Array.isArray(o)?o[0]:o)?.trim();if(i)return Bo(i)}let r=e.ip||e.socket?.remoteAddress;if(r)return Bo(r)}function Bo(e){return e.startsWith("::ffff:")?e.substring(7):e}
|
|
40
|
+
export{k as a,qn as b,Wn as c,Jn as d,Kn as e,Oo as f,ae as g,yi as h,Pi as i,Ti as j,Pt as k,Mi as l};//# sourceMappingURL=chunk-6FAEWW7A.js.map
|
|
41
|
+
//# sourceMappingURL=chunk-6FAEWW7A.js.map
|