-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserve.ts
More file actions
411 lines (363 loc) · 15.7 KB
/
serve.ts
File metadata and controls
411 lines (363 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Args, Command, Flags } from '@oclif/core';
import path from 'path';
import fs from 'fs';
import net from 'net';
import chalk from 'chalk';
import { bundleRequire } from 'bundle-require';
import { loadConfig } from '../utils/config.js';
import { isHostConfig } from '../utils/plugin-detection.js';
import {
printHeader,
printKV,
printSuccess,
printError,
printStep,
printInfo,
printServerReady,
} from '../utils/format.js';
import {
STUDIO_PATH,
resolveStudioPath,
hasStudioDist,
createStudioStaticPlugin,
} from '../utils/studio.js';
import dotenvFlow from 'dotenv-flow';
// Helper to find available port
const getAvailablePort = async (startPort: number): Promise<number> => {
const isPortAvailable = (port: number): Promise<boolean> => {
return new Promise((resolve) => {
const server = net.createServer();
server.once('error', (err: any) => {
resolve(false);
});
server.once('listening', () => {
server.close(() => resolve(true));
});
server.listen(port);
});
};
let port = startPort;
while (!(await isPortAvailable(port))) {
port++;
if (port > startPort + 100) {
throw new Error(`Could not find an available port starting from ${startPort}`);
}
}
return port;
};
export default class Serve extends Command {
static override description = 'Start ObjectStack server with plugins from configuration';
static override args = {
config: Args.string({ description: 'Configuration file path', required: false, default: 'objectstack.config.ts' }),
};
static override flags = {
port: Flags.string({ char: 'p', description: 'Server port', default: '3000' }),
dev: Flags.boolean({ description: 'Run in development mode (load devPlugins)' }),
ui: Flags.boolean({ description: 'Enable Studio UI at /_studio/ (default: true in dev mode)' }),
server: Flags.boolean({ description: 'Start HTTP server plugin', default: true, allowNo: true }),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(Serve);
let port = parseInt(flags.port);
try {
const availablePort = await getAvailablePort(port);
if (availablePort !== port) {
port = availablePort;
}
} catch (e) {
// Ignore error and try with original port
}
// Load .env files following Vite/Next.js convention
const mode = flags.dev ? 'development'
: (process.env.NODE_ENV === 'test' ? 'test'
: (process.env.NODE_ENV || 'production'));
dotenvFlow.config({ node_env: mode, silent: true });
const isDev = flags.dev || process.env.NODE_ENV === 'development';
const absolutePath = path.resolve(process.cwd(), args.config!);
const relativeConfig = path.relative(process.cwd(), absolutePath);
if (!fs.existsSync(absolutePath)) {
printError(`Configuration file not found: ${absolutePath}`);
console.log(chalk.dim(' Hint: Run `objectstack init` to create a new project'));
this.exit(1);
}
// Quiet loading — only show a single spinner line
console.log('');
console.log(chalk.dim(` Loading ${relativeConfig}...`));
// Track loaded plugins for summary
const loadedPlugins: string[] = [];
const shortPluginName = (raw: string) => {
// Map verbose internal IDs to short display names
if (raw.includes('objectql')) return 'ObjectQL';
if (raw.includes('driver') && raw.includes('memory')) return 'MemoryDriver';
if (raw.startsWith('plugin.app.')) return raw.replace('plugin.app.', '').split('.').pop() || raw;
if (raw.includes('hono')) return 'HonoServer';
return raw;
};
const trackPlugin = (name: string) => { loadedPlugins.push(shortPluginName(name)); };
// Save original console/stdout methods — we'll suppress noise during boot
const originalConsoleLog = console.log;
const originalConsoleDebug = console.debug;
const origStdoutWrite = process.stdout.write.bind(process.stdout);
let bootQuiet = false;
const restoreOutput = () => {
bootQuiet = false;
process.stdout.write = origStdoutWrite;
console.log = originalConsoleLog;
console.debug = originalConsoleDebug;
};
const portShifted = parseInt(flags.port) !== port;
try {
// ── Suppress ALL runtime noise during boot ────────────────────
// Multiple sources write to stdout during startup:
// • Pino-pretty (direct process.stdout.write)
// • ObjectLogger browser fallback (console.log)
// • SchemaRegistry (console.log)
// We capture stdout entirely, then restore after runtime.start().
bootQuiet = true;
process.stdout.write = (chunk: any, ...rest: any[]) => {
if (bootQuiet) return true; // swallow
return (origStdoutWrite as any)(chunk, ...rest);
};
console.log = (...args: any[]) => { if (!bootQuiet) originalConsoleLog(...args); };
console.debug = (...args: any[]) => { if (!bootQuiet) originalConsoleDebug(...args); };
// Load configuration
const { mod } = await bundleRequire({
filepath: absolutePath,
});
const config = mod.default || mod;
if (!config) {
throw new Error(`No default export found in ${args.config}`);
}
// Import ObjectStack runtime
const { Runtime } = await import('@objectstack/runtime');
// Set kernel logger to 'silent' — the CLI manages its own output
const loggerConfig = { level: 'silent' as const };
const runtime = new Runtime({
kernel: {
logger: loggerConfig
}
});
const kernel = runtime.getKernel();
// Load plugins from configuration
let plugins = config.plugins || [];
// Merge devPlugins if in dev mode
if (flags.dev && config.devPlugins) {
plugins = [...plugins, ...config.devPlugins];
}
// 1. Auto-register ObjectQL Plugin if objects define but plugins missing
const hasObjectQL = plugins.some((p: any) => p.name?.includes('objectql') || p.constructor?.name?.includes('ObjectQL'));
if (config.objects && !hasObjectQL) {
try {
const { ObjectQLPlugin } = await import('@objectstack/objectql');
await kernel.use(new ObjectQLPlugin());
trackPlugin('ObjectQL');
} catch (e: any) {
// silent
}
}
// 2. Auto-register Memory Driver if in Dev and no driver configured
const hasDriver = plugins.some((p: any) => p.name?.includes('driver') || p.constructor?.name?.includes('Driver'));
if (isDev && !hasDriver && config.objects) {
try {
const { DriverPlugin } = await import('@objectstack/runtime');
const { InMemoryDriver } = await import('@objectstack/driver-memory');
await kernel.use(new DriverPlugin(new InMemoryDriver()));
trackPlugin('MemoryDriver');
} catch (e: any) {
// silent
}
}
// 3. Auto-register AppPlugin if config contains app definitions
// Skip if config is a host/aggregator config that already contains
// instantiated plugins — wrapping it would cause duplicate registration
// and startup failures (e.g. plugin.app.dev-workspace).
if (!isHostConfig(config) && (config.objects || config.manifest || config.apps)) {
try {
const { AppPlugin } = await import('@objectstack/runtime');
await kernel.use(new AppPlugin(config));
trackPlugin('App');
} catch (e: any) {
// silent
}
}
// 3b. Auto-register I18nServicePlugin if config contains translations/i18n
// This ensures i18n REST routes work out of the box without manual plugin registration.
const hasI18nPlugin = plugins.some(
(p: any) => p.name === 'com.objectstack.service.i18n'
|| p.constructor?.name === 'I18nServicePlugin'
);
const configHasTranslations = (
(Array.isArray(config.translations) && config.translations.length > 0)
|| config.i18n
|| (config.manifest && (
(Array.isArray(config.manifest.translations) && config.manifest.translations.length > 0)
|| config.manifest.i18n
))
);
if (!hasI18nPlugin && configHasTranslations) {
try {
// Dynamic import with variable to prevent tsc from resolving the optional package
const i18nPkg = '@objectstack/service-i18n';
const { I18nServicePlugin } = await import(/* webpackIgnore: true */ i18nPkg);
const i18nCfg = config.i18n || config.manifest?.i18n || {};
await kernel.use(new I18nServicePlugin({
defaultLocale: i18nCfg.defaultLocale,
fallbackLocale: i18nCfg.fallbackLocale || i18nCfg.defaultLocale || 'en',
}));
trackPlugin('I18nService');
} catch {
// @objectstack/service-i18n not installed — kernel memory fallback will handle i18n
}
} else if (!hasI18nPlugin && !configHasTranslations) {
// No translations and no explicit i18n plugin — this is fine, kernel fallback works
}
// Add HTTP server plugin BEFORE config plugins so that the
// http-server service is available for any plugin that needs it
// during init/start (e.g. AuthPlugin).
// Skip if config already contains a HonoServerPlugin to avoid
// duplicate registration.
const configHasHonoServer = plugins.some(
(p: any) => p.name === 'com.objectstack.server.hono' || p.constructor?.name === 'HonoServerPlugin'
);
if (flags.server && !configHasHonoServer) {
try {
const { HonoServerPlugin } = await import('@objectstack/plugin-hono-server');
const serverPlugin = new HonoServerPlugin({ port });
await kernel.use(serverPlugin);
trackPlugin('HonoServer');
} catch (e: any) {
console.warn(chalk.yellow(` ⚠ HTTP server plugin not available: ${e.message}`));
}
}
// 5. Auto-register SetupPlugin BEFORE config plugins so that other
// plugins (e.g. AuthPlugin) can call setupNav.contribute() during init.
const hasSetupPlugin = plugins.some(
(p: any) => p.name === 'com.objectstack.setup' || p.constructor?.name === 'SetupPlugin'
);
if (!hasSetupPlugin) {
try {
const setupPkg = '@objectstack/plugin-setup';
const { SetupPlugin } = await import(/* webpackIgnore: true */ setupPkg);
await kernel.use(new SetupPlugin());
trackPlugin('Setup');
} catch {
// @objectstack/plugin-setup not installed — setup app unavailable
}
}
if (plugins.length > 0) {
for (const plugin of plugins) {
try {
let pluginToLoad = plugin;
// Resolve string references (package names)
if (typeof plugin === 'string') {
try {
const imported = await import(plugin);
pluginToLoad = imported.default || imported;
} catch (importError: any) {
throw new Error(`Failed to import plugin '${plugin}': ${importError.message}`);
}
}
// Wrap raw config objects (no init/start) into AppPlugin
// This handles plugins defined as plain { name, objects, ... } bundles
if (pluginToLoad && typeof pluginToLoad === 'object' && !pluginToLoad.init) {
try {
const { AppPlugin } = await import('@objectstack/runtime');
pluginToLoad = new AppPlugin(pluginToLoad);
} catch (e: any) {
// Fall through to kernel.use which will report the error
}
}
await kernel.use(pluginToLoad);
const pluginName = plugin.name || plugin.constructor?.name || 'unnamed';
trackPlugin(pluginName);
} catch (e: any) {
console.error(chalk.red(` ✗ Failed to load plugin: ${e.message}`));
}
}
}
// Register REST API and Dispatcher plugins (consume http.server + protocol services)
if (flags.server) {
try {
const { createRestApiPlugin } = await import('@objectstack/rest');
await kernel.use(createRestApiPlugin());
trackPlugin('RestAPI');
} catch (e: any) {
// @objectstack/rest is optional
}
// Register Dispatcher plugin (auth, graphql, analytics, packages, hub, storage, automation)
try {
const { createDispatcherPlugin } = await import('@objectstack/runtime');
await kernel.use(createDispatcherPlugin());
trackPlugin('Dispatcher');
} catch (e: any) {
// optional
}
}
// 4. Auto-register AIServicePlugin if not already loaded by config plugins.
// Registered AFTER Dispatcher so that the ai:routes hook listener is
// already in place when AIServicePlugin.start() fires the hook.
const hasAIPlugin = plugins.some(
(p: any) => p.name === 'com.objectstack.service-ai'
|| p.constructor?.name === 'AIServicePlugin'
);
if (!hasAIPlugin) {
try {
const aiPkg = '@objectstack/service-ai';
const { AIServicePlugin } = await import(/* webpackIgnore: true */ aiPkg);
// AIServicePlugin will auto-detect LLM provider from environment variables
// (AI_GATEWAY_MODEL, OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY)
// No need to manually construct the adapter here.
await kernel.use(new AIServicePlugin());
trackPlugin('AIService');
} catch {
// @objectstack/service-ai not installed — AI features unavailable
}
}
// ── Studio UI ─────────────────────────────────────────────────
// In dev mode, Studio UI is enabled by default (use --no-ui to disable).
// Always serves the pre-built dist/ — no Vite dev server, no extra port.
const enableUI = flags.ui || isDev;
if (enableUI) {
const studioPath = resolveStudioPath();
if (!studioPath) {
console.warn(chalk.yellow(` ⚠ @objectstack/studio not found — skipping UI`));
} else if (hasStudioDist(studioPath)) {
const distPath = path.join(studioPath, 'dist');
await kernel.use(createStudioStaticPlugin(distPath, { isDev }));
trackPlugin('StudioUI');
} else {
console.warn(chalk.yellow(` ⚠ Studio dist not found — run "pnpm --filter @objectstack/studio build" first`));
}
}
// Boot the runtime
await runtime.start();
// Wait briefly for pino worker thread buffers to flush, then restore
await new Promise(r => setTimeout(r, 100));
restoreOutput();
// ── Clean startup summary ──────────────────────────────────────
printServerReady({
port,
configFile: relativeConfig,
isDev,
pluginCount: loadedPlugins.length,
pluginNames: loadedPlugins,
uiEnabled: enableUI,
studioPath: STUDIO_PATH,
});
// Keep process alive
process.on('SIGINT', async () => {
console.warn(chalk.yellow(`\n\n⏹ Stopping server...`));
await runtime.getKernel().shutdown();
console.log(chalk.green(`✅ Server stopped`));
process.exit(0);
});
} catch (error: any) {
restoreOutput();
console.log('');
printError(error.message || String(error));
if (process.env.DEBUG) console.error(chalk.dim(error.stack));
this.exit(1);
}
}
}