Skip to content

Commit 389fc18

Browse files
committed
fix(cli): a config boot carries the seed file bytes os build bundles
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012eJQ8dtut5bZsnhFE3XGHF
1 parent b62f351 commit 389fc18

2 files changed

Lines changed: 229 additions & 0 deletions

File tree

‎packages/cli/src/commands/serve.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2807,6 +2807,22 @@ export default class Serve extends Command {
28072807
}
28082808
}
28092809

2810+
// [#25779] Seed files, mirrored the same way. `os build` reads each file
2811+
// a seed record names with `seedFile(path)` into its dataset's `files`
2812+
// map (compile.ts step 4a), and the seed loader stores it from there.
2813+
// `defineStack(...)` carries the reference and not the bytes, so a config
2814+
// boot without this would refuse every such row that an artifact boot of
2815+
// the same project seeds. A path it cannot read is reported and left out;
2816+
// the loader then refuses that row, by name, and the boot goes on.
2817+
if (!useArtifactFallback) {
2818+
const { collectSeedFiles, placeSeedFiles } = await import('../utils/bundle-seed-files.js');
2819+
const seedFiles = collectSeedFiles(absolutePath, config as Record<string, unknown>);
2820+
placeSeedFiles(seedFiles);
2821+
for (const issue of seedFiles.issues) {
2822+
console.warn(chalk.yellow(` ⚠ ${issue.location}: ${issue.message}`));
2823+
}
2824+
}
2825+
28102826
// Boot-mode dispatch: this open-core CLI only supports `standalone`
28112827
// (and the artifact-fallback shortcut). Cloud / multi-environment
28122828
// boot modes live in a separate distribution and are no longer
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #25779 — a seed record fills a required file field with a file the package
5+
* ships, `seedFile(path)`, and the booted platform serves that file.
6+
*
7+
* The card's acceptance, measured through the doors a user reaches: `os serve
8+
* objectstack.config.ts --dev` on a project whose `clm_version.file` is
9+
* required, seeded with two versions naming the same fixture. Each seeded row
10+
* holds a file of its own, and following `GET /storage/files/:fileId` for it
11+
* answers the fixture's bytes, so the file is stored, committed and owned (an
12+
* uncommitted or unowned file is not served).
13+
*
14+
* ## Why it spawns the real command
15+
*
16+
* The collection and the loader are pinned in-process
17+
* (`src/utils/bundle-seed-files.test.ts`, metadata-protocol's
18+
* `seed-loader-seed-files.test.ts`, service-storage's
19+
* `field-file-service.test.ts`). Only a boot reaches the seams between them: the
20+
* config-load mirror in `serve.ts` (a config carries the reference, not the
21+
* bytes), the `field-files` service the storage plugin registers, and the
22+
* inline seed deferred to `kernel:bootstrapped`.
23+
*/
24+
25+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
26+
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
27+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
28+
import { tmpdir } from 'node:os';
29+
import { join } from 'node:path';
30+
import {
31+
CLI,
32+
E2E_SECRET_KEY,
33+
KERNEL_ASSIGNED_PORT,
34+
TSX,
35+
childEnv,
36+
probeThroughChild,
37+
readKernelAssignedPort,
38+
} from './helpers/serve-process.js';
39+
import { linkSpec } from './helpers/define-stack-fixture.js';
40+
41+
/** The banner's tail — every row above it has printed. */
42+
const READY = /Press Ctrl\+C to stop/;
43+
44+
const PDF = '%PDF-1.7 MARKER-25779 a seeded contract';
45+
46+
const CONFIG = `import { defineStack } from '@objectstack/spec';
47+
import { seedFile } from '@objectstack/spec/data';
48+
49+
export default defineStack({
50+
manifest: { id: 'com.example.clm', name: 'clm', version: '1.0.0', type: 'app', namespace: 'clm' },
51+
objects: [
52+
{
53+
name: 'clm_version',
54+
label: 'Version',
55+
sharingModel: 'private',
56+
fields: {
57+
code: { type: 'text', label: 'Code' },
58+
file: { type: 'file', label: 'File', required: true },
59+
},
60+
},
61+
],
62+
data: [
63+
{
64+
object: 'clm_version',
65+
externalId: 'code',
66+
records: [
67+
{ code: 'V1', file: seedFile('fixtures/nda.pdf') },
68+
{ code: 'V2', file: seedFile('fixtures/nda.pdf', { name: 'NDA v2.pdf' }) },
69+
],
70+
},
71+
],
72+
}, { strict: false });
73+
`;
74+
75+
let dir = '';
76+
let child: ChildProcessWithoutNullStreams | null = null;
77+
let output = '';
78+
79+
beforeAll(() => {
80+
dir = mkdtempSync(join(tmpdir(), 'os-seed-files-serve-'));
81+
mkdirSync(join(dir, 'fixtures'));
82+
writeFileSync(join(dir, 'fixtures', 'nda.pdf'), PDF);
83+
writeFileSync(join(dir, 'objectstack.config.ts'), CONFIG);
84+
linkSpec(dir);
85+
});
86+
87+
afterAll(async () => {
88+
if (child && child.exitCode === null && child.signalCode === null) {
89+
await new Promise<void>((done) => {
90+
const give = setTimeout(() => {
91+
try { child!.kill('SIGKILL'); } catch { /* already gone */ }
92+
done();
93+
}, 10_000);
94+
child!.once('exit', () => { clearTimeout(give); done(); });
95+
try { child!.kill('SIGTERM'); } catch { clearTimeout(give); done(); }
96+
});
97+
}
98+
if (dir) rmSync(dir, { recursive: true, force: true });
99+
});
100+
101+
/** Boot `os serve objectstack.config.ts --dev`; `--dev` seeds the admin. Answers the port it bound. */
102+
function bootServe(): Promise<number> {
103+
return new Promise((resolveBoot, rejectBoot) => {
104+
child = spawn(TSX, [CLI, 'serve', 'objectstack.config.ts', '-p', KERNEL_ASSIGNED_PORT, '--dev'], {
105+
cwd: dir,
106+
stdio: ['pipe', 'pipe', 'pipe'],
107+
env: childEnv({
108+
NO_COLOR: '1',
109+
OS_DATABASE_URL: ':memory:',
110+
OS_LOG_LEVEL: '',
111+
OS_DISABLE_CONSOLE: '1',
112+
OS_SECRET_KEY: E2E_SECRET_KEY,
113+
}),
114+
}) as ChildProcessWithoutNullStreams;
115+
const what = `os serve --dev in ${dir}`;
116+
let settled = false;
117+
const settle = (verdict: Error | number) => {
118+
if (settled) return;
119+
settled = true;
120+
clearTimeout(timer);
121+
if (verdict instanceof Error) rejectBoot(verdict);
122+
else resolveBoot(verdict);
123+
};
124+
const timer = setTimeout(
125+
() => settle(new Error(`${what} never printed ${READY}\n--- output ---\n${output.slice(-4000)}`)),
126+
180_000,
127+
);
128+
const onData = (d: unknown) => {
129+
output += String(d);
130+
if (READY.test(output)) settle(readKernelAssignedPort(output, what));
131+
};
132+
child.stdout.on('data', onData);
133+
child.stderr.on('data', onData);
134+
child.on('exit', (code) =>
135+
settle(new Error(`${what} exited ${String(code)} before ${READY}\n--- output ---\n${output.slice(-4000)}`)),
136+
);
137+
});
138+
}
139+
140+
/** One HTTP exchange, attributed to the child if the transport fails. ⛔ No assertion inside. */
141+
async function request(what: string, url: string, init: RequestInit = {}): Promise<{ status: number; headers: Headers; text: string; body: any }> {
142+
return probeThroughChild(
143+
{
144+
child: child!,
145+
transcript: () => `\n--- child output ---\n${output.slice(-4000)}`,
146+
label: 'serve-config-boot-seed-files',
147+
what,
148+
},
149+
async () => {
150+
const r = await fetch(url, init);
151+
const text = await r.text();
152+
let body: unknown = text;
153+
try { body = JSON.parse(text); } catch { /* keep the text */ }
154+
return { status: r.status, headers: r.headers, text, body };
155+
},
156+
);
157+
}
158+
159+
/** The rows a data read answers, whichever envelope carries them. */
160+
function rowsOf(body: any): Array<Record<string, any>> {
161+
const candidates = [body?.data?.records, body?.data?.items, body?.records, body?.items, body?.data, body?.value];
162+
return (candidates.find(Array.isArray) ?? []) as Array<Record<string, any>>;
163+
}
164+
165+
/** A file field's value as read: the bare id, or the expanded form carrying it. */
166+
function fileIdOf(value: unknown): string | undefined {
167+
if (typeof value === 'string') return value;
168+
if (value && typeof value === 'object') {
169+
const v = value as Record<string, unknown>;
170+
for (const key of ['id', 'fileId', 'file_id']) if (typeof v[key] === 'string') return v[key] as string;
171+
}
172+
return undefined;
173+
}
174+
175+
describe('a config boot seeds and serves the files seed records name (#25779)', () => {
176+
it('each seeded version holds a stored file of its own, and the file door serves the fixture\'s bytes', async () => {
177+
const port = await bootServe();
178+
const base = `http://localhost:${port}/api/v1`;
179+
180+
const signIn = await request('the sign-in probe', `${base}/auth/sign-in/email`, {
181+
method: 'POST',
182+
headers: { 'content-type': 'application/json' },
183+
body: JSON.stringify({ email: 'admin@objectos.ai', password: 'admin123' }),
184+
});
185+
expect(signIn.status, `sign-in: ${signIn.text}`).toBe(200);
186+
const headers = { authorization: `Bearer ${signIn.body.token}` };
187+
188+
// The inline seed of a stack carrying seed files runs at
189+
// `kernel:bootstrapped`; read until both rows are there, bounded.
190+
let rows: Array<Record<string, any>> = [];
191+
let last = '';
192+
for (let attempt = 0; attempt < 60 && rows.length < 2; attempt++) {
193+
const read = await request('the data read', `${base}/data/clm_version`, { headers });
194+
last = `${read.status} ${read.text.slice(0, 2000)}`;
195+
rows = rowsOf(read.body);
196+
if (rows.length < 2) await new Promise((r) => setTimeout(r, 1000));
197+
}
198+
expect(rows.map((r) => r.code).sort(), `last read: ${last}\n--- output ---\n${output.slice(-4000)}`).toEqual(['V1', 'V2']);
199+
200+
const ids = rows.map((r) => fileIdOf(r.file));
201+
expect(ids.every((id) => typeof id === 'string' && id.length > 0), JSON.stringify(rows)).toBe(true);
202+
expect(new Set(ids).size, 'each row holds a file of its own').toBe(2);
203+
204+
for (const id of ids) {
205+
const redirect = await request(`the file door for ${id}`, `${base}/storage/files/${id}`, { headers, redirect: 'manual' });
206+
expect(redirect.status, `GET /storage/files/${id}: ${redirect.text}`).toBe(302);
207+
const location = new URL(redirect.headers.get('location')!, `http://localhost:${port}`).toString();
208+
const bytes = await request(`the bytes of ${id}`, location, { headers });
209+
expect(bytes.status).toBe(200);
210+
expect(bytes.text).toBe(PDF);
211+
}
212+
}, 300_000);
213+
});

0 commit comments

Comments
 (0)