modelence 0.22.0 → 0.23.0-setup.dev.1
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 +4 -3
- package/dist/bin/modelence.js.map +1 -1
- package/dist/bson.d-M1rp21TC.d.ts +137 -0
- package/dist/{chunk-VF4RU7MF.js → chunk-B5WLEHNH.js} +2 -2
- package/dist/{chunk-VF4RU7MF.js.map → chunk-B5WLEHNH.js.map} +1 -1
- package/dist/chunk-B7EXKTEZ.js +3 -0
- package/dist/chunk-B7EXKTEZ.js.map +1 -0
- package/dist/chunk-I25TKIJW.js +37 -0
- package/dist/chunk-I25TKIJW.js.map +1 -0
- package/dist/chunk-MTG3OZWX.js +2 -0
- package/dist/chunk-MTG3OZWX.js.map +1 -0
- package/dist/chunk-PGNYB3ZP.js +3 -0
- package/dist/chunk-PGNYB3ZP.js.map +1 -0
- package/dist/{chunk-PJRYLKYW.js → chunk-SIKRUWRN.js} +2 -2
- package/dist/{chunk-PJRYLKYW.js.map → chunk-SIKRUWRN.js.map} +1 -1
- package/dist/chunk-VW6ML4HX.js +2 -0
- package/dist/chunk-VW6ML4HX.js.map +1 -0
- package/dist/chunk-VYR7VQMQ.js +2 -0
- package/dist/chunk-VYR7VQMQ.js.map +1 -0
- package/dist/chunk-WHC2SP5P.js +4 -0
- package/dist/chunk-WHC2SP5P.js.map +1 -0
- package/dist/client.d.ts +88 -6
- package/dist/client.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{package-RFIDFU5I.js → package-XAQYEUWG.js} +2 -2
- package/dist/{package-RFIDFU5I.js.map → package-XAQYEUWG.js.map} +1 -1
- package/dist/render-RN75WGWX.js +2 -0
- package/dist/{render-CBIFY4DG.js.map → render-RN75WGWX.js.map} +1 -1
- package/dist/renderApp-DDIZBBPN.js +2 -0
- package/dist/{renderApp-J347DR2B.js.map → renderApp-DDIZBBPN.js.map} +1 -1
- package/dist/server-46L3FOLX.js +2 -0
- package/dist/{server-LA5VRAGR.js.map → server-46L3FOLX.js.map} +1 -1
- package/dist/server.d.ts +4 -137
- package/dist/server.js +1 -1
- package/dist/telemetry.js +1 -1
- package/dist/transport-JPOZOWQ6.js +2 -0
- package/dist/{transport-C7DEK6NV.js.map → transport-JPOZOWQ6.js.map} +1 -1
- package/package.json +1 -1
- package/dist/chunk-4L4E6PFO.js +0 -3
- package/dist/chunk-4L4E6PFO.js.map +0 -1
- package/dist/chunk-AMJHJA2V.js +0 -2
- package/dist/chunk-AMJHJA2V.js.map +0 -1
- package/dist/chunk-BCUSVRAY.js +0 -2
- package/dist/chunk-BCUSVRAY.js.map +0 -1
- package/dist/chunk-MIRF7FP3.js +0 -2
- package/dist/chunk-MIRF7FP3.js.map +0 -1
- package/dist/chunk-OFRRQZVE.js +0 -37
- package/dist/chunk-OFRRQZVE.js.map +0 -1
- package/dist/chunk-OJ3LMWVQ.js +0 -2
- package/dist/chunk-OJ3LMWVQ.js.map +0 -1
- package/dist/chunk-YOJ4ZP5D.js +0 -4
- package/dist/chunk-YOJ4ZP5D.js.map +0 -1
- package/dist/render-CBIFY4DG.js +0 -2
- package/dist/renderApp-J347DR2B.js +0 -2
- package/dist/server-LA5VRAGR.js +0 -2
- package/dist/transport-C7DEK6NV.js +0 -2
package/dist/bin/modelence.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import {readFileSync,promises,createWriteStream
|
|
3
|
-
`);await promises.
|
|
4
|
-
`)
|
|
2
|
+
import {Command}from'commander';import {readFileSync,promises,createWriteStream}from'fs';import {fileURLToPath}from'url';import P,{dirname,join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import z$1 from'open';import B from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ue from'archiver';async function E(e,{pickEnvironment:o=false}={}){let t=await fetch(`${e}/api/cli/auth`,{method:"POST"});if(!t.ok)throw new Error("Failed to create CLI authentication code");let{code:r,verificationUrl:s}=await t.json(),n=o?`${s}&pick=environment`:s;return console.log(`Please visit ${n} to authenticate`),console.log(`Code: ${r}`),await z$1(n),{token:await J(e,r)}}async function J(e,o){let s=Date.now()+6e5;for(;Date.now()<s;){try{let n=await q(e,o);if(n)return n}catch(n){console.error("Error polling for CLI token:",n);}await new Promise(n=>setTimeout(n,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function q(e,o){let t=await fetch(`${e}/api/cli/token?code=${o}`,{method:"GET"});if(!t.ok)throw new Error(`CLI token polling failed: ${t.statusText}`);let{token:r}=await t.json();return r}var S=".modelence.env",x=".modelence",N="project.json";async function K(e,o){let t="setupToken"in o?{"X-Modelence-Setup-Token":o.setupToken}:{Authorization:`Bearer ${o.cliToken}`},r=await fetch(`${e}/api/setup`,{method:"GET",headers:t});if(!r.ok){let s=await r.text();throw new Error(s||`Request failed with status ${r.status}`)}return r.json()}async function X(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${S} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function Y(e){return String(e).replace(/"/g,'\\"')}async function H(e){let o=join(process.cwd(),x),t=join(o,N),r={};try{r=JSON.parse(await promises.readFile(t,"utf8"));}catch{}await promises.mkdir(o,{recursive:true}),await promises.writeFile(t,JSON.stringify({...r,appId:e},null,2)+`
|
|
3
|
+
`);}async function Q(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function O(e){try{let o=join(process.cwd(),S),t={},r=!1;try{let a=await promises.readFile(o,"utf8");t=parse(a),r=!0,await Q(o),await X()||(console.log("Setup canceled"),process.exit(0));}catch{}let s;if(e.token)s={setupToken:e.token};else {let{token:a}=await E(e.host,{pickEnvironment:!0});s={cliToken:a};}console.log("Fetching service configuration...");let n=await K(e.host,s),c={...t,MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:n.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:n.serviceToken,MODELENCE_CONTAINER_ID:n.containerId},i=Object.entries(c).map(([a,f])=>`${a}="${Y(f)}"`).join(`
|
|
4
|
+
`);if(await promises.writeFile(o,i.trim()+`
|
|
5
|
+
`),console.log(`Successfully configured ${S} file`),n.appId)try{await H(n.appId),console.log(`Recorded the app ID in ${x}/${N}`);}catch(a){console.warn(`Failed to record the app ID in ${x}/${N}:`,a);}r&&console.log("The project now points to a different environment. Restart your dev server, and if you use an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.");}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var oe=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()});async function $(){let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:true,requireCache:false}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");return oe.parse(t)}var y=null,T=null;function re(){if(!y)throw new Error("Environment variables not loaded");return y}function M(){if(!T)throw new Error("Configuration not loaded");return T}function j(e){return `${re().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function p(){let{serverDir:e,serverEntry:o}=M();return join(e,o).replace(/\\/g,"/")}function I(){return M().postBuildCommand}function C(e){let o=D("build");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}function u(e){return join(process.cwd(),e).replace(/\\/g,"/")}function D(e){let o=u(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function w(){try{T=await $();}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await B.readFile(join(process.cwd(),".modelence.env"),"utf-8");y=parse(e);}catch(e){if(e.code==="ENOENT")y={};else throw e}}async function ce(){let e=I();if(e){console.log("Running post-build command..."),execSync(e);return}await ae(),await le();}async function ae(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:P.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true,ssrManifest:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function le(){console.log("Building SSR bundle with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{ssr:P.resolve(process.cwd(),"src/client/index.tsx").replace(/\\/g,"/"),outDir:P.resolve(process.cwd(),".modelence/build/ssr").replace(/\\/g,"/"),emptyOutDir:true,rollupOptions:{output:{format:"esm",entryFileNames:"index.mjs"}}}};await build$1(mergeConfig(e?.config||{},t,true));}async function de(){return console.log("Building server with tsup..."),new Promise(e=>{build({entry:[p()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,skipNodeModulesBundle:true,treeshake:true,platform:"node",outExtension:()=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function b(){console.log("Building Modelence project...");try{let e=C();await B.rm(e,{recursive:!0,force:!0}),await de(),await ce(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await B.access(D());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function L(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip"),s=e.host||j("");await b(),await me(r);let{token:n}=await E(s),{bundleName:c}=await fe(e.app,e.env,r,n,s);await promises.unlink(r),await ge(e.app,e.env,c,join(".modelence","build","app.mjs"),n,s);}async function me(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=ue("zip",{zlib:{level:9}});t.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),t.on("error",i=>{throw i});let r=new Promise((i,a)=>{o.on("close",i),o.on("error",a),t.on("error",a);});t.pipe(o);let s=["package.json","next.config.js","next.config.ts","modelence.config.ts"],n=["public","server",join(".modelence","build"),".next"];for(let i of s)await promises.access(u(i)).then(()=>true).catch(()=>false)&&t.file(u(i),{name:i});for(let i of n)await promises.access(u(i)).then(()=>true).catch(()=>false)&&t.directory(u(i),i);await t.finalize(),await r;let c=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(c.size/1024/1024).toFixed(2)} MB)`);}async function fe(e,o,t,r,s){let n=await fetch(`${s}/api/upload-bundle`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!n.ok)throw console.error(await n.text()),new Error(`Failed to create upload URL: ${n.statusText}`);let{uploadUrl:c,bundleName:i}=await n.json(),a=await promises.readFile(t),f=await fetch(c,{method:"PUT",body:new Uint8Array(a),headers:{"Content-Type":"application/zip"}});if(!f.ok)throw new Error(`Failed to upload bundle: ${f.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${i}`),{bundleName:i}}async function ge(e,o,t,r,s,n){let c=await fetch(`${n}/api/deploy`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!c.ok)throw new Error(`Failed to trigger deployment: ${c.statusText}`);let{deploymentUrl:i}=await c.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${i}`);}function V(){console.log("Starting Modelence dev server...");let e=p(),o=P.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch --ignore "vite.config.ts.timestamp-*" "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}function A(){console.log("Starting Modelence production server...");let e=p(),o=P.basename(e,P.extname(e)),t=C(`${o}.mjs`);execSync(`node "${t}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"production"}});}var Se=fileURLToPath(import.meta.url),xe=dirname(Se),Ne=JSON.parse(readFileSync(join(xe,"../../package.json"),"utf-8")),m=new Command().name("modelence").description("Modelence CLI tool").version(Ne.version);m.command("setup").description("Setup Modelence environment variables").option("-t, --token <token>","Modelence setup token (omit to authorize in the browser)").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await O(e);});m.command("build").description("Build the application").action(async()=>{await w(),await b();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").option("-h, --host <host>","Modelence host").action(async e=>{await w(),await L(e);});m.command("dev").description("Start development server").action(async()=>{await w(),V();});m.command("start").description("Start production server").action(async()=>{await w(),A();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
|
|
5
6
|
//# sourceMappingURL=modelence.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","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","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","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":";ueAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,EAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,MAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MAClB,CAAC,EAED,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BF,CAAAA,CAAG,QAAA,CACD,CAAA,SAAA,EAAYP,CAAkB,CAAA,oDAAA,CAAA,CAC7BU,CAAAA,EAAW,CACVH,CAAAA,CAAG,KAAA,EAAM,CACTE,CAAAA,CAAQC,EAAO,WAAA,EAAY,GAAM,GAAG,EACtC,CACF,EACF,CAAC,CACH,CAEA,SAASC,CAAAA,CAAeC,CAAAA,CAAgC,CAEtD,OAAO,MAAA,CAAOA,CAAK,CAAA,CAAE,QAAQ,IAAA,CAAM,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AAO,EACf,WAAA,CAAY,yBAAyB,EACrC,MAAA,CAAO,SAAY,CAClB,MAAM9D,CAAAA,GACNqD,CAAAA,GACF,CAAC,CAAA,CAEHS,CAAAA,CAAQ,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\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\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\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\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 // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n } 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 open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli(host: string) {\n // TODO: check if a token already exists in .modelence/auth.json\n\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\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(verificationUrl);\n\n const token = await waitForAuth(host, code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\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 { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pickEnvironment","response","code","verificationUrl","url","open","waitForAuth","pollExpireTs","token","pollForToken","error","resolve","MODELENCE_ENV_FILE","MODELENCE_DIR","PROJECT_FILE","fetchServiceConfig","auth","headers","errorText","confirmOverwrite","rl","createInterface","answer","escapeEnvValue","value","recordProjectAppId","appId","dirPath","join","projectPath","existing","fs","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getEnv","getConfig","getStudioUrl","path","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","tsupBuild","build","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","reject","bundleFiles","bundleDirs","file","dir","stats","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","__filename","fileURLToPath","__dirname","dirname","packageJson","readFileSync","program","Command"],"mappings":";0dAaA,eAAsBA,EACpBC,CAAAA,CACA,CAAE,gBAAAC,CAAAA,CAAkB,KAAM,EAAmC,EAAC,CAClC,CAC5B,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGF,CAAI,CAAA,aAAA,CAAA,CAAiB,CACnD,OAAQ,MACV,CAAC,EAED,GAAI,CAACE,EAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,KAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,CAAA,CAAI,MAAMF,EAAS,IAAA,EAAK,CAChDG,EAAMJ,CAAAA,CAAkB,CAAA,EAAGG,CAAe,CAAA,iBAAA,CAAA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B,0DAA0D,EACxF,MAAA,CAAO,mBAAA,CAAqB,iBAAkB,6BAA6B,CAAA,CAC3E,MAAA,CAAO,MAAOnF,GAAY,CACzB,MAAMD,EAAMC,CAAO,EACrB,CAAC,CAAA,CAEHmF,CAAAA,CACG,OAAA,CAAQ,OAAO,EACf,WAAA,CAAY,uBAAuB,EACnC,MAAA,CAAO,SAAY,CAClB,MAAMrD,CAAAA,EAAQ,CACd,MAAMc,IACR,CAAC,EAEHuC,CAAAA,CACG,OAAA,CAAQ,QAAQ,CAAA,CAChB,WAAA,CAAY,2BAA2B,CAAA,CACvC,eAAe,iBAAA,CAAmB,mBAAmB,EACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,MAAA,CAAO,mBAAA,CAAqB,gBAAgB,EAC5C,MAAA,CAAO,MAAOnF,GAAY,CACzB,MAAM8B,GAAQ,CACd,MAAMe,CAAAA,CAAO7C,CAAO,EACtB,CAAC,CAAA,CAEHmF,EACG,OAAA,CAAQ,KAAK,EACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAMrD,GAAQ,CACdyC,CAAAA,GACF,CAAC,CAAA,CAEHY,CAAAA,CACG,OAAA,CAAQ,OAAO,CAAA,CACf,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CAAO,SAAY,CAClB,MAAMrD,CAAAA,EAAQ,CACd4C,IACF,CAAC,EAEHS,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization. The returned token is short-lived and\n user-scoped; commands re-authorize on every run, so no credential is ever\n stored on disk.\n\n With `pickEnvironment`, the approval page also asks the user to choose an\n environment. The choice never travels back through the CLI — the server\n stamps it on the token itself, and /api/setup derives the target from\n there, so the authorization is only good for the environment the user\n approved.\n*/\nexport async function authenticateCli(\n host: string,\n { pickEnvironment = false }: { pickEnvironment?: boolean } = {}\n): Promise<{ token: string }> {\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n const url = pickEnvironment ? `${verificationUrl}&pick=environment` : verificationUrl;\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n await open(url);\n\n const token = await waitForAuth(host, code);\n\n return { token };\n}\n\nasync function waitForAuth(host: string, code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(host, code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(host: string, code: string) {\n const response = await fetch(`${host}/api/cli/token?code=${code}`, {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { authenticateCli } from './auth';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\nconst MODELENCE_DIR = '.modelence';\nconst PROJECT_FILE = 'project.json';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `,\n (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n }\n );\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like cache/ are\n temporary), so the whole team gets it. It's a hint in the git-remote sense —\n connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value.\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n const dirPath = join(process.cwd(), MODELENCE_DIR);\n const projectPath = join(dirPath, PROJECT_FILE);\n\n let existing: Record<string, unknown> = {};\n try {\n existing = JSON.parse(await fs.readFile(projectPath, 'utf8'));\n } catch {\n // Missing or malformed — start fresh.\n }\n\n await fs.mkdir(dirPath, { recursive: true });\n await fs.writeFile(projectPath, JSON.stringify({ ...existing, appId }, null, 2) + '\\n');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, { pickEnvironment: true });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n if (fileExisted) {\n // Anything that read the old file holds stale credentials: the dev\n // server loads it at boot, and MCP connections send its token per\n // connection.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, reconnect its Modelence MCP server (in Claude Code: /mcp) or start a new session.'\n );\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getProjectPath, getStudioUrl } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { app: string; env: string; host?: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n const host = options.host || getStudioUrl('');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli(host);\n\n const { bundleName } = await uploadBundle(options.app, options.env, bundlePath, token, host);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(\n options.app,\n options.env,\n bundleName,\n join('.modelence', 'build', 'app.mjs'),\n token,\n host\n );\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 }, // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = ['package.json', 'next.config.js', 'next.config.ts', 'modelence.config.ts'];\n\n const bundleDirs = ['public', 'server', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (\n await fs\n .access(getProjectPath(file))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (\n await fs\n .access(getProjectPath(dir))\n .then(() => true)\n .catch(() => false)\n ) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(\n `Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`\n );\n}\n\nasync function uploadBundle(\n appAlias: string,\n envAlias: string,\n bundlePath: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/upload-bundle`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n }),\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(\n appAlias: string,\n envAlias: string,\n bundleName: string,\n entryPoint: string,\n token: string,\n host: string\n) {\n const response = await fetch(`${host}/api/deploy`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'development' },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { start } from './start';\nimport { loadEnv } from './config';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageJson = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version(packageJson.version);\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .option('-t, --token <token>', 'Modelence setup token (omit to authorize in the browser)')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/** @public */
|
|
2
|
+
declare abstract class BSONValue {
|
|
3
|
+
/** @public */
|
|
4
|
+
abstract get _bsontype(): string;
|
|
5
|
+
/* Excluded from this release type: [BSON_VERSION_SYMBOL] */
|
|
6
|
+
/**
|
|
7
|
+
* @public
|
|
8
|
+
* Prints a human-readable string of BSON value information
|
|
9
|
+
* If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
|
|
10
|
+
*/
|
|
11
|
+
abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
|
|
12
|
+
/* Excluded from this release type: toExtendedJSON */
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
declare type InspectFn = (x: unknown, options?: unknown) => string;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A class representation of the BSON ObjectId type.
|
|
19
|
+
* @public
|
|
20
|
+
* @category BSONType
|
|
21
|
+
*/
|
|
22
|
+
declare class ObjectId extends BSONValue {
|
|
23
|
+
get _bsontype(): 'ObjectId';
|
|
24
|
+
/* Excluded from this release type: index */
|
|
25
|
+
static cacheHexString: boolean;
|
|
26
|
+
/* Excluded from this release type: buffer */
|
|
27
|
+
/**
|
|
28
|
+
* Create ObjectId from a number.
|
|
29
|
+
*
|
|
30
|
+
* @param inputId - A number.
|
|
31
|
+
* @deprecated Instead, use `static createFromTime()` to set a numeric value for the new ObjectId.
|
|
32
|
+
*/
|
|
33
|
+
constructor(inputId: number);
|
|
34
|
+
/**
|
|
35
|
+
* Create ObjectId from a 24 character hex string.
|
|
36
|
+
*
|
|
37
|
+
* @param inputId - A 24 character hex string.
|
|
38
|
+
*/
|
|
39
|
+
constructor(inputId: string);
|
|
40
|
+
/**
|
|
41
|
+
* Create ObjectId from the BSON ObjectId type.
|
|
42
|
+
*
|
|
43
|
+
* @param inputId - The BSON ObjectId type.
|
|
44
|
+
*/
|
|
45
|
+
constructor(inputId: ObjectId);
|
|
46
|
+
/**
|
|
47
|
+
* Create ObjectId from the object type that has the toHexString method.
|
|
48
|
+
*
|
|
49
|
+
* @param inputId - The ObjectIdLike type.
|
|
50
|
+
*/
|
|
51
|
+
constructor(inputId: ObjectIdLike);
|
|
52
|
+
/**
|
|
53
|
+
* Create ObjectId from a 12 byte binary Buffer.
|
|
54
|
+
*
|
|
55
|
+
* @param inputId - A 12 byte binary Buffer.
|
|
56
|
+
*/
|
|
57
|
+
constructor(inputId: Uint8Array);
|
|
58
|
+
/** To generate a new ObjectId, use ObjectId() with no argument. */
|
|
59
|
+
constructor();
|
|
60
|
+
/**
|
|
61
|
+
* Implementation overload.
|
|
62
|
+
*
|
|
63
|
+
* @param inputId - All input types that are used in the constructor implementation.
|
|
64
|
+
*/
|
|
65
|
+
constructor(inputId?: string | number | ObjectId | ObjectIdLike | Uint8Array);
|
|
66
|
+
/**
|
|
67
|
+
* The ObjectId bytes
|
|
68
|
+
* @readonly
|
|
69
|
+
*/
|
|
70
|
+
get id(): Uint8Array;
|
|
71
|
+
set id(value: Uint8Array);
|
|
72
|
+
/* Excluded from this release type: validateHexString */
|
|
73
|
+
/** Returns the ObjectId id as a 24 lowercase character hex string representation */
|
|
74
|
+
toHexString(): string;
|
|
75
|
+
/* Excluded from this release type: getInc */
|
|
76
|
+
/**
|
|
77
|
+
* Generate a 12 byte id buffer used in ObjectId's
|
|
78
|
+
*
|
|
79
|
+
* @param time - pass in a second based timestamp.
|
|
80
|
+
*/
|
|
81
|
+
static generate(time?: number): Uint8Array;
|
|
82
|
+
/**
|
|
83
|
+
* Converts the id into a 24 character hex string for printing, unless encoding is provided.
|
|
84
|
+
* @param encoding - hex or base64
|
|
85
|
+
*/
|
|
86
|
+
toString(encoding?: 'hex' | 'base64'): string;
|
|
87
|
+
/** Converts to its JSON the 24 character hex string representation. */
|
|
88
|
+
toJSON(): string;
|
|
89
|
+
/* Excluded from this release type: is */
|
|
90
|
+
/**
|
|
91
|
+
* Compares the equality of this ObjectId with `otherID`.
|
|
92
|
+
*
|
|
93
|
+
* @param otherId - ObjectId instance to compare against.
|
|
94
|
+
*/
|
|
95
|
+
equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean;
|
|
96
|
+
/** Returns the generation date (accurate up to the second) that this ID was generated. */
|
|
97
|
+
getTimestamp(): Date;
|
|
98
|
+
/* Excluded from this release type: createPk */
|
|
99
|
+
/* Excluded from this release type: serializeInto */
|
|
100
|
+
/**
|
|
101
|
+
* Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
|
|
102
|
+
*
|
|
103
|
+
* @param time - an integer number representing a number of seconds.
|
|
104
|
+
*/
|
|
105
|
+
static createFromTime(time: number): ObjectId;
|
|
106
|
+
/**
|
|
107
|
+
* Creates an ObjectId from a hex string representation of an ObjectId.
|
|
108
|
+
*
|
|
109
|
+
* @param hexString - create a ObjectId from a passed in 24 character hexstring.
|
|
110
|
+
*/
|
|
111
|
+
static createFromHexString(hexString: string): ObjectId;
|
|
112
|
+
/** Creates an ObjectId instance from a base64 string */
|
|
113
|
+
static createFromBase64(base64: string): ObjectId;
|
|
114
|
+
/**
|
|
115
|
+
* Checks if a value can be used to create a valid bson ObjectId
|
|
116
|
+
* @param id - any JS value
|
|
117
|
+
*/
|
|
118
|
+
static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean;
|
|
119
|
+
/* Excluded from this release type: toExtendedJSON */
|
|
120
|
+
/* Excluded from this release type: fromExtendedJSON */
|
|
121
|
+
/* Excluded from this release type: isCached */
|
|
122
|
+
/**
|
|
123
|
+
* Converts to a string representation of this Id.
|
|
124
|
+
*
|
|
125
|
+
* @returns return the 24 character hex string representation.
|
|
126
|
+
*/
|
|
127
|
+
inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** @public */
|
|
131
|
+
declare interface ObjectIdLike {
|
|
132
|
+
id: string | Uint8Array;
|
|
133
|
+
__id?: string;
|
|
134
|
+
toHexString(): string;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export { ObjectId as O };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import P from'elastic-apm-node';import v from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import l from'process';var f={},L={},S=false;function d(t){return L[t]?.value??f[t]?.default}function G(){if(!S)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(f).filter(([t,e])=>e.isPublic).map(([t,e])=>[t,{key:t,type:e.type,value:L[t]?.value??e.default}]))}function Y(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!f[e]||(L[e]={key:e,type:o,value:n});}),S=true;}function $(){return f}function F(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:r}=o;if(n==="secret"&&r)throw new Error(`Config ${e} with type "secret" cannot be public`)}),f=t;}var s={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function I({elasticCloudId:t,elasticApiKey:e}){let o=l.stdout.write,n=l.stderr.write;l.stdout.write=function(r,...i){return h(r.toString(),s.stdout),o.call(l.stdout,r,...i)},l.stderr.write=function(r,...i){return h(r.toString(),s.stderr),n.call(l.stderr,r,...i)},T();}function h(t,e){if(t.length===0)return;let o=new Date;for(let n=0;n<t.length;n++){let r=e[e.length-1];r.timestamp||(r.timestamp=o,r.sequenceId=z++),t[n]===`
|
|
2
|
-
`?e.push({log:"",timestamp:null}):r.log+=t[n];}}async function N(){let t=s.stdout.slice(0,-1);s.stdout=[s.stdout[s.stdout.length-1]];let e=s.stderr.slice(0,-1);s.stderr=[s.stderr[s.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:r})=>{b(o,{timestamp:n,source:"console",sequenceId:r});}),e.forEach(({log:o,timestamp:n,sequenceId:r})=>{w(o,{timestamp:n,source:"console",sequenceId:r});});}function T(){setTimeout(()=>{N(),T();},1e3);}var c=null;function Z(){}function tt(t){c=Object.assign({},c,t);}function j(){return c?.environmentId}function K(){return c?.appAlias}function R(){return c?.environmentAlias}function M(){return c?.telemetry?.serviceName}function a(){return !!c?.telemetry?.isEnabled}var _=false,p=null,m=null,ct=async()=>{if(_)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');_=true,a()&&await W();};async function W(){let t=d("_system.elastic.apmEndpoint"),e=d("_system.elastic.cloudId"),o=d("_system.elastic.apiKey"),n=K()??"unknown",r=R()??"unknown",i=j()??"unknown",g=M();p=P.start({serviceName:g,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:i,appAlias:n,environmentAlias:r}});let u=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});u.on("error",O=>{console.error("Elasticsearch Transport Error:",O);}),m=v.createLogger({level:"debug",defaultMeta:{serviceName:g},format:v.format.combine(v.format.json()),transports:[u]}),I({elasticCloudId:e,elasticApiKey:o});}function A(){if(!p)throw new Error("APM is not initialized");return p}function y(){return m!==null}function E(){if(!m)throw new Error("Logger is not initialized");return m}var k=["token","password","secret","nonce","code"];function C(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(C);let e={};for(let[o,n]of Object.entries(t)){let r=k.some(i=>o.toLowerCase().includes(i));e[o]=r?"[redacted]":C(n);}return e}function x(){let t="";return a()||(t="info"),process.env.MODELENCE_LOG_LEVEL||t}function q(t,e){a()&&y()&&E().debug(t,e),x()==="debug"&&console.debug(t,e);}function b(t,e){a()&&y()&&E().info(t,e),["debug","info"].includes(x())&&console.info(t,e);}function w(t,e){a()&&y()&&E().error(t,e),["debug","info","error"].includes(x())&&console.error(t,e);}function U(t,e,o){if(!a())return {end:()=>{},setContext:()=>{}};let n=A(),r=n.startTransaction(e,t);return o&&n.setCustomContext(o),{end:(i,{endTime:g,context:u}={})=>{u&&n.setCustomContext(u),r.end(i,g);},setContext:i=>{n.setCustomContext(i);}}}function V(t){if(!a()){console.error(t);return}A().captureError(t);}export{d as a,G as b,Y as c,$ as d,F as e,Z as f,tt as g,
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
`?e.push({log:"",timestamp:null}):r.log+=t[n];}}async function N(){let t=s.stdout.slice(0,-1);s.stdout=[s.stdout[s.stdout.length-1]];let e=s.stderr.slice(0,-1);s.stderr=[s.stderr[s.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:r})=>{b(o,{timestamp:n,source:"console",sequenceId:r});}),e.forEach(({log:o,timestamp:n,sequenceId:r})=>{w(o,{timestamp:n,source:"console",sequenceId:r});});}function T(){setTimeout(()=>{N(),T();},1e3);}var c=null;function Z(){}function tt(t){c=Object.assign({},c,t);}function j(){return c?.environmentId}function K(){return c?.appAlias}function R(){return c?.environmentAlias}function M(){return c?.telemetry?.serviceName}function a(){return !!c?.telemetry?.isEnabled}var _=false,p=null,m=null,ct=async()=>{if(_)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');_=true,a()&&await W();};async function W(){let t=d("_system.elastic.apmEndpoint"),e=d("_system.elastic.cloudId"),o=d("_system.elastic.apiKey"),n=K()??"unknown",r=R()??"unknown",i=j()??"unknown",g=M();p=P.start({serviceName:g,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:i,appAlias:n,environmentAlias:r}});let u=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});u.on("error",O=>{console.error("Elasticsearch Transport Error:",O);}),m=v.createLogger({level:"debug",defaultMeta:{serviceName:g},format:v.format.combine(v.format.json()),transports:[u]}),I({elasticCloudId:e,elasticApiKey:o});}function A(){if(!p)throw new Error("APM is not initialized");return p}function y(){return m!==null}function E(){if(!m)throw new Error("Logger is not initialized");return m}var k=["token","password","secret","nonce","code"];function C(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(C);let e={};for(let[o,n]of Object.entries(t)){let r=k.some(i=>o.toLowerCase().includes(i));e[o]=r?"[redacted]":C(n);}return e}function x(){let t="";return a()||(t="info"),process.env.MODELENCE_LOG_LEVEL||t}function q(t,e){a()&&y()&&E().debug(t,e),x()==="debug"&&console.debug(t,e);}function b(t,e){a()&&y()&&E().info(t,e),["debug","info"].includes(x())&&console.info(t,e);}function w(t,e){a()&&y()&&E().error(t,e),["debug","info","error"].includes(x())&&console.error(t,e);}function U(t,e,o){if(!a())return {end:()=>{},setContext:()=>{}};let n=A(),r=n.startTransaction(e,t);return o&&n.setCustomContext(o),{end:(i,{endTime:g,context:u}={})=>{u&&n.setCustomContext(u),r.end(i,g);},setContext:i=>{n.setCustomContext(i);}}}function V(t){if(!a()){console.error(t);return}A().captureError(t);}export{d as a,G as b,Y as c,$ as d,F as e,Z as f,tt as g,j as h,ct as i,C as j,q as k,b as l,w as m,U as n,V as o};//# sourceMappingURL=chunk-B5WLEHNH.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-B5WLEHNH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","getSchema","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","isLoggerReady","getLogger","SENSITIVE_KEYS","redactSensitive","result","val","isSensitive","k","getLogLevel","defaultLoglevel","logDebug","message","startTransaction","name","context","transaction","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAsCb,SAASC,EAAUC,CAAAA,CAAuD,CAC/E,OAAOH,CA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jC,CAAA,CACA,UAAA,CAAaF,CAAAA,EAAqC,CAChD/B,CAAAA,CAAI,gBAAA,CAAiB+B,CAAO,EAC9B,CACF,CACF,CAEO,SAASG,CAAAA,CAAapB,EAAc,CACzC,GAAI,CAACf,CAAAA,GAAsB,CACzB,OAAA,CAAQ,KAAA,CAAMe,CAAK,EACnB,MACF,CAEAE,GAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-VF4RU7MF.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n *\n * @param key - The configuration key to retrieve\n * @returns The configuration value (string, number, or boolean)\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the site URL\n * const siteUrl = getConfig('_system.site.url');\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_URL=https://myapp.com\n * ```\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the current environment (e.g., 'development', 'staging', 'production')\n * const env = getConfig('_system.env');\n *\n * if (env === 'production') {\n * // Enable production features\n * }\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_ENV=production\n * ```\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n return config[key]?.value ?? configSchema[key]?.default;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function getSchema() {\n return configSchema;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stdout.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stderr.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n void sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [esTransport],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function isLoggerReady() {\n return logger !== null;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm, isLoggerReady } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\ntype LogLevel = 'error' | 'info' | 'debug' | '';\n\n// Secret-bearing keys to scrub before request args/query/body reach the APM sink.\n// Matched case-insensitively as a substring (`authToken` matches `token`).\nconst SENSITIVE_KEYS = ['token', 'password', 'secret', 'nonce', 'code'];\n\n/**\n * Deep-copies `value`, replacing any {@link SENSITIVE_KEYS} match with\n * `'[redacted]'`. Non-object values pass through unchanged.\n */\nexport function redactSensitive(value: unknown): unknown {\n if (!value || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(redactSensitive);\n }\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n const isSensitive = SENSITIVE_KEYS.some((k) => key.toLowerCase().includes(k));\n result[key] = isSensitive ? '[redacted]' : redactSensitive(val);\n }\n return result;\n}\n\n/**\n * Gets the logging level for console logs based on the MODELENCE_LOG_LEVEL environment variable.\n *\n * @returns The log level ('error' | 'info' | 'debug' | '')\n *\n * Behavior:\n * - If MODELENCE_LOG_LEVEL is set, returns that value\n * - If telemetry is disabled and MODELENCE_LOG_LEVEL is not set, defaults to 'info'\n * - If telemetry is enabled and MODELENCE_LOG_LEVEL is not set, returns '' (no console logging)\n */\nfunction getLogLevel(): LogLevel {\n let defaultLoglevel: LogLevel = '';\n if (!isTelemetryEnabled()) {\n defaultLoglevel = 'info';\n }\n\n return (process.env.MODELENCE_LOG_LEVEL as LogLevel) || defaultLoglevel;\n}\n\nexport function logDebug(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().debug(message, args);\n }\n if (getLogLevel() === 'debug') {\n console.debug(message, args);\n }\n}\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().info(message, args);\n }\n if (['debug', 'info'].includes(getLogLevel())) {\n console.info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().error(message, args);\n }\n if (['debug', 'info', 'error'].includes(getLogLevel())) {\n console.error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom' | 'route',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","getSchema","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","isLoggerReady","getLogger","SENSITIVE_KEYS","redactSensitive","result","val","isSensitive","k","getLogLevel","defaultLoglevel","logDebug","message","startTransaction","name","context","transaction","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAsCb,SAASC,EAAUC,CAAAA,CAAuD,CAC/E,OAAOH,CAAAA,CAAOG,CAAG,CAAA,EAAG,KAAA,EAASJ,CAAAA,CAAaI,CAAG,GAAG,OAClD,CAEO,SAASC,CAAAA,EAAmB,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,0FACF,CAAA,CAGF,OAAO,MAAA,CAAO,WAAA,CACZ,MAAA,CAAO,OAAA,CAAQF,CAAY,CAAA,CACxB,MAAA,CAAO,CAAC,CAACM,EAAGC,CAAM,CAAA,GAAMA,CAAAA,CAAO,QAAQ,EACvC,GAAA,CAAI,CAAC,CAACH,CAAAA,CAAKG,CAAM,CAAA,GACT,CACLH,CAAAA,CACA,CACE,IAAAA,CAAAA,CACA,IAAA,CAAMG,CAAAA,CAAO,IAAA,CACb,MAAON,CAAAA,CAAOG,CAAG,CAAA,EAAG,KAA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EAASjD,CAAI,CAAA,CAE7B,CAAC,OAAA,CAAS,OAAQ,OAAO,CAAA,CAAE,QAAA,CAAS8C,CAAAA,EAAa,CAAA,EACnD,OAAA,CAAQ,KAAA,CAAMG,CAAAA,CAASjD,CAAI,EAE/B,CAOO,SAASkD,CAAAA,CACdhE,EACAiE,CAAAA,CACAC,CAAAA,CACoB,CACpB,GAAI,CAAChC,GAAmB,CACtB,OAAO,CACL,GAAA,CAAK,IAAM,CAEX,CAAA,CACA,UAAA,CAAY,IAAM,CAElB,CACF,CAAA,CAGF,IAAMC,CAAAA,CAAMgB,GAAO,CACbgB,CAAAA,CAAchC,CAAAA,CAAI,gBAAA,CAAiB8B,EAAMjE,CAAI,CAAA,CACnD,OAAIkE,CAAAA,EACF/B,EAAI,gBAAA,CAAiB+B,CAAO,CAAA,CAGvB,CACL,IAAK,CACHV,CAAAA,CACA,CAAE,OAAA,CAAAY,EAAS,OAAA,CAAAF,CAAQ,CAAA,CAA6D,KAC7E,CACCA,CAAAA,EACF/B,CAAAA,CAAI,gBAAA,CAAiB+B,CAAO,CAAA,CAE9BC,CAAAA,CAAY,GAAA,CAAIX,CAAAA,CAAQY,CAAO,EACjC,CAAA,CACA,UAAA,CAAaF,CAAAA,EAAqC,CAChD/B,CAAAA,CAAI,gBAAA,CAAiB+B,CAAO,EAC9B,CACF,CACF,CAEO,SAASG,CAAAA,CAAapB,EAAc,CACzC,GAAI,CAACf,CAAAA,GAAsB,CACzB,OAAA,CAAQ,KAAA,CAAMe,CAAK,EACnB,MACF,CAEAE,GAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-B5WLEHNH.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n *\n * @param key - The configuration key to retrieve\n * @returns The configuration value (string, number, or boolean)\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the site URL\n * const siteUrl = getConfig('_system.site.url');\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_URL=https://myapp.com\n * ```\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the current environment (e.g., 'development', 'staging', 'production')\n * const env = getConfig('_system.env');\n *\n * if (env === 'production') {\n * // Enable production features\n * }\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_ENV=production\n * ```\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n return config[key]?.value ?? configSchema[key]?.default;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function getSchema() {\n return configSchema;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stdout.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stderr.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n void sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [esTransport],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function isLoggerReady() {\n return logger !== null;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm, isLoggerReady } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\ntype LogLevel = 'error' | 'info' | 'debug' | '';\n\n// Secret-bearing keys to scrub before request args/query/body reach the APM sink.\n// Matched case-insensitively as a substring (`authToken` matches `token`).\nconst SENSITIVE_KEYS = ['token', 'password', 'secret', 'nonce', 'code'];\n\n/**\n * Deep-copies `value`, replacing any {@link SENSITIVE_KEYS} match with\n * `'[redacted]'`. Non-object values pass through unchanged.\n */\nexport function redactSensitive(value: unknown): unknown {\n if (!value || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(redactSensitive);\n }\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n const isSensitive = SENSITIVE_KEYS.some((k) => key.toLowerCase().includes(k));\n result[key] = isSensitive ? '[redacted]' : redactSensitive(val);\n }\n return result;\n}\n\n/**\n * Gets the logging level for console logs based on the MODELENCE_LOG_LEVEL environment variable.\n *\n * @returns The log level ('error' | 'info' | 'debug' | '')\n *\n * Behavior:\n * - If MODELENCE_LOG_LEVEL is set, returns that value\n * - If telemetry is disabled and MODELENCE_LOG_LEVEL is not set, defaults to 'info'\n * - If telemetry is enabled and MODELENCE_LOG_LEVEL is not set, returns '' (no console logging)\n */\nfunction getLogLevel(): LogLevel {\n let defaultLoglevel: LogLevel = '';\n if (!isTelemetryEnabled()) {\n defaultLoglevel = 'info';\n }\n\n return (process.env.MODELENCE_LOG_LEVEL as LogLevel) || defaultLoglevel;\n}\n\nexport function logDebug(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().debug(message, args);\n }\n if (getLogLevel() === 'debug') {\n console.debug(message, args);\n }\n}\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().info(message, args);\n }\n if (['debug', 'info'].includes(getLogLevel())) {\n console.info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().error(message, args);\n }\n if (['debug', 'info', 'error'].includes(getLogLevel())) {\n console.error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom' | 'route',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {l,f as f$1,I as I$1,D,C as C$1,i,h as h$1,j as j$1,e}from'./chunk-MTG3OZWX.js';import {c}from'./chunk-5M6FUMUK.js';import {useState,useEffect}from'react';import {jsx,jsxs}from'react/jsx-runtime';import Y from'socket.io-client';import {hashKey,QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var a={page:{minHeight:"100vh",backgroundColor:"#f3f4f6",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 16px",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",color:"#111827"},container:{maxWidth:"576px",width:"100%"},logoWrap:{display:"flex",justifyContent:"center",marginBottom:"32px"},title:{fontSize:"30px",lineHeight:"36px",fontWeight:700,textAlign:"center",margin:0},subtitle:{marginTop:"16px",color:"#4b5563",textAlign:"center"},steps:{marginTop:"32px",listStyle:"none",padding:0,display:"flex",flexDirection:"column",gap:"16px"},step:{display:"flex",gap:"16px",alignItems:"flex-start",backgroundColor:"#ffffff",borderRadius:"8px",border:"1px solid #e5e7eb",padding:"16px"},stepNumber:{flex:"none",width:"28px",height:"28px",borderRadius:"9999px",backgroundColor:"#111827",color:"#ffffff",fontSize:"14px",fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center"},stepText:{color:"#374151",lineHeight:"28px"},code:{fontSize:"14px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace",backgroundColor:"#e5e7eb",borderRadius:"4px",padding:"2px 4px"},footer:{marginTop:"32px",fontSize:"14px",color:"#6b7280",textAlign:"center"}};function Q(){return jsx("div",{style:a.page,children:jsxs("div",{style:a.container,children:[jsx("div",{style:a.logoWrap,children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"80",height:"80",viewBox:"0 0 48 48",fill:"none","aria-label":"Modelence Logo",children:jsx("path",{fill:"#5509D9",d:"M45 22.788V12L24 0l-9.437 5.392L45 22.788ZM25.152 35.24l10.589 6.052 8.107-4.632-10.589-6.052-8.107 4.632Zm9.26-15.872v9.264L45 34.684V25.42l-10.589-6.052ZM3 25.212V36l21 12 9.441-5.392L3 25.212ZM22.848 12.76 12.26 6.708 4.152 11.34l10.589 6.052 8.107-4.632Zm-9.26 15.872v-9.264L3 13.316v9.264l10.589 6.052Z"})})}),jsx("h1",{style:a.title,children:"Connect this project to Modelence Cloud"}),jsx("p",{style:a.subtitle,children:"One quick step before you can use this app locally."}),jsxs("ol",{style:a.steps,children:[jsxs(T,{number:1,children:["Run ",jsx("code",{style:a.code,children:"npx modelence setup"})," in the project folder."]}),jsx(T,{number:2,children:"Your browser opens \u2014 log in and choose your environment."}),jsxs(T,{number:3,children:["Restart the dev server (",jsx("code",{style:a.code,children:"npm run dev"}),")."]})]}),jsx("p",{style:a.footer,children:"This page refreshes automatically once the project is connected."})]})})}function T({number:e,children:t}){return jsxs("li",{style:a.step,children:[jsx("span",{style:a.stepNumber,children:e}),jsx("span",{style:a.stepText,children:t})]})}var Z="__MODELENCE_STATE__",$=3e3,z=false;function V(){return typeof document<"u"&&document.getElementById(Z)!==null}function Se({children:e,loadingElement:t,setupElement:n}){let r=typeof window>"u",[i$1,c]=useState(()=>!r&&!l()&&!V()),[d,s]=useState(()=>!r&&l()&&f$1());return useEffect(()=>{async function l$1(){if(!z){if(z=true,l()){i()&&await h$1();return}await j$1(),s(f$1()),c(false);}}l$1();},[]),useEffect(()=>{if(!d)return;let l=setInterval(async()=>{try{let{setupRequired:o}=await I$1("_system.setupStatus",{},{errorHandler:()=>{}});o||window.location.reload();}catch{}},$);return ()=>clearInterval(l)},[d]),i$1?t??jsx("div",{children:"Loading..."}):d&&n!==null?n??jsx(Q,{}):e}var b=null,m=new Map;function h(){if(!b)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return b}function J(){let e=C$1(),t=D();for(let n of m.values())b?.emit("subscribeLiveQuery",{subscriptionId:n.subscriptionId,method:n.method,args:n.args,authToken:e,clientInfo:t});}function G(e$1){let t=e()?.baseUrl??"/";b=Y(t,{transports:["websocket"],auth:{token:C$1()}}),b.on("connect",()=>{m.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${m.size} live queries`),J());}),e$1.channels?.forEach(n=>n.init());}function X({category:e,listener:t}){h().on(e,t);}function ee({category:e,listener:t}){h().once(e,t);}function te({category:e,listener:t}){h().off(e,t);}function R({eventName:e,category:t,id:n}){h().emit(e,`${t}:${n}`);}function ne({category:e,id:t}){R({eventName:"joinChannel",category:e,id:t});}function re({category:e,id:t}){R({eventName:"leaveChannel",category:e,id:t});}var oe=0;function M(e,t,n,r){let i=`sub-${++oe}-${Date.now()}`,c$1=({subscriptionId:l,data:o,typeMap:y})=>{l===i&&n(c(o,y));},d=({subscriptionId:l,error:o})=>{l===i&&(console.error(`[Modelence] Live query error for ${e}:`,o),r?.(o));},s=h();return s.on("liveQueryData",c$1),s.on("liveQueryError",d),m.set(i,{subscriptionId:i,method:e,args:t}),s.connected&&s.emit("subscribeLiveQuery",{subscriptionId:i,method:e,args:t,authToken:C$1(),clientInfo:D()}),()=>{m.delete(i),s.emit("unsubscribeLiveQuery",{subscriptionId:i}),s.off("liveQueryData",c$1),s.off("liveQueryError",d);}}var ie={init:G,on:X,once:ee,off:te,emit:R,joinChannel:ne,leaveChannel:re},K=ie;var E=null;function O(e){E=e;}function Pe(){return E}function F(e){if(E){console.warn("WebSocket already initialized. Skipping initialization.");return}let t=e?.provider||K;O(t);try{t.init({channels:e?.channels});}catch(n){throw O(null),n}}var p=null,C=null,P=false,f=new Map;function I(e){p!==e&&(p&&se(),p=e,C=e.getQueryCache().subscribe(t=>{if(t.type==="removed"){let n=hashKey(t.query.queryKey),r=f.get(n);if(r){if(r.resolvers.size>0){let i=new Error("Query was removed from cache");r.resolvers.forEach(c=>c.reject(i)),r.resolvers.clear();}r.unsubscribe(),f.delete(n);}}}));}function Ne(){return p!==null}function se(){C&&(C(),C=null),f.forEach(e=>e.unsubscribe()),f.clear(),p=null,P=false;}var j=class{connect(t){I(t);}};function De(e,t={}){return {queryKey:[e,t],queryFn:()=>I$1(e,t)}}function qe(e,t={}){let n=["live",e,t],r=hashKey(n);return {queryKey:n,queryFn:()=>new Promise((i,c)=>{if(typeof window>"u")return;if(!p){let s=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",s.message),c(s);return}P||(F(),P=true);let d=f.get(r);d||(d={unsubscribe:M(e,t,l=>{let o=f.get(r);o?.resolvers.size&&(o.resolvers.forEach(y=>y.resolve(l)),o.resolvers.clear()),p&&p.setQueryData(n,l);},l=>{let o=f.get(r);o&&(o.resolvers.size&&(o.resolvers.forEach(y=>y.reject(new Error(l))),o.resolvers.clear()),o.unsubscribe(),f.delete(r));}),resolvers:new Set},f.set(r,d)),d.resolvers.add({resolve:i,reject:c});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function ze(e,t={}){return {mutationFn:(n={})=>I$1(e,{...t,...n})}}function Ue(e,t={}){return [e,t]}var de="__MODELENCE_QUERY_STATE__";function fe(){if(typeof document>"u")return;let e=document.getElementById(de);if(!(!e||!e.textContent))try{return JSON.parse(e.textContent)}catch(t){console.error("Modelence: failed to parse SSR query state",t);return}}function Be({children:e,client:t,dehydratedState:n}){let[r]=useState(()=>{let c=t??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&I(c),c}),i=n??fe();return jsx(QueryClientProvider,{client:r,children:jsx(HydrationBoundary,{state:i,children:e})})}
|
|
2
|
+
export{Se as a,M as b,O as c,Pe as d,F as e,I as f,Ne as g,se as h,j as i,De as j,qe as k,ze as l,Ue as m,Be as n};//# sourceMappingURL=chunk-B7EXKTEZ.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-B7EXKTEZ.js.map
|