@lark-base-open/base-database-toolchain 1.0.0 → 1.1.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.1.0] - 2026-11-20
4
+
5
+ ### Added
6
+
7
+ - SQL batch metadata helpers that bind discovered capabilities to the selected site, environment and local SQL sources, with warnings for unsupported SDK versions.
8
+ - Optional verified batch snapshots and contract reports in the JSON subprocess interface, while preserving ordinary contract generation.
9
+ - HTML and JavaScript/TypeScript source inspection for Page bootstrap, registered template HMR and external-link warnings, with source positions.
10
+ - A long-running `base-database-dev` subprocess for paired local Page development, with current backend snapshots, file-change events and graceful shutdown.
11
+
3
12
  ## [1.0.0] - 2026-11-18
4
13
 
5
14
  ### Added
package/README.md CHANGED
@@ -27,6 +27,8 @@ const result = await buildProject('/absolute/project');
27
27
 
28
28
  Additional exports are `convertLoadedContract`, `runSDKCodegen`, `validateTriggerDeclarations`, `parseDurableEvents` and `driveLocalDurable`. The caller supplies project dependencies, explicit runtime context and compatibility checks; the compiler never supplies a user identity.
29
29
 
30
+ The `./batch` export provides shared SQL batch capability/execution-snapshot normalization, local-source binding and SDK compatibility warnings. Platform discovery remains the caller's responsibility. These metadata helpers do not authorize invocation.
31
+
30
32
  ## JSON subprocess protocol
31
33
 
32
34
  Run `base-database-toolchain` with one JSON object on stdin. It exits after one operation:
@@ -44,6 +46,38 @@ Run `base-database-toolchain` with one JSON object on stdin. It exits after one
44
46
 
45
47
  Supported operations: `contracts`, `verify-contracts`, `build`, `durable-dev`. `inputMode`, `runtimeOnly`, `legacyBuild` and `durableDev` select project compatibility options. Page builds remain the caller's responsibility.
46
48
 
49
+ For SQL batch clients, supply an authenticated, consistently discovered `batchSnapshot` with the siteToken, environment, versionId, skillHash and per-Function detail. The toolchain binds it to the actual project token, `runtimeProfile` (default online), and current local SQL source hashes. Verification reuses that bound observation; edited declarations lose the cached capability until a new discovery. An execution view is provenance, not a future lock. An older SDK can still generate single-call clients and returns a `BATCH_SDK_UNSUPPORTED` warning; no batch types are synthesized.
50
+
51
+ Successful contract operations write `lark-site-contract-report.json` under stateDirectory with protocolVersion 1 and warnings, and include nonempty warnings in the stdout success object. Callers requesting batch generation must check that report before claiming the snapshot was consumed; older workers ignore unknown request fields. The shared report is local state, not a deploy artifact.
52
+
47
53
  Success emits `{"ok":true,"operation":"contracts"}` on stdout. Failure emits a bounded JSON error on stderr and exits nonzero. Callers must not pass access tokens or application secrets to the process. SQL is not executed here; local Timer checks do not establish platform quota or calendar semantics. Durable local execution cannot invoke hosted Functions without a real host context.
48
54
 
49
55
  For `1.x`, compatible fixes increment patch, compatible features increment minor and incompatible APIs/protocols increment major. Published versions are immutable.
