modelence 0.26.0-nd.dev.7 → 0.26.0-nd.dev.9

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/project.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/authCache.ts","../../src/bin/workspaces.ts","../../src/bin/detect.ts","../../src/bin/source.ts","../../src/bin/studioApi.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/logout.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pick","pickEnvironment","appId","response","code","verificationUrl","url","resolvedPick","open","waitForAuth","pollExpireTs","result","pollForToken","error","resolve","token","expiresAt","target","MODELENCE_DIR","PROJECT_FILE","getProjectFilePath","cwd","join","readProject","content","fs","parsed","updateProject","patch","existing","MODELENCE_ENV_FILE","fetchServiceConfig","auth","headers","errorText","ask","question","rl","createInterface","answer","confirmOverwrite","escapeEnvValue","value","readProjectAppId","recordProjectAppId","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACE_REPO","CLAUDE_MARKETPLACES","CLAUDE_PLUGIN_DOCS_URL","CLAUDE_PLUGIN_INSTALL_HINT","ensureClaudePluginEnabled","settingsPath","settings","runClaude","args","spawnSync","offerClaudePluginInstall","probe","marketplace","install","failed","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getConfig","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","path","viteBuild","mergeConfig","buildServer","tsupBuild","build","AUTH_FILE","EXPIRY_MARGIN_MS","getAuthCachePath","home","os","readAuthFile","writeAuthFile","dirname","readCachedToken","hosts","cached","writeCachedToken","current","clearCachedToken","_removed","rest","PNPM_MAJOR_BY_LOCKFILE","pnpmMajorFromLockfile","lockfileText","match","parsePnpmWorkspaceGlobs","yamlText","globs","inPackages","line","item","parsePackageJsonWorkspaces","packageJson","field","entry","packages","globToRegExp","glob","pattern","segment","listPackageDirs","root","maxDepth","found","walk","dir","depth","entries","full","MAX_WORKSPACE_DEPTH","findWorkspacePackages","include","exclude","candidates","rel","relative","sep","re","a","b","workspaceStartCommand","packageManager","name","workspaceBuildCommand","member","detectWorkspaceStart","startable","MINIMUM_NODE_MAJOR","exists","readJson","parseNodeMajor","range","major","parseProcfileWebCommand","isLockfileInSync","lockfile","declared","locked","names","parsePackageManagerVersion","manager","commandsFor","hasLockfile","pinnedVersion","script","detectBuildPlan","notes","scripts","engines","isModelence","useNpmLockfile","commands","buildCommand","startCommand","workspace","nodeVersion","staticOutput","detectStaticOutput","deps","hasViteConfig","execFileAsync","promisify","execFile","MAX_SOURCE_BYTES","ALWAYS_EXCLUDED_DIRS","ALWAYS_EXCLUDED_FILES","toPosix","isExcludedPath","relativePath","segments","fileName","isGitRepository","stdout","listGitFiles","files","listSourceFiles","usedGit","file","packSource","zipPath","output","createWriteStream","archive","archiver","done","reject","size","StudioApiError","message","status","studioRequest","method","body","query","text","DEFAULT_HOST","POLL_INTERVAL_MS","POLL_TIMEOUT_MS","PROVISION_TIMEOUT_MS","deploy","resolveHost","kind","overrides","planOverrides","project","detected","archivePath","createBundle","plan","printDetectedPlan","definedOnly","fileCount","sizeBytes","formatMb","resolveTargetFromOptions","resolveToken","rememberToken","rememberTarget","session","signInAgain","started","runDeploy","isUnauthorized","followDeploy","upload","waitForEnvironmentReady","fileBuffer","uploadResponse","reportResolvedPlan","environmentId","deadline","announced","buildId","lastStatus","lastMessage","logOffset","signedInAgain","describeStatus","flag","note","used","differences","detectedValue","bytes","bundlePath","archiveComplete","bundleFiles","bundleDirs","pathExists","stats","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","logout","__filename","fileURLToPath","__dirname","readFileSync","program","Command"],"mappings":";ijBAmCA,eAAsBA,EACpBC,CAAAA,CACA,CACE,IAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAAkB,KAAA,CAClB,MAAAC,CACF,CAAA,CAAuE,EAAC,CAChD,CACxB,IAAMC,CAAAA,CAAW,MAAM,MAAM,CAAA,EAAGJ,CAAI,gBAAiB,CACnD,MAAA,CAAQ,MACV,CAAC,CAAA,CAED,GAAI,CAACI,EAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,KAAAC,CAAAA,CAAM,eAAA,CAAAC,CAAgB,CAAA,CAAI,MAAMF,EAAS,IAAA,EAAK,CAChDG,EAAM,IAAI,GAAA,CAAID,CAAe,CAAA,CAC7BE,EAAeP,CAAAA,GAASC,CAAAA,CAAkB,cAAgB,MAAA,CAAA,CAC5DM,CAAAA,EACFD,EAAI,YAAA,CAAa,GAAA,CAAI,OAAQC,CAAY,CAAA,CAEvCL,GACFI,CAAAA,CAAI,YAAA,CAAa,IAAI,OAAA,CAASJ,CAAK,EAGrC,OAAA,CAAQ,GAAA,CAAI,CAAA,aAAA,EAAgBI,CAAG,kBAAkB,CAAA,CACjD,OAAA,CAAQ,IAAI,CAAA,MAAA,EAASF,CAAI,EAAE,CAAA,CAE3B,GAAI,CACF,MAAMI,EAAAA,CAAKF,EAAI,QAAA,EAAU,EAC3B,CAAA,KAAQ,CAGN,QAAQ,GAAA,CAAI,6EAA6E,EAC3F,CAEA,OAAO,MAAMG,EAAAA,CAAYV,EAAMK,CAAI,CACrC,CAEA,eAAeK,EAAAA,CAAYV,EAAcK,CAAAA,CAAsC,CAG7E,IAAMM,CAAAA,CAAe,IAAA,CAAK,KAAI,CAAI,GAAA,CAClC,KAAO,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAA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ACnF,MAAA,CAAO,MAAO/O,CAAAA,EAAY,CACzB,GAAI,CACF,MAAMiL,EAAAA,CAAOjL,CAAO,EACtB,CAAA,MAAStD,CAAAA,CAAO,CACd,OAAA,CAAQ,KAAA,CAAM,kBAAkBA,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,MAAA,CAAOA,CAAK,CAAC,CAAA,CAAE,EACxF,OAAA,CAAQ,IAAA,CAAK,CAAC,EAChB,CACF,CAAC,CAAA,CAEHqS,CAAAA,CACG,OAAA,CAAQ,QAAQ,CAAA,CAChB,WAAA,CAAY,wCAAwC,CAAA,CACpD,MAAA,CAAO,mBAAA,CAAqB,qCAAqC,CAAA,CACjE,MAAA,CAAO,MAAO/O,CAAAA,EAAY,CACzB,MAAM0O,EAAAA,CAAO1O,CAAO,EACtB,CAAC,CAAA,CAEH+O,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,EACtC,MAAA,CACC,YAAA,CACA,gFACF,CAAA,CACC,MAAA,CAAO,MAAO/O,CAAAA,EAAY,CACzB,MAAM2B,CAAAA,EAAQ,CACdyM,EAAAA,CAAIpO,CAAO,EACb,CAAC,CAAA,CAEH+O,CAAAA,CACG,QAAQ,OAAO,CAAA,CACf,WAAA,CAAY,yBAAyB,CAAA,CACrC,MAAA,CAAO,SAAY,CAClB,MAAMpN,CAAAA,EAAQ,CACd4M,EAAAA,GACF,CAAC,CAAA,CAEHQ,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization: the CLI mints a code, the user approves it in\n the browser, and the CLI polls until approval binds a token to the code.\n\n Two approval modes, chosen by `pick`:\n 'environment' — `modelence setup`: the page also asks which environment to\n connect the local project to. The choice is stamped on the\n token; /api/setup derives its target from there.\n 'deploy' — `modelence deploy`: the page asks where to deploy (an\n existing or newly created app / cloud environment) and the\n token route reports the pick back so the CLI can record it\n in .modelence/project.json.\n Without `pick` the page only authorizes the device.\n\n `appId` is the hint from .modelence/project.json used to preselect the app.\n*/\n\nexport type CliAuthPick = 'environment' | 'deploy';\n\nexport interface CliAuthTarget {\n appId: string;\n appAlias: string;\n environmentId: string;\n envAlias: string;\n}\n\nexport interface CliAuthResult {\n token: string;\n // Absent on older Studio versions (tokens then last one hour).\n expiresAt?: string;\n target?: CliAuthTarget;\n}\n\nexport async function authenticateCli(\n host: string,\n {\n pick,\n pickEnvironment = false,\n appId,\n }: { pick?: CliAuthPick; pickEnvironment?: boolean; appId?: string } = {}\n): Promise<CliAuthResult> {\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n const url = new URL(verificationUrl);\n const resolvedPick = pick ?? (pickEnvironment ? 'environment' : undefined);\n if (resolvedPick) {\n url.searchParams.set('pick', resolvedPick);\n }\n if (appId) {\n url.searchParams.set('appId', appId);\n }\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n try {\n await open(url.toString());\n } catch {\n // Headless/SSH/container — no browser to open. The URL and code above\n // are already printed, so authentication can proceed manually.\n console.log('Could not open a browser automatically. Please open the URL above manually.');\n }\n\n return await waitForAuth(host, code);\n}\n\nasync function waitForAuth(host: string, code: string): Promise<CliAuthResult> {\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 result = await pollForToken(host, code);\n if (result) {\n return result;\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): Promise<CliAuthResult | null> {\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, expiresAt, target } = await response.json();\n if (!token) {\n return null;\n }\n return { token, expiresAt, target };\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport const MODELENCE_DIR = '.modelence';\nexport const PROJECT_FILE = 'project.json';\n\n/*\n .modelence/project.json — CLI-managed project state that is meant to be\n committed (unlike .modelence.env, which holds per-developer credentials).\n It records which app the project belongs to and, once a deploy target has\n been picked in the browser, which environment `modelence deploy` ships to.\n Everything in it is a hint, never a credential: access is re-checked on\n every request with the user's token.\n*/\n\nexport interface DeployTarget {\n environmentId: string;\n appAlias: string;\n envAlias: string;\n}\n\nexport interface ProjectFile {\n appId?: string;\n deploy?: DeployTarget;\n [key: string]: unknown;\n}\n\nexport function getProjectFilePath(cwd = process.cwd()): string {\n return join(cwd, MODELENCE_DIR, PROJECT_FILE);\n}\n\n// Missing or malformed reads as an empty project rather than failing the\n// command: the file only ever pre-fills choices.\nexport async function readProject(cwd = process.cwd()): Promise<ProjectFile> {\n try {\n const content = await fs.readFile(getProjectFilePath(cwd), 'utf8');\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport async function updateProject(\n patch: Partial<ProjectFile>,\n cwd = process.cwd()\n): Promise<void> {\n const existing = await readProject(cwd);\n await fs.mkdir(join(cwd, MODELENCE_DIR), { recursive: true });\n await fs.writeFile(\n getProjectFilePath(cwd),\n JSON.stringify({ ...existing, ...patch }, null, 2) + '\\n'\n );\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { spawnSync } from 'child_process';\nimport { authenticateCli } from './auth';\nimport { MODELENCE_DIR, PROJECT_FILE, readProject, updateProject } from './project';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function ask(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const answer = await ask(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `\n );\n return answer.toLowerCase() === 'y';\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n const { appId } = await readProject();\n return typeof appId === 'string' && appId ? appId : undefined;\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like build/, cache/ and\n tmp/ are temporary), so the whole team gets it. It's a hint in the git-remote\n sense — connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value. (The deploy target recorded by `modelence deploy` is different: it is\n shared on purpose, like a git remote.)\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n await updateProject({ appId });\n}\n\nconst CLAUDE_DIR = '.claude';\nconst CLAUDE_SETTINGS_FILE = join(CLAUDE_DIR, 'settings.json');\nconst CLAUDE_PLUGIN_ID = 'modelence@modelence';\n// Without the marketplace declared alongside enabledPlugins, Claude Code\n// can't resolve the plugin unless the user already ran\n// `claude plugin marketplace add` themselves.\nconst CLAUDE_MARKETPLACE_REPO = 'modelence/modelence';\nconst CLAUDE_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: CLAUDE_MARKETPLACE_REPO } },\n};\nconst CLAUDE_PLUGIN_DOCS_URL = 'https://docs.modelence.com/ai-coding-agents';\nconst CLAUDE_PLUGIN_INSTALL_HINT =\n 'Install the Modelence plugin for Claude Code by hand:\\n' +\n ` claude plugin marketplace add ${CLAUDE_MARKETPLACE_REPO}\\n` +\n ` claude plugin install ${CLAUDE_PLUGIN_ID} --scope project\\n` +\n `Guide: ${CLAUDE_PLUGIN_DOCS_URL}`;\n\n/*\n Declares the Modelence Claude Code plugin in the project's settings.json,\n merging into an existing file rather than replacing it. An explicit\n `false` is a deliberate opt-out and is never flipped back on. The file is\n inert for people who don't use Claude Code, and failing to write it doesn't\n fail the setup.\n*/\nasync function ensureClaudePluginEnabled(): Promise<void> {\n const settingsPath = join(process.cwd(), CLAUDE_SETTINGS_FILE);\n\n let content: string | undefined;\n try {\n content = await fs.readFile(settingsPath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n console.warn(`Could not read ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n let settings: Record<string, any> = {};\n if (content !== undefined) {\n try {\n settings = JSON.parse(content);\n } catch {\n console.warn(`Could not parse ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n // The marketplace is only a pointer, so it's always (re)declared — a file\n // with just enabledPlugins, as `claude plugin install --scope project`\n // leaves behind, can't be resolved by teammates without it. An explicit\n // `false` in enabledPlugins is the user's opt-out and is left alone.\n settings.extraKnownMarketplaces = { ...settings.extraKnownMarketplaces, ...CLAUDE_MARKETPLACES };\n if (settings.enabledPlugins?.[CLAUDE_PLUGIN_ID] === undefined) {\n settings.enabledPlugins = { ...settings.enabledPlugins, [CLAUDE_PLUGIN_ID]: true };\n }\n\n try {\n await fs.mkdir(join(process.cwd(), CLAUDE_DIR), { recursive: true });\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n console.log(`Declared the Modelence Claude Code plugin in ${CLAUDE_SETTINGS_FILE}`);\n } catch (error) {\n console.warn(`Failed to write ${CLAUDE_SETTINGS_FILE}:`, error);\n }\n}\n\nfunction runClaude(args: string[]) {\n return spawnSync('claude', args, { encoding: 'utf8', shell: process.platform === 'win32' });\n}\n\n/*\n Installs the plugin through the Claude Code CLI — the one install path that\n behaves the same for the terminal, the IDE extensions and the desktop app,\n which all read the same plugin state. Touches the user's machine-wide Claude\n config, so it asks first, and it never fails the setup: without the CLI on\n PATH it prints the commands to run by hand.\n*/\nasync function offerClaudePluginInstall(): Promise<void> {\n const probe = runClaude(['--version']);\n if (probe.error || probe.status !== 0) {\n console.log(CLAUDE_PLUGIN_INSTALL_HINT);\n return;\n }\n\n const answer = (await ask('Install the Modelence plugin for Claude Code? (Y/n) ')).toLowerCase();\n if (answer && answer !== 'y' && answer !== 'yes') {\n return;\n }\n\n // Makes the install work before Claude Code has picked up the marketplace\n // declared in .claude/settings.json. Its result only matters if the install\n // then fails: a network or auth error here is the real cause, and the\n // install's own message wouldn't point at it.\n const marketplace = runClaude(['plugin', 'marketplace', 'add', CLAUDE_MARKETPLACE_REPO]);\n const install = runClaude(['plugin', 'install', CLAUDE_PLUGIN_ID, '--scope', 'project']);\n if (install.status === 0) {\n console.log(\n 'Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: ' +\n 'run /mcp, choose modelence, then Authenticate.'\n );\n } else {\n const failed = marketplace.status !== 0 ? marketplace : install;\n console.warn(\n `Could not install the Modelence plugin: ${(failed.stderr || failed.stdout || '').trim()}`\n );\n console.warn(CLAUDE_PLUGIN_INSTALL_HINT);\n }\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n // Where this working copy runs; Studio sandboxes pre-set \"sandbox\".\n MODELENCE_RUNTIME: process.env.MODELENCE_RUNTIME || 'local',\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n await ensureClaudePluginEnabled();\n // Interactive runs only: with --token (CI) or without a terminal there is\n // nobody to ask, and no Claude Code to set up.\n if (!options.token && process.stdin.isTTY) {\n await offerClaudePluginInstall();\n }\n\n if (fileExisted) {\n // The dev server reads the file at boot, and an open agent session may\n // still hold the old environment id in its context.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, start a new session.'\n );\n }\n\n // Only for a first-time setup: re-running it on an existing file already\n // told them to restart the dev server they're running.\n if (!fileExisted && newEnv.MODELENCE_RUNTIME === 'local') {\n console.log('\\nNext step — run the app on this machine:\\n');\n console.log(\" npm install (if you haven't already)\");\n console.log(' npm run dev (starts the app)\\n');\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { promises as fs } from 'fs';\nimport os from 'os';\nimport { dirname, join } from 'path';\n\n/*\n Cached deploy authorization, per Studio host, in the user's home directory\n (never in the project). Written only after a browser approval, dropped by\n `modelence logout` or when Studio rejects it. MODELENCE_HOME overrides the\n location (tests, sandboxes).\n*/\n\nconst AUTH_FILE = 'auth.json';\n// A token about to expire is treated as expired so a deploy doesn't fail\n// halfway through its polling.\nconst EXPIRY_MARGIN_MS = 60 * 1000;\n\ninterface CachedToken {\n token: string;\n expiresAt: string;\n}\n\ninterface AuthFile {\n hosts?: Record<string, CachedToken>;\n}\n\nexport function getAuthCachePath(): string {\n const home = process.env.MODELENCE_HOME || join(os.homedir(), '.modelence');\n return join(home, AUTH_FILE);\n}\n\nasync function readAuthFile(): Promise<AuthFile> {\n try {\n const parsed = JSON.parse(await fs.readFile(getAuthCachePath(), 'utf8'));\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\nasync function writeAuthFile(content: AuthFile): Promise<void> {\n const path = getAuthCachePath();\n await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await fs.writeFile(path, JSON.stringify(content, null, 2) + '\\n', { mode: 0o600 });\n}\n\nexport async function readCachedToken(host: string): Promise<string | null> {\n const { hosts = {} } = await readAuthFile();\n const cached = hosts[host];\n if (!cached?.token || !cached.expiresAt) {\n return null;\n }\n if (new Date(cached.expiresAt).getTime() - EXPIRY_MARGIN_MS <= Date.now()) {\n return null;\n }\n return cached.token;\n}\n\nexport async function writeCachedToken(\n host: string,\n token: string,\n expiresAt: string\n): Promise<void> {\n const current = await readAuthFile();\n await writeAuthFile({\n ...current,\n hosts: { ...current.hosts, [host]: { token, expiresAt } },\n });\n}\n\nexport async function clearCachedToken(host?: string): Promise<void> {\n if (!host) {\n await writeAuthFile({});\n return;\n }\n const current = await readAuthFile();\n const { [host]: _removed, ...rest } = current.hosts ?? {};\n await writeAuthFile({ ...current, hosts: rest });\n}\n","import { promises as fs } from 'fs';\nimport { join, relative, sep } from 'path';\nimport type { PackageManager } from './detect';\n\n/*\n Monorepo detection. Two things a single-package project never needs:\n which pnpm major wrote the lockfile (so the build installs a compatible\n one), and which workspace package is the one to start.\n*/\n\nexport interface WorkspacePackage {\n name: string;\n // Relative to the workspace root, POSIX separators.\n dir: string;\n scripts: Record<string, string>;\n}\n\n// pnpm-lock.yaml `lockfileVersion` → the pnpm major that reads it. 9.0 is\n// written by pnpm 9 and 10 alike; 10 is picked because it reads both and\n// only warns about unapproved build scripts where 11 fails.\nconst PNPM_MAJOR_BY_LOCKFILE: Record<string, number> = {\n '5': 7,\n '6': 8,\n '9': 10,\n};\n\nexport function pnpmMajorFromLockfile(lockfileText: string): number | undefined {\n const match = /^lockfileVersion:\\s*['\"]?(\\d+)(?:\\.\\d+)?['\"]?\\s*$/m.exec(lockfileText);\n if (!match) {\n return undefined;\n }\n return PNPM_MAJOR_BY_LOCKFILE[match[1]];\n}\n\n// The `packages:` list of pnpm-workspace.yaml. Only the flat \"- glob\" form\n// pnpm documents is handled; anything else yields no globs.\nexport function parsePnpmWorkspaceGlobs(yamlText: string): string[] {\n const globs: string[] = [];\n let inPackages = false;\n for (const line of yamlText.split('\\n')) {\n if (/^packages:\\s*$/.test(line)) {\n inPackages = true;\n continue;\n }\n if (!inPackages) {\n continue;\n }\n const item = /^\\s+-\\s*['\"]?([^'\"#]+?)['\"]?\\s*(?:#.*)?$/.exec(line);\n if (item) {\n globs.push(item[1].trim());\n } else if (line.trim() !== '' && !line.startsWith(' ') && !line.startsWith('\\t')) {\n inPackages = false;\n }\n }\n return globs;\n}\n\n// package.json `workspaces`: an array, or yarn's `{ packages: [...] }`.\nexport function parsePackageJsonWorkspaces(packageJson: Record<string, unknown>): string[] {\n const field = packageJson.workspaces;\n if (Array.isArray(field)) {\n return field.filter((entry): entry is string => typeof entry === 'string');\n }\n if (field && typeof field === 'object') {\n const packages = (field as { packages?: unknown }).packages;\n return Array.isArray(packages)\n ? packages.filter((entry): entry is string => typeof entry === 'string')\n : [];\n }\n return [];\n}\n\nfunction globToRegExp(glob: string): RegExp {\n const normalized = glob.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n const pattern = normalized\n .split('/')\n .map((segment) => {\n if (segment === '**') {\n return '.*';\n }\n return segment.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '[^/]*');\n })\n .join('/');\n return new RegExp(`^${pattern}$`);\n}\n\nasync function listPackageDirs(root: string, maxDepth: number): Promise<string[]> {\n const found: string[] = [];\n async function walk(dir: string, depth: number) {\n if (depth > maxDepth) {\n return;\n }\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name === 'node_modules' || entry.name.startsWith('.')) {\n continue;\n }\n const full = join(dir, entry.name);\n found.push(full);\n await walk(full, depth + 1);\n }\n }\n await walk(root, 1);\n return found;\n}\n\nconst MAX_WORKSPACE_DEPTH = 4;\n\n// Workspace members: directories under the root matching the globs that\n// hold a package.json. Negated globs (\"!apps/legacy\") exclude.\nexport async function findWorkspacePackages(\n root: string,\n globs: string[]\n): Promise<WorkspacePackage[]> {\n if (globs.length === 0) {\n return [];\n }\n const include = globs.filter((glob) => !glob.startsWith('!')).map(globToRegExp);\n const exclude = globs\n .filter((glob) => glob.startsWith('!'))\n .map((glob) => globToRegExp(glob.slice(1)));\n const candidates = await listPackageDirs(root, MAX_WORKSPACE_DEPTH);\n const packages: WorkspacePackage[] = [];\n for (const dir of candidates) {\n const rel = relative(root, dir).split(sep).join('/');\n if (!include.some((re) => re.test(rel)) || exclude.some((re) => re.test(rel))) {\n continue;\n }\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(await fs.readFile(join(dir, 'package.json'), 'utf8'));\n } catch {\n continue;\n }\n if (typeof parsed.name !== 'string') {\n continue;\n }\n packages.push({\n name: parsed.name,\n dir: rel,\n scripts: (parsed.scripts ?? {}) as Record<string, string>,\n });\n }\n return packages.sort((a, b) => a.dir.localeCompare(b.dir));\n}\n\nexport function workspaceStartCommand(packageManager: PackageManager, name: string): string {\n switch (packageManager) {\n case 'pnpm':\n return `pnpm --filter ${name} start`;\n case 'yarn':\n return `yarn workspace ${name} start`;\n default:\n return `npm start --workspace ${name}`;\n }\n}\n\n// Builds one member plus its workspace dependencies. pnpm's `name...` filter\n// is the dependency closure; npm and yarn classic have no equivalent, so\n// only the member itself is built there.\nexport function workspaceBuildCommand(\n packageManager: PackageManager,\n member: WorkspacePackage\n): string | undefined {\n switch (packageManager) {\n case 'pnpm':\n return `pnpm --filter ${member.name}... --if-present run build`;\n case 'yarn':\n return member.scripts.build ? `yarn workspace ${member.name} run build` : undefined;\n default:\n return member.scripts.build\n ? `npm run build --if-present --workspace ${member.name}`\n : undefined;\n }\n}\n\nexport interface WorkspaceStartDetection {\n startCommand?: string;\n buildCommand?: string;\n note?: string;\n}\n\n// Picks the workspace package to run when the root has no start script: the\n// one member with a `start` script. Several candidates need a human choice.\nexport async function detectWorkspaceStart(\n cwd: string,\n packageManager: PackageManager,\n packageJson: Record<string, unknown>\n): Promise<WorkspaceStartDetection> {\n let globs = parsePackageJsonWorkspaces(packageJson);\n if (packageManager === 'pnpm') {\n try {\n globs = parsePnpmWorkspaceGlobs(await fs.readFile(join(cwd, 'pnpm-workspace.yaml'), 'utf8'));\n } catch {\n // Not a pnpm workspace.\n }\n }\n const members = await findWorkspacePackages(cwd, globs);\n const startable = members.filter((member) => member.scripts.start);\n if (startable.length === 1) {\n const [member] = startable;\n return {\n startCommand: workspaceStartCommand(packageManager, member.name),\n buildCommand: workspaceBuildCommand(packageManager, member),\n note:\n `No root start script; the container starts the ${member.name} workspace package (${member.dir}/), ` +\n 'and the build is scoped to it and its workspace dependencies. Pass --build-command to build differently.',\n };\n }\n if (startable.length > 1) {\n const names = startable.map((member) => member.name).join(', ');\n return {\n note: `Several workspace packages have a start script (${names}); pass --start-command to choose one.`,\n };\n }\n return {};\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { detectWorkspaceStart, pnpmMajorFromLockfile } from './workspaces';\n\n/*\n Infers the build contract from the project the way Heroku's Node buildpack\n does: the lockfile picks the package manager, package.json scripts pick the\n build and start commands, a Procfile `web:` line wins for start, and\n engines.node pins the Node.js major. Studio uses these as defaults for\n whatever the environment's settings leave blank.\n*/\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn';\n\nexport interface DetectedBuildPlan {\n preset: 'modelence' | 'node' | 'static';\n packageManager: PackageManager;\n nodeVersion?: string;\n installCommand: string;\n // Undefined when nothing was found, so the server's defaults apply.\n buildCommand?: string;\n startCommand?: string;\n // 'static' preset: where the build writes the site.\n outputDirectory?: string;\n // Human-readable notes about what was (not) found.\n notes: string[];\n}\n\nconst MINIMUM_NODE_MAJOR = 18;\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n try {\n const parsed = JSON.parse(await fs.readFile(path, 'utf8'));\n return parsed && typeof parsed === 'object' ? parsed : null;\n } catch {\n return null;\n }\n}\n\n// The first version number in a semver range, e.g. \">=20.10 <23\" → \"20\",\n// \"22.x\" → \"22\". Anything below the supported floor is ignored.\nexport function parseNodeMajor(range: unknown): string | undefined {\n if (typeof range !== 'string') {\n return undefined;\n }\n const match = range.match(/(\\d+)(?:\\.\\d+)?(?:\\.\\d+)?/);\n if (!match) {\n return undefined;\n }\n const major = Number(match[1]);\n return major >= MINIMUM_NODE_MAJOR ? String(major) : undefined;\n}\n\nexport function parseProcfileWebCommand(content: string): string | undefined {\n for (const line of content.split(/\\r?\\n/)) {\n const match = line.match(/^\\s*web\\s*:\\s*(.+?)\\s*$/);\n if (match) {\n return match[1];\n }\n }\n return undefined;\n}\n\n/*\n `npm ci` refuses a package-lock.json that disagrees with package.json — a\n common state for generated projects (Lovable adds a dependency without\n refreshing the lock). Compares the root package's declared dependencies\n with the lock's root entry (lockfileVersion 2+). An old v1 lock has no root\n entry, so it is trusted as-is.\n*/\nexport function isLockfileInSync(\n packageJson: Record<string, unknown>,\n lockfile: Record<string, unknown>\n): boolean {\n const packages = lockfile.packages as Record<string, Record<string, unknown>> | undefined;\n const root = packages?.[''];\n if (!root) {\n return true;\n }\n for (const field of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) {\n const declared = (packageJson[field] ?? {}) as Record<string, string>;\n const locked = (root[field] ?? {}) as Record<string, string>;\n const names = new Set([...Object.keys(declared), ...Object.keys(locked)]);\n for (const name of names) {\n if (declared[name] !== locked[name]) {\n return false;\n }\n }\n }\n return true;\n}\n\n// package.json `packageManager` (\"pnpm@10.4.1+sha512...\") → \"10.4.1\" when it\n// names the given manager. Anything that is not a plain semver version is\n// ignored rather than passed to npm.\nexport function parsePackageManagerVersion(\n field: unknown,\n manager: PackageManager\n): string | undefined {\n if (typeof field !== 'string') {\n return undefined;\n }\n const match = /^([a-z]+)@(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)(?:\\+.*)?$/.exec(field.trim());\n if (!match || match[1] !== manager) {\n return undefined;\n }\n return match[2];\n}\n\nfunction commandsFor(packageManager: PackageManager, hasLockfile: boolean, pinnedVersion?: string) {\n switch (packageManager) {\n case 'pnpm': {\n // Without a pin `npm install -g pnpm` picks whatever is latest, which\n // can be a major ahead of the lockfile and refuse the install.\n const pnpmPackage = pinnedVersion ? `pnpm@${pinnedVersion}` : 'pnpm';\n return {\n install: `npm install -g ${pnpmPackage} && pnpm install --frozen-lockfile`,\n run: (script: string) => `pnpm run ${script}`,\n start: 'pnpm start',\n };\n }\n case 'yarn':\n return {\n install: 'yarn install --frozen-lockfile',\n run: (script: string) => `yarn ${script}`,\n start: 'yarn start',\n };\n default:\n return {\n install: hasLockfile ? 'npm ci' : 'npm install',\n run: (script: string) => `npm run ${script}`,\n start: 'npm start',\n };\n }\n}\n\nexport async function detectBuildPlan(cwd = process.cwd()): Promise<DetectedBuildPlan> {\n const notes: string[] = [];\n\n const packageJson = await readJson(join(cwd, 'package.json'));\n if (!packageJson) {\n throw new Error('No package.json found in the current directory');\n }\n const scripts = (packageJson.scripts ?? {}) as Record<string, string>;\n const engines = (packageJson.engines ?? {}) as Record<string, unknown>;\n\n const isModelence =\n (await exists(join(cwd, 'modelence.config.ts'))) ||\n (await exists(join(cwd, 'modelence.config.js')));\n\n let packageManager: PackageManager = 'npm';\n if (await exists(join(cwd, 'pnpm-lock.yaml'))) {\n packageManager = 'pnpm';\n } else if (await exists(join(cwd, 'yarn.lock'))) {\n packageManager = 'yarn';\n }\n let useNpmLockfile = await exists(join(cwd, 'package-lock.json'));\n if (packageManager === 'npm' && !useNpmLockfile) {\n notes.push('No package-lock.json found; dependencies are installed with `npm install`.');\n }\n if (packageManager === 'npm' && useNpmLockfile) {\n const lockfile = await readJson(join(cwd, 'package-lock.json'));\n if (lockfile && !isLockfileInSync(packageJson, lockfile)) {\n useNpmLockfile = false;\n notes.push(\n 'package-lock.json is out of date with package.json, so dependencies are installed with `npm install`. ' +\n 'Run `npm install` locally and commit the lockfile to get reproducible `npm ci` installs.'\n );\n }\n }\n\n let pinnedVersion = parsePackageManagerVersion(packageJson.packageManager, packageManager);\n if (packageManager === 'pnpm' && !pinnedVersion) {\n // No explicit pin: the lockfile format still tells which major wrote it.\n const major = pnpmMajorFromLockfile(await fs.readFile(join(cwd, 'pnpm-lock.yaml'), 'utf8'));\n if (major) {\n pinnedVersion = String(major);\n } else {\n notes.push(\n 'Could not tell which pnpm version wrote pnpm-lock.yaml; the build installs the latest. ' +\n 'Add e.g. \"packageManager\": \"pnpm@10.4.1\" to package.json to pin it.'\n );\n }\n }\n const commands = commandsFor(packageManager, useNpmLockfile, pinnedVersion);\n\n let buildCommand: string | undefined;\n if (scripts.build) {\n buildCommand = commands.run('build');\n } else if (!isModelence) {\n notes.push('No `build` script found; the deploy skips the build step.');\n }\n\n let startCommand: string | undefined;\n try {\n startCommand = parseProcfileWebCommand(await fs.readFile(join(cwd, 'Procfile'), 'utf8'));\n } catch {\n // No Procfile — fall through to package.json.\n }\n if (!startCommand && scripts.start) {\n startCommand = commands.start;\n }\n if (!startCommand && !isModelence) {\n const workspace = await detectWorkspaceStart(cwd, packageManager, packageJson);\n startCommand = workspace.startCommand;\n if (workspace.startCommand) {\n // Deploying one member: a root build that builds every package can\n // drag in siblings with their own requirements.\n buildCommand = workspace.buildCommand;\n }\n if (workspace.note) {\n notes.push(workspace.note);\n }\n }\n const nodeVersion = parseNodeMajor(engines.node);\n\n // A client-only site (Vite, Lovable, CRA…): something to build, nothing to\n // start. The runtime serves the build output itself.\n const staticOutput =\n !isModelence && !startCommand && buildCommand\n ? await detectStaticOutput(cwd, packageJson)\n : undefined;\n if (staticOutput) {\n notes.push(\n `No start script found; the site is served from ${staticOutput}/ with single-page app fallback.`\n );\n return {\n preset: 'static',\n packageManager,\n nodeVersion,\n installCommand: commands.install,\n buildCommand,\n outputDirectory: staticOutput,\n notes,\n };\n }\n\n if (!startCommand) {\n notes.push(\n 'No `start` script or Procfile found; the container runs `npm start`. Pass --start-command to override.'\n );\n }\n\n return {\n preset: isModelence ? 'modelence' : 'node',\n packageManager,\n nodeVersion,\n installCommand: commands.install,\n buildCommand,\n startCommand,\n notes,\n };\n}\n\n// Output directory of the common static-site toolchains, or undefined when\n// the project doesn't look like one.\nasync function detectStaticOutput(\n cwd: string,\n packageJson: Record<string, unknown>\n): Promise<string | undefined> {\n const deps = {\n ...((packageJson.dependencies ?? {}) as Record<string, string>),\n ...((packageJson.devDependencies ?? {}) as Record<string, string>),\n };\n const hasViteConfig =\n (await exists(join(cwd, 'vite.config.ts'))) ||\n (await exists(join(cwd, 'vite.config.js'))) ||\n (await exists(join(cwd, 'vite.config.mts')));\n if (deps.vite || hasViteConfig) {\n return 'dist';\n }\n if (deps['react-scripts']) {\n return 'build';\n }\n if (deps['@angular/cli']) {\n return 'dist';\n }\n if (deps.astro) {\n return 'dist';\n }\n // A root index.html with a build script is the Vite/Parcel convention.\n if (await exists(join(cwd, 'index.html'))) {\n return 'dist';\n }\n return undefined;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join, relative, sep } from 'path';\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport archiver from 'archiver';\n\nconst execFileAsync = promisify(execFile);\n\n/*\n Packs the project's source tree for a remote build. Inside a git repository\n the file list is git's own (tracked + untracked, minus ignored), so the\n upload matches what a push would carry. Outside git a plain walk is used\n with a fixed exclusion list.\n\n Credentials and build output are never uploaded regardless.\n*/\n\nexport const MAX_SOURCE_BYTES = 200 * 1024 * 1024;\n\nconst ALWAYS_EXCLUDED_DIRS = [\n '.git',\n 'node_modules',\n '.modelence/build',\n '.modelence/tmp',\n '.modelence/cache',\n];\nconst ALWAYS_EXCLUDED_FILES = [/^\\.modelence(\\.[^/]+)?\\.env$/];\n\nfunction toPosix(path: string): string {\n return path.split(sep).join('/');\n}\n\nexport function isExcludedPath(relativePath: string): boolean {\n const path = toPosix(relativePath);\n const segments = path.split('/');\n for (const dir of ALWAYS_EXCLUDED_DIRS) {\n const dirSegments = dir.split('/');\n // Excluded at any depth for single names (node_modules), at the root for\n // nested ones (.modelence/build).\n if (dirSegments.length === 1) {\n if (segments.slice(0, -1).includes(dir)) {\n return true;\n }\n } else if (path === dir || path.startsWith(`${dir}/`)) {\n return true;\n }\n }\n const fileName = segments[segments.length - 1];\n return ALWAYS_EXCLUDED_FILES.some((pattern) => pattern.test(fileName));\n}\n\nasync function isGitRepository(cwd: string): Promise<boolean> {\n try {\n const { stdout } = await execFileAsync('git', ['rev-parse', '--is-inside-work-tree'], { cwd });\n return stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\nasync function listGitFiles(cwd: string): Promise<string[]> {\n const { stdout } = await execFileAsync(\n 'git',\n ['ls-files', '--cached', '--others', '--exclude-standard', '-z'],\n { cwd, maxBuffer: 64 * 1024 * 1024 }\n );\n return stdout.split('\\0').filter((entry) => entry.length > 0);\n}\n\nasync function walk(cwd: string, dir = ''): Promise<string[]> {\n const entries = await fs.readdir(join(cwd, dir), { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const path = dir ? `${dir}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedPath(`${path}/x`)) {\n files.push(...(await walk(cwd, path)));\n }\n } else if (entry.isFile()) {\n files.push(path);\n }\n }\n return files;\n}\n\nexport async function listSourceFiles(\n cwd = process.cwd()\n): Promise<{ files: string[]; usedGit: boolean }> {\n const usedGit = await isGitRepository(cwd);\n const candidates = usedGit ? await listGitFiles(cwd) : await walk(cwd);\n\n const files: string[] = [];\n for (const file of candidates) {\n if (isExcludedPath(file)) {\n continue;\n }\n // git ls-files still lists tracked files deleted from the working tree.\n try {\n const stat = await fs.stat(join(cwd, file));\n if (stat.isFile()) {\n files.push(file);\n }\n } catch {\n // Gone from disk — nothing to upload.\n }\n }\n return { files: files.sort(), usedGit };\n}\n\nexport async function packSource(\n cwd: string,\n zipPath: string\n): Promise<{ fileCount: number; sizeBytes: number; usedGit: boolean }> {\n const { files, usedGit } = await listSourceFiles(cwd);\n if (files.length === 0) {\n throw new Error('No files to upload');\n }\n\n await fs.mkdir(join(zipPath, '..'), { recursive: true });\n await fs.rm(zipPath, { force: true });\n\n const output = createWriteStream(zipPath);\n const archive = archiver('zip', { zlib: { level: 6 } });\n const done = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n archive.pipe(output);\n for (const file of files) {\n archive.file(join(cwd, file), { name: toPosix(relative('', file)) });\n }\n await archive.finalize();\n await done;\n\n const { size } = await fs.stat(zipPath);\n if (size > MAX_SOURCE_BYTES) {\n await fs.rm(zipPath, { force: true });\n throw new Error(\n `Source is ${(size / 1024 / 1024).toFixed(0)} MB compressed; the limit is ${MAX_SOURCE_BYTES / 1024 / 1024} MB. ` +\n 'Add build output and large assets to .gitignore.'\n );\n }\n\n return { fileCount: files.length, sizeBytes: size, usedGit };\n}\n","/*\n Thin JSON client for Studio's CLI routes. Errors carry the HTTP status so\n callers can tell an expired token (401) from everything else.\n*/\n\nexport class StudioApiError extends Error {\n constructor(\n message: string,\n public readonly status: number\n ) {\n super(message);\n this.name = 'StudioApiError';\n }\n}\n\nexport async function studioRequest<T>(\n host: string,\n path: string,\n {\n method = 'GET',\n token,\n body,\n query,\n }: {\n method?: 'GET' | 'POST';\n token?: string;\n body?: unknown;\n query?: Record<string, string | number>;\n } = {}\n): Promise<T> {\n const url = new URL(path, host);\n for (const [key, value] of Object.entries(query ?? {})) {\n url.searchParams.set(key, String(value));\n }\n\n const headers: Record<string, string> = {};\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n\n const response = await fetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n if (!response.ok) {\n const text = await response.text();\n let message = text || response.statusText;\n try {\n const parsed = JSON.parse(text);\n message = parsed.error || parsed.message || message;\n } catch {\n // Plain-text error body.\n }\n throw new StudioApiError(message, response.status);\n }\n\n return (await response.json()) as T;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseDotenv } from 'dotenv';\nimport archiver from 'archiver';\nimport { authenticateCli, type CliAuthTarget } from './auth';\nimport { clearCachedToken, readCachedToken, writeCachedToken } from './authCache';\nimport { detectBuildPlan } from './detect';\nimport { loadEnv, getProjectPath } from './config';\nimport { readProject, updateProject, type DeployTarget } from './project';\nimport { packSource } from './source';\nimport { StudioApiError, studioRequest } from './studioApi';\nimport { build } from './build';\n\n/*\n `modelence deploy`: ship the current directory to a Modelence Cloud\n environment.\n\n Default path — any Node.js app: the source tree is uploaded and built\n remotely (install → build → start commands detected here, overridable with\n flags, stored on the environment). `--prebuilt` keeps the historical\n Modelence path: build locally, upload .modelence/build.\n\n Target: -a/-e flags → --env with the app recorded in project.json → the\n deploy target recorded in project.json → the browser picker. Auth: the\n MODELENCE_TOKEN variable → the cached token → the browser.\n*/\n\nconst DEFAULT_HOST = 'https://cloud.modelence.com';\nconst POLL_INTERVAL_MS = 3000;\nconst POLL_TIMEOUT_MS = 30 * 60 * 1000;\nconst PROVISION_TIMEOUT_MS = 10 * 60 * 1000;\n\nexport interface DeployOptions {\n app?: string;\n env?: string;\n host?: string;\n prebuilt?: boolean;\n preset?: string;\n nodeVersion?: string;\n rootDir?: string;\n installCommand?: string;\n buildCommand?: string;\n startCommand?: string;\n outputDir?: string;\n}\n\ntype CliTarget =\n | { environmentId: string }\n | { appAlias: string; envAlias: string }\n | { appId: string; envAlias: string };\n\ntype UploadKind = 'bundle' | 'source';\n\ninterface BuildPlanInput {\n preset?: string;\n nodeVersion?: string;\n rootDirectory?: string;\n installCommand?: string;\n buildCommand?: string;\n startCommand?: string;\n outputDirectory?: string;\n}\n\ninterface DeployStatus {\n status: string;\n errors: string[];\n rolloutProgress: { updatedCount: number; totalCount: number } | null;\n logs: string[];\n logCount: number;\n siteUrl: string | null;\n // Last output of the containers a failed rollout tried to start.\n containerLogs?: string[];\n}\n\n// The token in use, shared so a re-authorization mid-deploy reaches every\n// later request without threading a new value through each call.\ninterface Session {\n host: string;\n token: string;\n}\n\nexport async function deploy(options: DeployOptions) {\n const cwd = process.cwd();\n const host = await resolveHost(options.host, cwd);\n const kind: UploadKind = options.prebuilt ? 'bundle' : 'source';\n const overrides = planOverrides(options);\n const project = await readProject(cwd);\n\n // Local work first, so nothing is uploaded when it fails.\n let detected: BuildPlanInput | undefined;\n const archivePath = join(cwd, '.modelence', 'tmp', `${kind}.zip`);\n if (kind === 'bundle') {\n await loadEnv();\n await build();\n await createBundle(archivePath);\n } else {\n const plan = await detectBuildPlan(cwd);\n detected = {\n preset: plan.preset,\n nodeVersion: plan.nodeVersion,\n installCommand: plan.installCommand,\n buildCommand: plan.buildCommand,\n startCommand: plan.startCommand,\n outputDirectory: plan.outputDirectory,\n };\n printDetectedPlan({ ...detected, ...definedOnly(overrides) }, plan.notes);\n const { fileCount, sizeBytes, usedGit } = await packSource(cwd, archivePath);\n console.log(\n `Packed ${fileCount} files (${formatMb(sizeBytes)})` +\n (usedGit ? ' from git' : '; not a git repository, so only default exclusions applied')\n );\n }\n\n let target = resolveTargetFromOptions(options, project);\n let token = await resolveToken(host);\n if (!token || !target) {\n // The browser flow hands back both a token and, when picked there, the\n // target — one visit covers a fresh machine and a fresh project.\n const auth = await authenticateCli(host, { pick: 'deploy', appId: project.appId });\n token = auth.token;\n await rememberToken(host, auth.token, auth.expiresAt);\n if (auth.target) {\n target = { environmentId: auth.target.environmentId };\n await rememberTarget(auth.target);\n }\n }\n if (!target) {\n throw new Error(\n 'No deploy target selected. Run again and pick an environment in the browser, or pass --app and --env.'\n );\n }\n\n const session: Session = { host, token };\n // Cached token expired or was revoked: authorize once more. The deploy\n // itself is never repeated — an upload that failed authentication did not\n // start anything, and a build already running is simply followed again.\n const signInAgain = async () => {\n await clearCachedToken(host);\n console.log('Your saved login has expired; please sign in again.');\n const auth = await authenticateCli(host, { pick: 'deploy', appId: project.appId });\n await rememberToken(host, auth.token, auth.expiresAt);\n if (auth.target) {\n target = { environmentId: auth.target.environmentId };\n await rememberTarget(auth.target);\n }\n session.token = auth.token;\n };\n\n try {\n let started: StartedDeploy;\n try {\n started = await runDeploy({\n session,\n target,\n kind,\n archivePath,\n overrides,\n detected,\n project,\n });\n } catch (error) {\n if (!isUnauthorized(error)) {\n throw error;\n }\n await signInAgain();\n started = await runDeploy({\n session,\n target,\n kind,\n archivePath,\n overrides,\n detected,\n project,\n });\n }\n if (started.buildId) {\n await followDeploy(session, signInAgain, started.environmentId, started.buildId);\n }\n } finally {\n await fs.rm(archivePath, { force: true });\n }\n}\n\nfunction isUnauthorized(error: unknown): boolean {\n return error instanceof StudioApiError && error.status === 401;\n}\n\ninterface StartedDeploy {\n environmentId: string;\n // Null from a Studio too old to have the status route.\n buildId: string | null;\n}\n\nasync function runDeploy({\n session,\n target,\n kind,\n archivePath,\n overrides,\n detected,\n project,\n}: {\n session: Session;\n target: CliTarget;\n kind: UploadKind;\n archivePath: string;\n overrides: BuildPlanInput;\n detected?: BuildPlanInput;\n project: Awaited<ReturnType<typeof readProject>>;\n}): Promise<StartedDeploy> {\n const { host, token } = session;\n const upload = await studioRequest<{\n uploadUrl: string;\n bundleName: string;\n appAlias: string;\n envAlias: string;\n environmentId: string;\n }>(host, '/api/upload-bundle', { method: 'POST', token, body: { ...target, kind } });\n\n await waitForEnvironmentReady(host, token, upload.environmentId);\n\n console.log(`Uploading to ${upload.appAlias}/${upload.envAlias}...`);\n const fileBuffer = await fs.readFile(archivePath);\n const uploadResponse = await fetch(upload.uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: { 'Content-Type': 'application/zip' },\n });\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload: ${uploadResponse.statusText}`);\n }\n\n const result = await studioRequest<{\n deploymentUrl: string;\n appAlias: string;\n envAlias: string;\n environmentId: string;\n buildId: string | null;\n plan?: BuildPlanInput | null;\n }>(host, '/api/deploy', {\n method: 'POST',\n token,\n body: {\n environmentId: upload.environmentId,\n bundleName: upload.bundleName,\n kind,\n plan: definedOnly(overrides),\n detected: detected ? definedOnly(detected) : undefined,\n },\n });\n\n // Whatever the target was resolved from, the next run can skip the picker.\n if (!project.deploy || project.deploy.environmentId !== result.environmentId) {\n await rememberTarget({\n environmentId: result.environmentId,\n appAlias: result.appAlias,\n envAlias: result.envAlias,\n });\n }\n\n if (result.plan) {\n reportResolvedPlan(result.plan, detected);\n }\n\n console.log(`Deployment started: ${result.deploymentUrl}`);\n return { environmentId: result.environmentId, buildId: result.buildId };\n}\n\n// An environment created moments ago in the browser is still provisioning\n// its database and telemetry; deploys are refused until it is ready.\nasync function waitForEnvironmentReady(host: string, token: string, environmentId: string) {\n const deadline = Date.now() + PROVISION_TIMEOUT_MS;\n let announced = false;\n while (Date.now() < deadline) {\n let status: string;\n try {\n ({ status } = await studioRequest<{ status: string }>(host, '/api/environment/status', {\n token,\n query: { environmentId },\n }));\n } catch (error) {\n if (error instanceof StudioApiError && error.status === 404) {\n // Older Studio without the route: let /api/deploy decide.\n return;\n }\n throw error;\n }\n if (status === 'ready') {\n return;\n }\n if (status === 'failed') {\n throw new Error('The environment failed to provision; check it in the dashboard.');\n }\n if (!announced) {\n console.log('Waiting for the environment to finish provisioning...');\n announced = true;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n throw new Error('Timed out waiting for the environment to be ready.');\n}\n\n// Prints phase transitions and streams build log lines until the deploy\n// settles. Exit code reflects the outcome so CI and agents can act on it.\nasync function followDeploy(\n session: Session,\n signInAgain: () => Promise<void>,\n environmentId: string,\n buildId: string\n) {\n const deadline = Date.now() + POLL_TIMEOUT_MS;\n let lastStatus = '';\n let lastMessage = '';\n let logOffset = 0;\n let signedInAgain = false;\n\n while (Date.now() < deadline) {\n let status: DeployStatus;\n try {\n status = await studioRequest<DeployStatus>(session.host, '/api/deploy/status', {\n token: session.token,\n query: { environmentId, buildId, logOffset },\n });\n } catch (error) {\n // A token can expire while a long rollout is being watched; the\n // build keeps going on the server, so only the watching resumes.\n if (!isUnauthorized(error) || signedInAgain) {\n throw error;\n }\n signedInAgain = true;\n await signInAgain();\n continue;\n }\n\n for (const line of status.logs) {\n process.stdout.write(` │ ${line.replace(/\\n$/, '')}\\n`);\n }\n // A poll that could not read CloudWatch reports zero lines; keeping the\n // offset avoids replaying the whole log on the next poll.\n logOffset = Math.max(logOffset, status.logCount);\n\n if (status.status !== lastStatus) {\n lastStatus = status.status;\n const message = describeStatus(status);\n // Two statuses can share a message (deploy-pending and deploying).\n if (message && message !== lastMessage) {\n lastMessage = message;\n console.log(message);\n }\n }\n\n if (status.status === 'deploy-completed') {\n if (status.siteUrl) {\n console.log(`Live at ${status.siteUrl}`);\n }\n return;\n }\n if (status.status === 'build-failed' || status.status === 'deploy-failed') {\n for (const error of status.errors) {\n console.error(` ${error}`);\n }\n if (status.containerLogs && status.containerLogs.length > 0) {\n console.error('Container output:');\n for (const line of status.containerLogs) {\n console.error(` │ ${line.replace(/\\n$/, '')}`);\n }\n }\n process.exitCode = 1;\n return;\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n console.error('Timed out waiting for the deployment; check the dashboard for its status.');\n process.exitCode = 1;\n}\n\nfunction describeStatus(status: DeployStatus): string | null {\n switch (status.status) {\n case 'build-pending':\n return 'Building image...';\n case 'deploy-pending':\n case 'deploying':\n return 'Image built. Deploying containers...';\n case 'rolling-out':\n return 'Rolling out new containers...';\n case 'deploy-completed':\n return 'Deployed successfully.';\n case 'build-failed':\n return 'Build failed.';\n case 'deploy-failed':\n return 'Deployment failed.';\n default:\n return null;\n }\n}\n\nfunction resolveTargetFromOptions(\n options: DeployOptions,\n project: Awaited<ReturnType<typeof readProject>>\n): CliTarget | null {\n if (options.app && options.env) {\n return { appAlias: options.app, envAlias: options.env };\n }\n if (options.env && project.deploy?.appAlias) {\n return { appAlias: project.deploy.appAlias, envAlias: options.env };\n }\n if (options.env && project.appId) {\n return { appId: project.appId, envAlias: options.env };\n }\n if (options.app || options.env) {\n throw new Error('Pass both --app and --env, or neither to pick the target in the browser.');\n }\n if (project.deploy?.environmentId) {\n return { environmentId: project.deploy.environmentId };\n }\n return null;\n}\n\nasync function resolveToken(host: string): Promise<string | null> {\n if (process.env.MODELENCE_TOKEN) {\n return process.env.MODELENCE_TOKEN;\n }\n return await readCachedToken(host);\n}\n\nasync function rememberToken(host: string, token: string, expiresAt?: string) {\n if (!expiresAt) {\n // Older Studio: the token lasts an hour, not worth caching.\n return;\n }\n try {\n await writeCachedToken(host, token, expiresAt);\n } catch (error) {\n console.warn('Could not save the login for next time:', error);\n }\n}\n\nasync function rememberTarget(target: CliAuthTarget | DeployTarget) {\n const deploy: DeployTarget = {\n environmentId: target.environmentId,\n appAlias: target.appAlias,\n envAlias: target.envAlias,\n };\n try {\n await updateProject({ deploy, ...('appId' in target ? { appId: target.appId } : {}) });\n } catch (error) {\n console.warn('Could not record the deploy target in .modelence/project.json:', error);\n }\n}\n\n// The Studio host: flag → environment → the project's .modelence.env → default.\n// Read directly rather than through loadEnv(), which requires a\n// modelence.config.ts that plain Node.js projects don't have.\nasync function resolveHost(flag: string | undefined, cwd: string): Promise<string> {\n if (flag) {\n return flag.replace(/\\/$/, '');\n }\n if (process.env.MODELENCE_SERVICE_ENDPOINT) {\n return process.env.MODELENCE_SERVICE_ENDPOINT.replace(/\\/$/, '');\n }\n try {\n const env = parseDotenv(await fs.readFile(join(cwd, '.modelence.env'), 'utf8'));\n if (env.MODELENCE_SERVICE_ENDPOINT) {\n return env.MODELENCE_SERVICE_ENDPOINT.replace(/\\/$/, '');\n }\n } catch {\n // No .modelence.env — plain Node.js projects usually have none.\n }\n return DEFAULT_HOST;\n}\n\nfunction planOverrides(options: DeployOptions): BuildPlanInput {\n return {\n preset: options.preset,\n nodeVersion: options.nodeVersion,\n rootDirectory: options.rootDir,\n installCommand: options.installCommand,\n buildCommand: options.buildCommand,\n startCommand: options.startCommand,\n outputDirectory: options.outputDir,\n };\n}\n\nfunction definedOnly<T extends object>(value: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined)\n ) as Partial<T>;\n}\n\nfunction printDetectedPlan(plan: BuildPlanInput, notes: string[]) {\n console.log('Build plan:');\n console.log(` preset: ${plan.preset ?? 'node'}`);\n console.log(` node: ${plan.nodeVersion ?? 'default (22)'}`);\n if (plan.rootDirectory) {\n console.log(` root: ${plan.rootDirectory}`);\n }\n console.log(` install: ${plan.installCommand ?? 'default'}`);\n console.log(` build: ${plan.buildCommand || '(none)'}`);\n if (plan.preset === 'static') {\n console.log(` serve: ${plan.outputDirectory ?? 'dist'}/ (static site)`);\n } else {\n console.log(` start: ${plan.startCommand ?? 'npm start'}`);\n }\n for (const note of notes) {\n console.log(` note: ${note}`);\n }\n}\n\n// Stored environment settings can override what was detected here; say so,\n// since the difference is otherwise only visible in the dashboard.\nfunction reportResolvedPlan(used: BuildPlanInput, detected?: BuildPlanInput) {\n if (!detected) {\n return;\n }\n const differences: string[] = [];\n if (used.preset && detected.preset && used.preset !== detected.preset) {\n differences.push(`preset ${used.preset} (detected ${detected.preset})`);\n }\n for (const field of ['installCommand', 'buildCommand', 'startCommand'] as const) {\n const detectedValue = detected[field];\n if (detectedValue !== undefined && used[field] !== undefined && used[field] !== detectedValue) {\n differences.push(\n `${field.replace('Command', '')} \"${used[field]}\" (detected \"${detectedValue}\")`\n );\n }\n }\n if (differences.length > 0) {\n console.log(\"Using the environment's Build & Deploy settings: \" + differences.join(', '));\n console.log('Edit them in the dashboard, or pass --preset/--*-command to change them.');\n }\n}\n\nfunction formatMb(bytes: number): string {\n return `${(bytes / 1024 / 1024).toFixed(2)} MB`;\n}\n\n// The historical --prebuilt bundle: build output plus the manifests the\n// container needs to install production dependencies.\nasync function createBundle(bundlePath: string) {\n await fs.rm(bundlePath, { force: true });\n console.log('Creating deployment bundle...');\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', { zlib: { level: 9 } });\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 archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'package-lock.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n const bundleDirs = ['public', 'server', 'scripts', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (await pathExists(getProjectPath(file))) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n for (const dir of bundleDirs) {\n if (await pathExists(getProjectPath(dir))) {\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(`Deployment bundle created (${formatMb(stats.size)})`);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(options: { takeover?: boolean } = {}) {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: {\n ...process.env,\n NODE_ENV: 'development',\n ...(options.takeover ? { MODELENCE_TAKEOVER: '1' } : {}),\n },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","import { clearCachedToken, getAuthCachePath } from './authCache';\n\n// Forgets the saved deploy login (all hosts, or one with --host).\nexport async function logout(options: { host?: string }) {\n await clearCachedToken(options.host);\n console.log(\n options.host\n ? `Removed the saved login for ${options.host}.`\n : `Removed saved logins (${getAuthCachePath()}).`\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 { logout } from './logout';\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(\n 'Deploy the current directory to Modelence Cloud (any Node.js app; picks the target in the browser on first run)'\n )\n .option('-a, --app <app>', 'Application alias')\n .option('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .option(\n '--prebuilt',\n 'Build locally and upload the .modelence/build bundle (Modelence apps only)'\n )\n .option('--preset <preset>', 'Build preset: node, static or modelence (default: detected)')\n .option('--node-version <version>', 'Node.js version for the container, e.g. 22')\n .option('--root-dir <path>', 'Subdirectory containing the app (monorepos)')\n .option('--install-command <command>', 'Override the detected install command')\n .option('--build-command <command>', 'Override the detected build command (\"\" to skip)')\n .option('--start-command <command>', 'Override the detected start command')\n .option('--output-dir <path>', 'Static sites: directory the build writes, e.g. dist')\n .action(async (options) => {\n try {\n await deploy(options);\n } catch (error) {\n console.error(`Deploy failed: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('logout')\n .description('Forget the saved Modelence Cloud login')\n .option('-h, --host <host>', 'Only forget the login for this host')\n .action(async (options) => {\n await logout(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .option(\n '--takeover',\n 'Disconnect any instance currently holding the environment and connect this one'\n )\n .action(async (options) => {\n await loadEnv();\n dev(options);\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}
1
+ {"version":3,"sources":["../../src/bin/auth.ts","../../src/bin/project.ts","../../src/bin/setup.ts","../../src/app/modelenceConfig.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/appSpec.ts","../../src/bin/authCache.ts","../../src/bin/detect/commands.ts","../../src/bin/detect/types.ts","../../src/bin/detect/conventions.ts","../../src/bin/detect/parsers.ts","../../src/bin/detect/facts.ts","../../src/bin/detect/profiles/lovable.ts","../../src/bin/detect/profiles/replit.ts","../../src/bin/detect/index.ts","../../src/bin/source.ts","../../src/bin/studioApi.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/start.ts","../../src/bin/logout.ts","../../src/bin/init.ts","../../src/bin/modelence.ts"],"names":["authenticateCli","host","pick","purpose","pickEnvironment","appId","response","code","verificationUrl","url","resolvedPick","open","waitForAuth","pollExpireTs","result","pollForToken","error","resolve","token","expiresAt","target","MODELENCE_DIR","PROJECT_FILE","getProjectFilePath","cwd","join","readProject","content","fs","parsed","updateProject","patch","existing","MODELENCE_ENV_FILE","fetchServiceConfig","auth","headers","errorText","ask","question","rl","createInterface","answer","confirmOverwrite","escapeEnvValue","value","readProjectAppId","recordProjectAppId","CLAUDE_DIR","CLAUDE_SETTINGS_FILE","CLAUDE_PLUGIN_ID","CLAUDE_MARKETPLACE_REPO","CLAUDE_MARKETPLACES","CLAUDE_PLUGIN_DOCS_URL","CLAUDE_PLUGIN_INSTALL_HINT","ensureClaudePluginEnabled","settingsPath","settings","runClaude","args","spawnSync","offerClaudePluginInstall","probe","marketplace","install","failed","backupEnvFile","envPath","backupPath","setup","options","existingEnv","fileExisted","envContent","parseEnv","cliToken","config","newEnv","key","configSchema","z","loadModelenceConfig","configPath","configModule","createJiti","env","getConfig","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","buildViteSsr","userConfig","loadConfigFromFile","modelenceConfig","path","viteBuild","mergeConfig","buildServer","tsupBuild","build","APP_SPEC_FILE_NAME","getAppSpecFilePath","readAppSpecFile","writeAppSpecFile","spec","mergeAppSpecs","layers","merged","layer","web","dropEmpty","definedOnly","entry","formatAppSpec","lines","mount","AUTH_FILE","EXPIRY_MARGIN_MS","getAuthCachePath","home","os","readAuthFile","writeAuthFile","dirname","readCachedToken","hosts","cached","writeCachedToken","current","clearCachedToken","_removed","rest","commandsFor","packageManager","version","useLockfile","script","member","withBuild","draft","withWeb","withNote","note","runtimeFromModelenceConfig","facts","nodeVersionFromEngines","installFromPackageManager","commands","next","buildFromScripts","commandContext","startFromProcfileOrScripts","startFromWorkspaceMember","startable","names","built","started","staticSiteFromBuildOutput","dir","staticOutputDirectory","mounted","startFallbackNote","CONVENTIONS","runDetectors","detectors","detector","frontendMembers","parseNodeMajor","range","match","major","parseProcfileWebCommand","line","isLockfileInSync","packageJson","lockfile","root","field","declared","locked","name","parsePackageManagerVersion","manager","PNPM_MAJOR_BY_LOCKFILE","pnpmMajorFromLockfile","lockfileText","parsePnpmWorkspaceGlobs","yamlText","globs","inPackages","item","parsePackageJsonWorkspaces","packages","parseViteOutDir","configText","parseReplitModules","replitText","globToRegExp","glob","pattern","segment","mergedDependencies","allDependencies","exists","readText","readJson","text","VITE_CONFIG_NAMES","readViteConfig","detectPackageManager","pnpmLock","pinned","npmLock","MAX_WORKSPACE_DEPTH","listDirectories","maxDepth","found","walk","depth","entries","full","findWorkspaceMembers","include","exclude","candidates","members","rel","relative","sep","re","vite","b","readWorkspaceGlobs","yaml","gatherProjectFacts","engines","procfile","replit","lovableProfile","DESIGN_TOOL_MEMBERS","DEFAULT_ARTIFACT_OUT_DIR","mountPathFor","single","basename","mountFrontends","frontends","mounts","frontendBuilds","index","command","noteProvisionedServices","module","replitProfile","PROFILES","detectFromFacts","conventional","profile","candidate","detectAppSpec","execFileAsync","promisify","execFile","MAX_SOURCE_BYTES","ALWAYS_EXCLUDED_DIRS","ALWAYS_EXCLUDED_FILES","toPosix","isExcludedPath","relativePath","segments","fileName","isGitRepository","stdout","listGitFiles","files","listSourceFiles","usedGit","file","packSource","zipPath","output","createWriteStream","archive","archiver","done","reject","size","StudioApiError","message","status","studioRequest","method","body","query","DEFAULT_HOST","POLL_INTERVAL_MS","POLL_TIMEOUT_MS","PROVISION_TIMEOUT_MS","deploy","resolveHost","kind","project","archivePath","createBundle","prepareSpecLayers","fileCount","sizeBytes","formatMb","resolveTargetFromOptions","resolveToken","rememberToken","rememberTarget","session","signInAgain","runDeploy","isUnauthorized","followDeploy","detected","overrides","specFromFlags","preview","sources","upload","waitForEnvironmentReady","fileBuffer","uploadResponse","reportEnvironmentSettings","environmentId","deadline","announced","buildId","lastStatus","lastMessage","logOffset","signedInAgain","describeStatus","flag","parseStaticFlag","separator","used","local","differences","compare","label","usedValue","localValue","usedMounts","bytes","bundlePath","archiveComplete","bundleFiles","bundleDirs","pathExists","stats","dev","serverPath","tsxPath","start","serverFilename","builtServerPath","logout","DEFAULT_SCHEMA_HOST","init","__filename","fileURLToPath","__dirname","readFileSync","program","Command","previous"],"mappings":";2jBAuCA,eAAsBA,CAAAA,CACpBC,EACA,CACE,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,EACA,eAAA,CAAAC,CAAAA,CAAkB,MAClB,KAAA,CAAAC,CACF,EAKI,EAAC,CACmB,CACxB,IAAMC,CAAAA,CAAW,MAAM,KAAA,CAAM,CAAA,EAAGL,CAAI,CAAA,aAAA,CAAA,CAAiB,CACnD,OAAQ,MACV,CAAC,EAED,GAAI,CAACK,EAAS,EAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0CAA0C,EAG5D,GAAM,CAAE,KAA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,CACdgR,KACF,CAAC,EAEHU,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import open from 'open';\n\n/*\n Browser device authorization: the CLI mints a code, the user approves it in\n the browser, and the CLI polls until approval binds a token to the code.\n\n Two approval modes, chosen by `pick`:\n 'environment' — `modelence setup`: the page also asks which environment to\n connect the local project to. The choice is stamped on the\n token; /api/setup derives its target from there.\n 'deploy' — `modelence deploy`: the page asks where to deploy (an\n existing or newly created app / cloud environment) and the\n token route reports the pick back so the CLI can record it\n in .modelence/project.json.\n Without `pick` the page only authorizes the device.\n\n `purpose: 'deploy'` asks for a deploy-lifetime token (30 days) without a\n picker — for a deploy whose target is already known from flags or\n .modelence/project.json. `pick: 'deploy'` implies it.\n\n `appId` is the hint from .modelence/project.json used to preselect the app.\n*/\n\nexport type CliAuthPick = 'environment' | 'deploy';\n\nexport interface CliAuthTarget {\n appId: string;\n appAlias: string;\n environmentId: string;\n envAlias: string;\n}\n\nexport interface CliAuthResult {\n token: string;\n // Absent on older Studio versions (tokens then last one hour).\n expiresAt?: string;\n target?: CliAuthTarget;\n}\n\nexport async function authenticateCli(\n host: string,\n {\n pick,\n purpose,\n pickEnvironment = false,\n appId,\n }: {\n pick?: CliAuthPick;\n purpose?: 'deploy';\n pickEnvironment?: boolean;\n appId?: string;\n } = {}\n): Promise<CliAuthResult> {\n const response = await fetch(`${host}/api/cli/auth`, {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n const url = new URL(verificationUrl);\n const resolvedPick = pick ?? (pickEnvironment ? 'environment' : undefined);\n if (resolvedPick) {\n url.searchParams.set('pick', resolvedPick);\n }\n if (purpose) {\n url.searchParams.set('purpose', purpose);\n }\n if (appId) {\n url.searchParams.set('appId', appId);\n }\n\n console.log(`Please visit ${url} to authenticate`);\n console.log(`Code: ${code}`);\n\n try {\n await open(url.toString());\n } catch {\n // Headless/SSH/container — no browser to open. The URL and code above\n // are already printed, so authentication can proceed manually.\n console.log('Could not open a browser automatically. Please open the URL above manually.');\n }\n\n return await waitForAuth(host, code);\n}\n\nasync function waitForAuth(host: string, code: string): Promise<CliAuthResult> {\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 result = await pollForToken(host, code);\n if (result) {\n return result;\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): Promise<CliAuthResult | null> {\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, expiresAt, target } = await response.json();\n if (!token) {\n return null;\n }\n return { token, expiresAt, target };\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport const MODELENCE_DIR = '.modelence';\nexport const PROJECT_FILE = 'project.json';\n\n/*\n .modelence/project.json — CLI-managed project state that is meant to be\n committed (unlike .modelence.env, which holds per-developer credentials).\n It records which app the project belongs to and, once a deploy target has\n been picked in the browser, which environment `modelence deploy` ships to.\n Everything in it is a hint, never a credential: access is re-checked on\n every request with the user's token.\n*/\n\nexport interface DeployTarget {\n environmentId: string;\n appAlias: string;\n envAlias: string;\n}\n\nexport interface ProjectFile {\n appId?: string;\n deploy?: DeployTarget;\n [key: string]: unknown;\n}\n\nexport function getProjectFilePath(cwd = process.cwd()): string {\n return join(cwd, MODELENCE_DIR, PROJECT_FILE);\n}\n\n// Missing or malformed reads as an empty project rather than failing the\n// command: the file only ever pre-fills choices.\nexport async function readProject(cwd = process.cwd()): Promise<ProjectFile> {\n try {\n const content = await fs.readFile(getProjectFilePath(cwd), 'utf8');\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport async function updateProject(\n patch: Partial<ProjectFile>,\n cwd = process.cwd()\n): Promise<void> {\n const existing = await readProject(cwd);\n await fs.mkdir(join(cwd, MODELENCE_DIR), { recursive: true });\n await fs.writeFile(\n getProjectFilePath(cwd),\n JSON.stringify({ ...existing, ...patch }, null, 2) + '\\n'\n );\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\nimport { spawnSync } from 'child_process';\nimport { authenticateCli } from './auth';\nimport { MODELENCE_DIR, PROJECT_FILE, readProject, updateProject } from './project';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n // Absent on older Modelence Cloud versions.\n appId?: string;\n}\n\n/*\n Two ways to authenticate against /api/setup, matching the two ways setup is\n run: a setup token pasted from the dashboard, or a CLI token from the\n browser device flow. Either way the credential itself carries the\n environment choice — the server derives the target from it, so nothing\n else needs to be sent.\n*/\ntype SetupAuth = { setupToken: string } | { cliToken: string };\n\nasync function fetchServiceConfig(host: string, auth: SetupAuth): Promise<SetupResponse> {\n const headers: Record<string, string> =\n 'setupToken' in auth\n ? { 'X-Modelence-Setup-Token': auth.setupToken }\n : { Authorization: `Bearer ${auth.cliToken}` };\n\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function ask(question: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const answer = await ask(\n `Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `\n );\n return answer.toLowerCase() === 'y';\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\n/*\n The app this project was last connected to, if a previous setup (by anyone\n on the team — the file is committed) recorded it. Used only to preselect\n the app on the approval page; anything unreadable means \"no hint\".\n*/\nasync function readProjectAppId(): Promise<string | undefined> {\n const { appId } = await readProject();\n return typeof appId === 'string' && appId ? appId : undefined;\n}\n\n/*\n Records which app this project belongs to in .modelence/project.json. Unlike\n .modelence.env this file is meant to be committed (the .modelence/ root holds\n CLI-managed project state; only designated subdirs like build/, cache/ and\n tmp/ are temporary), so the whole team gets it. It's a hint in the git-remote\n sense — connect flows use it to preselect the app, never to block a different\n choice — which is why failing to write it doesn't fail the setup.\n\n Only the app goes here: which ENVIRONMENT a working copy connects to is\n per-developer state, already recorded by .modelence.env, and committing it\n would make teammates connected to different environments fight over the\n value. (The deploy target recorded by `modelence deploy` is different: it is\n shared on purpose, like a git remote.)\n*/\nasync function recordProjectAppId(appId: string): Promise<void> {\n await updateProject({ appId });\n}\n\nconst CLAUDE_DIR = '.claude';\nconst CLAUDE_SETTINGS_FILE = join(CLAUDE_DIR, 'settings.json');\nconst CLAUDE_PLUGIN_ID = 'modelence@modelence';\n// Without the marketplace declared alongside enabledPlugins, Claude Code\n// can't resolve the plugin unless the user already ran\n// `claude plugin marketplace add` themselves.\nconst CLAUDE_MARKETPLACE_REPO = 'modelence/modelence';\nconst CLAUDE_MARKETPLACES = {\n modelence: { source: { source: 'github', repo: CLAUDE_MARKETPLACE_REPO } },\n};\nconst CLAUDE_PLUGIN_DOCS_URL = 'https://docs.modelence.com/ai-coding-agents';\nconst CLAUDE_PLUGIN_INSTALL_HINT =\n 'Install the Modelence plugin for Claude Code by hand:\\n' +\n ` claude plugin marketplace add ${CLAUDE_MARKETPLACE_REPO}\\n` +\n ` claude plugin install ${CLAUDE_PLUGIN_ID} --scope project\\n` +\n `Guide: ${CLAUDE_PLUGIN_DOCS_URL}`;\n\n/*\n Declares the Modelence Claude Code plugin in the project's settings.json,\n merging into an existing file rather than replacing it. An explicit\n `false` is a deliberate opt-out and is never flipped back on. The file is\n inert for people who don't use Claude Code, and failing to write it doesn't\n fail the setup.\n*/\nasync function ensureClaudePluginEnabled(): Promise<void> {\n const settingsPath = join(process.cwd(), CLAUDE_SETTINGS_FILE);\n\n let content: string | undefined;\n try {\n content = await fs.readFile(settingsPath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n console.warn(`Could not read ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n let settings: Record<string, any> = {};\n if (content !== undefined) {\n try {\n settings = JSON.parse(content);\n } catch {\n console.warn(`Could not parse ${CLAUDE_SETTINGS_FILE}; leaving it unchanged.`);\n return;\n }\n }\n\n // The marketplace is only a pointer, so it's always (re)declared — a file\n // with just enabledPlugins, as `claude plugin install --scope project`\n // leaves behind, can't be resolved by teammates without it. An explicit\n // `false` in enabledPlugins is the user's opt-out and is left alone.\n settings.extraKnownMarketplaces = { ...settings.extraKnownMarketplaces, ...CLAUDE_MARKETPLACES };\n if (settings.enabledPlugins?.[CLAUDE_PLUGIN_ID] === undefined) {\n settings.enabledPlugins = { ...settings.enabledPlugins, [CLAUDE_PLUGIN_ID]: true };\n }\n\n try {\n await fs.mkdir(join(process.cwd(), CLAUDE_DIR), { recursive: true });\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n console.log(`Declared the Modelence Claude Code plugin in ${CLAUDE_SETTINGS_FILE}`);\n } catch (error) {\n console.warn(`Failed to write ${CLAUDE_SETTINGS_FILE}:`, error);\n }\n}\n\nfunction runClaude(args: string[]) {\n return spawnSync('claude', args, { encoding: 'utf8', shell: process.platform === 'win32' });\n}\n\n/*\n Installs the plugin through the Claude Code CLI — the one install path that\n behaves the same for the terminal, the IDE extensions and the desktop app,\n which all read the same plugin state. Touches the user's machine-wide Claude\n config, so it asks first, and it never fails the setup: without the CLI on\n PATH it prints the commands to run by hand.\n*/\nasync function offerClaudePluginInstall(): Promise<void> {\n const probe = runClaude(['--version']);\n if (probe.error || probe.status !== 0) {\n console.log(CLAUDE_PLUGIN_INSTALL_HINT);\n return;\n }\n\n const answer = (await ask('Install the Modelence plugin for Claude Code? (Y/n) ')).toLowerCase();\n if (answer && answer !== 'y' && answer !== 'yes') {\n return;\n }\n\n // Makes the install work before Claude Code has picked up the marketplace\n // declared in .claude/settings.json. Its result only matters if the install\n // then fails: a network or auth error here is the real cause, and the\n // install's own message wouldn't point at it.\n const marketplace = runClaude(['plugin', 'marketplace', 'add', CLAUDE_MARKETPLACE_REPO]);\n const install = runClaude(['plugin', 'install', CLAUDE_PLUGIN_ID, '--scope', 'project']);\n if (install.status === 0) {\n console.log(\n 'Installed the Modelence plugin for Claude Code. Sign in once from Claude Code: ' +\n 'run /mcp, choose modelence, then Authenticate.'\n );\n } else {\n const failed = marketplace.status !== 0 ? marketplace : install;\n console.warn(\n `Could not install the Modelence plugin: ${(failed.stderr || failed.stdout || '').trim()}`\n );\n console.warn(CLAUDE_PLUGIN_INSTALL_HINT);\n }\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token?: string; host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n let fileExisted = false;\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n fileExisted = true;\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch {\n // File doesn't exist, we'll create it\n }\n\n let auth: SetupAuth;\n if (options.token) {\n auth = { setupToken: options.token };\n } else {\n // No token given: authorize in the browser, where the approval page\n // also asks which environment to connect to.\n const { token: cliToken } = await authenticateCli(options.host, {\n pickEnvironment: true,\n appId: await readProjectAppId(),\n });\n auth = { cliToken };\n }\n\n // Fetch service configuration\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.host, auth);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n // Where this working copy runs; Studio sandboxes pre-set \"sandbox\".\n MODELENCE_RUNTIME: process.env.MODELENCE_RUNTIME || 'local',\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n if (config.appId) {\n try {\n await recordProjectAppId(config.appId);\n console.log(`Recorded the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}`);\n } catch (error) {\n console.warn(`Failed to record the app ID in ${MODELENCE_DIR}/${PROJECT_FILE}:`, error);\n }\n }\n\n await ensureClaudePluginEnabled();\n // Interactive runs only: with --token (CI) or without a terminal there is\n // nobody to ask, and no Claude Code to set up.\n if (!options.token && process.stdin.isTTY) {\n await offerClaudePluginInstall();\n }\n\n if (fileExisted) {\n // The dev server reads the file at boot, and an open agent session may\n // still hold the old environment id in its context.\n console.log(\n 'The project now points to a different environment. Restart your dev server, and if you use ' +\n 'an AI coding agent, start a new session.'\n );\n }\n\n // Only for a first-time setup: re-running it on an existing file already\n // told them to restart the dev server they're running.\n if (!fileExisted && newEnv.MODELENCE_RUNTIME === 'local') {\n console.log('\\nNext step — run the app on this machine:\\n');\n console.log(\" npm install (if you haven't already)\");\n console.log(' npm run dev (starts the app)\\n');\n }\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { join } from 'path';\nimport { createJiti } from 'jiti';\nimport { z } from 'zod';\nimport type { ModelenceConfig } from '../types';\n\nconst configSchema = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional(),\n});\n\nexport async function loadModelenceConfig(): Promise<ModelenceConfig> {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false,\n });\n\n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n\n return configSchema.parse(configModule);\n}\n","import { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport type { ModelenceConfig } from '../types';\nimport { loadModelenceConfig } from '../app/modelenceConfig';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\n}\n\nexport async function loadEnv() {\n try {\n config = await loadModelenceConfig();\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n // Always emit SSR artifacts; `startApp({ ssr: true })` decides if they're used.\n await buildVite();\n await buildViteSsr();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n // Emit `.vite/ssr-manifest.json` for ssr/collectCss.ts.\n ssrManifest: true,\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildViteSsr() {\n console.log('Building SSR bundle with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const ssrEntry = path.resolve(process.cwd(), 'src/client/index.tsx').replace(/\\\\/g, '/');\n const modelenceConfig = {\n build: {\n ssr: ssrEntry,\n outDir: path.resolve(process.cwd(), '.modelence/build/ssr').replace(/\\\\/g, '/'),\n emptyOutDir: true,\n rollupOptions: {\n output: {\n format: 'esm' as const,\n entryFileNames: 'index.mjs',\n },\n },\n },\n };\n\n await viteBuild(mergeConfig(userConfig?.config || {}, modelenceConfig, true));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve) => {\n void tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n skipNodeModulesBundle: true,\n treeshake: true,\n platform: 'node',\n outExtension: () => ({\n js: '.mjs',\n }),\n onSuccess: async () => {\n resolve(undefined);\n },\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n\n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n try {\n await fs.access(getModelencePath());\n } catch {\n throw new Error(\n 'Could not find the .modelence directory. Looks like something went wrong during the build.'\n );\n }\n}\n","import { promises as fs } from 'fs';\nimport { join } from 'path';\n\n/*\n modelence.json — how the project is built and run on Modelence Cloud. The\n CLI reads it as-is and sends it to Studio, which validates it against the\n schema published at /schema/modelence.json and merges it with the\n environment's settings and the CLI's detection. The types here mirror that\n schema; the server is the authority.\n*/\n\nexport const APP_SPEC_FILE_NAME = 'modelence.json';\n\nexport type AppRuntime = 'node' | 'modelence';\n\nexport interface StaticMount {\n path: string;\n dir: string;\n}\n\nexport interface AppSpec {\n $schema?: string;\n runtime?: AppRuntime;\n build?: {\n node?: string;\n root?: string;\n install?: string;\n command?: string;\n env?: Record<string, string>;\n };\n web?: {\n start?: string;\n static?: StaticMount[];\n };\n}\n\nexport function getAppSpecFilePath(cwd = process.cwd()): string {\n return join(cwd, APP_SPEC_FILE_NAME);\n}\n\n// The file's content, or null when there is none. A file that is not valid\n// JSON is an error: silently ignoring it would deploy something else.\nexport async function readAppSpecFile(cwd = process.cwd()): Promise<AppSpec | null> {\n let content: string;\n try {\n content = await fs.readFile(getAppSpecFilePath(cwd), 'utf8');\n } catch {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(\n `${APP_SPEC_FILE_NAME} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${APP_SPEC_FILE_NAME} must contain a JSON object`);\n }\n return parsed as AppSpec;\n}\n\nexport async function writeAppSpecFile(spec: AppSpec, cwd = process.cwd()): Promise<void> {\n await fs.writeFile(getAppSpecFilePath(cwd), JSON.stringify(spec, null, 2) + '\\n');\n}\n\n// Layers merged the way the server does, for the plan shown before the\n// upload: later arguments win; build.env merges by key, mount lists replace.\nexport function mergeAppSpecs(...layers: (AppSpec | null | undefined)[]): AppSpec {\n return layers.reduce<AppSpec>((merged, layer) => {\n if (!layer) {\n return merged;\n }\n const build = { ...merged.build, ...layer.build };\n if (merged.build?.env || layer.build?.env) {\n build.env = { ...merged.build?.env, ...layer.build?.env };\n }\n const web = { ...merged.web, ...layer.web };\n return dropEmpty({\n ...merged,\n ...(layer.runtime ? { runtime: layer.runtime } : {}),\n build,\n web,\n });\n }, {});\n}\n\nfunction dropEmpty(spec: AppSpec): AppSpec {\n const result: AppSpec = { ...spec };\n if (result.build && Object.keys(result.build).length === 0) {\n delete result.build;\n }\n if (result.web && Object.keys(result.web).length === 0) {\n delete result.web;\n }\n return result;\n}\n\n// Only the keys a user actually set, so \"unset\" stays distinguishable from\n// \"empty\" on the server.\nexport function definedOnly<T extends object>(value: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined)\n ) as Partial<T>;\n}\n\nexport function formatAppSpec(spec: AppSpec): string[] {\n const lines: string[] = [];\n lines.push(` runtime: ${spec.runtime ?? 'node'}`);\n lines.push(` node: ${spec.build?.node ?? 'default (22)'}`);\n if (spec.build?.root && spec.build.root !== '.') {\n lines.push(` root: ${spec.build.root}`);\n }\n lines.push(` install: ${spec.build?.install ?? 'default'}`);\n lines.push(` build: ${spec.build?.command || '(none)'}`);\n for (const [key, value] of Object.entries(spec.build?.env ?? {})) {\n lines.push(` env: ${key}=${value}`);\n }\n if (spec.web?.start) {\n lines.push(` start: ${spec.web.start}`);\n } else if (!spec.web?.static?.length) {\n lines.push(' start: (none)');\n }\n for (const mount of spec.web?.static ?? []) {\n lines.push(` static: ${mount.path} -> ${mount.dir}/`);\n }\n return lines;\n}\n","import { promises as fs } from 'fs';\nimport os from 'os';\nimport { dirname, join } from 'path';\n\n/*\n Cached deploy authorization, per Studio host, in the user's home directory\n (never in the project). Written only after a browser approval, dropped by\n `modelence logout` or when Studio rejects it. MODELENCE_HOME overrides the\n location (tests, sandboxes).\n*/\n\nconst AUTH_FILE = 'auth.json';\n// A token about to expire is treated as expired so a deploy doesn't fail\n// halfway through its polling.\nconst EXPIRY_MARGIN_MS = 60 * 1000;\n\ninterface CachedToken {\n token: string;\n expiresAt: string;\n}\n\ninterface AuthFile {\n hosts?: Record<string, CachedToken>;\n}\n\nexport function getAuthCachePath(): string {\n const home = process.env.MODELENCE_HOME || join(os.homedir(), '.modelence');\n return join(home, AUTH_FILE);\n}\n\nasync function readAuthFile(): Promise<AuthFile> {\n try {\n const parsed = JSON.parse(await fs.readFile(getAuthCachePath(), 'utf8'));\n return parsed && typeof parsed === 'object' ? parsed : {};\n } catch {\n return {};\n }\n}\n\nasync function writeAuthFile(content: AuthFile): Promise<void> {\n const path = getAuthCachePath();\n await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await fs.writeFile(path, JSON.stringify(content, null, 2) + '\\n', { mode: 0o600 });\n}\n\nexport async function readCachedToken(host: string): Promise<string | null> {\n const { hosts = {} } = await readAuthFile();\n const cached = hosts[host];\n if (!cached?.token || !cached.expiresAt) {\n return null;\n }\n if (new Date(cached.expiresAt).getTime() - EXPIRY_MARGIN_MS <= Date.now()) {\n return null;\n }\n return cached.token;\n}\n\nexport async function writeCachedToken(\n host: string,\n token: string,\n expiresAt: string\n): Promise<void> {\n const current = await readAuthFile();\n await writeAuthFile({\n ...current,\n hosts: { ...current.hosts, [host]: { token, expiresAt } },\n });\n}\n\nexport async function clearCachedToken(host?: string): Promise<void> {\n if (!host) {\n await writeAuthFile({});\n return;\n }\n const current = await readAuthFile();\n const { [host]: _removed, ...rest } = current.hosts ?? {};\n await writeAuthFile({ ...current, hosts: rest });\n}\n","import type { PackageManager } from './parsers';\n\n/*\n The shell commands each package manager needs for the same intents, so\n detectors say \"install\", \"run build in member X\" and never spell out a\n manager-specific line themselves.\n*/\n\nexport interface PackageManagerCommands {\n install: string;\n run: (script: string) => string;\n start: string;\n // Run a script in one workspace member.\n runIn: (member: string, script: string) => string;\n // Build one member plus its workspace dependencies (pnpm's `name...`\n // filter); npm and yarn classic have no closure syntax, so only the\n // member itself is built there.\n buildWithDependencies: (member: string) => string;\n startIn: (member: string) => string;\n}\n\nexport function commandsFor({\n packageManager,\n version,\n useLockfile,\n}: {\n packageManager: PackageManager;\n version?: string;\n useLockfile: boolean;\n}): PackageManagerCommands {\n switch (packageManager) {\n case 'pnpm': {\n // Without a pin `npm install -g pnpm` picks whatever is latest, which\n // can be a major ahead of the lockfile and refuse the install.\n const pnpmPackage = version ? `pnpm@${version}` : 'pnpm';\n return {\n install: `npm install -g ${pnpmPackage} && pnpm install --frozen-lockfile`,\n run: (script) => `pnpm run ${script}`,\n start: 'pnpm start',\n runIn: (member, script) => `pnpm --filter ${member} run ${script}`,\n buildWithDependencies: (member) => `pnpm --filter ${member}... --if-present run build`,\n startIn: (member) => `pnpm --filter ${member} start`,\n };\n }\n case 'yarn':\n return {\n install: 'yarn install --frozen-lockfile',\n run: (script) => `yarn ${script}`,\n start: 'yarn start',\n runIn: (member, script) => `yarn workspace ${member} run ${script}`,\n buildWithDependencies: (member) => `yarn workspace ${member} run build`,\n startIn: (member) => `yarn workspace ${member} start`,\n };\n default:\n return {\n install: useLockfile ? 'npm ci' : 'npm install',\n run: (script) => `npm run ${script}`,\n start: 'npm start',\n runIn: (member, script) => `npm run ${script} --workspace ${member}`,\n buildWithDependencies: (member) => `npm run build --if-present --workspace ${member}`,\n startIn: (member) => `npm start --workspace ${member}`,\n };\n }\n}\n","import type { AppSpec } from '../appSpec';\nimport type { ProjectFacts } from './facts';\n\n/*\n A detector is a pure step of the pipeline: it looks at the project facts\n and the draft so far, and returns a new draft. Conventions are origin-blind\n rules (lockfile → install command, Procfile → start command…); profiles\n recognize where a project came from and add what that tooling assumes.\n Neither does I/O, so each is tested with a facts object.\n*/\n\nexport interface Draft {\n spec: AppSpec;\n notes: string[];\n}\n\nexport type Detector = (facts: ProjectFacts, draft: Draft) => Draft;\n\nexport interface Profile {\n name: string;\n matches: (facts: ProjectFacts) => boolean;\n apply: Detector;\n}\n\nexport function withBuild(draft: Draft, patch: NonNullable<AppSpec['build']>): Draft {\n return { ...draft, spec: { ...draft.spec, build: { ...draft.spec.build, ...patch } } };\n}\n\nexport function withWeb(draft: Draft, patch: NonNullable<AppSpec['web']>): Draft {\n return { ...draft, spec: { ...draft.spec, web: { ...draft.spec.web, ...patch } } };\n}\n\nexport function withNote(draft: Draft, note: string): Draft {\n return { ...draft, notes: [...draft.notes, note] };\n}\n","import { commandsFor } from './commands';\nimport type { ProjectFacts, WorkspaceMember } from './facts';\nimport { withBuild, withNote, withWeb, type Detector, type Draft } from './types';\n\n/*\n Origin-blind conventions, in the order they run. Each fills in what it can\n and leaves the rest untouched, so a later detector (or the user's\n modelence.json) can still decide. Nothing here knows about Replit,\n Lovable or any other tool; that knowledge lives in profiles/.\n*/\n\nexport const runtimeFromModelenceConfig: Detector = (facts, draft) => {\n if (!facts.hasModelenceConfig) {\n return draft;\n }\n return { ...draft, spec: { ...draft.spec, runtime: 'modelence' } };\n};\n\nexport const nodeVersionFromEngines: Detector = (facts, draft) => {\n if (!facts.nodeMajor) {\n return draft;\n }\n return withBuild(draft, { node: facts.nodeMajor });\n};\n\nexport const installFromPackageManager: Detector = (facts, draft) => {\n const commands = commandsFor({\n packageManager: facts.packageManager,\n version: facts.packageManagerVersion,\n useLockfile: facts.lockfile.present && facts.lockfile.inSync,\n });\n let next = withBuild(draft, { install: commands.install });\n if (facts.packageManager === 'npm' && !facts.lockfile.present) {\n next = withNote(\n next,\n 'No package-lock.json found; dependencies are installed with `npm install`.'\n );\n }\n if (facts.packageManager === 'npm' && facts.lockfile.present && !facts.lockfile.inSync) {\n next = withNote(\n next,\n 'package-lock.json is out of date with package.json, so dependencies are installed with `npm install`. ' +\n 'Run `npm install` locally and commit the lockfile to get reproducible `npm ci` installs.'\n );\n }\n if (facts.packageManager === 'pnpm' && !facts.packageManagerVersion) {\n next = withNote(\n next,\n 'Could not tell which pnpm version wrote pnpm-lock.yaml; the build installs the latest. ' +\n 'Add e.g. \"packageManager\": \"pnpm@10.4.1\" to package.json to pin it.'\n );\n }\n return next;\n};\n\nexport const buildFromScripts: Detector = (facts, draft) => {\n if (!facts.scripts.build) {\n return draft;\n }\n return withBuild(draft, { command: commandsFor(commandContext(facts)).run('build') });\n};\n\nexport const startFromProcfileOrScripts: Detector = (facts, draft) => {\n if (facts.procfileWeb) {\n return withWeb(draft, { start: facts.procfileWeb });\n }\n if (facts.scripts.start) {\n return withWeb(draft, { start: commandsFor(commandContext(facts)).start });\n }\n return draft;\n};\n\n// Deploying one member of a workspace when the root has nothing to start:\n// the single member with a start script is the app, and the build is scoped\n// to it and its workspace dependencies rather than every sibling.\nexport const startFromWorkspaceMember: Detector = (facts, draft) => {\n if (draft.spec.web?.start || draft.spec.runtime === 'modelence') {\n return draft;\n }\n const startable = facts.workspace.members.filter((member) => member.scripts.start);\n if (startable.length === 0) {\n return draft;\n }\n if (startable.length > 1) {\n const names = startable.map((member) => member.name).join(', ');\n return withNote(\n draft,\n `Several workspace packages have a start script (${names}); set web.start in modelence.json or pass --start-command to choose one.`\n );\n }\n const [member] = startable;\n const commands = commandsFor(commandContext(facts));\n const built = withBuild(draft, { command: commands.buildWithDependencies(member.name) });\n const started = withWeb(built, { start: commands.startIn(member.name) });\n return withNote(\n started,\n `No root start script; the container starts the ${member.name} workspace package (${member.dir}/), ` +\n 'and the build is scoped to it and its workspace dependencies.'\n );\n};\n\n// A client-only site (Vite, Lovable, CRA…): something to build, nothing to\n// start. The runtime serves the build output itself.\nexport const staticSiteFromBuildOutput: Detector = (facts, draft) => {\n if (draft.spec.web?.start || draft.spec.runtime === 'modelence' || !draft.spec.build?.command) {\n return draft;\n }\n const dir = staticOutputDirectory(facts);\n if (!dir) {\n return draft;\n }\n const mounted = withWeb(draft, { static: [{ path: '/', dir }] });\n return withNote(\n mounted,\n `No start script found; the site is served from ${dir}/ with single-page app fallback.`\n );\n};\n\nexport const startFallbackNote: Detector = (facts, draft) => {\n if (\n draft.spec.web?.start ||\n draft.spec.web?.static?.length ||\n draft.spec.runtime === 'modelence'\n ) {\n return draft;\n }\n return withNote(\n draft,\n 'No `start` script or Procfile found; set web.start in modelence.json or pass --start-command.'\n );\n};\n\nexport const CONVENTIONS: Detector[] = [\n runtimeFromModelenceConfig,\n nodeVersionFromEngines,\n installFromPackageManager,\n buildFromScripts,\n startFromProcfileOrScripts,\n startFromWorkspaceMember,\n staticSiteFromBuildOutput,\n startFallbackNote,\n];\n\nexport function runDetectors(facts: ProjectFacts, detectors: Detector[], draft: Draft): Draft {\n return detectors.reduce((current, detector) => detector(facts, current), draft);\n}\n\nexport function commandContext(facts: ProjectFacts) {\n return {\n packageManager: facts.packageManager,\n version: facts.packageManagerVersion,\n useLockfile: facts.lockfile.present && facts.lockfile.inSync,\n };\n}\n\nfunction staticOutputDirectory(facts: ProjectFacts): string | undefined {\n if (facts.dependencies.vite || facts.hasViteConfig) {\n return facts.viteOutDir ?? 'dist';\n }\n if (facts.dependencies['react-scripts']) {\n return 'build';\n }\n if (facts.dependencies['@angular/cli'] || facts.dependencies.astro) {\n return 'dist';\n }\n // A root index.html with a build script is the Vite/Parcel convention.\n if (facts.hasIndexHtml) {\n return 'dist';\n }\n return undefined;\n}\n\n// Workspace members that are Vite apps without a process of their own:\n// frontends a profile may mount next to the app.\nexport function frontendMembers(facts: ProjectFacts): WorkspaceMember[] {\n return facts.workspace.members.filter(\n (member) => member.hasViteConfig && !member.scripts.start && member.scripts.build\n );\n}\n","/*\n Pure parsers for the files detection reads. No I/O, no decisions: each\n turns one file's text or JSON into a fact the detectors can use.\n*/\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn';\n\nconst MINIMUM_NODE_MAJOR = 18;\n\n// The first version number in a semver range, e.g. \">=20.10 <23\" → \"20\",\n// \"22.x\" → \"22\". Anything below the supported floor is ignored.\nexport function parseNodeMajor(range: unknown): string | undefined {\n if (typeof range !== 'string') {\n return undefined;\n }\n const match = range.match(/(\\d+)(?:\\.\\d+)?(?:\\.\\d+)?/);\n if (!match) {\n return undefined;\n }\n const major = Number(match[1]);\n return major >= MINIMUM_NODE_MAJOR ? String(major) : undefined;\n}\n\nexport function parseProcfileWebCommand(content: string): string | undefined {\n for (const line of content.split(/\\r?\\n/)) {\n const match = line.match(/^\\s*web\\s*:\\s*(.+?)\\s*$/);\n if (match) {\n return match[1];\n }\n }\n return undefined;\n}\n\n/*\n `npm ci` refuses a package-lock.json that disagrees with package.json — a\n common state for generated projects (Lovable adds a dependency without\n refreshing the lock). Compares the root package's declared dependencies\n with the lock's root entry (lockfileVersion 2+). An old v1 lock has no root\n entry, so it is trusted as-is.\n*/\nexport function isLockfileInSync(\n packageJson: Record<string, unknown>,\n lockfile: Record<string, unknown>\n): boolean {\n const packages = lockfile.packages as Record<string, Record<string, unknown>> | undefined;\n const root = packages?.[''];\n if (!root) {\n return true;\n }\n for (const field of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) {\n const declared = (packageJson[field] ?? {}) as Record<string, string>;\n const locked = (root[field] ?? {}) as Record<string, string>;\n const names = new Set([...Object.keys(declared), ...Object.keys(locked)]);\n for (const name of names) {\n if (declared[name] !== locked[name]) {\n return false;\n }\n }\n }\n return true;\n}\n\n// package.json `packageManager` (\"pnpm@10.4.1+sha512...\") → \"10.4.1\" when it\n// names the given manager. Anything that is not a plain semver version is\n// ignored rather than passed to npm.\nexport function parsePackageManagerVersion(\n field: unknown,\n manager: PackageManager\n): string | undefined {\n if (typeof field !== 'string') {\n return undefined;\n }\n const match = /^([a-z]+)@(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)(?:\\+.*)?$/.exec(field.trim());\n if (!match || match[1] !== manager) {\n return undefined;\n }\n return match[2];\n}\n\n// pnpm-lock.yaml `lockfileVersion` → the pnpm major that reads it. 9.0 is\n// written by pnpm 9 and 10 alike; 10 is picked because it reads both and\n// only warns about unapproved build scripts where 11 fails.\nconst PNPM_MAJOR_BY_LOCKFILE: Record<string, number> = {\n '5': 7,\n '6': 8,\n '9': 10,\n};\n\nexport function pnpmMajorFromLockfile(lockfileText: string): number | undefined {\n const match = /^lockfileVersion:\\s*['\"]?(\\d+)(?:\\.\\d+)?['\"]?\\s*$/m.exec(lockfileText);\n if (!match) {\n return undefined;\n }\n return PNPM_MAJOR_BY_LOCKFILE[match[1]];\n}\n\n// The `packages:` list of pnpm-workspace.yaml. Only the flat \"- glob\" form\n// pnpm documents is handled; anything else yields no globs.\nexport function parsePnpmWorkspaceGlobs(yamlText: string): string[] {\n const globs: string[] = [];\n let inPackages = false;\n for (const line of yamlText.split('\\n')) {\n if (/^packages:\\s*$/.test(line)) {\n inPackages = true;\n continue;\n }\n if (!inPackages) {\n continue;\n }\n const item = /^\\s+-\\s*['\"]?([^'\"#]+?)['\"]?\\s*(?:#.*)?$/.exec(line);\n if (item) {\n globs.push(item[1].trim());\n } else if (line.trim() !== '' && !line.startsWith(' ') && !line.startsWith('\\t')) {\n inPackages = false;\n }\n }\n return globs;\n}\n\n// package.json `workspaces`: an array, or yarn's `{ packages: [...] }`.\nexport function parsePackageJsonWorkspaces(packageJson: Record<string, unknown>): string[] {\n const field = packageJson.workspaces;\n if (Array.isArray(field)) {\n return field.filter((entry): entry is string => typeof entry === 'string');\n }\n if (field && typeof field === 'object') {\n const packages = (field as { packages?: unknown }).packages;\n return Array.isArray(packages)\n ? packages.filter((entry): entry is string => typeof entry === 'string')\n : [];\n }\n return [];\n}\n\n// The `outDir` of a Vite config, when it is a string literal or a\n// path.resolve(..., \"literal\") — enough for the generated configs\n// detection cares about. Anything else means \"unknown\".\nexport function parseViteOutDir(configText: string): string | undefined {\n const match =\n /outDir:\\s*(?:path\\.resolve\\([^)]*?,\\s*)?[\"'`]([^\"'`]+)[\"'`]/.exec(configText) ??\n /outDir:\\s*[\"'`]([^\"'`]+)[\"'`]/.exec(configText);\n return match ? match[1].replace(/^\\.\\//, '').replace(/\\/+$/, '') : undefined;\n}\n\n// `modules = [\"nodejs-24\", \"postgresql-16\"]` from a .replit file.\nexport function parseReplitModules(replitText: string): string[] {\n const match = /^modules\\s*=\\s*\\[([^\\]]*)\\]/m.exec(replitText);\n if (!match) {\n return [];\n }\n return [...match[1].matchAll(/[\"']([^\"']+)[\"']/g)].map((entry) => entry[1]);\n}\n\nexport function globToRegExp(glob: string): RegExp {\n const normalized = glob.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n const pattern = normalized\n .split('/')\n .map((segment) => {\n if (segment === '**') {\n return '.*';\n }\n return segment.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '[^/]*');\n })\n .join('/');\n return new RegExp(`^${pattern}$`);\n}\n","import { promises as fs } from 'fs';\nimport { join, relative, sep } from 'path';\nimport {\n globToRegExp,\n isLockfileInSync,\n parseNodeMajor,\n parsePackageJsonWorkspaces,\n parsePackageManagerVersion,\n parsePnpmWorkspaceGlobs,\n parseProcfileWebCommand,\n parseReplitModules,\n parseViteOutDir,\n pnpmMajorFromLockfile,\n type PackageManager,\n} from './parsers';\n\n/*\n Everything detection may want to know about a project, read once. The\n detectors themselves are pure functions over this object, which keeps\n them trivially testable and keeps file access in one place.\n*/\n\nexport interface WorkspaceMember {\n name: string;\n // Relative to the workspace root, POSIX separators.\n dir: string;\n scripts: Record<string, string>;\n dependencies: Record<string, string>;\n hasViteConfig: boolean;\n // From the member's vite config when it could be read; undefined otherwise.\n viteOutDir?: string;\n}\n\nexport interface ProjectFacts {\n cwd: string;\n packageJson: Record<string, unknown>;\n scripts: Record<string, string>;\n // dependencies and devDependencies together: what the project uses.\n dependencies: Record<string, string>;\n nodeMajor?: string;\n packageManager: PackageManager;\n // The version pinned for the package manager: package.json's\n // `packageManager` field, else what the lockfile format implies.\n packageManagerVersion?: string;\n lockfile: {\n present: boolean;\n // npm only: whether package-lock.json agrees with package.json.\n inSync: boolean;\n };\n procfileWeb?: string;\n hasModelenceConfig: boolean;\n hasIndexHtml: boolean;\n hasViteConfig: boolean;\n viteOutDir?: string;\n // Present when the project came from Replit (.replit at the root).\n replit?: { modules: string[] };\n workspace: {\n globs: string[];\n members: WorkspaceMember[];\n };\n}\n\nfunction mergedDependencies(packageJson: Record<string, unknown>): Record<string, string> {\n return {\n ...((packageJson.dependencies ?? {}) as Record<string, string>),\n ...((packageJson.devDependencies ?? {}) as Record<string, string>),\n };\n}\n\n// Every package the project or one of its workspace members depends on.\nexport function allDependencies(facts: ProjectFacts): Record<string, string> {\n return Object.assign(\n {},\n facts.dependencies,\n ...facts.workspace.members.map((member) => member.dependencies)\n );\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readText(path: string): Promise<string | null> {\n try {\n return await fs.readFile(path, 'utf8');\n } catch {\n return null;\n }\n}\n\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n const text = await readText(path);\n if (text === null) {\n return null;\n }\n try {\n const parsed = JSON.parse(text);\n return parsed && typeof parsed === 'object' ? parsed : null;\n } catch {\n return null;\n }\n}\n\nconst VITE_CONFIG_NAMES = [\n 'vite.config.ts',\n 'vite.config.js',\n 'vite.config.mts',\n 'vite.config.mjs',\n];\n\nasync function readViteConfig(dir: string): Promise<{ present: boolean; outDir?: string }> {\n for (const name of VITE_CONFIG_NAMES) {\n const text = await readText(join(dir, name));\n if (text !== null) {\n return { present: true, outDir: parseViteOutDir(text) };\n }\n }\n return { present: false };\n}\n\nasync function detectPackageManager(cwd: string, packageJson: Record<string, unknown>) {\n const pnpmLock = await readText(join(cwd, 'pnpm-lock.yaml'));\n if (pnpmLock !== null) {\n const pinned = parsePackageManagerVersion(packageJson.packageManager, 'pnpm');\n const major = pnpmMajorFromLockfile(pnpmLock);\n return {\n packageManager: 'pnpm' as const,\n packageManagerVersion: pinned ?? (major ? String(major) : undefined),\n lockfile: { present: true, inSync: true },\n };\n }\n if (await exists(join(cwd, 'yarn.lock'))) {\n return {\n packageManager: 'yarn' as const,\n packageManagerVersion: parsePackageManagerVersion(packageJson.packageManager, 'yarn'),\n lockfile: { present: true, inSync: true },\n };\n }\n const npmLock = await readJson(join(cwd, 'package-lock.json'));\n return {\n packageManager: 'npm' as const,\n packageManagerVersion: undefined,\n lockfile: {\n present: npmLock !== null,\n inSync: npmLock !== null && isLockfileInSync(packageJson, npmLock),\n },\n };\n}\n\nconst MAX_WORKSPACE_DEPTH = 4;\n\nasync function listDirectories(root: string, maxDepth: number): Promise<string[]> {\n const found: string[] = [];\n async function walk(dir: string, depth: number) {\n if (depth > maxDepth) {\n return;\n }\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name === 'node_modules' || entry.name.startsWith('.')) {\n continue;\n }\n const full = join(dir, entry.name);\n found.push(full);\n await walk(full, depth + 1);\n }\n }\n await walk(root, 1);\n return found;\n}\n\n// Workspace members: directories under the root matching the globs that\n// hold a package.json. Negated globs (\"!apps/legacy\") exclude.\nexport async function findWorkspaceMembers(\n root: string,\n globs: string[]\n): Promise<WorkspaceMember[]> {\n if (globs.length === 0) {\n return [];\n }\n const include = globs.filter((glob) => !glob.startsWith('!')).map(globToRegExp);\n const exclude = globs\n .filter((glob) => glob.startsWith('!'))\n .map((glob) => globToRegExp(glob.slice(1)));\n const candidates = await listDirectories(root, MAX_WORKSPACE_DEPTH);\n const members: WorkspaceMember[] = [];\n for (const dir of candidates) {\n const rel = relative(root, dir).split(sep).join('/');\n if (!include.some((re) => re.test(rel)) || exclude.some((re) => re.test(rel))) {\n continue;\n }\n const packageJson = await readJson(join(dir, 'package.json'));\n if (!packageJson || typeof packageJson.name !== 'string') {\n continue;\n }\n const vite = await readViteConfig(dir);\n members.push({\n name: packageJson.name,\n dir: rel,\n scripts: (packageJson.scripts ?? {}) as Record<string, string>,\n dependencies: mergedDependencies(packageJson),\n hasViteConfig: vite.present,\n ...(vite.outDir ? { viteOutDir: vite.outDir } : {}),\n });\n }\n return members.sort((a, b) => a.dir.localeCompare(b.dir));\n}\n\nasync function readWorkspaceGlobs(\n cwd: string,\n packageJson: Record<string, unknown>,\n packageManager: PackageManager\n): Promise<string[]> {\n if (packageManager === 'pnpm') {\n const yaml = await readText(join(cwd, 'pnpm-workspace.yaml'));\n if (yaml !== null) {\n return parsePnpmWorkspaceGlobs(yaml);\n }\n }\n return parsePackageJsonWorkspaces(packageJson);\n}\n\nexport async function gatherProjectFacts(cwd = process.cwd()): Promise<ProjectFacts> {\n const packageJson = await readJson(join(cwd, 'package.json'));\n if (!packageJson) {\n throw new Error('No package.json found in the current directory');\n }\n const engines = (packageJson.engines ?? {}) as Record<string, unknown>;\n const manager = await detectPackageManager(cwd, packageJson);\n const procfile = await readText(join(cwd, 'Procfile'));\n const vite = await readViteConfig(cwd);\n const replit = await readText(join(cwd, '.replit'));\n const globs = await readWorkspaceGlobs(cwd, packageJson, manager.packageManager);\n\n return {\n cwd,\n packageJson,\n scripts: (packageJson.scripts ?? {}) as Record<string, string>,\n dependencies: mergedDependencies(packageJson),\n nodeMajor: parseNodeMajor(engines.node),\n ...manager,\n procfileWeb: procfile === null ? undefined : parseProcfileWebCommand(procfile),\n hasModelenceConfig:\n (await exists(join(cwd, 'modelence.config.ts'))) ||\n (await exists(join(cwd, 'modelence.config.js'))),\n hasIndexHtml: await exists(join(cwd, 'index.html')),\n hasViteConfig: vite.present,\n viteOutDir: vite.outDir,\n ...(replit === null ? {} : { replit: { modules: parseReplitModules(replit) } }),\n workspace: { globs, members: await findWorkspaceMembers(cwd, globs) },\n };\n}\n","import { withNote, type Profile } from '../types';\n\n/*\n Projects exported from Lovable: a Vite + React site, often with Supabase.\n The conventions already build and serve it; what Lovable's environment\n provided is the Supabase connection, which the site reads at build time\n from VITE_* variables. Naming them here beats a blank page after deploy.\n*/\n\nexport const lovableProfile: Profile = {\n name: 'lovable',\n matches: (facts) => 'lovable-tagger' in facts.dependencies,\n apply: (facts, draft) => {\n if (!('@supabase/supabase-js' in facts.dependencies)) {\n return draft;\n }\n return withNote(\n draft,\n 'Lovable project using Supabase: set VITE_SUPABASE_URL and VITE_SUPABASE_PUBLISHABLE_KEY in the environment variables (they are inlined at build time).'\n );\n },\n};\n","import { basename } from 'path';\nimport { commandContext, frontendMembers } from '../conventions';\nimport { commandsFor } from '../commands';\nimport { allDependencies, type ProjectFacts, type WorkspaceMember } from '../facts';\nimport { withBuild, withNote, withWeb, type Draft, type Profile } from '../types';\n\n/*\n Projects exported from Replit. Two things Replit's tooling assumes that\n nothing in the repo says:\n\n - Replit's \"artifacts\" workspaces run each artifact as its own process\n behind Replit's application router: the API owns /api and each Vite\n frontend owns a BASE_PATH. In one container that becomes static mounts\n in front of the API, with each frontend built for its mount path.\n - Its Vite configs refuse to load without PORT and BASE_PATH, so those\n are handed to each frontend's build.\n\n Replit also provisions services (Postgres, Clerk keys) through its own\n environment; those are named here so the first deploy doesn't have to\n crash to reveal them.\n*/\n\n// Replit's design-time artifact, not part of the product.\nconst DESIGN_TOOL_MEMBERS = ['@workspace/mockup-sandbox'];\n// Replit's artifact template builds Vite frontends here.\nconst DEFAULT_ARTIFACT_OUT_DIR = 'dist/public';\n\nfunction mountPathFor(member: WorkspaceMember, single: boolean): string {\n return single ? '/' : `/${basename(member.dir)}`;\n}\n\nfunction mountFrontends(facts: ProjectFacts, draft: Draft): Draft {\n if (!draft.spec.web?.start || draft.spec.web.static?.length) {\n return draft;\n }\n const frontends = frontendMembers(facts).filter(\n (member) => !DESIGN_TOOL_MEMBERS.includes(member.name)\n );\n if (frontends.length === 0) {\n return draft;\n }\n const commands = commandsFor(commandContext(facts));\n const mounts = frontends.map((member) => ({\n path: mountPathFor(member, frontends.length === 1),\n dir: `${member.dir}/${member.viteOutDir ?? DEFAULT_ARTIFACT_OUT_DIR}`,\n }));\n const frontendBuilds = frontends.map(\n (member, index) => `BASE_PATH=${mounts[index].path} ${commands.runIn(member.name, 'build')}`\n );\n const command = [draft.spec.build?.command, ...frontendBuilds].filter(Boolean).join(' && ');\n\n let next = withWeb(withBuild(draft, { command }), { static: mounts });\n next = withNote(\n next,\n `Replit artifacts: ${frontends.map((member) => member.name).join(', ')} ` +\n (frontends.length === 1\n ? 'is served at / in front of the API.'\n : 'are served at their folder names in front of the API; edit web.static in modelence.json to change the paths.')\n );\n return next;\n}\n\nfunction noteProvisionedServices(facts: ProjectFacts, draft: Draft): Draft {\n let next = draft;\n if (facts.replit?.modules.some((module) => module.startsWith('postgresql'))) {\n next = withNote(\n next,\n 'Replit provisioned a Postgres database; set DATABASE_URL in the environment variables to one this app can reach.'\n );\n }\n if (Object.keys(allDependencies(facts)).some((name) => name.startsWith('@clerk/'))) {\n next = withNote(\n next,\n 'Replit managed Clerk auth; set CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY in the environment variables.'\n );\n }\n return next;\n}\n\nexport const replitProfile: Profile = {\n name: 'replit',\n matches: (facts) => facts.replit !== undefined,\n apply: (facts, draft) => noteProvisionedServices(facts, mountFrontends(facts, draft)),\n};\n","import type { AppSpec } from '../appSpec';\nimport { CONVENTIONS, runDetectors } from './conventions';\nimport { gatherProjectFacts, type ProjectFacts } from './facts';\nimport { lovableProfile } from './profiles/lovable';\nimport { replitProfile } from './profiles/replit';\nimport type { Draft, Profile } from './types';\n\n/*\n Infers an app spec from the project, the way Heroku's Node buildpack\n infers its build: conventions first (lockfile, scripts, Procfile,\n engines, workspaces), then the profile of the tool the project came from,\n when one is recognized. The result is one layer of the spec the server\n merges under modelence.json and the environment's settings — so anything\n it gets wrong is overridable, and `modelence init` writes it to the file\n where it can be edited.\n\n Adding support for a new origin means adding a profile file and a\n fixture; nothing here or in the conventions changes.\n*/\n\nexport const PROFILES: Profile[] = [replitProfile, lovableProfile];\n\nexport interface DetectedAppSpec {\n spec: AppSpec;\n notes: string[];\n // The recognized origin, if any.\n profile: string | null;\n}\n\nexport function detectFromFacts(facts: ProjectFacts): DetectedAppSpec {\n const start: Draft = { spec: {}, notes: [] };\n const conventional = runDetectors(facts, CONVENTIONS, start);\n const profile = PROFILES.find((candidate) => candidate.matches(facts)) ?? null;\n const final = profile ? profile.apply(facts, conventional) : conventional;\n return { ...final, profile: profile?.name ?? null };\n}\n\nexport async function detectAppSpec(cwd = process.cwd()): Promise<DetectedAppSpec> {\n return detectFromFacts(await gatherProjectFacts(cwd));\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join, relative, sep } from 'path';\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport archiver from 'archiver';\n\nconst execFileAsync = promisify(execFile);\n\n/*\n Packs the project's source tree for a remote build. Inside a git repository\n the file list is git's own (tracked + untracked, minus ignored), so the\n upload matches what a push would carry. Outside git a plain walk is used\n with a fixed exclusion list.\n\n Credentials and build output are never uploaded regardless.\n*/\n\nexport const MAX_SOURCE_BYTES = 200 * 1024 * 1024;\n\nconst ALWAYS_EXCLUDED_DIRS = [\n '.git',\n 'node_modules',\n '.modelence/build',\n '.modelence/tmp',\n '.modelence/cache',\n];\nconst ALWAYS_EXCLUDED_FILES = [/^\\.modelence(\\.[^/]+)?\\.env$/];\n\nfunction toPosix(path: string): string {\n return path.split(sep).join('/');\n}\n\nexport function isExcludedPath(relativePath: string): boolean {\n const path = toPosix(relativePath);\n const segments = path.split('/');\n for (const dir of ALWAYS_EXCLUDED_DIRS) {\n const dirSegments = dir.split('/');\n // Excluded at any depth for single names (node_modules), at the root for\n // nested ones (.modelence/build).\n if (dirSegments.length === 1) {\n if (segments.slice(0, -1).includes(dir)) {\n return true;\n }\n } else if (path === dir || path.startsWith(`${dir}/`)) {\n return true;\n }\n }\n const fileName = segments[segments.length - 1];\n return ALWAYS_EXCLUDED_FILES.some((pattern) => pattern.test(fileName));\n}\n\nasync function isGitRepository(cwd: string): Promise<boolean> {\n try {\n const { stdout } = await execFileAsync('git', ['rev-parse', '--is-inside-work-tree'], { cwd });\n return stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\nasync function listGitFiles(cwd: string): Promise<string[]> {\n const { stdout } = await execFileAsync(\n 'git',\n ['ls-files', '--cached', '--others', '--exclude-standard', '-z'],\n { cwd, maxBuffer: 64 * 1024 * 1024 }\n );\n return stdout.split('\\0').filter((entry) => entry.length > 0);\n}\n\nasync function walk(cwd: string, dir = ''): Promise<string[]> {\n const entries = await fs.readdir(join(cwd, dir), { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const path = dir ? `${dir}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedPath(`${path}/x`)) {\n files.push(...(await walk(cwd, path)));\n }\n } else if (entry.isFile()) {\n files.push(path);\n }\n }\n return files;\n}\n\nexport async function listSourceFiles(\n cwd = process.cwd()\n): Promise<{ files: string[]; usedGit: boolean }> {\n const usedGit = await isGitRepository(cwd);\n const candidates = usedGit ? await listGitFiles(cwd) : await walk(cwd);\n\n const files: string[] = [];\n for (const file of candidates) {\n if (isExcludedPath(file)) {\n continue;\n }\n // git ls-files still lists tracked files deleted from the working tree.\n try {\n const stat = await fs.stat(join(cwd, file));\n if (stat.isFile()) {\n files.push(file);\n }\n } catch {\n // Gone from disk — nothing to upload.\n }\n }\n return { files: files.sort(), usedGit };\n}\n\nexport async function packSource(\n cwd: string,\n zipPath: string\n): Promise<{ fileCount: number; sizeBytes: number; usedGit: boolean }> {\n const { files, usedGit } = await listSourceFiles(cwd);\n if (files.length === 0) {\n throw new Error('No files to upload');\n }\n\n await fs.mkdir(join(zipPath, '..'), { recursive: true });\n await fs.rm(zipPath, { force: true });\n\n const output = createWriteStream(zipPath);\n const archive = archiver('zip', { zlib: { level: 6 } });\n const done = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n archive.pipe(output);\n for (const file of files) {\n archive.file(join(cwd, file), { name: toPosix(relative('', file)) });\n }\n await archive.finalize();\n await done;\n\n const { size } = await fs.stat(zipPath);\n if (size > MAX_SOURCE_BYTES) {\n await fs.rm(zipPath, { force: true });\n throw new Error(\n `Source is ${(size / 1024 / 1024).toFixed(0)} MB compressed; the limit is ${MAX_SOURCE_BYTES / 1024 / 1024} MB. ` +\n 'Add build output and large assets to .gitignore.'\n );\n }\n\n return { fileCount: files.length, sizeBytes: size, usedGit };\n}\n","/*\n Thin JSON client for Studio's CLI routes. Errors carry the HTTP status so\n callers can tell an expired token (401) from everything else.\n*/\n\nexport class StudioApiError extends Error {\n constructor(\n message: string,\n public readonly status: number\n ) {\n super(message);\n this.name = 'StudioApiError';\n }\n}\n\nexport async function studioRequest<T>(\n host: string,\n path: string,\n {\n method = 'GET',\n token,\n body,\n query,\n }: {\n method?: 'GET' | 'POST';\n token?: string;\n body?: unknown;\n query?: Record<string, string | number>;\n } = {}\n): Promise<T> {\n const url = new URL(path, host);\n for (const [key, value] of Object.entries(query ?? {})) {\n url.searchParams.set(key, String(value));\n }\n\n const headers: Record<string, string> = {};\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n\n const response = await fetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n\n if (!response.ok) {\n const text = await response.text();\n let message = text || response.statusText;\n try {\n const parsed = JSON.parse(text);\n message = parsed.error || parsed.message || message;\n } catch {\n // Plain-text error body.\n }\n throw new StudioApiError(message, response.status);\n }\n\n return (await response.json()) as T;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport { parse as parseDotenv } from 'dotenv';\nimport archiver from 'archiver';\nimport {\n APP_SPEC_FILE_NAME,\n definedOnly,\n formatAppSpec,\n mergeAppSpecs,\n readAppSpecFile,\n type AppSpec,\n type StaticMount,\n} from './appSpec';\nimport { authenticateCli, type CliAuthTarget } from './auth';\nimport { clearCachedToken, readCachedToken, writeCachedToken } from './authCache';\nimport { detectAppSpec } from './detect';\nimport { loadEnv, getProjectPath } from './config';\nimport { readProject, updateProject, type DeployTarget } from './project';\nimport { packSource } from './source';\nimport { StudioApiError, studioRequest } from './studioApi';\nimport { build } from './build';\n\n/*\n `modelence deploy`: ship the current directory to a Modelence Cloud\n environment.\n\n Default path — any Node.js app: the source tree is uploaded and built\n remotely from its app spec, which Studio merges from (highest first) the\n flags of this run, the environment's Build & Deploy settings, the\n project's modelence.json and what is detected here. `--prebuilt` keeps the\n historical Modelence path: build locally, upload .modelence/build.\n\n Target: -a/-e flags → --env with the app recorded in project.json → the\n deploy target recorded in project.json → the browser picker. Auth: the\n MODELENCE_TOKEN variable → the cached token → the browser.\n*/\n\nconst DEFAULT_HOST = 'https://cloud.modelence.com';\nconst POLL_INTERVAL_MS = 3000;\nconst POLL_TIMEOUT_MS = 30 * 60 * 1000;\nconst PROVISION_TIMEOUT_MS = 10 * 60 * 1000;\n\nexport interface DeployOptions {\n app?: string;\n env?: string;\n host?: string;\n prebuilt?: boolean;\n runtime?: string;\n nodeVersion?: string;\n rootDir?: string;\n installCommand?: string;\n buildCommand?: string;\n startCommand?: string;\n // \"path=dir\", repeatable.\n static?: string[];\n}\n\ntype CliTarget =\n | { environmentId: string }\n | { appAlias: string; envAlias: string }\n | { appId: string; envAlias: string };\n\ntype UploadKind = 'bundle' | 'source';\n\ninterface DeployStatus {\n status: string;\n errors: string[];\n rolloutProgress: { updatedCount: number; totalCount: number } | null;\n logs: string[];\n logCount: number;\n siteUrl: string | null;\n // Last output of the containers a failed rollout tried to start.\n containerLogs?: string[];\n}\n\n// The token in use, shared so a re-authorization mid-deploy reaches every\n// later request without threading a new value through each call.\ninterface Session {\n host: string;\n token: string;\n}\n\n// The spec layers this run sends along with the source.\ninterface SpecLayers {\n file: AppSpec | null;\n overrides: AppSpec;\n detected: AppSpec;\n}\n\nexport async function deploy(options: DeployOptions) {\n const cwd = process.cwd();\n const host = await resolveHost(options.host, cwd);\n const kind: UploadKind = options.prebuilt ? 'bundle' : 'source';\n const project = await readProject(cwd);\n\n // Local work first, so nothing is uploaded when it fails.\n let layers: SpecLayers | undefined;\n const archivePath = join(cwd, '.modelence', 'tmp', `${kind}.zip`);\n if (kind === 'bundle') {\n await loadEnv();\n await build();\n await createBundle(archivePath);\n } else {\n layers = await prepareSpecLayers(cwd, options);\n const { fileCount, sizeBytes, usedGit } = await packSource(cwd, archivePath);\n console.log(\n `Packed ${fileCount} files (${formatMb(sizeBytes)})` +\n (usedGit ? ' from git' : '; not a git repository, so only default exclusions applied')\n );\n }\n\n let target = resolveTargetFromOptions(options, project);\n let token = await resolveToken(host);\n if (!token || !target) {\n // The browser flow hands back a token and, when the target is not known\n // yet, the environment picked there — one visit covers a fresh machine\n // and a fresh project. A target from flags or the project file is final,\n // so the page then only authorizes.\n const auth = await authenticateCli(host, {\n pick: target ? undefined : 'deploy',\n purpose: 'deploy',\n appId: project.appId,\n });\n token = auth.token;\n await rememberToken(host, auth.token, auth.expiresAt);\n if (auth.target) {\n target = { environmentId: auth.target.environmentId };\n await rememberTarget(auth.target);\n }\n }\n if (!target) {\n throw new Error(\n 'No deploy target selected. Run again and pick an environment in the browser, or pass --app and --env.'\n );\n }\n\n const session: Session = { host, token };\n // Cached token expired or was revoked: authorize once more. The deploy\n // itself is never repeated — an upload that failed authentication did not\n // start anything, and a build already running is simply followed again.\n const signInAgain = async () => {\n await clearCachedToken(host);\n console.log('Your saved login has expired; please sign in again.');\n const auth = await authenticateCli(host, {\n pick: target ? undefined : 'deploy',\n purpose: 'deploy',\n appId: project.appId,\n });\n await rememberToken(host, auth.token, auth.expiresAt);\n if (auth.target) {\n target = { environmentId: auth.target.environmentId };\n await rememberTarget(auth.target);\n }\n session.token = auth.token;\n };\n\n try {\n let started: StartedDeploy;\n try {\n started = await runDeploy({ session, target, kind, archivePath, layers, project });\n } catch (error) {\n if (!isUnauthorized(error)) {\n throw error;\n }\n await signInAgain();\n started = await runDeploy({ session, target, kind, archivePath, layers, project });\n }\n if (started.buildId) {\n await followDeploy(session, signInAgain, started.environmentId, started.buildId);\n }\n } finally {\n await fs.rm(archivePath, { force: true });\n }\n}\n\n// Reads modelence.json, runs detection and prints the plan this run will\n// deploy with (before the environment's own settings, which only the server\n// knows).\nasync function prepareSpecLayers(cwd: string, options: DeployOptions): Promise<SpecLayers> {\n const file = await readAppSpecFile(cwd);\n const detected = await detectAppSpec(cwd);\n const overrides = specFromFlags(options);\n const preview = mergeAppSpecs(detected.spec, file, overrides);\n\n const sources = [\n detected.profile ? `${detected.profile} project` : null,\n file ? APP_SPEC_FILE_NAME : null,\n Object.keys(overrides).length > 0 ? 'flags' : null,\n ].filter(Boolean);\n console.log(`Build plan${sources.length > 0 ? ` (${sources.join(', ')})` : ''}:`);\n for (const line of formatAppSpec(preview)) {\n console.log(line);\n }\n for (const note of detected.notes) {\n console.log(` note: ${note}`);\n }\n if (!file) {\n console.log(` tip: run \\`modelence init\\` to write this plan to ${APP_SPEC_FILE_NAME}.`);\n }\n\n return { file, overrides, detected: detected.spec };\n}\n\nfunction isUnauthorized(error: unknown): boolean {\n return error instanceof StudioApiError && error.status === 401;\n}\n\ninterface StartedDeploy {\n environmentId: string;\n // Null from a Studio too old to have the status route.\n buildId: string | null;\n}\n\nasync function runDeploy({\n session,\n target,\n kind,\n archivePath,\n layers,\n project,\n}: {\n session: Session;\n target: CliTarget;\n kind: UploadKind;\n archivePath: string;\n layers?: SpecLayers;\n project: Awaited<ReturnType<typeof readProject>>;\n}): Promise<StartedDeploy> {\n const { host, token } = session;\n const upload = await studioRequest<{\n uploadUrl: string;\n bundleName: string;\n appAlias: string;\n envAlias: string;\n environmentId: string;\n }>(host, '/api/upload-bundle', { method: 'POST', token, body: { ...target, kind } });\n\n await waitForEnvironmentReady(host, token, upload.environmentId);\n\n console.log(`Uploading to ${upload.appAlias}/${upload.envAlias}...`);\n const fileBuffer = await fs.readFile(archivePath);\n const uploadResponse = await fetch(upload.uploadUrl, {\n method: 'PUT',\n body: new Uint8Array(fileBuffer),\n headers: { 'Content-Type': 'application/zip' },\n });\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload: ${uploadResponse.statusText}`);\n }\n\n const result = await studioRequest<{\n deploymentUrl: string;\n appAlias: string;\n envAlias: string;\n environmentId: string;\n buildId: string | null;\n spec?: ResolvedSpec | null;\n }>(host, '/api/deploy', {\n method: 'POST',\n token,\n body: {\n environmentId: upload.environmentId,\n bundleName: upload.bundleName,\n kind,\n spec: layers?.file ?? undefined,\n overrides: layers?.overrides,\n detected: layers?.detected,\n },\n });\n\n // Whatever the target was resolved from, the next run can skip the picker.\n if (!project.deploy || project.deploy.environmentId !== result.environmentId) {\n await rememberTarget({\n environmentId: result.environmentId,\n appAlias: result.appAlias,\n envAlias: result.envAlias,\n });\n }\n\n if (result.spec && layers) {\n reportEnvironmentSettings(\n result.spec,\n mergeAppSpecs(layers.detected, layers.file, layers.overrides)\n );\n }\n\n console.log(`Deployment started: ${result.deploymentUrl}`);\n return { environmentId: result.environmentId, buildId: result.buildId };\n}\n\n// An environment created moments ago in the browser is still provisioning\n// its database and telemetry; deploys are refused until it is ready.\nasync function waitForEnvironmentReady(host: string, token: string, environmentId: string) {\n const deadline = Date.now() + PROVISION_TIMEOUT_MS;\n let announced = false;\n while (Date.now() < deadline) {\n let status: string;\n try {\n ({ status } = await studioRequest<{ status: string }>(host, '/api/environment/status', {\n token,\n query: { environmentId },\n }));\n } catch (error) {\n if (error instanceof StudioApiError && error.status === 404) {\n // Older Studio without the route: let /api/deploy decide.\n return;\n }\n throw error;\n }\n if (status === 'ready') {\n return;\n }\n if (status === 'failed') {\n throw new Error('The environment failed to provision; check it in the dashboard.');\n }\n if (!announced) {\n console.log('Waiting for the environment to finish provisioning...');\n announced = true;\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n throw new Error('Timed out waiting for the environment to be ready.');\n}\n\n// Prints phase transitions and streams build log lines until the deploy\n// settles. Exit code reflects the outcome so CI and agents can act on it.\nasync function followDeploy(\n session: Session,\n signInAgain: () => Promise<void>,\n environmentId: string,\n buildId: string\n) {\n const deadline = Date.now() + POLL_TIMEOUT_MS;\n let lastStatus = '';\n let lastMessage = '';\n let logOffset = 0;\n let signedInAgain = false;\n\n while (Date.now() < deadline) {\n let status: DeployStatus;\n try {\n status = await studioRequest<DeployStatus>(session.host, '/api/deploy/status', {\n token: session.token,\n query: { environmentId, buildId, logOffset },\n });\n } catch (error) {\n // A token can expire while a long rollout is being watched; the\n // build keeps going on the server, so only the watching resumes.\n if (!isUnauthorized(error) || signedInAgain) {\n throw error;\n }\n signedInAgain = true;\n await signInAgain();\n continue;\n }\n\n for (const line of status.logs) {\n process.stdout.write(` │ ${line.replace(/\\n$/, '')}\\n`);\n }\n // A poll that could not read CloudWatch reports zero lines; keeping the\n // offset avoids replaying the whole log on the next poll.\n logOffset = Math.max(logOffset, status.logCount);\n\n if (status.status !== lastStatus) {\n lastStatus = status.status;\n const message = describeStatus(status);\n // Two statuses can share a message (deploy-pending and deploying).\n if (message && message !== lastMessage) {\n lastMessage = message;\n console.log(message);\n }\n }\n\n if (status.status === 'deploy-completed') {\n if (status.siteUrl) {\n console.log(`Live at ${status.siteUrl}`);\n }\n return;\n }\n if (status.status === 'build-failed' || status.status === 'deploy-failed') {\n for (const error of status.errors) {\n console.error(` ${error}`);\n }\n if (status.containerLogs && status.containerLogs.length > 0) {\n console.error('Container output:');\n for (const line of status.containerLogs) {\n console.error(` │ ${line.replace(/\\n$/, '')}`);\n }\n }\n process.exitCode = 1;\n return;\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n console.error('Timed out waiting for the deployment; check the dashboard for its status.');\n process.exitCode = 1;\n}\n\nfunction describeStatus(status: DeployStatus): string | null {\n switch (status.status) {\n case 'build-pending':\n return 'Building image...';\n case 'deploy-pending':\n case 'deploying':\n return 'Image built. Deploying containers...';\n case 'rolling-out':\n return 'Rolling out new containers...';\n case 'deploy-completed':\n return 'Deployed successfully.';\n case 'build-failed':\n return 'Build failed.';\n case 'deploy-failed':\n return 'Deployment failed.';\n default:\n return null;\n }\n}\n\nfunction resolveTargetFromOptions(\n options: DeployOptions,\n project: Awaited<ReturnType<typeof readProject>>\n): CliTarget | null {\n if (options.app && options.env) {\n return { appAlias: options.app, envAlias: options.env };\n }\n if (options.env && project.deploy?.appAlias) {\n return { appAlias: project.deploy.appAlias, envAlias: options.env };\n }\n if (options.env && project.appId) {\n return { appId: project.appId, envAlias: options.env };\n }\n if (options.app || options.env) {\n throw new Error('Pass both --app and --env, or neither to pick the target in the browser.');\n }\n if (project.deploy?.environmentId) {\n return { environmentId: project.deploy.environmentId };\n }\n return null;\n}\n\nasync function resolveToken(host: string): Promise<string | null> {\n if (process.env.MODELENCE_TOKEN) {\n return process.env.MODELENCE_TOKEN;\n }\n return await readCachedToken(host);\n}\n\nasync function rememberToken(host: string, token: string, expiresAt?: string) {\n if (!expiresAt) {\n // Older Studio: the token lasts an hour, not worth caching.\n return;\n }\n try {\n await writeCachedToken(host, token, expiresAt);\n } catch (error) {\n console.warn('Could not save the login for next time:', error);\n }\n}\n\nasync function rememberTarget(target: CliAuthTarget | DeployTarget) {\n const deploy: DeployTarget = {\n environmentId: target.environmentId,\n appAlias: target.appAlias,\n envAlias: target.envAlias,\n };\n try {\n await updateProject({ deploy, ...('appId' in target ? { appId: target.appId } : {}) });\n } catch (error) {\n console.warn('Could not record the deploy target in .modelence/project.json:', error);\n }\n}\n\n// The Studio host: flag → environment → the project's .modelence.env → default.\n// Read directly rather than through loadEnv(), which requires a\n// modelence.config.ts that plain Node.js projects don't have.\nasync function resolveHost(flag: string | undefined, cwd: string): Promise<string> {\n if (flag) {\n return flag.replace(/\\/$/, '');\n }\n if (process.env.MODELENCE_SERVICE_ENDPOINT) {\n return process.env.MODELENCE_SERVICE_ENDPOINT.replace(/\\/$/, '');\n }\n try {\n const env = parseDotenv(await fs.readFile(join(cwd, '.modelence.env'), 'utf8'));\n if (env.MODELENCE_SERVICE_ENDPOINT) {\n return env.MODELENCE_SERVICE_ENDPOINT.replace(/\\/$/, '');\n }\n } catch {\n // No .modelence.env — plain Node.js projects usually have none.\n }\n return DEFAULT_HOST;\n}\n\n// Flags → one spec layer, only the keys that were passed.\nexport function specFromFlags(options: DeployOptions): AppSpec {\n const build = definedOnly({\n node: options.nodeVersion,\n root: options.rootDir,\n install: options.installCommand,\n command: options.buildCommand,\n });\n const web = definedOnly({\n start: options.startCommand,\n static: options.static === undefined ? undefined : options.static.map(parseStaticFlag),\n });\n return {\n ...(options.runtime ? { runtime: options.runtime as AppSpec['runtime'] } : {}),\n ...(Object.keys(build).length > 0 ? { build } : {}),\n ...(Object.keys(web).length > 0 ? { web } : {}),\n };\n}\n\n// --static \"/=client/dist\" or \"/docs=docs/build\"; a bare directory mounts at /.\nexport function parseStaticFlag(value: string): StaticMount {\n const separator = value.indexOf('=');\n if (separator === -1) {\n return { path: '/', dir: value };\n }\n return { path: value.slice(0, separator) || '/', dir: value.slice(separator + 1) };\n}\n\n// A resolved spec as the server reports it: every key present.\ninterface ResolvedSpec {\n runtime: string;\n build: { node: string; root: string; install: string; command: string };\n web: { start?: string | null; static: StaticMount[] };\n}\n\n// The environment's Build & Deploy settings sit between the flags and the\n// file; when they changed the outcome, say so, since that is otherwise only\n// visible in the dashboard.\nfunction reportEnvironmentSettings(used: ResolvedSpec, local: AppSpec) {\n const differences: string[] = [];\n const compare = (\n label: string,\n usedValue: string | null | undefined,\n localValue: string | undefined\n ) => {\n if (localValue !== undefined && (usedValue ?? '') !== localValue) {\n differences.push(`${label} \"${usedValue ?? ''}\" (here \"${localValue}\")`);\n }\n };\n compare('install', used.build.install, local.build?.install);\n compare('build', used.build.command, local.build?.command);\n compare('start', used.web.start, local.web?.start);\n if (local.runtime && used.runtime !== local.runtime) {\n differences.push(`runtime ${used.runtime} (here ${local.runtime})`);\n }\n const usedMounts = JSON.stringify(used.web.static);\n if (local.web?.static && usedMounts !== JSON.stringify(local.web.static)) {\n differences.push('static directories');\n }\n if (differences.length > 0) {\n console.log(\"Using the environment's Build & Deploy settings: \" + differences.join(', '));\n console.log('Edit them in the dashboard to change this.');\n }\n}\n\nfunction formatMb(bytes: number): string {\n return `${(bytes / 1024 / 1024).toFixed(2)} MB`;\n}\n\n// The historical --prebuilt bundle: build output plus the manifests the\n// container needs to install production dependencies.\nasync function createBundle(bundlePath: string) {\n await fs.rm(bundlePath, { force: true });\n console.log('Creating deployment bundle...');\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', { zlib: { level: 9 } });\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 archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'package-lock.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n const bundleDirs = ['public', 'server', 'scripts', join('.modelence', 'build'), '.next'];\n\n for (const file of bundleFiles) {\n if (await pathExists(getProjectPath(file))) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n for (const dir of bundleDirs) {\n if (await pathExists(getProjectPath(dir))) {\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(`Deployment bundle created (${formatMb(stats.size)})`);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev(options: { takeover?: boolean } = {}) {\n console.log('Starting Modelence dev server...');\n\n const serverPath = getServerPath();\n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch --ignore \"vite.config.ts.timestamp-*\" \"${serverPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: {\n ...process.env,\n NODE_ENV: 'development',\n ...(options.takeover ? { MODELENCE_TAKEOVER: '1' } : {}),\n },\n });\n}\n","import { getBuildPath, getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function start() {\n console.log('Starting Modelence production server...');\n\n const serverPath = getServerPath();\n const serverFilename = path.basename(serverPath, path.extname(serverPath));\n const builtServerPath = getBuildPath(`${serverFilename}.mjs`);\n\n execSync(`node \"${builtServerPath}\"`, {\n stdio: 'inherit',\n cwd: process.cwd(),\n env: { ...process.env, NODE_ENV: 'production' },\n });\n}\n","import { clearCachedToken, getAuthCachePath } from './authCache';\n\n// Forgets the saved deploy login (all hosts, or one with --host).\nexport async function logout(options: { host?: string }) {\n await clearCachedToken(options.host);\n console.log(\n options.host\n ? `Removed the saved login for ${options.host}.`\n : `Removed saved logins (${getAuthCachePath()}).`\n );\n}\n","import { promises as fs } from 'fs';\nimport {\n APP_SPEC_FILE_NAME,\n formatAppSpec,\n getAppSpecFilePath,\n writeAppSpecFile,\n type AppSpec,\n} from './appSpec';\nimport { detectAppSpec } from './detect';\n\n/*\n `modelence init`: detect how the project builds and runs, and write it to\n modelence.json so the next deploy is deterministic and the result can be\n read and edited. Detection still runs on every deploy for whatever the\n file leaves out.\n*/\n\nconst DEFAULT_SCHEMA_HOST = 'https://cloud.modelence.com';\n\nexport interface InitOptions {\n force?: boolean;\n host?: string;\n}\n\nexport async function init(options: InitOptions) {\n const cwd = process.cwd();\n const path = getAppSpecFilePath(cwd);\n if (!options.force && (await exists(path))) {\n throw new Error(`${APP_SPEC_FILE_NAME} already exists; pass --force to overwrite it.`);\n }\n\n const detected = await detectAppSpec(cwd);\n const schemaHost = (options.host ?? DEFAULT_SCHEMA_HOST).replace(/\\/$/, '');\n const spec: AppSpec = {\n $schema: `${schemaHost}/schema/modelence.json`,\n ...detected.spec,\n };\n await writeAppSpecFile(spec, cwd);\n\n console.log(\n `Wrote ${APP_SPEC_FILE_NAME}` + (detected.profile ? ` (${detected.profile} project)` : '')\n );\n for (const line of formatAppSpec(spec)) {\n console.log(line);\n }\n for (const note of detected.notes) {\n console.log(` note: ${note}`);\n }\n console.log('Edit the file to change any of this, then run `modelence deploy`.');\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\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 { logout } from './logout';\nimport { init } from './init';\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(\n 'Deploy the current directory to Modelence Cloud (any Node.js app; picks the target in the browser on first run)'\n )\n .option('-a, --app <app>', 'Application alias')\n .option('-e, --env <env>', 'Environment alias')\n .option('-h, --host <host>', 'Modelence host')\n .option(\n '--prebuilt',\n 'Build locally and upload the .modelence/build bundle (Modelence apps only)'\n )\n .option('--runtime <runtime>', 'node or modelence (default: from modelence.json or detected)')\n .option('--node-version <version>', 'Node.js version for the container, e.g. 22')\n .option('--root-dir <path>', 'Subdirectory containing the app (monorepos)')\n .option('--install-command <command>', 'Install command for this deploy')\n .option('--build-command <command>', 'Build command for this deploy (\"\" to skip)')\n .option('--start-command <command>', 'Start command for this deploy')\n .option(\n '--static <path=dir>',\n 'Serve a built directory at a URL path, e.g. /=client/dist (repeatable)',\n (value: string, previous: string[] = []) => [...previous, value]\n )\n .action(async (options) => {\n try {\n await deploy(options);\n } catch (error) {\n console.error(`Deploy failed: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('init')\n .description('Detect how this project builds and runs, and write it to modelence.json')\n .option('--force', 'Overwrite an existing modelence.json')\n .option('-h, --host <host>', 'Modelence host used for the schema URL')\n .action(async (options) => {\n try {\n await init(options);\n } catch (error) {\n console.error(`Init failed: ${error instanceof Error ? error.message : String(error)}`);\n process.exit(1);\n }\n });\n\nprogram\n .command('logout')\n .description('Forget the saved Modelence Cloud login')\n .option('-h, --host <host>', 'Only forget the login for this host')\n .action(async (options) => {\n await logout(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .option(\n '--takeover',\n 'Disconnect any instance currently holding the environment and connect this one'\n )\n .action(async (options) => {\n await loadEnv();\n dev(options);\n });\n\nprogram\n .command('start')\n .description('Start production server')\n .action(async () => {\n await loadEnv();\n start();\n });\n\nprogram.parse(process.argv);\n"]}