@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.
@@ -0,0 +1,6 @@
1
+ export { startVite, resolveSDKViteEntry, injectDevObserver, type ViteStart, type ViteLifecycleEvent, } from './dev-vite-server.js';
2
+ export { watchSnapshot, changedFiles, snapshotFingerprint, } from './dev-snapshot.js';
3
+ export { runViteIPCWorker } from './dev-ipc-worker.js';
4
+ export { DEVELOPMENT_PAIRING } from './development-pairing.generated.js';
5
+ export { redactPairing } from './dev-redaction.js';
6
+ export { DEPENDENCY_INPUTS, isDependencyInput, blocksAutomaticPreview, } from './dependency-inputs.js';
@@ -0,0 +1,6 @@
1
+ export { startVite, resolveSDKViteEntry, injectDevObserver, } from './dev-vite-server.js';
2
+ export { watchSnapshot, changedFiles, snapshotFingerprint, } from './dev-snapshot.js';
3
+ export { runViteIPCWorker } from './dev-ipc-worker.js';
4
+ export { DEVELOPMENT_PAIRING } from './development-pairing.generated.js';
5
+ export { redactPairing } from './dev-redaction.js';
6
+ export { DEPENDENCY_INPUTS, isDependencyInput, blocksAutomaticPreview, } from './dependency-inputs.js';
@@ -0,0 +1,48 @@
1
+ export interface DMLBatchCapability {
2
+ version: 1;
3
+ maxGroups: number;
4
+ maxRowsPerGroup: 1;
5
+ maxTotalRows: number;
6
+ }
7
+ export interface FunctionExecutionSnapshot {
8
+ version: 1;
9
+ environment: 'preview' | 'prod';
10
+ view: 'draft' | 'online';
11
+ sourceDigest: string;
12
+ }
13
+ export interface FunctionBatchSnapshot {
14
+ siteToken: string;
15
+ environment: 'preview' | 'prod';
16
+ versionId: string;
17
+ skillHash: string;
18
+ functions: Record<string, {
19
+ batchCapability?: DMLBatchCapability;
20
+ inputSchema?: Record<string, unknown>;
21
+ executionSnapshot?: FunctionExecutionSnapshot;
22
+ }>;
23
+ }
24
+ export interface BoundFunctionBatchSnapshot extends FunctionBatchSnapshot {
25
+ runtimeProfile: string;
26
+ localSources: Record<string, string>;
27
+ }
28
+ /** Closed published contract; generated types never establish runtime permission. */
29
+ export declare function normalizeDMLBatchCapability(functionType: number, capability: unknown): DMLBatchCapability | undefined;
30
+ /** Execution provenance describes the observed provider view, not a future lock. */
31
+ export declare function normalizeFunctionExecutionSnapshot(value: unknown, environment: 'preview' | 'prod'): FunctionExecutionSnapshot | undefined;
32
+ export declare function bindFunctionBatchSnapshot(options: {
33
+ siteToken: string;
34
+ runtimeProfile: string;
35
+ localSources: Record<string, string>;
36
+ snapshot?: FunctionBatchSnapshot;
37
+ previous?: unknown;
38
+ }): BoundFunctionBatchSnapshot | undefined;
39
+ export declare function withFunctionBatchCapability<T extends {
40
+ functionId: string;
41
+ functionType: number;
42
+ }>(contract: T, snapshot: BoundFunctionBatchSnapshot | undefined, localSources: Record<string, string>): T & {
43
+ batchCapability?: DMLBatchCapability;
44
+ };
45
+ /** An older SDK keeps its single-call clients; callers must report this warning. */
46
+ export declare function batchClientWarning(data: unknown, files: {
47
+ content: string;
48
+ }[]): string | undefined;
@@ -0,0 +1,99 @@
1
+ function record(value) {
2
+ return !!value && typeof value === 'object' && !Array.isArray(value);
3
+ }
4
+ /** Closed published contract; generated types never establish runtime permission. */
5
+ export function normalizeDMLBatchCapability(functionType, capability) {
6
+ if (functionType !== 1 || !record(capability))
7
+ return;
8
+ if (Object.keys(capability).some((key) => !['version', 'maxGroups', 'maxRowsPerGroup', 'maxTotalRows'].includes(key)) ||
9
+ capability.version !== 1 ||
10
+ capability.maxRowsPerGroup !== 1 ||
11
+ !Number.isSafeInteger(capability.maxGroups) ||
12
+ capability.maxGroups < 1 ||
13
+ capability.maxGroups > 200 ||
14
+ !Number.isSafeInteger(capability.maxTotalRows) ||
15
+ capability.maxTotalRows < 1 ||
16
+ capability.maxTotalRows > 200)
17
+ return;
18
+ return {
19
+ version: 1,
20
+ maxGroups: capability.maxGroups,
21
+ maxRowsPerGroup: 1,
22
+ maxTotalRows: capability.maxTotalRows,
23
+ };
24
+ }
25
+ /** Execution provenance describes the observed provider view, not a future lock. */
26
+ export function normalizeFunctionExecutionSnapshot(value, environment) {
27
+ if (!record(value) ||
28
+ Object.keys(value).length !== 4 ||
29
+ Object.keys(value).some((key) => !['version', 'environment', 'view', 'sourceDigest'].includes(key)) ||
30
+ value.version !== 1 ||
31
+ value.environment !== environment ||
32
+ value.view !== (environment === 'preview' ? 'draft' : 'online') ||
33
+ typeof value.sourceDigest !== 'string' ||
34
+ !/^[a-f0-9]{64}$/.test(value.sourceDigest))
35
+ return;
36
+ return value;
37
+ }
38
+ export function bindFunctionBatchSnapshot(options) {
39
+ const { snapshot, previous, siteToken, runtimeProfile, localSources } = options;
40
+ if (snapshot && snapshot.siteToken !== siteToken) {
41
+ throw new Error('BATCH_CAPABILITY_SITE_MISMATCH: discovery must use this project site');
42
+ }
43
+ if (snapshot &&
44
+ (!['preview', 'prod'].includes(snapshot.environment) ||
45
+ typeof snapshot.versionId !== 'string' ||
46
+ !/^\d+$/.test(snapshot.versionId) ||
47
+ typeof snapshot.skillHash !== 'string' ||
48
+ !record(snapshot.functions))) {
49
+ throw new Error('BATCH_CAPABILITY_SNAPSHOT_INVALID: discovery requires a valid site, environment and Function snapshot');
50
+ }
51
+ if (snapshot)
52
+ return { ...snapshot, localSources: { ...localSources }, runtimeProfile };
53
+ if (record(previous) &&
54
+ previous.siteToken === siteToken &&
55
+ previous.runtimeProfile === runtimeProfile &&
56
+ ['preview', 'prod'].includes(String(previous.environment)) &&
57
+ typeof previous.versionId === 'string' &&
58
+ /^\d+$/.test(previous.versionId) &&
59
+ typeof previous.skillHash === 'string' &&
60
+ record(previous.functions) &&
61
+ record(previous.localSources)) {
62
+ return previous;
63
+ }
64
+ return;
65
+ }
66
+ export function withFunctionBatchCapability(contract, snapshot, localSources) {
67
+ const id = contract.functionId;
68
+ const remote = snapshot && Object.hasOwn(snapshot.functions, id)
69
+ ? snapshot.functions[id]
70
+ : undefined;
71
+ const capability = snapshot &&
72
+ typeof localSources[id] === 'string' &&
73
+ snapshot.localSources[id] === localSources[id] &&
74
+ normalizeFunctionExecutionSnapshot(remote?.executionSnapshot, snapshot.environment)
75
+ ? normalizeDMLBatchCapability(contract.functionType, remote?.batchCapability)
76
+ : undefined;
77
+ return capability && record(remote?.inputSchema)
78
+ ? {
79
+ ...contract,
80
+ batchCapability: capability,
81
+ ...('input' in contract ? { input: remote.inputSchema } : {}),
82
+ ...('inputSchema' in contract
83
+ ? { inputSchema: remote.inputSchema }
84
+ : {}),
85
+ }
86
+ : contract;
87
+ }
88
+ /** An older SDK keeps its single-call clients; callers must report this warning. */
89
+ export function batchClientWarning(data, files) {
90
+ if (!record(data) || data.client !== true || !Array.isArray(data.functions))
91
+ return;
92
+ const ids = data.functions
93
+ .filter((fn) => record(fn) && typeof fn.functionId === 'string' && fn.batchCapability)
94
+ .map((fn) => fn.functionId);
95
+ if (!ids.length ||
96
+ files.some((file) => file.content.includes('export const batchFunctions')))
97
+ return;
98
+ return `BATCH_SDK_UNSUPPORTED: The installed SDK generated no SQL batch DML client for: ${ids.join(', ')}. Generation continues with single-call clients; Page batch writes are unavailable. Do not add batch types manually. For multiple writes, obtain the user's acceptance of non-atomic single writes before invoking them individually. When a batch-capable SDK release is available, upgrade with user authorization, then run contracts generate and check --json again.`;
99
+ }
@@ -1,4 +1,11 @@
1
1
  export declare function runCompiler(request: any): Promise<{
2
+ protocolVersion: 1;
3
+ bootstrap: import("./page-bootstrap.js").DevBootstrapStatus;
4
+ warnings: import("./page-link-guard.js").LinkGuardWarning[];
2
5
  ok: boolean;
3
6
  operation: any;
7
+ } | {
8
+ ok: boolean;
9
+ operation: any;
10
+ warnings?: any[] | undefined;
4
11
  }>;