56
+
57
+ ## Page source inspection
58
+
59
+ The `./page-inspection` API and the Go adapter's `inspect-page` operation inspect HTML and JavaScript/TypeScript syntax without executing application code. The result contains bootstrap detection and LinkGuard warnings with one-based source positions. Only registered template HMR is accepted as known inline module code. Unsupported source trees return an inspection warning.
60
+
61
+ These results do not prove that initialization executes successfully, that an external-link guard works in a browser, or that a site is published. The adapter writes the same report to the caller's state directory as `lark-site-page-inspection.json`.
62
+
63
+ ## Local Page development worker
64
+
65
+ `base-database-dev` provides a long-running, newline-delimited JSON subprocess interface to the same Vite server used by the Node CLI. It uses the project's installed Vite and SDK. The caller supplies only a pairing token through `BASE_APP_DEV_PAIRING_TOKEN`; authentication, host URL discovery, locking, Preview publication and decisions about automatic deployment remain with the caller.
66
+
67
+ Keep stdin open and send one startup line:
68
+
69
+ ```json
70
+ {"protocolVersion":1,"workspace":"/absolute/project","port":43100,"hostOrigin":"https://example.test","templateVersion":2}
71
+ ```
72
+
73
+ Only loopback ports 43100–43109 and an exact HTTPS host origin are accepted. Events on stdout include `snapshot`, `listening`, `ready`, `changed`, `error` and `stopped`, each with `protocolVersion: 1`. `ready` only reports that the SDK observed the local origin; it does not establish authentication or successful application behavior. Tokens are excluded from event payloads and redacted from errors.
74
+
75
+ The backend snapshot excludes generated contract projections and observes source declarations, dependencies, bindings and authored Skill metadata. Individual input files are limited to 2 MiB, the tree to 20,000 entries and total content to 64 MiB. Changed-file lists have a byte/count budget; `filesTruncated: true` requires manual review rather than automatic publication. Request a fresh snapshot before a build or remote write:
76
+
77
+ ```json
78
+ {"protocolVersion":1,"command":"snapshot","requestId":"before-write"}
79
+ ```
80
+
81
+ The response echoes `requestId` with the current `fingerprint`. A matching snapshot alone does not authorize publication; the caller must also check its own reviewed publication inputs. Stop with `{"protocolVersion":1,"command":"stop"}`, stdin EOF or SIGINT/SIGTERM. The worker closes its Vite server before exiting. Each input line is limited to 64 KiB.
82
+
83
+ Node hosts can import `startVite`, `watchSnapshot`, `changedFiles`, `snapshotFingerprint` and `runViteIPCWorker` from `@lark-base-open/base-database-toolchain/development`. The IPC worker uses Node child-process messages; `base-database-dev` retains the newline-delimited JSON interface. Both use the same server and snapshot implementation. Hosts remain responsible for authentication, deployment and process supervision.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { runDevelopmentWorker } from '../dist/dev-worker.mjs';
3
+
4
+ runDevelopmentWorker();
@@ -0,0 +1,11 @@
1
+ {
2
+ "tokenEnv": "BASE_APP_DEV_PAIRING_TOKEN",
3
+ "endpoint": "/__base_app/dev-pair",
4
+ "proofPrefix": "base-app-dev-pair.v1",
5
+ "pairApi": "site.v1.development.pair",
6
+ "pairedEvent": "site.v1.development.paired",
7
+ "host": "127.0.0.1",
8
+ "portMin": 43100,
9
+ "portMax": 43109,
10
+ "secretBytes": 32
11
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "scripts": [
4
+ {
5
+ "sha256": "6e07b18ba1e30eca8bcaf3c99393e174d404d43e3f3ae31568d0075473d6bee2",
6
+ "code": "\n if (import.meta.hot?.on) {\n import.meta.hot.on('vite:error', (error) => {\n if (error.err) {\n console.error(\n [error.err.message, error.err.frame].filter(Boolean).join('\\n'),\n )\n }\n })\n }\n "
7
+ }
8
+ ]
9
+ }
@@ -0,0 +1,3 @@
1
+ export declare const DEPENDENCY_INPUTS: readonly ['package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', '.npmrc', '.yarnrc', '.yarnrc.yml'];
2
+ export declare function isDependencyInput(path: string): boolean;
3
+ export declare function blocksAutomaticPreview(path: string): boolean;
@@ -0,0 +1,18 @@
1
+ export const DEPENDENCY_INPUTS = [
2
+ 'package.json',
3
+ 'package-lock.json',
4
+ 'npm-shrinkwrap.json',
5
+ 'pnpm-lock.yaml',
6
+ 'yarn.lock',
7
+ '.npmrc',
8
+ '.yarnrc',
9
+ '.yarnrc.yml',
10
+ ];
11
+ export function isDependencyInput(path) {
12
+ return DEPENDENCY_INPUTS.includes(path.replaceAll('\\', '/').split('/').at(-1));
13
+ }
14
+ export function blocksAutomaticPreview(path) {
15
+ const normalized = path.replaceAll('\\', '/');
16
+ return (isDependencyInput(normalized) ||
17
+ !/^(server|server-functions|contract|contracts)\//.test(normalized));
18
+ }
@@ -0,0 +1 @@
1
+ export declare function runViteIPCWorker(sdkMissingMessage?: () => string): void;
@@ -0,0 +1,35 @@
1
+ import { startVite } from './dev-vite-server.js';
2
+ import { DEVELOPMENT_PAIRING } from './development-pairing.generated.js';
3
+ import { redactPairing } from './dev-redaction.js';
4
+ export function runViteIPCWorker(sdkMissingMessage) {
5
+ if (!process.send)
6
+ return;
7
+ let server;
8
+ let stopping = false;
9
+ const stop = async () => {
10
+ if (stopping)
11
+ return;
12
+ stopping = true;
13
+ await server?.close();
14
+ process.exit(0);
15
+ };
16
+ process.on('SIGTERM', stop);
17
+ process.on('SIGINT', stop);
18
+ process.on('disconnect', stop);
19
+ process.once('message', async (input) => {
20
+ try {
21
+ server = await startVite(input, undefined, sdkMissingMessage);
22
+ if (stopping)
23
+ await server.close();
24
+ }
25
+ catch (error) {
26
+ process.send?.({
27
+ event: 'error',
28
+ code: error.code,
29
+ message: redactPairing(error.message, process.env[DEVELOPMENT_PAIRING.tokenEnv]),
30
+ });
31
+ process.exitCode = 1;
32
+ process.disconnect();
33
+ }
34
+ });
35
+ }
@@ -0,0 +1 @@
1
+ export declare function redactPairing(value: string, token?: string): string;
@@ -0,0 +1,3 @@
1
+ export function redactPairing(value, token) {
2
+ return (token ? value.replaceAll(token, '[REDACTED]') : value).replace(/#t=[^\s"\\]*/g, '#t=[REDACTED]');
3
+ }
@@ -0,0 +1,3 @@
1
+ export declare function watchSnapshot(workspace: string): Map<string, string>;
2
+ export declare function changedFiles(a: Map<string, string>, b: Map<string, string>): string[];
3
+ export declare function snapshotFingerprint(snapshot: Map<string, string>): string;
@@ -0,0 +1,98 @@
1
+ import { DEPENDENCY_INPUTS } from './dependency-inputs.js';
2
+ import { usesDefineFunction } from './contract-extractor.js';
3
+ import { createHash } from 'node:crypto';
4
+ import { existsSync, readdirSync, readFileSync, lstatSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ export function watchSnapshot(workspace) {
7
+ const files = new Map();
8
+ let entries = 0;
9
+ let bytes = 0;
10
+ const read = (file) => {
11
+ const info = lstatSync(file);
12
+ if (!info.isFile() || info.nlink !== 1 || info.size > 2 * 1024 * 1024)
13
+ throw new Error('DEV_SOURCE_INVALID: Development files must be regular, unlinked files no larger than 2 MiB.');
14
+ bytes += info.size;
15
+ if (bytes > 64 * 1024 * 1024)
16
+ throw new Error('DEV_SOURCE_TOO_LARGE: Development inputs exceed 64 MiB.');
17
+ return readFileSync(file);
18
+ };
19
+ // An empty AI root declares a replacement set, unlike a missing root.
20
+ if (existsSync(join(workspace, 'ai')))
21
+ files.set('ai/', 'present');
22
+ const visit = (path) => {
23
+ const absolute = join(workspace, path);
24
+ if (!existsSync(absolute))
25
+ return;
26
+ if (!lstatSync(absolute).isDirectory())
27
+ throw new Error('DEV_SOURCE_INVALID: Development source roots must be regular directories.');
28
+ const children = readdirSync(absolute, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
29
+ for (const entry of children) {
30
+ if ([
31
+ 'node_modules',
32
+ 'dist',
33
+ 'generated',
34
+ '.git',
35
+ '.base-database-cli',
36
+ '.lark-cli',
37
+ 'contracts.generated.json',
38
+ ].includes(entry.name))
39
+ continue;
40
+ if (++entries > 20000)
41
+ throw new Error('DEV_SOURCE_TOO_LARGE: Development inputs exceed 20000 entries.');
42
+ const child = join(path, entry.name);
43
+ if (entry.isSymbolicLink())
44
+ throw new Error('DEV_SOURCE_INVALID: Development source links are not supported.');
45
+ if (entry.isDirectory())
46
+ visit(child);
47
+ else if (entry.isFile()) {
48
+ let contents = read(join(workspace, child));
49
+ if (entry.name === 'meta.json' &&
50
+ existsSync(join(workspace, path, 'index.ts'))) {
51
+ read(join(workspace, path, 'index.ts'));
52
+ if (usesDefineFunction(join(workspace, path, 'index.ts'))) {
53
+ const meta = JSON.parse(contents.toString());
54
+ delete meta.contract;
55
+ delete meta.inputSchema;
56
+ delete meta.outputSchema;
57
+ contents = Buffer.from(JSON.stringify(meta));
58
+ }
59
+ }
60
+ files.set(child.replaceAll('\\', '/'), createHash('sha256').update(contents).digest('hex'));
61
+ }
62
+ }
63
+ };
64
+ for (const root of [
65
+ 'server',
66
+ 'server-functions',
67
+ 'contract',
68
+ 'contracts',
69
+ 'database-functions',
70
+ 'sql',
71
+ 'mutations',
72
+ 'ai',
73
+ 'skill',
74
+ ])
75
+ visit(root);
76
+ for (const file of [
77
+ 'base-database.jsonc',
78
+ 'base-app.config.ts',
79
+ 'catalog.json',
80
+ 'agent-tools.json',
81
+ 'README.md',
82
+ ...DEPENDENCY_INPUTS,
83
+ ...DEPENDENCY_INPUTS.map((file) => 'page/' + file),
84
+ ])
85
+ if (existsSync(join(workspace, file)))
86
+ files.set(file, createHash('sha256')
87
+ .update(read(join(workspace, file)))
88
+ .digest('hex'));
89
+ return files;
90
+ }
91
+ export function changedFiles(a, b) {
92
+ return [...new Set([...a.keys(), ...b.keys()])].filter((key) => a.get(key) !== b.get(key));
93
+ }
94
+ export function snapshotFingerprint(snapshot) {
95
+ return createHash('sha256')
96
+ .update(JSON.stringify([...snapshot].sort(([a], [b]) => a.localeCompare(b))))
97
+ .digest('hex');
98
+ }
@@ -0,0 +1,14 @@
1
+ import path from 'node:path';
2
+ export interface ViteStart {
3
+ workspace: string;
4
+ port: number;
5
+ hostOrigin: string;
6
+ templateVersion: number;
7
+ }
8
+ export declare function resolveSDKViteEntry(packageRoot: string, entry: unknown, paths?: path.PlatformPath): string;
9
+ export declare function injectDevObserver(html: string): string;
10
+ export interface ViteLifecycleEvent {
11
+ event: 'listening' | 'ready';
12
+ localOrigin?: string;
13
+ }
14
+ export declare function startVite(input: ViteStart, observe?: (event: ViteLifecycleEvent) => void, sdkMissingMessage?: () => string): Promise<any>;
@@ -0,0 +1,213 @@
1
+ import { parse as parseHTML, parseFragment, serialize, } from 'parse5';
2
+ import { DEVELOPMENT_PAIRING } from './development-pairing.generated.js';
3
+ // Runs in a separate process with an allowlisted environment. Never receives CLI credentials.
4
+ import { createRequire } from 'node:module';
5
+ import { pathToFileURL } from 'node:url';
6
+ import path, { join } from 'node:path';
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ export function resolveSDKViteEntry(packageRoot, entry, paths = path) {
9
+ if (typeof entry === 'string' && entry.startsWith('./')) {
10
+ const resolved = paths.resolve(packageRoot, entry);
11
+ const relative = paths.relative(packageRoot, resolved);
12
+ if (relative !== '' &&
13
+ relative !== '..' &&
14
+ !relative.startsWith(`..${paths.sep}`) &&
15
+ !paths.isAbsolute(relative))
16
+ return resolved;
17
+ }
18
+ throw new Error('DEV_SDK_VITE_UNSUPPORTED: The project SDK does not export a Vite plugin.');
19
+ }
20
+ export function injectDevObserver(html) {
21
+ const document = parseHTML(html, { sourceCodeLocationInfo: true });
22
+ const find = (node) => {
23
+ if (node.nodeName === 'head')
24
+ return node;
25
+ if ('childNodes' in node)
26
+ for (const child of node.childNodes) {
27
+ const found = find(child);
28
+ if (found)
29
+ return found;
30
+ }
31
+ return undefined;
32
+ };
33
+ const head = find(document);
34
+ if (!head)
35
+ throw new Error('DEV_HTML_UNKNOWN: cannot locate HTML head; repair index.html before dev');
36
+ // Vite's own head injection can also hit a comment. Import its client from this real module.
37
+ const module = '<script type="module">import "/@vite/client"; import "virtual:base-app-dev-observer";</script>';
38
+ const offset = head.sourceCodeLocation?.startTag?.endOffset;
39
+ if (offset !== undefined)
40
+ return html.slice(0, offset) + module + html.slice(offset);
41
+ const script = parseFragment(module).childNodes[0];
42
+ script.parentNode = head;
43
+ head.childNodes.unshift(script);
44
+ return serialize(document);
45
+ }
46
+ export async function startVite(input, observe = (event) => process.send?.(event), sdkMissingMessage = () => 'DEV_SDK_MISSING: Install the project SDK and Vite dependencies before starting local development.') {
47
+ const require = createRequire(join(input.workspace, 'page/package.json'));
48
+ const vite = await import(pathToFileURL(require.resolve('vite')).href);
49
+ const origin = `http://${DEVELOPMENT_PAIRING.host}:${input.port}`;
50
+ const base = '/';
51
+ const control = `${base}__lifecycle`;
52
+ const plugins = [];
53
+ {
54
+ const packageName = '@lark-base-open/base-database-app-sdk';
55
+ const packageRoot = require.resolve
56
+ .paths(packageName)
57
+ ?.map((p) => join(p, packageName))
58
+ .find((p) => existsSync(join(p, 'package.json')));
59
+ if (!packageRoot)
60
+ throw new Error(sdkMissingMessage());
61
+ const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'));
62
+ const entry = resolveSDKViteEntry(packageRoot, manifest.exports?.['./vite']?.import);
63
+ const sdk = await import(pathToFileURL(entry).href);
64
+ if (typeof sdk.baseAppDevelopmentPairingPlugin !== 'function')
65
+ throw new Error('DEV_SDK_PAIRING_UNSUPPORTED: Upgrade the project SDK before using the paired development entry.');
66
+ plugins.push(sdk.baseAppDevelopmentPairingPlugin());
67
+ }
68
+ // Both templates load the SDK boundary; legacy helpers share its channel singleton.
69
+ const runtime = '@lark-base-open/base-database-app-sdk/page';
70
+ plugins.push({
71
+ name: 'base-app-dev-boundary',
72
+ enforce: 'pre',
73
+ configResolved(config) {
74
+ if (config.server.host !== '127.0.0.1' ||
75
+ config.server.port !== input.port ||
76
+ config.server.strictPort !== true ||
77
+ config.server.https ||
78
+ config.server.middlewareMode ||
79
+ config.server.open ||
80
+ config.server.cors !== false ||
81
+ Object.keys(config.server.proxy ?? {}).length ||
82
+ config.base !== base)
83
+ throw new Error('DEV_VITE_UNSAFE_CONFIG: Project configuration overrides local development boundaries.');
84
+ },
85
+ resolveId(id) {
86
+ if (id === 'virtual:base-app-dev-observer')
87
+ return '\0base-app-dev-observer';
88
+ },
89
+ load(id) {
90
+ if (id !== '\0base-app-dev-observer')
91
+ return;
92
+ return `import {siteRuntime} from ${JSON.stringify(runtime)};
93
+ const original = siteRuntime.ready.bind(siteRuntime);
94
+ siteRuntime.ready = async (...args) => { const result = await original(...args); const context = await siteRuntime.getRuntimeContext(); if (context.development?.localOrigin === ${JSON.stringify(origin)}) await globalThis.fetch(${JSON.stringify(control)}, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({localOrigin:context.development.localOrigin})}); return result; };`;
95
+ },
96
+ transformIndexHtml: {
97
+ order: 'pre',
98
+ handler: injectDevObserver,
99
+ },
100
+ configureServer(server) {
101
+ server.middlewares.use((req, res, next) => {
102
+ if (req.headers.host !== `127.0.0.1:${input.port}` ||
103
+ (req.headers.origin !== undefined && req.headers.origin !== origin)) {
104
+ res.writeHead(403).end();
105
+ return;
106
+ }
107
+ if (req.headers.accept?.includes('text/html')) {
108
+ const dest = req.headers['sec-fetch-dest'];
109
+ let validReferer = true;
110
+ if (req.headers.referer) {
111
+ try {
112
+ validReferer =
113
+ new URL(req.headers.referer).origin === input.hostOrigin;
114
+ }
115
+ catch {
116
+ validReferer = false;
117
+ }
118
+ }
119
+ if ((dest !== undefined && dest !== 'iframe') || !validReferer) {
120
+ res.writeHead(403).end();
121
+ return;
122
+ }
123
+ }
124
+ if (req.url === control) {
125
+ if (req.method !== 'POST' ||
126
+ req.headers.origin !== origin ||
127
+ req.headers['content-type'] !== 'application/json') {
128
+ res.writeHead(403).end();
129
+ return;
130
+ }
131
+ let body = '';
132
+ req.on('data', (data) => {
133
+ body += data;
134
+ if (body.length > 1024)
135
+ req.destroy();
136
+ });
137
+ req.on('end', () => {
138
+ try {
139
+ if (JSON.parse(body).localOrigin !== origin)
140
+ throw new Error();
141
+ observe({ event: 'ready', localOrigin: origin });
142
+ res.writeHead(204).end();
143
+ }
144
+ catch {
145
+ res.writeHead(400).end();
146
+ }
147
+ });
148
+ return;
149
+ }
150
+ if (req.url === `${base}__health`) {
151
+ res.setHeader('Content-Type', 'application/json');
152
+ res.end('{"ready":true}');
153
+ return;
154
+ }
155
+ if (req.headers['sec-fetch-dest'] === 'document') {
156
+ res.writeHead(403).end();
157
+ return;
158
+ }
159
+ if (req.headers.accept?.includes('text/html') &&
160
+ req.url?.split('?')[0] !== base) {
161
+ res.writeHead(404).end();
162
+ return;
163
+ }
164
+ res.setHeader('Content-Security-Policy', `frame-ancestors ${input.hostOrigin ?? "'none'"}; connect-src 'self' ws://127.0.0.1:${input.port}; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'`);
165
+ next();
166
+ });
167
+ server.httpServer?.prependListener('upgrade', (req, socket) => {
168
+ if (req.headers.host !== `127.0.0.1:${input.port}` ||
169
+ req.headers.origin !== origin ||
170
+ req.url?.split('?')[0] !== `${base}__hmr`)
171
+ socket.destroy();
172
+ });
173
+ },
174
+ });
175
+ const server = await vite.createServer({
176
+ root: join(input.workspace, 'page'),
177
+ base,
178
+ plugins,
179
+ logLevel: 'silent',
180
+ clearScreen: false,
181
+ server: {
182
+ host: '127.0.0.1',
183
+ port: input.port,
184
+ strictPort: true,
185
+ open: false,
186
+ cors: false,
187
+ proxy: {},
188
+ hmr: {
189
+ host: '127.0.0.1',
190
+ port: input.port,
191
+ clientPort: input.port,
192
+ path: '__hmr',
193
+ },
194
+ fs: {
195
+ strict: true,
196
+ deny: [
197
+ '.env',
198
+ '.env.*',
199
+ '*.{crt,pem}',
200
+ '**/.git/**',
201
+ '**/.base-database-cli/**',
202
+ '**/.lark-cli/**',
203
+ '**/server/**',
204
+ '**/server-functions/**',
205
+ '**/database-functions/**',
206
+ ],
207
+ },
208
+ },
209
+ });
210
+ await server.listen();
211
+ observe({ event: 'listening' });
212
+ return server;
213
+ }
@@ -0,0 +1 @@
1
+ export declare function runDevelopmentWorker(): void;
@@ -0,0 +1,134 @@
1
+ // Long-running, credential-free Vite worker. The Go host owns auth and publishing.
2
+ import { isAbsolute } from 'node:path';
3
+ import { createInterface } from 'node:readline';
4
+ import { startVite } from './dev-vite-server.js';
5
+ import { watchSnapshot, changedFiles, snapshotFingerprint, } from './dev-snapshot.js';
6
+ import { DEVELOPMENT_PAIRING as protocol } from './development-pairing.generated.js';
7
+ import { redactPairing } from './dev-redaction.js';
8
+ export function runDevelopmentWorker() {
9
+ const token = process.env[protocol.tokenEnv];
10
+ const redact = (value) => redactPairing(String(value), token).slice(0, 4096);
11
+ const emit = (value) => process.stdout.write(JSON.stringify({ protocolVersion: 1, ...value }) + '\n');
12
+ let server;
13
+ let started = false;
14
+ let stopping = false;
15
+ let startup = Promise.resolve();
16
+ let scanTimer;
17
+ let workspace;
18
+ let snapshot;
19
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
20
+ async function stop(code = 0) {
21
+ if (stopping)
22
+ return;
23
+ stopping = true;
24
+ clearInterval(scanTimer);
25
+ lines.close();
26
+ process.stdin.pause();
27
+ await startup.catch(() => { });
28
+ await server?.close();
29
+ emit({ event: 'stopped' });
30
+ process.exit(code);
31
+ }
32
+ function fail(error) {
33
+ emit({ event: 'error', message: redact(error?.message ?? error) });
34
+ setImmediate(() => void stop(1));
35
+ }
36
+ process.once('SIGINT', () => void stop());
37
+ process.once('SIGTERM', () => void stop());
38
+ lines.once('close', () => {
39
+ if (!stopping)
40
+ void stop();
41
+ });
42
+ let inputBytes = 0;
43
+ process.stdin.prependListener('data', (chunk) => {
44
+ for (const byte of chunk) {
45
+ if (byte === 10)
46
+ inputBytes = 0;
47
+ else if (++inputBytes > 64 * 1024) {
48
+ fail(Error('DEV_INPUT_TOO_LARGE: Development input exceeds its line budget.'));
49
+ break;
50
+ }
51
+ }
52
+ });
53
+ lines.on('line', (line) => {
54
+ if (stopping)
55
+ return;
56
+ try {
57
+ const input = JSON.parse(line);
58
+ if (input.protocolVersion !== 1)
59
+ throw Error('DEV_PROTOCOL_UNSUPPORTED: Unsupported development protocol.');
60
+ if (started) {
61
+ if (input.command === 'snapshot' &&
62
+ typeof input.requestId === 'string' &&
63
+ /^[A-Za-z0-9-]{1,64}$/.test(input.requestId)) {
64
+ const current = watchSnapshot(workspace);
65
+ emit({
66
+ event: 'snapshot',
67
+ requestId: input.requestId,
68
+ fingerprint: snapshotFingerprint(current),
69
+ });
70
+ return;
71
+ }
72
+ if (input.command !== 'stop')
73
+ throw Error('DEV_CONTROL_INVALID: Expected stop or an identified snapshot request.');
74
+ void stop();
75
+ return;
76
+ }
77
+ started = true;
78
+ const host = new URL(input.hostOrigin);
79
+ if (!isAbsolute(input.workspace) ||
80
+ !Number.isInteger(input.port) ||
81
+ input.port < protocol.portMin ||
82
+ input.port > protocol.portMax ||
83
+ host.protocol !== 'https:' ||
84
+ host.origin !== input.hostOrigin ||
85
+ host.username ||
86
+ host.password ||
87
+ ![1, 2].includes(input.templateVersion) ||
88
+ !/^[A-Za-z0-9_-]{43}$/.test(token ?? ''))
89
+ throw Error('DEV_INPUT_INVALID: Invalid project, loopback port, host origin or pairing token.');
90
+ workspace = input.workspace;
91
+ snapshot = watchSnapshot(workspace);
92
+ emit({ event: 'snapshot', fingerprint: snapshotFingerprint(snapshot) });
93
+ startup = (async () => {
94
+ try {
95
+ server = await startVite(input, emit);
96
+ if (!stopping)
97
+ scanTimer = setInterval(() => {
98
+ try {
99
+ const current = watchSnapshot(workspace);
100
+ const changed = changedFiles(snapshot, current);
101
+ snapshot = current;
102
+ if (changed.length) {
103
+ const files = [];
104
+ let size = 0;
105
+ for (const file of changed) {
106
+ const bytes = Buffer.byteLength(JSON.stringify(file)) + 1;
107
+ if (files.length === 100 || size + bytes > 8192)
108
+ break;
109
+ files.push(file);
110
+ size += bytes;
111
+ }
112
+ emit({
113
+ event: 'changed',
114
+ files,
115
+ filesTruncated: files.length !== changed.length,
116
+ fingerprint: snapshotFingerprint(current),
117
+ });
118
+ }
119
+ }
120
+ catch (error) {
121
+ fail(error);
122
+ }
123
+ }, 200);
124
+ }
125
+ catch (error) {
126
+ fail(error);
127
+ }
128
+ })();
129
+ }
130
+ catch (error) {
131
+ fail(error);
132
+ }
133
+ });
134
+ }
@@ -0,0 +1,11 @@
1
+ export declare const DEVELOPMENT_PAIRING: {
2
+ readonly tokenEnv: 'BASE_APP_DEV_PAIRING_TOKEN';
3
+ readonly endpoint: '/__base_app/dev-pair';
4
+ readonly proofPrefix: 'base-app-dev-pair.v1';
5
+ readonly pairApi: 'site.v1.development.pair';
6
+ readonly pairedEvent: 'site.v1.development.paired';
7
+ readonly host: '127.0.0.1';
8
+ readonly portMin: 43100;
9
+ readonly portMax: 43109;
10
+ readonly secretBytes: 32;
11
+ };
@@ -0,0 +1,12 @@
1
+ // Generated from SDK development-pairing.json; run scripts/sync-development-pairing.mjs.
2
+ export const DEVELOPMENT_PAIRING = {
3
+ tokenEnv: 'BASE_APP_DEV_PAIRING_TOKEN',
4
+ endpoint: '/__base_app/dev-pair',
5
+ proofPrefix: 'base-app-dev-pair.v1',
6
+ pairApi: 'site.v1.development.pair',
7
+ pairedEvent: 'site.v1.development.paired',
8
+ host: '127.0.0.1',
9
+ portMin: 43100,
10
+ portMax: 43109,
11
+ secretBytes: 32,
12
+ };