-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathformat.ts
More file actions
446 lines (401 loc) · 16.8 KB
/
Copy pathformat.ts
File metadata and controls
446 lines (401 loc) · 16.8 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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import chalk from 'chalk';
import type { ZodError } from 'zod';
// ─── Constants ──────────────────────────────────────────────────────
export const CLI_NAME = 'objectstack';
export const CLI_ALIAS = 'os';
// ─── Banner ─────────────────────────────────────────────────────────
export function printBanner(version: string) {
console.log('');
console.log(chalk.bold.cyan(' ╔═══════════════════════════════════╗'));
console.log(chalk.bold.cyan(' ║') + chalk.bold(' ◆ ObjectStack CLI ') + chalk.dim(`v${version}`) + chalk.bold.cyan(' ║'));
console.log(chalk.bold.cyan(' ╚═══════════════════════════════════╝'));
console.log('');
}
// ─── Section Header ─────────────────────────────────────────────────
export function printHeader(title: string) {
console.log(chalk.bold(`\n◆ ${title}`));
console.log(chalk.dim('─'.repeat(40)));
}
// ─── Key-Value Line ─────────────────────────────────────────────────
export function printKV(key: string, value: string | number, icon?: string) {
const prefix = icon ? `${icon} ` : ' ';
console.log(`${prefix}${chalk.dim(key + ':')} ${chalk.white(String(value))}`);
}
// ─── Status Line ────────────────────────────────────────────────────
export function printSuccess(msg: string) {
console.log(chalk.green(` ✓ ${msg}`));
}
export function printWarning(msg: string) {
console.log(chalk.yellow(` ⚠ ${msg}`));
}
export function printError(msg: string) {
console.log(chalk.red(` ✗ ${msg}`));
}
export function printInfo(msg: string) {
console.log(chalk.blue(` ℹ ${msg}`));
}
export function printStep(msg: string) {
console.log(chalk.yellow(` → ${msg}`));
}
// ─── Timer ──────────────────────────────────────────────────────────
export function createTimer() {
const start = Date.now();
return {
elapsed: () => Date.now() - start,
display: () => `${Date.now() - start}ms`,
};
}
// ─── Zod Error Formatting ───────────────────────────────────────────
export function formatZodErrors(error: ZodError) {
const issues = error.issues || (error as any).errors || [];
if (issues.length === 0) {
console.log(chalk.red(' Unknown validation error'));
return;
}
// Group by top-level path
const grouped = new Map<string, typeof issues>();
for (const issue of issues) {
const topPath = (issue as any).path?.[0] || '_root';
if (!grouped.has(String(topPath))) {
grouped.set(String(topPath), []);
}
grouped.get(String(topPath))!.push(issue);
}
for (const [section, sectionIssues] of grouped) {
console.log(chalk.bold.red(`\n ${section}:`));
for (const issue of sectionIssues) {
const path = (issue as any).path?.join('.') || '';
const code = (issue as any).code || '';
const msg = (issue as any).message || '';
console.log(chalk.red(` ✗ ${path}`));
console.log(chalk.dim(` ${code}: ${msg}`));
// Show expected/received for type errors
if ((issue as any).expected) {
console.log(chalk.dim(` expected: ${chalk.green((issue as any).expected)}`));
}
if ((issue as any).received) {
console.log(chalk.dim(` received: ${chalk.red((issue as any).received)}`));
}
}
}
console.log('');
console.log(chalk.dim(` ${issues.length} validation error(s) total`));
}
// ─── Metadata Statistics ────────────────────────────────────────────
export interface MetadataStats {
objects: number;
objectExtensions: number;
fields: number;
views: number;
pages: number;
apps: number;
dashboards: number;
reports: number;
actions: number;
flows: number;
workflows: number;
agents: number;
apis: number;
positions: number;
permissions: number;
themes: number;
datasources: number;
translations: number;
plugins: number;
devPlugins: number;
}
export function collectMetadataStats(config: any): MetadataStats {
const count = (val: any) => {
if (Array.isArray(val)) return val.length;
if (val && typeof val === 'object') return Object.keys(val).length;
return 0;
};
// Count total fields across all objects
let fields = 0;
const objects = Array.isArray(config.objects) ? config.objects :
(config.objects && typeof config.objects === 'object' ? Object.values(config.objects) : []);
for (const obj of objects as any[]) {
if (obj.fields && typeof obj.fields === 'object') {
fields += Object.keys(obj.fields).length;
}
}
return {
objects: count(config.objects),
objectExtensions: count(config.objectExtensions),
fields,
views: count(config.views),
pages: count(config.pages),
apps: count(config.apps),
dashboards: count(config.dashboards),
reports: count(config.reports),
actions: count(config.actions),
flows: count(config.flows),
workflows: count(config.workflows),
agents: count(config.agents),
apis: count(config.apis),
positions: count(config.positions),
permissions: count(config.permissions),
themes: count(config.themes),
datasources: count(config.datasources),
translations: count(config.translations),
plugins: count(config.plugins),
devPlugins: count(config.devPlugins),
};
}
// ─── Server Ready Banner ────────────────────────────────────────────
export interface ServerReadyOptions {
port: number;
configFile: string;
isDev: boolean;
pluginCount: number;
pluginNames?: string[];
uiEnabled?: boolean;
consolePath?: string;
/** Resolved storage driver display name (e.g. "MongoDBDriver", "SqlDriver(pg)"). */
driverLabel?: string;
/** Resolved DB URL with credentials redacted. */
databaseUrl?: string;
/** Whether the SecurityPlugin was wired in multi-tenant mode (default true). */
multiTenant?: boolean;
/**
* Credentials of the dev admin seeded on an empty DB this boot (dev only).
* When present, the banner surfaces them so backend debugging never has to
* guess the login. Absent when nothing was seeded.
*/
seededAdmin?: { email: string; password: string };
/**
* Automation wiring summary (2026-07-17 third-party eval). The boot-quiet
* stdout window swallows every info/warn the automation engine logs while
* binding flows to triggers, so the banner is the ONE reliable place a
* developer can see whether their record-change / schedule flows actually
* armed. Collected from the live engine after runtime.start().
*/
automation?: AutomationReadySummary;
/**
* Per-source seed outcomes for this boot (#3415/#3430). Seeds run inside the
* boot-quiet stdout window and SeedLoader's own logs sit under the default
* warn level, so without this line a fixture can silently lose most of its
* rows (the showcase shipped 1 of 5 projects for weeks) and a marketplace
* package can rehydrate onto a fresh DB with zero rows. Each config app and
* each rehydrated/healed marketplace package contributes one entry;
* rejections and empty installs are loud, a clean seed prints one dim line.
*/
seeds?: SeedSourceSummary[];
/**
* Whether the MCP server surface (`/api/v1/mcp`) is on (#3167). Default-on
* core capability, but nothing in the dev loop surfaces it — an AI client
* (Claude Code, Cursor, …) can operate the running app the instant a
* developer knows the endpoint is there. The banner is where they look, so
* print the URL + the SKILL.md pointer when it's live.
*/
mcpEnabled?: boolean;
}
export interface SeedSourceSummary {
/** Display label — the config app id / marketplace manifest id that seeded. */
source: string;
/** True when the source is a marketplace package (vs a config-declared app). */
marketplace?: boolean;
inserted: number;
updated: number;
skipped: number;
/** Records dropped by validation/reference errors — the silent-loss case. */
rejected: number;
/**
* Rows were (re)seeded onto a fresh/empty database during rehydrate — the
* "swap the DB out from under an installed package" self-heal (#3430).
*/
healed?: boolean;
/**
* A marketplace package rehydrated with seed datasets declared, yet every
* seeded object came up empty — the "installed but 0 rows" case (#3430).
*/
emptyInstall?: boolean;
}
export interface AutomationReadySummary {
/** Whether the automation service is registered at all. */
enabled: boolean;
/** Flows declared in the stack config (used when the engine is absent). */
declaredFlowCount: number;
/** Flows registered in the engine (0 when `enabled` is false). */
flowCount: number;
/** Flows bound to a trigger. */
boundCount: number;
/** Registered trigger types (record_change, schedule, api, …). */
triggerTypes: string[];
/** Enabled flows that declare a trigger but are NOT bound, with the fix. */
unbound: Array<{ flowName: string; triggerType: string; reason: string }>;
/** Bound record-change flows whose target object is not registered (dead binding). */
unknownObject: Array<{ flowName: string; object: string }>;
/** Enabled flows whose persisted status is 'draft' (they still fire). */
draftCount: number;
}
export function printServerReady(opts: ServerReadyOptions) {
const base = `http://localhost:${opts.port}`;
console.log('');
console.log(chalk.bold.green(' ✓ Server is ready'));
console.log('');
console.log(chalk.cyan(' ➜') + chalk.bold(' API: ') + chalk.cyan(base + '/'));
if (opts.uiEnabled && opts.consolePath) {
console.log(chalk.cyan(' ➜') + chalk.bold(' Console: ') + chalk.cyan(base + opts.consolePath + '/'));
}
if (opts.mcpEnabled) {
console.log(chalk.cyan(' ➜') + chalk.bold(' MCP: ') + chalk.cyan(base + '/api/v1/mcp'));
console.log(chalk.dim(` connect an AI client (Claude Code, Cursor, …) · skill: ${base}/api/v1/mcp/skill`));
}
if (opts.seededAdmin) {
console.log('');
console.log(
chalk.green(' 🔑') + chalk.bold(' Dev admin: ') +
chalk.bold.green(`${opts.seededAdmin.email} / ${opts.seededAdmin.password}`),
);
console.log(chalk.dim(' seeded on empty DB · dev only — do not use in production'));
}
console.log('');
console.log(chalk.dim(` Config: ${opts.configFile}`));
console.log(chalk.dim(` Mode: ${opts.isDev ? 'development' : 'production'}`));
if (opts.driverLabel) {
const dbInfo = opts.databaseUrl ? `${opts.driverLabel} ${chalk.dim('→')} ${opts.databaseUrl}` : opts.driverLabel;
console.log(chalk.dim(` Driver: ${dbInfo}`));
}
if (opts.multiTenant !== undefined) {
console.log(chalk.dim(` Tenancy: ${opts.multiTenant ? 'multi-tenant' : 'single-tenant'}`));
}
console.log(chalk.dim(` Plugins: ${opts.pluginCount} loaded`));
if (opts.pluginNames && opts.pluginNames.length > 0) {
console.log(chalk.dim(` ${opts.pluginNames.join(', ')}`));
}
if (opts.automation) printAutomationSummary(opts.automation);
if (opts.seeds) printSeedSummary(opts.seeds);
console.log('');
console.log(chalk.dim(' Press Ctrl+C to stop'));
console.log('');
}
/**
* One-glance answer to "did my flows actually arm?" — the question the
* boot-quiet stdout window otherwise makes unanswerable (the engine's own
* bind/registration logs are swallowed during startup).
*/
function printAutomationSummary(a: AutomationReadySummary) {
if (!a.enabled) {
if (a.declaredFlowCount > 0) {
console.log(
chalk.yellow(
` ⚠ Flows: ${a.declaredFlowCount} flow(s) declared but the automation engine is not enabled — ` +
`they will never run. Add requires: ['automation', 'triggers'] to objectstack.config.ts`,
),
);
}
return;
}
if (a.flowCount === 0) return;
const parts = [`${a.flowCount} flow(s)`, `${a.boundCount} bound to triggers`];
if (a.triggerTypes.length > 0) parts.push(`(${a.triggerTypes.join(', ')})`);
if (a.draftCount > 0) parts.push(`· ${a.draftCount} draft`);
console.log(chalk.dim(` Flows: ${parts.join(' ')}`));
for (const u of a.unbound) {
console.log(
chalk.yellow(` ⚠ flow '${u.flowName}' declares a '${u.triggerType}' trigger but is NOT bound — ${u.reason}`),
);
}
for (const u of a.unknownObject) {
console.log(
chalk.yellow(
` ⚠ flow '${u.flowName}' targets unknown object '${u.object}' — bound, but it will never fire ` +
`(object names match exactly; check the start node's config.objectName)`,
),
);
}
}
/**
* One-glance answer to "did my seed rows actually land — from every source?"
* (#3415/#3430). Follows printAutomationSummary's contract: quiet when
* everything is fine, yellow with the reason when rows were dropped or a
* marketplace package came up empty. Both config apps (AppPlugin) and
* rehydrated/healed marketplace packages contribute, e.g.
*
* Seeds: showcase 162 rows · hotcrm(marketplace) 157 ok / 5 errors ⚠
*
* A fixture contradiction (seed status vs a state_machine's initialStates), a
* row-level lookup failure, or a marketplace package that healed onto a fresh
* DB with zero rows must never pass silently again.
*/
function printSeedSummary(sources: SeedSourceSummary[]) {
const shown = sources.filter((s) => {
// Empty installs and rejections are ALWAYS shown (they're the whole point);
// a source that touched no rows and had no problem is noise — drop it.
if (s.emptyInstall || s.rejected > 0) return true;
return s.inserted + s.updated + s.skipped > 0;
});
if (shown.length === 0) return;
const anyProblem = shown.some((s) => s.rejected > 0 || s.emptyInstall);
const fragment = (s: SeedSourceSummary): string => {
const label = s.marketplace ? `${s.source}(marketplace)` : s.source;
if (s.emptyInstall) return `${label} installed but 0 rows ⚠`;
const ok = s.inserted + s.updated + s.skipped;
if (s.rejected > 0) {
return `${label} ${ok} ok / ${s.rejected} error${s.rejected === 1 ? '' : 's'} ⚠`;
}
return `${label} ${ok} rows${s.healed ? ' (healed on fresh db)' : ''}`;
};
const line = shown.map(fragment).join(' · ');
if (anyProblem) {
console.log(chalk.yellow(` ⚠ Seeds: ${line}`));
console.log(chalk.dim(' run with OS_LOG_LEVEL=info to see each dropped record'));
return;
}
console.log(chalk.dim(` Seeds: ${line}`));
}
export function printMetadataStats(stats: MetadataStats) {
const sections: Array<{ label: string; items: Array<[string, number]> }> = [
{
label: 'Data',
items: [
['Objects', stats.objects],
['Fields', stats.fields],
['Extensions', stats.objectExtensions],
['Datasources', stats.datasources],
],
},
{
label: 'UI',
items: [
['Apps', stats.apps],
['Views', stats.views],
['Pages', stats.pages],
['Dashboards', stats.dashboards],
['Reports', stats.reports],
['Actions', stats.actions],
['Themes', stats.themes],
],
},
{
label: 'Logic',
items: [
['Flows', stats.flows],
['Workflows', stats.workflows],
['Agents', stats.agents],
['APIs', stats.apis],
],
},
{
label: 'Security',
items: [
['Positions', stats.positions],
['Permissions', stats.permissions],
],
},
];
for (const section of sections) {
const nonZero = section.items.filter(([, v]) => v > 0);
if (nonZero.length === 0) continue;
const line = nonZero.map(([k, v]) => `${chalk.white(v)} ${chalk.dim(k)}`).join(' ');
console.log(` ${chalk.bold(section.label + ':')} ${line}`);
}
if (stats.plugins > 0 || stats.devPlugins > 0) {
const parts: string[] = [];
if (stats.plugins > 0) parts.push(`${stats.plugins} plugins`);
if (stats.devPlugins > 0) parts.push(`${stats.devPlugins} devPlugins`);
console.log(` ${chalk.bold('Runtime:')} ${chalk.dim(parts.join(', '))}`);
}
}