@@ -15,6 +15,9 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
15
15
  import { driveLocalDurable } from './durable-runner.js';
16
16
  import { buildProject } from './app-builder/core.mjs';
17
17
  import { runSDKCodegen } from './sdk-codegen.js';
18
+ import { inspectPage } from './page-inspection.js';
19
+ import { parse as parseJSONC } from 'jsonc-parser';
20
+ import { bindFunctionBatchSnapshot, withFunctionBatchCapability, batchClientWarning, } from './function-batch.js';
18
21
  export async function runCompiler(request) {
19
22
  if (request.protocolVersion !== 1)
20
23
  throw Error('Unsupported compiler protocol version');
@@ -22,6 +25,8 @@ export async function runCompiler(request) {
22
25
  !['server', 'server-functions'].includes(request.server))
23
26
  throw Error('Invalid compiler project layout');
24
27
  const triggerIDs = new Set();
28
+ const warnings = [];
29
+ const localSQLSources = Object.create(null);
25
30
  const triggerLocations = [];
26
31
  let triggerCount = 0;
27
32
  const permissionFlag = process.allowedNodeEnvironmentFlags.has('--permission')
@@ -273,7 +278,7 @@ export async function runCompiler(request) {
273
278
  throw Error('Invalid parameter enum: ' + id + '.' + p.name);
274
279
  }
275
280
  }
