← Files RivetARCHIVED FILE
node_modules/rivet-design/dist/server.js
34.8 KB · Nov 5, 2026 · 12:09 UTC
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.startServer = exports.runServerShutdownTasks = exports.isRivetCorsOriginAllowed = exports.isRivetUiStaticAssetPath = exports.isEmbeddedAgentUiHost = exports.resolveEmbeddedAgentUiOrigin = exports.resolveRivetListenHost = exports.sendInactiveVariantsEventStream = exports.readRivetUiIndexHtml = exports.injectRivetUiBootstrap = exports.DIST_UI_PATH = exports.RIVET_CORS_ALLOWED_HEADERS = exports.INACTIVE_VARIANTS_EVENT_HEARTBEAT_MS = void 0;
const editorSession_1 = require("./cli/editorSession");
const editorAccess_1 = require("./routes/editorAccess");
const editorAccess_2 = require("./utils/editorAccess");
const RuntimeAdmission_1 = require("./services/RuntimeAdmission");
const account_1 = require("./routes/account");
const installRef_1 = require("./routes/installRef");
const installationChannel_1 = require("./install/installationChannel");
const Sentry = __importStar(require("@sentry/node"));
const telemetryPolicy_1 = require("./config/telemetryPolicy");
const telemetry_1 = require("./routes/telemetry");
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const crypto_1 = require("crypto");
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const http_1 = require("http");
const index_core_1 = require("./index-core");
const _1 = require(".");
const integrations_1 = require("./routes/integrations");
const referenceProfiles_1 = require("./routes/referenceProfiles");
const WorktreeManager_1 = require("./services/WorktreeManager");
const support_1 = require("./routes/support");
const proxy_config_1 = require("./proxy-middleware/proxy-config");
const StaticFileService_1 = require("./services/StaticFileService");
const static_1 = require("./routes/static");
const ConfigManager_1 = require("./services/ConfigManager");
const evaluateFlags_1 = require("./config/evaluateFlags");
const FeatureFlagService_1 = require("./services/FeatureFlagService");
const featureFlagUserKey_1 = require("./config/featureFlagUserKey");
const mcp_1 = require("./routes/mcp");
const cli_1 = require("./routes/cli");
const agentVariants_1 = require("./routes/agentVariants");
const inlineStartTracker_1 = require("./routes/inlineStartTracker");
const serverHandshake_1 = require("./cli/serverHandshake");
const telemetry_2 = require("./config/telemetry");
const HistoryReplayService_1 = require("./services/HistoryReplayService");
const VariantHistoryService_1 = require("./services/VariantHistoryService");
const RequestAuthContext_1 = require("./services/RequestAuthContext");
const middleware_1 = require("./routes/library/middleware");
const errorMessage_1 = require("./utils/errorMessage");
const pluginContext_1 = require("./hosts/pluginContext");
const log = (0, index_core_1.createLogger)('RivetServer');
const QUEUE_ACCESS_TOKEN_BYTES = 32;
const RIVET_BOOTSTRAP_SCRIPT_ID = 'rivet-bootstrap-config';
const RIVET_UI_INDEX_FILENAME = 'index.html';
const EMBEDDED_AGENT_LISTEN_HOST = '127.0.0.1';
const EMBEDDED_AGENT_PREVIEW_HOST = 'localhost';
const OPAQUE_PREVIEW_ORIGIN = 'null';
const PREVIEW_PORT_ALLOWED_API_RE = /^\/api\/variants\/(?:[^/]+\/static\/|history\/[^/]+\/[^/]+\/(?:preview|site\/))/;
exports.INACTIVE_VARIANTS_EVENT_HEARTBEAT_MS = 30_000;
exports.RIVET_CORS_ALLOWED_HEADERS = [
'Content-Type',
'Authorization',
'x-rivet-queue-token',
editorAccess_2.EDITOR_ACCESS_TOKEN_HEADER,
];
const resolveUiPath = () => {
const bundledPath = path_1.default.join(__dirname, 'ui/dist');
const devPath = path_1.default.join(__dirname, '../src/ui/dist');
if (fs_1.default.existsSync(bundledPath)) {
log.debug(`Using bundled UI path: ${bundledPath}`);
return bundledPath;
}
log.debug(`Using development UI path: ${devPath}`);
return devPath;
};
exports.DIST_UI_PATH = resolveUiPath();
const NO_USER_DEV_SERVER_PORT = 0;
const setNoStoreHeaders = (res) => {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
};
const escapeScriptJson = (value) => JSON.stringify(value)
.replace(/</g, '\\u003c')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
const injectRivetUiBootstrap = (html, bootstrap) => {
const script = `<script id="${RIVET_BOOTSTRAP_SCRIPT_ID}">window.__RIVET_BOOTSTRAP__=${escapeScriptJson(bootstrap)};</script>`;
if (html.includes('</head>')) {
return html.replace('</head>', `${script}</head>`);
}
return `${script}${html}`;
};
exports.injectRivetUiBootstrap = injectRivetUiBootstrap;
const readRivetUiIndexHtml = () => fs_1.default.readFileSync(path_1.default.join(exports.DIST_UI_PATH, RIVET_UI_INDEX_FILENAME), 'utf8');
exports.readRivetUiIndexHtml = readRivetUiIndexHtml;
const sendInactiveVariantsEventStream = (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.flushHeaders?.();
res.write('data: {"active":false}\n\n');
const heartbeat = setInterval(() => {
res.write(': heartbeat\n\n');
}, exports.INACTIVE_VARIANTS_EVENT_HEARTBEAT_MS);
req.on('close', () => {
clearInterval(heartbeat);
});
};
exports.sendInactiveVariantsEventStream = sendInactiveVariantsEventStream;
const resolveRivetListenHost = (_agentApplyMode) => EMBEDDED_AGENT_LISTEN_HOST;
exports.resolveRivetListenHost = resolveRivetListenHost;
const resolveEmbeddedAgentUiOrigin = (port) => `http://${EMBEDDED_AGENT_LISTEN_HOST}:${port}`;
exports.resolveEmbeddedAgentUiOrigin = resolveEmbeddedAgentUiOrigin;
const isEmbeddedAgentUiHost = (hostname, agentApplyMode) => agentApplyMode !== 'embedded' || hostname === EMBEDDED_AGENT_LISTEN_HOST;
exports.isEmbeddedAgentUiHost = isEmbeddedAgentUiHost;
const isRivetUiStaticAssetPath = (requestPath) => requestPath === '/rivet/favicon.ico' ||
requestPath.startsWith('/rivet/assets/') ||
requestPath.startsWith('/rivet/fonts/');
exports.isRivetUiStaticAssetPath = isRivetUiStaticAssetPath;
const isRivetCorsOriginAllowed = ({ requestOrigin, requestHostname, requestPath, allowedOrigins, agentApplyMode, }) => {
if (!requestOrigin) {
return true;
}
if (allowedOrigins.has(requestOrigin)) {
return true;
}
return (agentApplyMode === 'embedded' &&
requestHostname === EMBEDDED_AGENT_PREVIEW_HOST &&
!requestPath.startsWith('/api/') &&
!requestPath.startsWith('/rivet') &&
requestOrigin === OPAQUE_PREVIEW_ORIGIN);
};
exports.isRivetCorsOriginAllowed = isRivetCorsOriginAllowed;
const DEV_PORT_FILENAME = '.rivet-dev-port';
const resolveDevPortFile = () => path_1.default.join(__dirname, '..', DEV_PORT_FILENAME);
const writeDevPortFile = (port) => {
const filePath = resolveDevPortFile();
const payload = JSON.stringify({
port,
pid: process.pid,
writtenAt: new Date().toISOString(),
});
try {
fs_1.default.writeFileSync(filePath, payload, 'utf8');
log.debug(`Wrote dev-port marker at ${filePath} (port ${port})`);
}
catch (err) {
log.debug(`Failed to write dev-port marker at ${filePath}: ${(0, errorMessage_1.errorMessage)(err)}`);
}
};
const removeDevPortFile = () => {
const filePath = resolveDevPortFile();
try {
const existing = fs_1.default.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(existing);
if (parsed.pid === process.pid) {
fs_1.default.unlinkSync(filePath);
log.debug(`Removed dev-port marker at ${filePath}`);
}
}
catch { }
};
const runServerShutdownTasks = async (options) => {
await options.beforeShutdown?.();
await options.telemetry?.shutdown();
await options.featureFlags?.shutdown();
};
exports.runServerShutdownTasks = runServerShutdownTasks;
const startServer = async (options) => {
const { userPort, userHost, telemetry, projectPath, framework, staticEntry, sessionBridge, mcpEditor, skipProcessHandlers, } = options;
const agentApplyMode = options.agentApplyMode;
const editorAccessToken = (0, editorSession_1.createEditorAccessToken)();
const startedAt = new Date().toISOString();
const userPortWithFallback = userPort ?? _1.DEFAULT_USER_PORT;
const userHostWithFallback = userHost ?? 'localhost';
const hasUserDevServer = typeof userPort === 'number' && Number.isInteger(userPort) && userPort > 0;
const queueAccessToken = sessionBridge && agentApplyMode === 'embedded'
? (0, crypto_1.randomBytes)(QUEUE_ACCESS_TOKEN_BYTES).toString('base64url')
: null;
const variantsOrchestrator = options.variantsRuntime?.orchestrator ?? options.agentVariantsOrchestrator;
const inlineStartTracker = (0, inlineStartTracker_1.createInlineStartTracker)();
const runtimeAdmission = new RuntimeAdmission_1.RuntimeAdmission(telemetry_2.RIVET_VERSION);
const variantsBridge = options.variantsRuntime?.bridge ?? sessionBridge;
const variantRunService = options.variantsRuntime?.runService ?? options.variantRunService;
const variantHistory = variantsOrchestrator
? (options.variantsRuntime?.history ?? new VariantHistoryService_1.VariantHistoryService())
: null;
const historyReplay = variantsOrchestrator && variantHistory
? new HistoryReplayService_1.HistoryReplayService({
history: variantHistory,
devServers: variantsOrchestrator.devServerManager,
switchPreviewPort: variantsBridge
? (port) => variantsBridge.switchPreviewPort(port)
: undefined,
})
: null;
if (process.env.SENTRY_DSN && (0, telemetryPolicy_1.getTelemetryMode)() === 'full') {
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV ?? 'development',
});
}
let staticService = null;
if (framework === 'static') {
const entryPoint = staticEntry || 'index.html';
staticService = new StaticFileService_1.StaticFileService(projectPath, entryPoint);
}
let listenPort = options.rivetPort ?? _1.DEFAULT_PORT;
const previewPort = options.previewPort;
let previewOrigin = previewPort !== undefined
? `http://${EMBEDDED_AGENT_LISTEN_HOST}:${previewPort}`
: `http://${EMBEDDED_AGENT_PREVIEW_HOST}:${listenPort}`;
let userDevProxy = null;
const app = (0, express_1.default)();
const requireEditorAccess = (0, editorAccess_1.authenticateEditor)(editorAccessToken);
app.use(editorAccess_2.EDITOR_ACCOUNT_PATHS, requireEditorAccess);
const editorHost = () => `${EMBEDDED_AGENT_LISTEN_HOST}:${listenPort}`;
const isPreviewRequest = (req) => req.headers.host === new URL(previewOrigin).host &&
(previewPort === undefined || req.socket.localPort === previewPort);
app.use((req, res, next) => {
const requestHost = req.headers.host;
const isEditorRequest = requestHost === editorHost() && req.socket.localPort === listenPort;
if (!isEditorRequest && !isPreviewRequest(req)) {
res.sendStatus(403);
return;
}
next();
});
const corsOrigins = new Set([
(0, exports.resolveEmbeddedAgentUiOrigin)(listenPort),
]);
const rawCorsOrigins = process.env.RIVET_CORS_ORIGINS;
if (rawCorsOrigins) {
rawCorsOrigins
.split(',')
.map((origin) => origin.trim())
.filter((origin) => origin.length > 0)
.forEach((origin) => corsOrigins.add(origin));
}
app.use((req, res, next) => {
(0, cors_1.default)({
origin: (origin, callback) => {
callback(null, (0, exports.isRivetCorsOriginAllowed)({
requestOrigin: origin,
requestHostname: req.hostname,
requestPath: req.path,
allowedOrigins: corsOrigins,
agentApplyMode,
}));
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: exports.RIVET_CORS_ALLOWED_HEADERS,
})(req, res, next);
});
app.use((req, res, next) => {
if (!isPreviewRequest(req)) {
next();
return;
}
if (req.headers[editorAccess_2.EDITOR_ACCESS_TOKEN_HEADER]) {
res.sendStatus(403);
return;
}
const isAppApi = req.path.toLowerCase().startsWith('/api/') &&
!PREVIEW_PORT_ALLOWED_API_RE.test(req.path.toLowerCase());
const isEditorUi = req.path.toLowerCase() === '/rivet' ||
req.path.toLowerCase().startsWith('/rivet/');
if (isEditorUi || /^\/api\/git(?:\/|$)/i.test(req.path)) {
res.status(404).end();
return;
}
if (isAppApi) {
if (userDevProxy) {
userDevProxy.middleware(req, res, (error) => {
if (error) {
next(error);
return;
}
res.sendStatus(404);
});
}
else {
res.sendStatus(404);
}
return;
}
next();
});
app.use((0, editorAccess_1.authenticateEditorApi)(editorAccessToken));
app.use('/api/telemetry', (0, telemetry_1.createTelemetryRouter)(telemetry));
const jsonBodyParser = express_1.default.json({ limit: '50mb' });
app.use(jsonBodyParser);
app.use((req, res, next) => {
log.debug(`${req.method} ${req.originalUrl}`);
next();
});
const uiStaticOptions = {
setHeaders: (res, filePath) => {
if (filePath.endsWith('.html')) {
setNoStoreHeaders(res);
}
else if (process.env.NODE_ENV !== 'production') {
setNoStoreHeaders(res);
}
else {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
},
};
const sendRivetUiIndex = (req, res) => {
if (!(0, exports.isEmbeddedAgentUiHost)(req.hostname, 'embedded')) {
res.redirect(302, `${(0, exports.resolveEmbeddedAgentUiOrigin)(listenPort)}${req.originalUrl}`);
return;
}
setNoStoreHeaders(res);
const libraryOrigin = options.resolveLibraryOrigin?.();
res.setHeader('Content-Security-Policy', `frame-ancestors 'self'${libraryOrigin ? ` ${new URL(libraryOrigin).origin}` : ''}`);
res.type('html').send((0, exports.injectRivetUiBootstrap)((0, exports.readRivetUiIndexHtml)(), {
agentApplyMode: agentApplyMode ?? null,
queueAccessToken,
previewOrigin,
}));
};
const serveEditorAssets = (directory) => {
const serve = express_1.default.static(directory, uiStaticOptions);
return (req, res, next) => isPreviewRequest(req) ? next() : serve(req, res, next);
};
app.use('/assets', serveEditorAssets(path_1.default.join(exports.DIST_UI_PATH, 'assets')));
app.use('/rivet/assets', serveEditorAssets(path_1.default.join(exports.DIST_UI_PATH, 'assets')));
app.use('/fonts', serveEditorAssets(path_1.default.join(exports.DIST_UI_PATH, 'fonts')));
app.use('/rivet/fonts', serveEditorAssets(path_1.default.join(exports.DIST_UI_PATH, 'fonts')));
app.get('/favicon.ico', (_req, res) => {
res.sendFile('favicon.ico', { root: exports.DIST_UI_PATH });
});
app.get('/rivet/favicon.ico', (_req, res) => {
res.sendFile('favicon.ico', { root: exports.DIST_UI_PATH });
});
app.get(/^\/rivet(?:\/.*)?$/, (req, res, next) => {
if ((0, exports.isRivetUiStaticAssetPath)(req.path)) {
next();
return;
}
sendRivetUiIndex(req, res);
});
log.info(`Serving UI assets from: ${exports.DIST_UI_PATH}`);
if (framework === 'static' && !hasUserDevServer) {
app.get('/', (req, res, next) => {
if (isPreviewRequest(req)) {
next();
return;
}
log.debug(`${framework} mode - serving Rivet at root`);
sendRivetUiIndex(req, res);
});
app.get(/^\/rivet(?:\/.*)?$/, (req, res, next) => {
if ((0, exports.isRivetUiStaticAssetPath)(req.path)) {
next();
return;
}
const rest = req.path.slice('/rivet'.length);
const target = rest && rest !== '/' ? rest : '/';
const queryStart = req.originalUrl.indexOf('?');
const search = queryStart >= 0 ? req.originalUrl.slice(queryStart) : '';
res.redirect(302, `${target}${search}`);
});
}
const getBearerTokenFromHeader = (authorizationHeader) => {
if (typeof authorizationHeader !== 'string') {
return undefined;
}
if (!authorizationHeader.startsWith('Bearer ')) {
return undefined;
}
const token = authorizationHeader.slice('Bearer '.length).trim();
return token.length > 0 ? token : undefined;
};
app.use((req, _res, next) => {
const headerToken = getBearerTokenFromHeader(req.headers.authorization);
if (!headerToken) {
next();
return;
}
(0, RequestAuthContext_1.runWithRequestAuthContext)({ token: headerToken }, () => {
next();
});
});
app.use('/api', (0, integrations_1.createIntegrationsRouter)());
app.use('/api', (0, referenceProfiles_1.createReferenceProfilesRouter)());
void (0, WorktreeManager_1.pruneWorktrees)(projectPath);
app.use('/api/git', (_req, res) => res.sendStatus(404));
app.use('/api', (0, support_1.createSupportRouter)(telemetry));
app.use((req, res, next) => {
const isPreviewPath = req.path.toLowerCase().startsWith('/static') ||
req.path.toLowerCase().startsWith('/__rivet/preview/') ||
PREVIEW_PORT_ALLOWED_API_RE.test(req.path.toLowerCase());
if (!isPreviewRequest(req) && isPreviewPath) {
if (req.headers[editorAccess_2.EDITOR_ACCESS_TOKEN_HEADER]) {
res.sendStatus(403);
return;
}
res.redirect(302, `${previewOrigin}${req.originalUrl}`);
return;
}
next();
});
if (staticService) {
app.use((0, static_1.createStaticRoutes)(staticService, projectPath, {
isPreviewBridgeEnabled: true,
get expectedPreviewParentOrigin() {
return (0, exports.resolveEmbeddedAgentUiOrigin)(listenPort);
},
}));
log.info('Static routes mounted at /static');
}
app.get('/api/health', (req, res) => {
let originalPreviewPath = null;
if (staticService) {
const entryPath = path_1.default.join(staticService.getBasePath(), staticService.getEntryFileName());
if (fs_1.default.existsSync(entryPath))
originalPreviewPath = '/static/';
}
else if (hasUserDevServer) {
originalPreviewPath = '/__rivet/preview/base/';
}
res.json({
status: 'healthy',
projectPath,
pid: process.pid,
channel: (0, installationChannel_1.installationChannel)(),
rivetVersion: telemetry_2.RIVET_VERSION,
pluginName: (0, pluginContext_1.getPluginName)(),
telemetryMode: (0, telemetryPolicy_1.getTelemetryMode)(),
timestamp: new Date().toISOString(),
framework,
ports: {
rivet: listenPort,
userDevServer: userPortWithFallback,
},
originalPreviewPath,
});
});
app.get('/api/feature-flags', async (req, res) => {
const configManager = (0, ConfigManager_1.getConfigManager)();
const featureFlagUserKey = (0, featureFlagUserKey_1.getConfigFeatureFlagUserKey)({
headers: req.headers,
fallbackEmail: configManager.getEmail(),
});
const featureFlags = await (0, evaluateFlags_1.getFeatureFlags)({ userKey: featureFlagUserKey });
res.json({ featureFlags });
});
app.get('/api/config', async (_req, res) => {
const configManager = (0, ConfigManager_1.getConfigManager)();
const livePath = sessionBridge?.getProjectPath() ?? projectPath;
res.json({
agentModeAvailable: configManager.isAuthenticated(),
email: configManager.getEmail(),
userId: configManager.getUserId(),
name: configManager.getDisplayName(),
isMCPSession: sessionBridge?.isActive() ?? false,
mcpEditor: mcpEditor ?? null,
agentApplyMode: sessionBridge?.isActive()
? (agentApplyMode ?? 'external')
: null,
projectPath: livePath,
projectId: options.projectId ?? null,
libraryOrigin: options.resolveLibraryOrigin?.() ?? null,
});
});
app.post('/api/library/browser-launches', express_1.default.urlencoded({ extended: false }), async (req, res) => {
if (!(0, middleware_1.isLocalBrowserRequest)(req))
return res.sendStatus(403);
const view = req.body?.view;
if (view !== 'projects' && view !== 'references')
return res.sendStatus(400);
try {
const url = await options.createLibraryViewUrl?.(view);
if (!url)
return res.sendStatus(503);
return res.json({ url });
}
catch (error) {
log.error('Could not open the project library', error);
return res.sendStatus(503);
}
});
app.use('/api', (0, installRef_1.createInstallRefRouter)());
app.use('/api', (0, account_1.createAccountRouter)(telemetry));
if (sessionBridge) {
app.use('/api/mcp', (0, mcp_1.createMCPRouter)(sessionBridge, options.telemetry, variantsOrchestrator, {
queueAccessToken: queueAccessToken ?? undefined,
}));
log.info('MCP bridge routes mounted at /api/mcp');
app.use('/api/cli', (0, cli_1.createCliRouter)({
bridge: sessionBridge,
orchestrator: variantsOrchestrator,
rivetPort: listenPort,
queueAccessToken,
onShutdown: options.cliShutdown,
beforeUpgrade: () => options.variantsRuntime?.runService.interruptWorkers(),
inlineStart: inlineStartTracker,
admission: runtimeAdmission,
restartArgs: options.restartArgs,
}));
log.info('CLI control routes mounted at /api/cli');
}
if (variantsOrchestrator) {
app.use('/api', (0, agentVariants_1.createAgentVariantsRouter)(variantsOrchestrator, variantsBridge, telemetry, variantHistory ?? undefined, undefined, variantRunService, historyReplay ?? undefined, {
isEnabled: true,
resolveLibraryOrigin: options.resolveLibraryOrigin,
get expectedParentOrigin() {
return (0, exports.resolveEmbeddedAgentUiOrigin)(listenPort);
},
}, inlineStartTracker, runtimeAdmission));
log.info('agent-variants routes mounted at /api/variants');
}
else {
app.get('/api/variants/active', (_req, res) => {
res.json({ active: false });
});
app.get('/api/variants/events', (req, res) => {
(0, exports.sendInactiveVariantsEventStream)(req, res);
});
}
if (framework !== 'static' || hasUserDevServer || variantsBridge) {
const proxyUserPort = framework === 'static' && !hasUserDevServer
? NO_USER_DEV_SERVER_PORT
: userPortWithFallback;
userDevProxy = (0, proxy_config_1.createUserDevServerProxy)(proxyUserPort, userHostWithFallback, {
isPreviewBridgeEnabled: true,
get expectedPreviewParentOrigin() {
return (0, exports.resolveEmbeddedAgentUiOrigin)(listenPort);
},
resolveVariantPreviewPort: (sessionId, variantId, options) => {
if (options?.source === 'history') {
return historyReplay?.getPort(sessionId, variantId) ?? null;
}
const port = variantsOrchestrator?.resolveDevServerPortForPreview(sessionId, variantId);
if (typeof port === 'number')
return port;
return historyReplay?.getPort(sessionId, variantId) ?? null;
},
});
variantsBridge?.registerVariantTargetSetter(userDevProxy.setVariantTarget);
app.use((req, res, next) => {
if (!isPreviewRequest(req)) {
if (req.path.toLowerCase().startsWith('/api/')) {
res.sendStatus(404);
return;
}
if (req.headers[editorAccess_2.EDITOR_ACCESS_TOKEN_HEADER]) {
res.sendStatus(403);
return;
}
res.redirect(302, `${previewOrigin}${req.originalUrl}`);
return;
}
if (req.headers[editorAccess_2.EDITOR_ACCESS_TOKEN_HEADER]) {
res.sendStatus(403);
return;
}
next();
});
app.get('/{*any}', userDevProxy.middleware);
app.post('/{*any}', userDevProxy.middleware);
app.put('/{*any}', userDevProxy.middleware);
app.delete('/{*any}', userDevProxy.middleware);
app.patch('/{*any}', userDevProxy.middleware);
log.info(proxyUserPort > 0
? `Proxying all unmatched routes to user dev server on ${userHostWithFallback}:${proxyUserPort}`
: 'Proxying variant previews without a base user dev server');
}
else {
log.info(`${framework} mode - skipping proxy setup`);
}
if (process.env.SENTRY_DSN && (0, telemetryPolicy_1.getTelemetryMode)() === 'full') {
Sentry.setupExpressErrorHandler(app);
}
app.use((err, req, res, _next) => {
const requestAborted = err.code === 'ECONNABORTED' ||
err.type === 'request.aborted';
if (requestAborted) {
log.debug('Request aborted by client');
return;
}
log.error('Unhandled route error:', err);
telemetry?.captureException(err, 'express_error_handler');
if (!res.headersSent) {
res.status(500).json({
error: 'Internal server error',
details: err.message,
});
}
});
const activeSockets = new Set();
let handshakeApplyMode = 'none';
if (sessionBridge) {
handshakeApplyMode = agentApplyMode === 'embedded' ? 'embedded' : 'none';
}
const advertiseCliHandshake = () => {
try {
(0, serverHandshake_1.writeHandshake)({
version: serverHandshake_1.CLI_HANDSHAKE_VERSION,
pid: process.pid,
rivetPort: listenPort,
projectPath,
startedAt,
sessionId: sessionBridge?.getSessionId() ?? null,
applyMode: handshakeApplyMode,
queueAccessToken,
rivetVersion: telemetry_2.RIVET_VERSION,
pluginName: (0, pluginContext_1.getPluginName)(),
telemetryMode: (0, telemetryPolicy_1.getTelemetryMode)(),
});
}
catch (err) {
log.debug('Failed to write CLI handshake (non-fatal)', err);
}
};
const retireCliHandshake = () => {
(0, serverHandshake_1.removeHandshake)(projectPath, process.pid);
(0, editorSession_1.removeEditorSession)({ pid: process.pid, port: listenPort, projectPath, startedAt }, editorAccessToken);
};
const httpServer = await new Promise((resolve, reject) => {
const listenHost = (0, exports.resolveRivetListenHost)(agentApplyMode);
const server = app.listen(listenPort, listenHost, (error) => {
if (error) {
reject(error);
return;
}
log.info(`🎨 Rivet server running on http://${listenHost}:${listenPort}`);
listenPort = server.address().port;
if (previewPort === undefined)
previewOrigin = `http://${EMBEDDED_AGENT_PREVIEW_HOST}:${listenPort}`;
corsOrigins.add((0, exports.resolveEmbeddedAgentUiOrigin)(listenPort));
try {
(0, editorSession_1.writeEditorSession)({
pid: process.pid,
port: listenPort,
projectPath,
token: editorAccessToken,
startedAt,
});
}
catch (error) {
server.close(() => reject(error));
return;
}
writeDevPortFile(listenPort);
advertiseCliHandshake();
resolve(server);
});
server.on('error', (err) => {
reject(err);
});
server.on('connection', (socket) => {
activeSockets.add(socket);
socket.on('close', () => activeSockets.delete(socket));
});
server.on('upgrade', (req, socket, head) => {
const pathname = req.url?.split('?')[0] ?? '';
log.debug(`WebSocket upgrade request for: ${pathname}`);
const proxyUpgrade = userDevProxy?.middleware?.upgrade;
if (proxyUpgrade) {
log.debug('Proxying upgrade to user dev server for HMR');
proxyUpgrade(req, socket, head);
return;
}
log.warn(`No handler for WebSocket upgrade: ${pathname}`);
socket.destroy();
});
});
let previewHttpServer = null;
if (previewPort !== undefined) {
try {
previewHttpServer = await new Promise((resolve, reject) => {
const pServer = (0, http_1.createServer)(app);
pServer.on('error', reject);
pServer.on('connection', (socket) => {
activeSockets.add(socket);
socket.on('close', () => activeSockets.delete(socket));
});
pServer.on('upgrade', (req, socket, head) => {
const proxyUpgrade = userDevProxy?.middleware?.upgrade;
if (proxyUpgrade) {
proxyUpgrade(req, socket, head);
return;
}
socket.destroy();
});
pServer.listen(previewPort, EMBEDDED_AGENT_LISTEN_HOST, () => {
log.info(`🔒 Rivet isolated preview origin on http://${EMBEDDED_AGENT_LISTEN_HOST}:${previewPort}`);
resolve(pServer);
});
});
}
catch (error) {
removeDevPortFile();
retireCliHandshake();
await new Promise((resolve) => {
httpServer.close(() => resolve());
for (const socket of activeSockets)
socket.destroy();
});
throw error;
}
}
if (!skipProcessHandlers) {
const shutdownAndExit = async (code) => {
log.info('Server shutting down, cleaning up...');
(0, WorktreeManager_1.cleanupOrphanedWorktrees)();
const results = await Promise.allSettled([
options.beforeShutdown?.(),
telemetry?.shutdown(),
(0, FeatureFlagService_1.getFeatureFlagService)().shutdown(),
]);
const labels = ['shutdown hook', 'telemetry', 'feature flags'];
for (let i = 0; i < results.length; i++) {
if (results[i].status === 'rejected') {
log.error(`Failed to cleanup ${labels[i]}:`, results[i].reason);
}
}
(0, serverHandshake_1.removeHandshake)(projectPath, process.pid);
(0, editorSession_1.removeEditorSession)({ pid: process.pid, port: listenPort, projectPath, startedAt }, editorAccessToken);
process.exit(code);
};
process.on('SIGINT', () => shutdownAndExit(0));
process.on('SIGTERM', () => shutdownAndExit(0));
process.on('uncaughtException', (err) => {
log.error('Uncaught exception:', err);
telemetry?.captureException(err, 'uncaught_exception');
shutdownAndExit(1);
});
process.on('unhandledRejection', (reason) => {
log.error('Unhandled rejection:', reason);
telemetry?.captureException(reason, 'unhandled_rejection');
shutdownAndExit(1);
});
}
return {
editorUrl: (0, editorAccess_2.createEditorUrl)({
port: httpServer.address().port,
token: editorAccessToken,
}),
close: () => new Promise((resolve, reject) => {
removeDevPortFile();
retireCliHandshake();
previewHttpServer?.close();
httpServer.close((err) => {
if (err) {
reject(err);
return;
}
void (async () => {
await (0, exports.runServerShutdownTasks)({
beforeShutdown: options.beforeShutdown,
telemetry,
});
resolve();
})();
});
for (const socket of activeSockets) {
socket.destroy();
}
}),
};
};
exports.startServer = startServer;
//# sourceMappingURL=server.js.mapSHA-256: f20f1858f23f703f12cab7d4ec62d4bc1c2f0c29c817a1cd50464ec25bbadfcd