- 50个后端模块用git mv移入core/与domains/<领域>/,入口server.js、launch.js、restore.js及server/原位不动 - 所有require路径由脚本按新旧位置统一换算(后端、server/、测试) - 新增test/app-paths.test.js,锁定默认数据目录、public目录与飞书配置文件的绝对位置 - 维护与部署.md补充目录说明并更新模块路径 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
73 lines
3.0 KiB
JavaScript
73 lines
3.0 KiB
JavaScript
'use strict';
|
|
// 入口:正式启动(运行锁 → 升级前备份 → 创建应用 → 显式迁移 → 监听);同时导出测试与 launch.js 使用的接口。
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const ShopSettings = require('./domains/team/shop-settings');
|
|
const { createApp } = require('./server/app');
|
|
const { createUser, demoSeed } = require('./server/accounts');
|
|
const { prepareTeamStartupDatabase, prepareStartupMigrations } = require('./server/startup');
|
|
function acquireLock(dataDir) {
|
|
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
|
const lock = path.join(dataDir, 'server.lock');
|
|
if (fs.existsSync(lock)) {
|
|
const pid = Number(fs.readFileSync(lock, 'utf8'));
|
|
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('运行锁内容异常,请维护者核对server.lock');
|
|
let alive = true;
|
|
try {
|
|
process.kill(pid, 0);
|
|
} catch (e) {
|
|
if (e.code === 'ESRCH') alive = false;
|
|
else throw e;
|
|
}
|
|
if (alive) throw new Error('这份数据库已有系统进程运行,请打开现有页面,不要启动第二个服务。');
|
|
fs.unlinkSync(lock);
|
|
}
|
|
fs.writeFileSync(lock, String(process.pid), { flag: 'wx', mode: 0o600 });
|
|
return () => {
|
|
try {
|
|
if (fs.readFileSync(lock, 'utf8') === String(process.pid)) fs.unlinkSync(lock);
|
|
} catch {}
|
|
};
|
|
}
|
|
if (require.main === module) {
|
|
let unlock, app;
|
|
(async () => {
|
|
try {
|
|
const mode = process.env.APP_MODE || 'trial',
|
|
dir = mode === 'production' ? process.env.DATA_DIR : path.join(__dirname, 'data', mode);
|
|
if (!dir) throw new Error('请配置持久化DATA_DIR');
|
|
unlock = acquireLock(dir);
|
|
process.on('exit', () => unlock?.());
|
|
await prepareTeamStartupDatabase(dir);
|
|
app = createApp();
|
|
await prepareStartupMigrations(app);
|
|
app.server.on('error', e => {
|
|
console.error(e.code === 'EADDRINUSE' ? '这个端口已在使用,请打开现有页面,或修改PORT再启动。' : e.message);
|
|
process.exitCode = 1;
|
|
app.ledger.close();
|
|
unlock?.();
|
|
});
|
|
app.server.listen(app.port, app.host, () => {
|
|
app.startTimers();
|
|
console.log(
|
|
`${ShopSettings.read(app.ledger).storeName} ${app.mode === 'production' ? '云端正式系统' : app.mode === 'demo' ? '演示练习(虚构数据)' : '本机试用(尚未云端上线)'}\n打开 http://${app.host}:${app.port}\n数据库目录:${app.dataDir}\n保持本窗口打开。按 Ctrl+C 停止。`,
|
|
);
|
|
});
|
|
process.on('SIGINT', () => {
|
|
app.stop();
|
|
process.exit(0);
|
|
});
|
|
process.on('SIGTERM', () => {
|
|
app.stop();
|
|
process.exit(0);
|
|
});
|
|
} catch (e) {
|
|
app?.ledger.close();
|
|
unlock?.();
|
|
console.error('启动失败:' + e.message);
|
|
process.exitCode = 1;
|
|
}
|
|
})();
|
|
}
|
|
module.exports = { createApp, createUser, demoSeed, acquireLock, prepareStartupMigrations, prepareTeamStartupDatabase };
|