@fudanda/create-arcbase 2.20261026.1-beta.1 → 2.20261109.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.runtime/npm/index.json +18 -18
  2. package/.runtime/sdk.json +3 -3
  3. package/LICENSE +21 -21
  4. package/README.md +99 -91
  5. package/cli.mjs +42 -39
  6. package/package.json +10 -5
  7. package/src/assistant.mjs +76 -0
  8. package/src/delivery.mjs +20 -20
  9. package/src/enhance.mjs +103 -104
  10. package/src/evolve.mjs +66 -66
  11. package/src/fields.mjs +73 -73
  12. package/src/goa-contracts.mjs +331 -331
  13. package/src/goa.mjs +202 -202
  14. package/src/history.mjs +16 -16
  15. package/src/layout.mjs +1 -1
  16. package/src/module.mjs +439 -477
  17. package/src/packages.mjs +12 -4
  18. package/src/page-antd.mjs +98 -77
  19. package/src/page-webmcp.mjs +51 -0
  20. package/src/project.mjs +112 -105
  21. package/src/records.mjs +15 -15
  22. package/src/release-vite.mjs +1 -0
  23. package/src/release.mjs +455 -0
  24. package/src/templates.mjs +20 -20
  25. package/src/upgrade.mjs +415 -249
  26. package/templates/module/02-migrations.go.txt +10 -10
  27. package/templates/module/03-service.go.txt +52 -52
  28. package/templates/module/04-module.go.txt +12 -12
  29. package/templates/module/06-queries.ts.txt +15 -15
  30. package/templates/module/08-service_test.go.txt +9 -9
  31. package/templates/module/09-TransferPanel.tsx.txt +16 -0
  32. package/templates/module-runtime-test.go.txt +86 -86
  33. package/templates/module-transfer.go.txt +74 -74
  34. package/templates/project-v2/.agents/skills/arcbase/SKILL.md +32 -0
  35. package/templates/project-v2/.agents/skills/goa-service-designer/SKILL.md +31 -0
  36. package/templates/project-v2/AGENTS.md +38 -0
  37. package/templates/project-v2/DEVELOPMENT.md +115 -84
  38. package/templates/project-v2/README.md +76 -74
  39. package/templates/project-v2/RELEASE.md +88 -0
  40. package/templates/project-v2/TEAM-TRIAL.md +32 -32
  41. package/templates/project-v2/arcbase.release.json +23 -0
  42. package/templates/project-v2/cmd/server/main.go +62 -36
  43. package/templates/project-v2/cmd/server/modules.gen.go +6 -6
  44. package/templates/project-v2/eslint.config.mjs +9 -9
  45. package/templates/project-v2/internal/dashboard/dist/README.txt +1 -1
  46. package/templates/project-v2/internal/dashboard/embed.go +11 -11
  47. package/templates/project-v2/package.json +11 -4
  48. package/templates/project-v2/scripts/application-version.mjs +138 -0
  49. package/templates/project-v2/scripts/assets.mjs +13 -14
  50. package/templates/project-v2/scripts/build-backend.mjs +11 -9
  51. package/templates/project-v2/scripts/build.mjs +12 -0
  52. package/templates/project-v2/scripts/check-generated.mjs +79 -48
  53. package/templates/project-v2/scripts/config.mjs +55 -54
  54. package/templates/project-v2/scripts/dev-watch.mjs +78 -78
  55. package/templates/project-v2/scripts/dev.mjs +50 -49
  56. package/templates/project-v2/scripts/doctor.mjs +94 -94
  57. package/templates/project-v2/scripts/generate-contracts.mjs +88 -88
  58. package/templates/project-v2/scripts/go-build-identity/main.go +210 -0
  59. package/templates/project-v2/scripts/go.mjs +17 -15
  60. package/templates/project-v2/scripts/layout.mjs +10 -10
  61. package/templates/project-v2/scripts/lifecycle.mjs +245 -245
  62. package/templates/project-v2/scripts/openobserve-build.mjs +115 -0
  63. package/templates/project-v2/scripts/project-info.mjs +105 -0
  64. package/templates/project-v2/scripts/release-metadata.mjs +13 -0
  65. package/templates/project-v2/scripts/release-vite.mjs +23 -0
  66. package/templates/project-v2/scripts/release.mjs +3 -0
  67. package/templates/project-v2/scripts/run.mjs +11 -11
  68. package/templates/project-v2/scripts/sdk-integrity.mjs +39 -39
  69. package/templates/project-v2/scripts/setup.mjs +44 -44
  70. package/templates/project-v2/web/admin/index.html +5 -5
  71. package/templates/project-v2/web/admin/package.json +3 -2
  72. package/templates/project-v2/web/admin/src/brand.json +1 -1
  73. package/templates/project-v2/web/admin/src/extensions.gen.ts +6 -6
  74. package/templates/project-v2/web/admin/src/extensions.ts +1 -1
  75. package/templates/project-v2/web/admin/src/main.tsx +20 -14
  76. package/templates/project-v2/web/admin/tsconfig.json +17 -17
  77. package/templates/project-v2/web/admin/vite.config.ts +47 -27
  78. package/src/page.mjs +0 -66
  79. package/templates/module/07-Page.tsx.txt +0 -20