276
- function legacyContracts(functions, inputs) {
281
+ function legacyContracts(functions, inputs, bindBatch) {
277
282
  for (const [directory, type] of [
278
283
  [
279
284
  fs.existsSync(path.join(root, 'database-functions'))
@@ -285,6 +290,18 @@ export async function runCompiler(request) {
285
290
  ]) {
286
291
  for (const id of entries(path.join(root, directory))) {
287
292
  const metadata = readJSON(path.join(root, directory, id, 'meta.json'));
293
+ if (type === 1 && bindBatch) {
294
+ let meta = metadata.meta;
295
+ if (meta === undefined)
296
+ meta = { params: [] };
297
+ else if (!meta || typeof meta !== 'object' || Array.isArray(meta))
298
+ throw Error('SQL meta must be an object: ' + id);
299
+ else if (!Object.hasOwn(meta, 'params'))
300
+ meta = { ...meta, params: [] };
301
+ const sql = fs.readFileSync(safe(path.join(root, directory, id, 'main.sql')), 'utf8');
302
+ localSQLSources[id] =
303
+ 'sha256:' + digest(JSON.stringify({ sql, meta }));
304
+ }
288
305
  const params = type === 1
289
306
  ? (metadata.meta?.params ?? [])
290
307
  : (readJSON(path.join(root, directory, id, 'spec.json')).params ??
@@ -481,6 +498,23 @@ export async function runCompiler(request) {
481
498
  stale();
482
499
  }
483
500
  async function contracts(write) {
501
+ const manifest = path.join(serverRoot, 'contracts.generated.json');
502
+ let previous;
503
+ if (fs.existsSync(safe(manifest))) {
504
+ try {
505
+ previous = readJSON(safe(manifest)).batchSnapshot;
506
+ }
507
+ catch (error) {
508
+ if (!write)
509
+ stale();
510
+ }
511
+ }
512
+ if (request.batchSnapshot !== undefined &&
513
+ (!request.batchSnapshot ||
514
+ typeof request.batchSnapshot !== 'object' ||
515
+ Array.isArray(request.batchSnapshot))) {
516
+ throw Error('BATCH_CAPABILITY_SNAPSHOT_INVALID: batchSnapshot must be an object');
517
+ }
484
518
  const functions = [];
485
519
  const inputs = [];
486
520
  const durable = [];
@@ -594,7 +628,25 @@ export async function runCompiler(request) {
594
628
  });
595
629
  }
596
630
  }
597
- legacyContracts(functions, inputs);
631
+ legacyContracts(functions, inputs, !!(request.batchSnapshot || previous));
632
+ let batchSnapshot;
633
+ if (request.batchSnapshot || previous) {
634
+ const errors = [];
635
+ const config = parseJSONC(fs.readFileSync(safe('base-database.jsonc'), 'utf8'), errors);
636
+ if (errors.length || !config || typeof config.appToken !== 'string')
637
+ throw Error('Batch discovery requires this project application token');
638
+ batchSnapshot = bindFunctionBatchSnapshot({
639
+ siteToken: config.appToken,
640
+ runtimeProfile: request.runtimeProfile ?? 'online',
641
+ localSources: localSQLSources,
642
+ snapshot: request.batchSnapshot,
643
+ previous,
644
+ });
645
+ for (let i = 0; i < functions.length; i++)
646
+ functions[i] = withFunctionBatchCapability(functions[i], batchSnapshot, localSQLSources);
647
+ for (let i = 0; i < inputs.length; i++)
648
+ inputs[i] = withFunctionBatchCapability(inputs[i], batchSnapshot, localSQLSources);
649
+ }
598
650
  writeJSON(path.join(stateRoot, 'lark-site-trigger-validation.json'), {
599
651
  local: 'passed',
600
652
  status: 'not_run',
@@ -607,6 +659,7 @@ export async function runCompiler(request) {
607
659
  version: 1,
608
660
  layout: server === 'server' ? 'workspace' : 'classic',
609
661
  schemaHash: 'sha256:' + digest(JSON.stringify(functions)),
662
+ ...(batchSnapshot ? { batchSnapshot } : {}),
610
663
  functions,
611
664
  ...(durable.length ? { durable } : {}),
612
665
  inputs,
@@ -616,7 +669,6 @@ export async function runCompiler(request) {
616
669
  if (write)
617
670
  for (const [file, data] of changes)
618
671
  writeJSON(file, data);
619
- const manifest = path.join(serverRoot, 'contracts.generated.json');
620
672
  if (write)
621
673
  writeJSON(manifest, generated);
622
674
  else if (!fs.existsSync(safe(manifest)) ||
@@ -628,7 +680,14 @@ export async function runCompiler(request) {
628
680
  catch (error) {
629
681
  if (sdkDeclarations)
630
682
  throw error;
683
+ const warning = batchClientWarning(generated, []);
684
+ if (warning)
685
+ warnings.push(warning);
631
686
  writeLegacyInputs(inputs, write);
687
+ writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), {
688
+ protocolVersion: 1,
689
+ warnings,
690
+ });
632
691
  return;
633
692
  }
634
693
  const durableFile = path.join(serverRoot, 'src/generated/durable.d.ts');
@@ -636,11 +695,18 @@ export async function runCompiler(request) {
636
695
  generatedFile(durableFile, `/* Generated by lark-cli. Do not edit. */\nimport '@lark-base-open/base-database-app-sdk/server';\nimport type { z } from 'zod';\ndeclare module '@lark-base-open/base-database-app-sdk/server' {\n interface DurableFunctions {\n ${durableTypes.join('\n ')}\n }\n}\n`, write);
637
696
  const { durable: workflowContracts, ...sdkContracts } = generated;
638
697
  const output = await isolatedCodegen(sdkContracts);
698
+ const warning = batchClientWarning(generated, output);
699
+ if (warning)
700
+ warnings.push(warning);
639
701
  for (const file of output) {
640
702
  if (typeof file.path !== 'string' || typeof file.content !== 'string')
641
703
  throw Error('Invalid SDK codegen result');
642
704
  generatedFile(file.path, file.content.replace(/(^\/\* Generated by )[^ .\r\n]+(?=[ .])/gm, '$1lark-cli'), write);
643
705
  }
706
+ writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), {
707
+ protocolVersion: 1,
708
+ warnings,
709
+ });
644
710
  }
645
711
  function inspectServerEnvironment() {
646
712
  const environment = new Set();
@@ -736,7 +802,12 @@ export async function runCompiler(request) {
736
802
  throw Error('Project runtime brand differs from the selected lark-cli profile');
737
803
  return buildProject(root, { profile });
738
804
  }
739
- if (operation === 'contracts' || operation === 'verify-contracts')
805
+ if (operation === 'inspect-page') {
806
+ const result = inspectPage(root);
807
+ writeJSON(path.join(stateRoot, 'lark-site-page-inspection.json'), result);
808
+ return { ok: true, operation, ...result };
809
+ }
810
+ else if (operation === 'contracts' || operation === 'verify-contracts')
740
811
  await contracts(operation === 'contracts');
741
812
  else if (operation === 'build' || operation === 'durable-dev') {
742
813
  if (!request.legacyBuild) {
@@ -772,5 +843,5 @@ export async function runCompiler(request) {
772
843
  }
773
844
  else
774
845
  throw Error('Unknown compiler operation');
775
- return { ok: true, operation };
846
+ return { ok: true, operation, ...(warnings.length ? { warnings } : {}) };
776
847
  }
package/dist/index.d.ts CHANGED
@@ -4,3 +4,5 @@ export { validateTriggerDeclarations } from './trigger-validation.js';
4
4
  export { driveLocalDurable, parseDurableEvents } from './durable-runner.js';
5
5
  export { runSDKCodegen, SDKCodegenError } from './sdk-codegen.js';
6
6
  export { runCompiler } from './go-adapter.mjs';
7
+ export { inspectPage, inspectDevBootstrap, sdkPackageRoot, checkLinkGuard, type PageInspection, type DevBootstrapStatus, } from './page-inspection.js';
8
+ export { normalizeDMLBatchCapability, normalizeFunctionExecutionSnapshot, bindFunctionBatchSnapshot, withFunctionBatchCapability, batchClientWarning, type DMLBatchCapability, type FunctionBatchSnapshot, type FunctionExecutionSnapshot, type BoundFunctionBatchSnapshot, } from './function-batch.js';
package/dist/index.js CHANGED
@@ -4,3 +4,5 @@ export { validateTriggerDeclarations } from './trigger-validation.js';
4
4
  export { driveLocalDurable, parseDurableEvents } from './durable-runner.js';
5
5
  export { runSDKCodegen, SDKCodegenError } from './sdk-codegen.js';
6
6
  export { runCompiler } from './go-adapter.mjs';
7
+ export { inspectPage, inspectDevBootstrap, sdkPackageRoot, checkLinkGuard, } from './page-inspection.js';
8
+ export { normalizeDMLBatchCapability, normalizeFunctionExecutionSnapshot, bindFunctionBatchSnapshot, withFunctionBatchCapability, batchClientWarning, } from './function-batch.js';
@@ -0,0 +1,3 @@
1
+ export type DevBootstrapStatus = 'ready' | 'not-bootstrapped' | 'uncertain';
2
+ export declare function sdkPackageRoot(workspace: string): string | undefined;
3
+ export declare function inspectDevBootstrap(workspace: string): DevBootstrapStatus;
@@ -0,0 +1,178 @@
1
+ import { createRequire } from 'node:module';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { parse } from 'parse5';
6
+ import { parse as parseJavaScript } from '@babel/parser';
7
+ import { parseModule, walkAst } from './contract-extractor.js';
8
+ const sdkPackage = '@lark-base-open/base-database-app-sdk';
9
+ const registeredHmr = JSON.parse(readFileSync(new URL('./data/template-hmr-scripts.json', import.meta.url), 'utf8')).scripts.map(({ code }) => shape(parseJavaScript(code, { sourceType: 'module' }).program));
10
+ function isRegisteredHmr(code) {
11
+ try {
12
+ const ast = shape(parseJavaScript(code, { sourceType: 'module' }).program);
13
+ return registeredHmr.some((expected) => isDeepStrictEqual(ast, expected));
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ export function sdkPackageRoot(workspace) {
20
+ const require = createRequire(join(workspace, 'page/package.json'));
21
+ return require.resolve
22
+ .paths(sdkPackage)
23
+ ?.map((path) => join(path, sdkPackage))
24
+ .find((path) => existsSync(join(path, 'package.json')));
25
+ }
26
+ // Compare semantic AST fields, never comments/text fragments. This deliberately
27
+ // accepts only the known migrated starter, including its React mount and effect.
28
+ function shape(value) {
29
+ if (Array.isArray(value))
30
+ return value.map(shape);
31
+ if (!value || typeof value !== 'object')
32
+ return value;
33
+ return Object.fromEntries(Object.entries(value)
34
+ .filter(([key]) => ![
35
+ 'start',
36
+ 'end',
37
+ 'loc',
38
+ 'extra',
39
+ 'comments',
40
+ 'leadingComments',
41
+ 'trailingComments',
42
+ 'innerComments',
43
+ 'tokens',
44
+ ].includes(key))
45
+ .map(([key, child]) => [key, shape(child)]));
46
+ }
47
+ export function inspectDevBootstrap(workspace) {
48
+ const html = join(workspace, 'page/index.html');
49
+ if (!existsSync(html))
50
+ return 'uncertain';
51
+ let source;
52
+ try {
53
+ source = readFileSync(html, 'utf8');
54
+ }
55
+ catch {
56
+ return 'uncertain';
57
+ }
58
+ const scripts = [];
59
+ let inlineCount = 0, invalidInline = false;
60
+ const visitHtml = (node) => {
61
+ if (node.tagName === 'script') {
62
+ const attrs = new Map(node.attrs.map((a) => [a.name, a.value]));
63
+ if (attrs.get('type')?.toLowerCase() === 'module') {
64
+ if (attrs.has('src'))
65
+ scripts.push(attrs.get('src'));
66
+ else {
67
+ inlineCount++;
68
+ const code = node.childNodes
69
+ .map((child) => child.value ?? '')
70
+ .join('');
71
+ if (attrs.size !== 1 || !isRegisteredHmr(code))
72
+ invalidInline = true;
73
+ }
74
+ }
75
+ }
76
+ for (const child of node.childNodes ?? [])
77
+ visitHtml(child);
78
+ };
79
+ visitHtml(parse(source));
80
+ if (invalidInline ||
81
+ inlineCount > 1 ||
82
+ scripts.length !== 1 ||
83
+ !scripts[0] ||
84
+ !/^\/?src\/main\.[cm]?[jt]sx?$/.test(scripts[0]))
85
+ return 'uncertain';
86
+ const entry = join(workspace, 'page', scripts[0].replace(/^\//, ''));
87
+ if (!existsSync(entry))
88
+ return 'uncertain';
89
+ try {
90
+ const ast = parseModule(entry);
91
+ let dynamicImport = false;
92
+ walkAst(ast.program, (n) => {
93
+ if (n.type === 'ImportExpression' ||
94
+ (n.type === 'CallExpression' &&
95
+ n.callee?.type === 'Import'))
96
+ dynamicImport = true;
97
+ });
98
+ const bindings = new Set();
99
+ const namespaces = new Set();
100
+ const hasUnsupportedImport = ast.program.body.some((n) => n.type === 'ImportDeclaration' &&
101
+ ![
102
+ 'react',
103
+ 'react-dom/client',
104
+ '@lark-base-open/base-site-channel/runtime',
105
+ `${sdkPackage}/page`,
106
+ './App',
107
+ './components/database-runtime-ready',
108
+ './lib/database-runtime',
109
+ './index.css',
110
+ ].includes(String(n.source?.value)));
111
+ for (const item of ast.program.body) {
112
+ if (item.type !== 'ImportDeclaration')
113
+ continue;
114
+ const importSource = item.source;
115
+ if (importSource?.value !== `${sdkPackage}/page` ||
116
+ item.importKind === 'type')
117
+ continue;
118
+ for (const specifier of item.specifiers ?? []) {
119
+ const local = specifier.local;
120
+ const imported = specifier.imported;
121
+ if (specifier.type === 'ImportNamespaceSpecifier' && local?.name)
122
+ namespaces.add(String(local.name));
123
+ if (specifier.type === 'ImportSpecifier' &&
124
+ local?.name &&
125
+ (imported?.name ?? imported?.value) === 'startBaseApp' &&
126
+ specifier.importKind !== 'type')
127
+ bindings.add(String(local.name));
128
+ }
129
+ }
130
+ // Only direct top-level expression/initializer calls are provably executed.
131
+ // Calls under functions, conditionals, aliases or computed access fail closed.
132
+ const isStart = (node) => {
133
+ if (!node)
134
+ return false;
135
+ if (node.type === 'AwaitExpression' ||
136
+ (node.type === 'UnaryExpression' && node.operator === 'void'))
137
+ return isStart(node.argument);
138
+ if (node.type !== 'CallExpression' || node.optional)
139
+ return false;
140
+ const callee = node.callee;
141
+ if (callee.type === 'Identifier')
142
+ return bindings.has(String(callee.name));
143
+ return (callee.type === 'MemberExpression' &&
144
+ !callee.computed &&
145
+ callee.object?.type === 'Identifier' &&
146
+ namespaces.has(String(callee.object.name)) &&
147
+ callee.property?.name === 'startBaseApp');
148
+ };
149
+ for (const item of ast.program.body) {
150
+ if (item.type === 'ExpressionStatement' &&
151
+ isStart(item.expression))
152
+ return 'ready';
153
+ if (item.type === 'VariableDeclaration' &&
154
+ item.declarations.some((d) => isStart(d.init)))
155
+ return 'ready';
156
+ // Stop at control flow: later calls may never be reached. Imports/declarations
157
+ // do not execute their bodies, so shadowed parameters cannot count as calls.
158
+ if ([
159
+ 'ThrowStatement',
160
+ 'IfStatement',
161
+ 'TryStatement',
162
+ 'WhileStatement',
163
+ 'ForStatement',
164
+ 'SwitchStatement',
165
+ ].includes(String(item.type)))
166
+ break;
167
+ }
168
+ if (bindings.size ||
169
+ namespaces.size ||
170
+ hasUnsupportedImport ||
171
+ dynamicImport)
172
+ return 'uncertain';
173
+ return 'not-bootstrapped';
174
+ }
175
+ catch {
176
+ return 'uncertain';
177
+ }
178
+ }
@@ -0,0 +1,11 @@
1
+ import { type DevBootstrapStatus } from './page-bootstrap.js';
2
+ import { type LinkGuardWarning } from './page-link-guard.js';
3
+ export { inspectDevBootstrap, sdkPackageRoot, type DevBootstrapStatus, } from './page-bootstrap.js';
4
+ export { checkLinkGuard, type LinkGuardWarning } from './page-link-guard.js';
5
+ export interface PageInspection {
6
+ protocolVersion: 1;
7
+ bootstrap: DevBootstrapStatus;
8
+ warnings: LinkGuardWarning[];
9
+ }
10
+ /** Inspection never follows project links or executes application modules. */
11
+ export declare function inspectPage(workspace: string): PageInspection;
@@ -0,0 +1,49 @@
1
+ import { existsSync, lstatSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { inspectDevBootstrap, } from './page-bootstrap.js';
4
+ import { checkLinkGuard } from './page-link-guard.js';
5
+ export { inspectDevBootstrap, sdkPackageRoot, } from './page-bootstrap.js';
6
+ export { checkLinkGuard } from './page-link-guard.js';
7
+ /** Inspection never follows project links or executes application modules. */
8
+ export function inspectPage(workspace) {
9
+ const result = {
10
+ protocolVersion: 1,
11
+ bootstrap: 'uncertain',
12
+ warnings: [],
13
+ };
14
+ try {
15
+ let files = 0;
16
+ const inspect = (file) => {
17
+ if (++files > 20000)
18
+ throw Error('Page source inspection budget exceeded');
19
+ const info = lstatSync(file);
20
+ if (info.isSymbolicLink())
21
+ throw Error('Page source contains a link');
22
+ if (info.isFile() && info.size > 2 * 1024 * 1024)
23
+ throw Error('Page source file exceeds the inspection budget');
24
+ if (info.isDirectory()) {
25
+ for (const name of readdirSync(file)) {
26
+ if (!['node_modules', 'dist', '.git', '.lark-cli'].includes(name))
27
+ inspect(join(file, name));
28
+ }
29
+ }
30
+ };
31
+ const root = join(workspace, 'page');
32
+ if (existsSync(root))
33
+ inspect(root);
34
+ result.bootstrap = inspectDevBootstrap(workspace);
35
+ result.warnings = checkLinkGuard(workspace).map((warning) => ({
36
+ ...warning,
37
+ locations: warning.locations.slice(0, 100),
38
+ ...(warning.locations.length > 100 ? { locationsTruncated: true } : {}),
39
+ }));
40
+ }
41
+ catch {
42
+ result.warnings.push({
43
+ code: 'PAGE_LINK_GUARD_CHECK_SKIPPED',
44
+ message: 'Page source inspection is unavailable or includes unsupported file entries; inspect the project before relying on this syntax check.',
45
+ locations: [],
46
+ });
47
+ }
48
+ return result;
49
+ }
@@ -0,0 +1,12 @@
1
+ export interface LinkGuardWarning {
2
+ code: 'AI_AGENT_TOOLS_SKIPPED' | 'AI_FUNCTION_ROOT_ABSENT_PRESERVED' | 'FUNCTION_CONTRACT_WARNING' | 'FUNCTION_NEEDS_UPGRADE' | 'PAGE_LINK_GUARD_MISSING' | 'PAGE_LINK_GUARD_CHECK_SKIPPED';
3
+ message: string;
4
+ locations: {
5
+ file: string;
6
+ line: number;
7
+ column: number;
8
+ }[];
9
+ locationsTruncated?: boolean;
10
+ }
11
+ /** Best-effort syntax warning; does not resolve symbols or execute user code. */
12
+ export declare function checkLinkGuard(workspace: string): LinkGuardWarning[];