@@ -1,10 +1,10 @@
1
- export function projectLayout(manifest) {
2
- if (manifest.format === 2) return {
3
- goRoot: '.', goEntry: './cmd/server', ent: 'internal/ent', domains: 'internal/modules',
4
- pages: 'web/admin/src/pages', goRegistry: 'cmd/server/modules.gen.go', webRegistry: 'web/admin/src/extensions.gen.ts',
5
- goImports: `${manifest.backendModule}/internal/modules`, entImport: `${manifest.backendModule}/internal/ent`,
6
- webImports: './pages', dashboard: 'internal/dashboard/dist', sdk: '.arcbase/sdk', sdkMetadata: '.arcbase/sdk.json',
7
- binary: 'build/arcbase', brand: 'web/admin/src/brand.json',
8
- };
9
- throw new Error('Unsupported project format; ArcBase requires format 2');
10
- }
1
+ export function projectLayout(manifest) {
2
+ if (manifest.format === 2) return {
3
+ goRoot: '.', goEntry: './cmd/server', ent: 'internal/ent', domains: 'internal/modules',
4
+ pages: 'web/admin/src/pages', goRegistry: 'cmd/server/modules.gen.go', webRegistry: 'web/admin/src/extensions.gen.ts',
5
+ goImports: `${manifest.backendModule}/internal/modules`, entImport: `${manifest.backendModule}/internal/ent`,
6
+ webImports: './pages', dashboard: 'internal/dashboard/dist', sdk: '.arcbase/sdk', sdkMetadata: '.arcbase/sdk.json',
7
+ binary: 'build/arcbase', brand: 'web/admin/src/brand.json',
8
+ };
9
+ throw new Error('Unsupported project format; ArcBase requires format 2');
10
+ }
@@ -1,245 +1,245 @@
1
- import { spawn, spawnSync } from 'node:child_process';
2
- import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readlinkSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
3
- import { resolve } from 'node:path';
4
- import { createServer } from 'node:net';
5
- import { environment, envFile, executable, root, urls } from './config.mjs';
6
-
7
- const directory = resolve(root, '.arcbase/runtime');
8
- const file = resolve(directory, 'processes.json');
9
- const lock = resolve(directory, 'control.lock');
10
- const pause = milliseconds => new Promise(done => setTimeout(done, milliseconds));
11
- const samePath = (left, right) => process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
12
-
13
- function prepareRuntime() {
14
- mkdirSync(directory, { recursive: true });
15
- if (!samePath(realpathSync(directory), directory)) throw new Error('Runtime directory must not traverse a symbolic link');
16
- for (const path of [file, lock]) if (existsSync(path) && !lstatSync(path).isFile()) throw new Error('Runtime state must be a regular file');
17
- }
18
- export function identity(pid) {
19
- if (!Number.isInteger(pid) || pid <= 0) throw new Error('Invalid managed process ID');
20
- if (process.platform === 'win32') {
21
- const command = `$taskManagedProcess = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; if ($taskManagedProcess) { @{ executable = $taskManagedProcess.ExecutablePath; started = $taskManagedProcess.CreationDate.ToUniversalTime().Ticks.ToString(); command = $taskManagedProcess.CommandLine } | ConvertTo-Json -Compress }`;
22
- const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { encoding: 'utf8', windowsHide: true });
23
- if (result.error || result.status !== 0) throw new Error('Cannot verify process ownership');
24
- return result.stdout.trim() ? JSON.parse(result.stdout) : null;
25
- }
26
- if (process.platform === 'linux') {
27
- try {
28
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
29
- return { executable: readlinkSync(`/proc/${pid}/exe`), started: readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() + ':' + stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19] };
30
- } catch (error) {
31
- if (error.code === 'ENOENT' || error.code === 'ESRCH') return null;
32
- throw error;
33
- }
34
- }
35
- const result = spawnSync('ps', ['-p', String(pid), '-o', 'lstart=', '-o', 'command='], { encoding: 'utf8' });
36
- if (result.status !== 0 || !result.stdout.trim()) return null;
37
- const line = result.stdout.trim();
38
- return { executable: line.slice(25).trim().split(' ')[0], started: line.slice(0, 24) };
39
- }
40
- function verified(record) {
41
- const actual = identity(record.pid);
42
- if (!actual) return false;
43
- if (actual.started !== record.identity.started || !actual.executable || !samePath(actual.executable, record.identity.executable)) throw new Error('Process identity changed; refusing to manage this PID');
44
- return true;
45
- }
46
- function state() {
47
- prepareRuntime();
48
- if (!existsSync(file)) return { format: 1, project: root, processes: [] };
49
- const value = JSON.parse(readFileSync(file, 'utf8'));
50
- if (value.format !== 1 || value.project !== root || !Array.isArray(value.processes)) throw new Error('Invalid project process state');
51
- return value;
52
- }
53
- function releaseOwnedLock(owner) {
54
- try { if (readFileSync(lock, 'utf8') === owner) unlinkSync(lock); }
55
- catch (error) { if (error.code !== 'ENOENT') throw error; }
56
- }
57
- function sameLock(snapshot) {
58
- try { return readFileSync(lock, 'utf8') === snapshot; }
59
- catch (error) { if (error.code === 'ENOENT') return false; throw error; }
60
- }
61
- export async function control(action, { wait = 0, command = 'control' } = {}) {
62
- prepareRuntime();
63
- const deadline = Date.now() + wait;
64
- const owner = JSON.stringify({ pid: process.pid, identity: identity(process.pid), command });
65
- while (existsSync(lock)) {
66
- let previous;
67
- let snapshot;
68
- try { snapshot = readFileSync(lock, 'utf8'); previous = JSON.parse(snapshot); }
69
- catch (error) {
70
- if ((error.code === 'ENOENT' || error instanceof SyntaxError) && Date.now() < deadline) { await pause(100); continue; }
71
- throw error;
72
- }
73
- let active;
74
- try { active = verified(previous); }
75
- catch (error) {
76
- // CIM can finish after stop releases its lock and exits. Its process
77
- // observation is relevant only while that exact lock is still current.
78
- if (!sameLock(snapshot)) continue;
79
- throw error;
80
- }
81
- if (!sameLock(snapshot)) continue;
82
- if (active) {
83
- if (Date.now() >= deadline) throw new Error('Another project lifecycle command is running');
84
- await pause(100);
85
- continue;
86
- }
87
- try {
88
- if (readFileSync(lock, 'utf8') !== snapshot) continue;
89
- unlinkSync(lock);
90
- } catch (error) { if (error.code !== 'ENOENT') throw error; }
91
- }
92
- let descriptor;
93
- try { descriptor = openSync(lock, 'wx', 0o600); }
94
- catch (error) {
95
- if (error.code === 'EEXIST' && Date.now() < deadline) return control(action, { wait: deadline - Date.now(), command });
96
- throw error;
97
- }
98
- try {
99
- writeFileSync(descriptor, owner);
100
- return await action();
101
- } finally {
102
- closeSync(descriptor);
103
- releaseOwnedLock(owner);
104
- }
105
- }
106
- export function current() {
107
- const value = state();
108
- return value.processes.filter(verified);
109
- }
110
- export function loginInfo(running = false) {
111
- const env = environment();
112
- const addresses = urls(env);
113
- console.log(JSON.stringify({ running, login: addresses.login, development: addresses.development,
114
- database: env.ARCBASE_DATABASE_URL?.startsWith('sqlite:') ? 'SQLite' : 'PostgreSQL',
115
- identityProvider: env.ARCBASE_IDENTITY_PROVIDER || 'local',
116
- username: env.ARCBASE_IDENTITY_PROVIDER === 'casdoor' ? null : env.ARCBASE_ADMIN_USERNAME ?? null,
117
- credentialsFile: envFile, passwordHint: env.ARCBASE_IDENTITY_PROVIDER === 'casdoor' ? 'Sign in with Casdoor; no local password is stored.' : 'Use ARCBASE_ADMIN_PASSWORD without the surrounding quotes; passwords are never printed.' }));
118
- }
119
- async function freePort(address) {
120
- const parsed = new URL(address);
121
- const socket = createServer();
122
- await new Promise((done, reject) => {
123
- socket.once('error', () => reject(new Error(`Port ${parsed.port} is occupied; inspect the listener or stop its owning project first`)));
124
- socket.listen(Number(parsed.port), parsed.hostname.replace(/^\[|\]$/g, ''), done);
125
- });
126
- await new Promise(done => socket.close(done));
127
- }
128
- export async function launch({ background = false, vite, apiExecutable = executable, retained = [], quiet = false } = {}) {
129
- const active = current();
130
- if (active.length !== retained.length || active.some(record => !retained.some(keep => keep.pid === record.pid && keep.kind === 'frontend'))) throw new Error('This project is already running; use npm run status or npm run restart');
131
- if (!existsSync(apiExecutable)) throw new Error('Run npm run setup or npm run build first');
132
- const env = environment();
133
- const addresses = urls(env);
134
- await freePort(addresses.api);
135
- if (vite) await freePort(addresses.development);
136
- const processes = [...retained];
137
- const children = [];
138
- const start = (command, args, kind) => {
139
- const log = background ? openSync(resolve(directory, `${kind}.log`), 'a', 0o600) : null;
140
- const child = spawn(command, args, { cwd: root, env, windowsHide: true, detached: background, stdio: log === null ? 'inherit' : ['ignore', log, log] });
141
- if (log !== null) closeSync(log);
142
- children.push(child);
143
- child.on('error', () => {});
144
- return child;
145
- };
146
- try {
147
- const api = start(apiExecutable, ['serve'], 'api');
148
- const deadline = Date.now() + 30000;
149
- while (true) {
150
- if (api.exitCode !== null || api.pid === undefined) throw new Error('Go service exited before becoming ready');
151
- try {
152
- const response = await fetch(addresses.api + '/api/v1/ready', { signal: AbortSignal.timeout(1000) });
153
- if (response.ok) break;
154
- } catch { /* the Go service is starting */ }
155
- if (Date.now() >= deadline) throw new Error('Go service did not become ready; inspect .arcbase/runtime/api.log');
156
- await pause(100);
157
- }
158
- await pause(100);
159
- if (api.exitCode !== null) throw new Error('Go service exited during startup');
160
- const apiIdentity = identity(api.pid);
161
- if (!apiIdentity?.executable || !samePath(apiIdentity.executable, realpathSync(apiExecutable))) throw new Error('Cannot establish Go process ownership');
162
- processes.push({ kind: 'api', pid: api.pid, identity: apiIdentity });
163
- if (vite) {
164
- const frontend = start(process.execPath, [vite, '--config', resolve(root, 'web/admin/vite.config.ts')], 'frontend');
165
- const deadline = Date.now() + 30000;
166
- while (true) {
167
- if (frontend.exitCode !== null || frontend.pid === undefined) throw new Error('Vite exited before becoming ready');
168
- try { if ((await fetch(addresses.development, { signal: AbortSignal.timeout(1000) })).ok) break; } catch { /* Vite is starting */ }
169
- if (Date.now() >= deadline) throw new Error('Vite did not become ready');
170
- await pause(100);
171
- }
172
- processes.push({ kind: 'frontend', pid: frontend.pid, identity: identity(frontend.pid) });
173
- }
174
- writeFileSync(file, JSON.stringify({ format: 1, project: root, processes }, null, 2) + '\n', { mode: 0o600 });
175
- if (background) children.forEach(child => child.unref());
176
- if (!quiet) loginInfo(true);
177
- return children;
178
- } catch (error) {
179
- await Promise.all(children.map(child => new Promise((done, reject) => {
180
- if (!child.pid || child.exitCode !== null || child.signalCode !== null) return done();
181
- const timer = setTimeout(() => reject(new Error('Failed startup process did not stop')), 15000);
182
- child.once('exit', () => { clearTimeout(timer); done(); });
183
- child.kill();
184
- })));
185
- throw error;
186
- }
187
- }
188
- async function terminate(records) {
189
- for (const record of records.toReversed()) {
190
- if (verified(record)) process.kill(record.pid, 'SIGTERM');
191
- const deadline = Date.now() + 15000;
192
- while (verified(record)) {
193
- if (Date.now() >= deadline) throw new Error('Managed process did not stop; no other process was terminated');
194
- await pause(100);
195
- }
196
- }
197
- }
198
- export async function stop() {
199
- await terminate(current());
200
- if (existsSync(file)) unlinkSync(file);
201
- }
202
- export function stopping() {
203
- if (!existsSync(file)) return true;
204
- try { return ['stop', 'restart'].includes(JSON.parse(readFileSync(lock, 'utf8')).command); }
205
- catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }
206
- }
207
- // Caller holds the lifecycle lock. A successful build is ready before we stop
208
- // the API; Vite stays alive. A failed startup restores the preceding binary.
209
- export async function reloadAPI(apiExecutable, expectedPID) {
210
- const records = current(), previous = records.find(record => record.kind === 'api');
211
- if (!previous || previous.pid !== expectedPID) return null;
212
- const retained = records.filter(record => record.kind === 'frontend');
213
- await terminate([previous]);
214
- writeFileSync(file, JSON.stringify({ format: 1, project: root, processes: retained }, null, 2) + '\n', { mode: 0o600 });
215
- try { return { api: (await launch({ apiExecutable, retained, quiet: true }))[0] }; }
216
- catch (error) {
217
- return { api: (await launch({ apiExecutable: previous.identity.executable, retained, quiet: true }))[0], error };
218
- }
219
- }
220
- export async function foreground(children) {
221
- let closing = false;
222
- const cleanup = async () => {
223
- if (closing) return;
224
- closing = true;
225
- await control(stop, { wait: 35000, command: 'cleanup' });
226
- };
227
- const signal = () => { void cleanup().catch(error => { console.error(error.message); process.exitCode = 1; }); };
228
- process.once('SIGINT', signal);
229
- process.once('SIGTERM', signal);
230
- try {
231
- const exit = await Promise.race(children.map(child => new Promise(done => {
232
- if (child.exitCode !== null) done({ code: child.exitCode });
233
- else child.once('exit', code => done({ code }));
234
- })));
235
- let externalStop = false;
236
- try { externalStop = ['stop', 'restart'].includes(JSON.parse(readFileSync(lock, 'utf8')).command); }
237
- catch (error) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; }
238
- const requestedStop = closing || externalStop || !existsSync(file);
239
- await cleanup();
240
- if (!requestedStop && exit.code !== 0) process.exitCode = exit.code ?? 1;
241
- } finally {
242
- process.removeListener('SIGINT', signal);
243
- process.removeListener('SIGTERM', signal);
244
- }
245
- }
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readlinkSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { createServer } from 'node:net';
5
+ import { environment, envFile, executable, root, urls } from './config.mjs';
6
+
7
+ const directory = resolve(root, '.arcbase/runtime');
8
+ const file = resolve(directory, 'processes.json');
9
+ const lock = resolve(directory, 'control.lock');
10
+ const pause = milliseconds => new Promise(done => setTimeout(done, milliseconds));
11
+ const samePath = (left, right) => process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
12
+
13
+ function prepareRuntime() {
14
+ mkdirSync(directory, { recursive: true });
15
+ if (!samePath(realpathSync(directory), directory)) throw new Error('Runtime directory must not traverse a symbolic link');
16
+ for (const path of [file, lock]) if (existsSync(path) && !lstatSync(path).isFile()) throw new Error('Runtime state must be a regular file');
17
+ }
18
+ export function identity(pid) {
19
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error('Invalid managed process ID');
20
+ if (process.platform === 'win32') {
21
+ const command = `$taskManagedProcess = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; if ($taskManagedProcess) { @{ executable = $taskManagedProcess.ExecutablePath; started = $taskManagedProcess.CreationDate.ToUniversalTime().Ticks.ToString(); command = $taskManagedProcess.CommandLine } | ConvertTo-Json -Compress }`;
22
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { encoding: 'utf8', windowsHide: true });
23
+ if (result.error || result.status !== 0) throw new Error('Cannot verify process ownership');
24
+ return result.stdout.trim() ? JSON.parse(result.stdout) : null;
25
+ }
26
+ if (process.platform === 'linux') {
27
+ try {
28
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
29
+ return { executable: readlinkSync(`/proc/${pid}/exe`), started: readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() + ':' + stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19] };
30
+ } catch (error) {
31
+ if (error.code === 'ENOENT' || error.code === 'ESRCH') return null;
32
+ throw error;
33
+ }
34
+ }
35
+ const result = spawnSync('ps', ['-p', String(pid), '-o', 'lstart=', '-o', 'command='], { encoding: 'utf8' });
36
+ if (result.status !== 0 || !result.stdout.trim()) return null;
37
+ const line = result.stdout.trim();
38
+ return { executable: line.slice(25).trim().split(' ')[0], started: line.slice(0, 24) };
39
+ }
40
+ function verified(record) {
41
+ const actual = identity(record.pid);
42
+ if (!actual) return false;
43
+ if (actual.started !== record.identity.started || !actual.executable || !samePath(actual.executable, record.identity.executable)) throw new Error('Process identity changed; refusing to manage this PID');
44
+ return true;
45
+ }
46
+ function state() {
47
+ prepareRuntime();
48
+ if (!existsSync(file)) return { format: 1, project: root, processes: [] };
49
+ const value = JSON.parse(readFileSync(file, 'utf8'));
50
+ if (value.format !== 1 || value.project !== root || !Array.isArray(value.processes)) throw new Error('Invalid project process state');
51
+ return value;
52
+ }
53
+ function releaseOwnedLock(owner) {
54
+ try { if (readFileSync(lock, 'utf8') === owner) unlinkSync(lock); }
55
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
56
+ }
57
+ function sameLock(snapshot) {
58
+ try { return readFileSync(lock, 'utf8') === snapshot; }
59
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
60
+ }
61
+ export async function control(action, { wait = 0, command = 'control' } = {}) {
62
+ prepareRuntime();
63
+ const deadline = Date.now() + wait;
64
+ const owner = JSON.stringify({ pid: process.pid, identity: identity(process.pid), command });
65
+ while (existsSync(lock)) {
66
+ let previous;
67
+ let snapshot;
68
+ try { snapshot = readFileSync(lock, 'utf8'); previous = JSON.parse(snapshot); }
69
+ catch (error) {
70
+ if ((error.code === 'ENOENT' || error instanceof SyntaxError) && Date.now() < deadline) { await pause(100); continue; }
71
+ throw error;
72
+ }
73
+ let active;
74
+ try { active = verified(previous); }
75
+ catch (error) {
76
+ // CIM can finish after stop releases its lock and exits. Its process
77
+ // observation is relevant only while that exact lock is still current.
78
+ if (!sameLock(snapshot)) continue;
79
+ throw error;
80
+ }
81
+ if (!sameLock(snapshot)) continue;
82
+ if (active) {
83
+ if (Date.now() >= deadline) throw new Error('Another project lifecycle command is running');
84
+ await pause(100);
85
+ continue;
86
+ }
87
+ try {
88
+ if (readFileSync(lock, 'utf8') !== snapshot) continue;
89
+ unlinkSync(lock);
90
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
91
+ }
92
+ let descriptor;
93
+ try { descriptor = openSync(lock, 'wx', 0o600); }
94
+ catch (error) {
95
+ if (error.code === 'EEXIST' && Date.now() < deadline) return control(action, { wait: deadline - Date.now(), command });
96
+ throw error;
97
+ }
98
+ try {
99
+ writeFileSync(descriptor, owner);
100
+ return await action();
101
+ } finally {
102
+ closeSync(descriptor);
103
+ releaseOwnedLock(owner);
104
+ }
105
+ }
106
+ export function current() {
107
+ const value = state();
108
+ return value.processes.filter(verified);
109
+ }
110
+ export function loginInfo(running = false) {
111
+ const env = environment();
112
+ const addresses = urls(env);
113
+ console.log(JSON.stringify({ running, login: addresses.login, development: addresses.development,
114
+ database: env.ARCBASE_DATABASE_URL?.startsWith('sqlite:') ? 'SQLite' : 'PostgreSQL',
115
+ identityProvider: env.ARCBASE_IDENTITY_PROVIDER || 'local',
116
+ username: env.ARCBASE_IDENTITY_PROVIDER === 'casdoor' ? null : env.ARCBASE_ADMIN_USERNAME ?? null,
117
+ credentialsFile: envFile, passwordHint: env.ARCBASE_IDENTITY_PROVIDER === 'casdoor' ? 'Sign in with Casdoor; no local password is stored.' : 'Use ARCBASE_ADMIN_PASSWORD without the surrounding quotes; passwords are never printed.' }));
118
+ }
119
+ async function freePort(address) {
120
+ const parsed = new URL(address);
121
+ const socket = createServer();
122
+ await new Promise((done, reject) => {
123
+ socket.once('error', () => reject(new Error(`Port ${parsed.port} is occupied; inspect the listener or stop its owning project first`)));
124
+ socket.listen(Number(parsed.port), parsed.hostname.replace(/^\[|\]$/g, ''), done);
125
+ });
126
+ await new Promise(done => socket.close(done));
127
+ }
128
+ export async function launch({ background = false, vite, apiExecutable = executable, retained = [], quiet = false } = {}) {
129
+ const active = current();
130
+ if (active.length !== retained.length || active.some(record => !retained.some(keep => keep.pid === record.pid && keep.kind === 'frontend'))) throw new Error('This project is already running; use npm run status or npm run restart');
131
+ if (!existsSync(apiExecutable)) throw new Error('Run npm run setup or npm run build first');
132
+ const env = environment();
133
+ const addresses = urls(env);
134
+ await freePort(addresses.api);
135
+ if (vite) await freePort(addresses.development);
136
+ const processes = [...retained];
137
+ const children = [];
138
+ const start = (command, args, kind) => {
139
+ const log = background ? openSync(resolve(directory, `${kind}.log`), 'a', 0o600) : null;
140
+ const child = spawn(command, args, { cwd: root, env, windowsHide: true, detached: background, stdio: log === null ? 'inherit' : ['ignore', log, log] });
141
+ if (log !== null) closeSync(log);
142
+ children.push(child);
143
+ child.on('error', () => {});
144
+ return child;
145
+ };
146
+ try {
147
+ const api = start(apiExecutable, ['serve'], 'api');
148
+ const deadline = Date.now() + 30000;
149
+ while (true) {
150
+ if (api.exitCode !== null || api.pid === undefined) throw new Error('Go service exited before becoming ready');
151
+ try {
152
+ const response = await fetch(addresses.api + '/api/v1/ready', { signal: AbortSignal.timeout(1000) });
153
+ if (response.ok) break;
154
+ } catch { /* the Go service is starting */ }
155
+ if (Date.now() >= deadline) throw new Error('Go service did not become ready; inspect .arcbase/runtime/api.log');
156
+ await pause(100);
157
+ }
158
+ await pause(100);
159
+ if (api.exitCode !== null) throw new Error('Go service exited during startup');
160
+ const apiIdentity = identity(api.pid);
161
+ if (!apiIdentity?.executable || !samePath(apiIdentity.executable, realpathSync(apiExecutable))) throw new Error('Cannot establish Go process ownership');
162
+ processes.push({ kind: 'api', pid: api.pid, identity: apiIdentity });
163
+ if (vite) {
164
+ const frontend = start(process.execPath, [vite, '--config', resolve(root, 'web/admin/vite.config.ts')], 'frontend');
165
+ const deadline = Date.now() + 30000;
166
+ while (true) {
167
+ if (frontend.exitCode !== null || frontend.pid === undefined) throw new Error('Vite exited before becoming ready');
168
+ try { if ((await fetch(addresses.development, { signal: AbortSignal.timeout(1000) })).ok) break; } catch { /* Vite is starting */ }
169
+ if (Date.now() >= deadline) throw new Error('Vite did not become ready');
170
+ await pause(100);
171
+ }
172
+ processes.push({ kind: 'frontend', pid: frontend.pid, identity: identity(frontend.pid) });
173
+ }
174
+ writeFileSync(file, JSON.stringify({ format: 1, project: root, processes }, null, 2) + '\n', { mode: 0o600 });
175
+ if (background) children.forEach(child => child.unref());
176
+ if (!quiet) loginInfo(true);
177
+ return children;
178
+ } catch (error) {
179
+ await Promise.all(children.map(child => new Promise((done, reject) => {
180
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) return done();
181
+ const timer = setTimeout(() => reject(new Error('Failed startup process did not stop')), 15000);
182
+ child.once('exit', () => { clearTimeout(timer); done(); });
183
+ child.kill();
184
+ })));
185
+ throw error;
186
+ }
187
+ }
188
+ async function terminate(records) {
189
+ for (const record of records.toReversed()) {
190
+ if (verified(record)) process.kill(record.pid, 'SIGTERM');
191
+ const deadline = Date.now() + 15000;
192
+ while (verified(record)) {
193
+ if (Date.now() >= deadline) throw new Error('Managed process did not stop; no other process was terminated');
194
+ await pause(100);
195
+ }
196
+ }
197
+ }
198
+ export async function stop() {
199
+ await terminate(current());
200
+ if (existsSync(file)) unlinkSync(file);
201
+ }
202
+ export function stopping() {
203
+ if (!existsSync(file)) return true;
204
+ try { return ['stop', 'restart'].includes(JSON.parse(readFileSync(lock, 'utf8')).command); }
205
+ catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return false; throw error; }
206
+ }
207
+ // Caller holds the lifecycle lock. A successful build is ready before we stop
208
+ // the API; Vite stays alive. A failed startup restores the preceding binary.
209
+ export async function reloadAPI(apiExecutable, expectedPID) {
210
+ const records = current(), previous = records.find(record => record.kind === 'api');
211
+ if (!previous || previous.pid !== expectedPID) return null;
212
+ const retained = records.filter(record => record.kind === 'frontend');
213
+ await terminate([previous]);
214
+ writeFileSync(file, JSON.stringify({ format: 1, project: root, processes: retained }, null, 2) + '\n', { mode: 0o600 });
215
+ try { return { api: (await launch({ apiExecutable, retained, quiet: true }))[0] }; }
216
+ catch (error) {
217
+ return { api: (await launch({ apiExecutable: previous.identity.executable, retained, quiet: true }))[0], error };
218
+ }
219
+ }
220
+ export async function foreground(children) {
221
+ let closing = false;
222
+ const cleanup = async () => {
223
+ if (closing) return;
224
+ closing = true;
225
+ await control(stop, { wait: 35000, command: 'cleanup' });
226
+ };
227
+ const signal = () => { void cleanup().catch(error => { console.error(error.message); process.exitCode = 1; }); };
228
+ process.once('SIGINT', signal);
229
+ process.once('SIGTERM', signal);
230
+ try {
231
+ const exit = await Promise.race(children.map(child => new Promise(done => {
232
+ if (child.exitCode !== null) done({ code: child.exitCode });
233
+ else child.once('exit', code => done({ code }));
234
+ })));
235
+ let externalStop = false;
236
+ try { externalStop = ['stop', 'restart'].includes(JSON.parse(readFileSync(lock, 'utf8')).command); }
237
+ catch (error) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; }
238
+ const requestedStop = closing || externalStop || !existsSync(file);
239
+ await cleanup();
240
+ if (!requestedStop && exit.code !== 0) process.exitCode = exit.code ?? 1;
241
+ } finally {
242
+ process.removeListener('SIGINT', signal);
243
+ process.removeListener('SIGTERM', signal);
244
+ }
245
+ }
@@ -0,0 +1,115 @@
1
+ import { readdir, readFile, unlink } from "node:fs/promises";
2
+ import { resolve, relative } from "node:path";
3
+ import { TextDecoder, TextEncoder } from "node:util";
4
+ // OpenObserve limits each map to 5 MiB. Keep original mappings and application
5
+ // source; omit vendor source bodies in oversized maps rather than losing frames.
6
+ export function prepareSourceMap(bytes, name) {
7
+ if (bytes.byteLength <= 5 * 1024 * 1024) return bytes;
8
+ const map = JSON.parse(new TextDecoder().decode(bytes));
9
+ if (Array.isArray(map.sourcesContent))
10
+ map.sourcesContent = map.sourcesContent.map((source, index) =>
11
+ /node_modules\//.test(map.sources[index]?.replaceAll("\\", "/")) &&
12
+ !/node_modules\/@fudanda\//.test(
13
+ map.sources[index]?.replaceAll("\\", "/"),
14
+ )
15
+ ? null
16
+ : source,
17
+ );
18
+ const compact = new TextEncoder().encode(JSON.stringify(map));
19
+ if (compact.byteLength > 5 * 1024 * 1024)
20
+ throw new Error(
21
+ "OpenObserve source map exceeds 5 MiB after vendor source removal: " +
22
+ name +
23
+ "; split this build chunk",
24
+ );
25
+ return compact;
26
+ }
27
+ export async function openObserveBuildPlugins(env, output) {
28
+ if (!env.OPENOBSERVE_AUTH) return [];
29
+ for (const key of [
30
+ "OPENOBSERVE_URL",
31
+ "OPENOBSERVE_SOURCEMAP_SERVICE",
32
+ "OPENOBSERVE_ENVIRONMENT",
33
+ "OPENOBSERVE_VERSION",
34
+ ])
35
+ if (!env[key]) throw new Error(key + " is required for source map upload");
36
+ const url = new URL(env.OPENOBSERVE_URL);
37
+ if (
38
+ !["http:", "https:"].includes(url.protocol) ||
39
+ url.username ||
40
+ url.password ||
41
+ url.search ||
42
+ url.hash
43
+ )
44
+ throw new Error("Invalid OpenObserve build URL");
45
+ const organization = env.OPENOBSERVE_ORGANIZATION || "default";
46
+ const services = env.OPENOBSERVE_SOURCEMAP_SERVICE.split(",")
47
+ .map((v) => v.trim())
48
+ .filter(Boolean);
49
+ if (!services.length) throw new Error("At least one source map service is required");
50
+ return [
51
+ {
52
+ name: "arcbase-openobserve-source-maps",
53
+ async closeBundle() {
54
+ const paths = [];
55
+ async function visit(folder) {
56
+ for (const entry of await readdir(folder, { withFileTypes: true })) {
57
+ const path = resolve(folder, entry.name);
58
+ if (entry.isDirectory()) await visit(path);
59
+ else if (entry.isFile() && entry.name.endsWith(".map"))
60
+ paths.push(path);
61
+ }
62
+ }
63
+ await visit(output);
64
+ if (!paths.length)
65
+ throw new Error("No source maps generated for this release");
66
+ const { zipSync } = await import("fflate");
67
+ const files = {};
68
+ for (const path of paths) {
69
+ const name = relative(output, path).replaceAll("\\", "/");
70
+ files[name] = prepareSourceMap(
71
+ new Uint8Array(await readFile(path)),
72
+ name,
73
+ );
74
+ }
75
+ const archive = zipSync(files);
76
+ if (archive.byteLength > 100 * 1024 * 1024) throw new Error("OpenObserve source map ZIP exceeds 100 MiB; split this build");
77
+ for (const service of services) {
78
+ const form = new FormData();
79
+ form.append(
80
+ "file",
81
+ new Blob([archive], { type: "application/zip" }),
82
+ "sourcemaps.zip",
83
+ );
84
+ form.append("service", service);
85
+ form.append("env", env.OPENOBSERVE_ENVIRONMENT);
86
+ form.append("version", env.OPENOBSERVE_VERSION);
87
+ const response = await fetch(
88
+ new URL(
89
+ "/api/" + encodeURIComponent(organization) + "/sourcemaps",
90
+ url,
91
+ ),
92
+ {
93
+ method: "POST",
94
+ headers: { Authorization: env.OPENOBSERVE_AUTH },
95
+ body: form,
96
+ redirect: "error",
97
+ signal: AbortSignal.timeout(60000),
98
+ },
99
+ );
100
+ if (!response.ok) {
101
+ await response.body?.cancel();
102
+ throw new Error(
103
+ "OpenObserve source map upload failed (" + response.status + ")",
104
+ );
105
+ }
106
+ await response.body?.cancel();
107
+ }
108
+ for (const path of paths) await unlink(path);
109
+ console.log(
110
+ "OpenObserve source maps uploaded; public map files removed.",
111
+ );
112
+ },
113
+ },
114
+ ];
115
+ }