@lark-base-open/base-database-toolchain 0.0.0-stage → 1.0.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 { extractContract, convertContract } from './contract-extractor.js';
2
+ export { convertLoadedContract } from './contract-conversion.js';
3
+ export { validateTriggerDeclarations } from './trigger-validation.js';
4
+ export { driveLocalDurable, parseDurableEvents } from './durable-runner.js';
5
+ export { runSDKCodegen, SDKCodegenError } from './sdk-codegen.js';
6
+ export { runCompiler } from './go-adapter.mjs';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { extractContract, convertContract } from './contract-extractor.js';
2
+ export { convertLoadedContract } from './contract-conversion.js';
3
+ export { validateTriggerDeclarations } from './trigger-validation.js';
4
+ export { driveLocalDurable, parseDurableEvents } from './durable-runner.js';
5
+ export { runSDKCodegen, SDKCodegenError } from './sdk-codegen.js';
6
+ export { runCompiler } from './go-adapter.mjs';
@@ -0,0 +1,16 @@
1
+ export interface CodegenFile {
2
+ path: string;
3
+ content: string;
4
+ }
5
+ export declare class SDKCodegenError extends Error {
6
+ readonly code: string;
7
+ readonly nextActions: string[];
8
+ constructor(code: string, message: string, nextActions?: string[]);
9
+ toJSON(): {
10
+ code: string;
11
+ message: string;
12
+ nextActions?: string[] | undefined;
13
+ };
14
+ }
15
+ /** Resolve/snapshot reads package bytes only; project modules execute only in the restricted child. */
16
+ export declare function runSDKCodegen(root: string, data: unknown, server?: string): CodegenFile[];
@@ -0,0 +1,208 @@
1
+ import { createRequire } from 'node:module';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, lstatSync, cpSync, mkdirSync, realpathSync, symlinkSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, dirname, relative, isAbsolute, sep } from 'node:path';
6
+ const SDK = '@lark-base-open/base-database-app-sdk';
7
+ export class SDKCodegenError extends Error {
8
+ code;
9
+ nextActions;
10
+ constructor(code, message, nextActions = []) {
11
+ super(`${code}: ${message}`);
12
+ this.code = code;
13
+ this.nextActions = nextActions;
14
+ this.name = 'SDKCodegenError';
15
+ }
16
+ toJSON() {
17
+ return {
18
+ code: this.code,
19
+ message: this.message,
20
+ ...(this.nextActions.length ? { nextActions: this.nextActions } : {}),
21
+ };
22
+ }
23
+ }
24
+ const locations = (root, server) => ['page', server, ''].map((p) => join(root, p, 'package.json'));
25
+ function dependencyRecovery(root) {
26
+ const layout = {
27
+ version: existsSync(join(root, 'server')) ? 2 : 1,
28
+ dependencies: ['page', 'server-functions'],
29
+ };
30
+ const install = layout.version === 2
31
+ ? 'npm ci'
32
+ : layout.dependencies
33
+ .map((directory) => `npm ci --prefix ${directory}`)
34
+ .join('; ');
35
+ return [
36
+ `From the project root, restore dependencies from the existing manifests and lockfiles: ${install}. Keep the declared SDK version unchanged.`,
37
+ 'If dependencies are already installed but the SDK lacks codegen, keep the current SDK and upgrade only with user authorization; follow its Migration instructions.',
38
+ 'Once codegen is available, use the same CLI and environment to run contracts generate, then check --json.',
39
+ ];
40
+ }
41
+ function unavailable(root, missingExport = false) {
42
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', missingExport
43
+ ? 'The installed SDK codegen does not export generateFunctionClients.'
44
+ : 'Cannot resolve the installed SDK codegen entry. Project dependencies may not be installed, or the installed SDK may not provide codegen.', missingExport
45
+ ? dependencyRecovery(root).slice(1)
46
+ : dependencyRecovery(root));
47
+ }
48
+ // Node 24 removed the experimental spelling; early Node 22 releases only have it.
49
+ const permissionFlag = process.allowedNodeEnvironmentFlags.has('--permission')
50
+ ? '--permission'
51
+ : '--experimental-permission';
52
+ /** Resolve/snapshot reads package bytes only; project modules execute only in the restricted child. */
53
+ export function runSDKCodegen(root, data, server = 'server') {
54
+ let entry;
55
+ for (const path of locations(root, server)) {
56
+ try {
57
+ entry = createRequire(path).resolve(`${SDK}/codegen`);
58
+ break;
59
+ }
60
+ catch { }
61
+ }
62
+ if (!entry)
63
+ unavailable(root);
64
+ const temp = realpathSync(mkdtempSync(join(tmpdir(), 'base-codegen-')));
65
+ try {
66
+ let packageRoot = dirname(entry);
67
+ while (!existsSync(join(packageRoot, 'package.json')) ||
68
+ JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'))
69
+ .name !== SDK) {
70
+ const parent = dirname(packageRoot);
71
+ if (parent === packageRoot)
72
+ unavailable(root);
73
+ packageRoot = parent;
74
+ }
75
+ snapshotPackage(packageRoot, join(temp, 'node_modules', SDK), new Map());
76
+ writeFileSync(join(temp, 'input.json'), JSON.stringify(data));
77
+ writeFileSync(join(temp, 'worker.cjs'), `
78
+ 'use strict';
79
+ globalThis.fetch = () => { throw new Error('NETWORK_DISABLED'); };
80
+ globalThis.WebSocket = undefined;
81
+ (async () => {
82
+ try {
83
+ const input = JSON.parse(require('node:fs').readFileSync(__dirname + '/input.json','utf8'));
84
+ const sdk = require('@lark-base-open/base-database-app-sdk/codegen');
85
+ if (typeof sdk.generateFunctionClients !== 'function') throw Object.assign(new Error('SDK codegen export missing'),{code:'SDK_CODEGEN_UNAVAILABLE'});
86
+ const files = await sdk.generateFunctionClients(input);
87
+ process.stdout.write(JSON.stringify({ok:true,files}));
88
+ } catch (error) {
89
+ process.stdout.write(JSON.stringify({ok:false,code:typeof error.code === 'string' ? error.code : 'SDK_CODEGEN_FAILED',message:String(error.message).slice(0,4096)}));
90
+ }
91
+ })();
92
+ `);
93
+ let result;
94
+ try {
95
+ result = JSON.parse(execFileSync(process.execPath, [
96
+ permissionFlag,
97
+ `--allow-fs-read=${temp}`,
98
+ '--max-old-space-size=128',
99
+ join(temp, 'worker.cjs'),
100
+ ], {
101
+ cwd: temp,
102
+ env: {},
103
+ encoding: 'utf8',
104
+ timeout: 5000,
105
+ maxBuffer: 4 * 1024 * 1024,
106
+ stdio: ['ignore', 'pipe', 'pipe'],
107
+ }));
108
+ }
109
+ catch (error) {
110
+ const stderr = String(error.stderr ?? '')
111
+ .trim()
112
+ .slice(0, 1024);
113
+ throw new SDKCodegenError('SDK_CODEGEN_FAILED', `Isolated SDK codegen failed, timed out, or returned invalid JSON${stderr ? `: ${stderr}` : ''}`);
114
+ }
115
+ if (!result.ok &&
116
+ result.code === 'SDK_CODEGEN_UNAVAILABLE' &&
117
+ result.message === 'SDK codegen export missing')
118
+ unavailable(root, true);
119
+ if (!result.ok)
120
+ throw new SDKCodegenError(result.code ?? 'SDK_CODEGEN_FAILED', (result.message ?? 'SDK codegen failed') +
121
+ (result.code === 'CONTRACT_DATA_INVALID'
122
+ ? '; The installed SDK rejected the contract. Verify the CLI/SDK pairing and upgrade to an SDK with structural Schema validation before regenerating; do not rename valid business fields or hand-edit generated files.'
123
+ : ''));
124
+ const allowed = new Set([
125
+ 'page/src/generated/functions.ts',
126
+ 'page/src/generated/function-inputs.ts',
127
+ 'page/src/lib/database-function-inputs.generated.ts',
128
+ 'page/src/lib/function-input-map.generated.ts',
129
+ ]);
130
+ const seen = new Set();
131
+ if (!Array.isArray(result.files) ||
132
+ !result.files.length ||
133
+ result.files.length > 3)
134
+ throw new SDKCodegenError('SDK_CODEGEN_OUTPUT_INVALID', 'Invalid generated file list');
135
+ for (const file of result.files) {
136
+ if (!file ||
137
+ typeof file.path !== 'string' ||
138
+ !allowed.has(file.path) ||
139
+ seen.has(file.path) ||
140
+ typeof file.content !== 'string' ||
141
+ Buffer.byteLength(file.content) > 1024 * 1024)
142
+ throw new SDKCodegenError('SDK_CODEGEN_OUTPUT_INVALID', 'Invalid generated path or content');
143
+ const parts = file.path.split('/');
144
+ for (let i = 1; i <= parts.length; i++) {
145
+ const target = join(root, ...parts.slice(0, i));
146
+ if (existsSync(target) && lstatSync(target).isSymbolicLink())
147
+ throw new SDKCodegenError('SDK_CODEGEN_OUTPUT_INVALID', 'Generated destinations cannot be symbolic links');
148
+ }
149
+ seen.add(file.path);
150
+ }
151
+ return result.files;
152
+ }
153
+ finally {
154
+ rmSync(temp, { recursive: true, force: true });
155
+ }
156
+ }
157
+ function resolvePackage(name, from) {
158
+ if (!/^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/.test(name) ||
159
+ name === '.' ||
160
+ name === '..')
161
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', 'Invalid SDK dependency name');
162
+ let directory = from;
163
+ while (true) {
164
+ const candidate = join(directory, 'node_modules', name);
165
+ if (existsSync(join(candidate, 'package.json')))
166
+ return realpathSync(candidate);
167
+ const parent = dirname(directory);
168
+ if (parent === directory)
169
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', `Missing installed SDK dependency: ${name}. Restore this project's existing locked dependencies and keep the SDK version unchanged.`);
170
+ directory = parent;
171
+ }
172
+ }
173
+ function snapshotPackage(source, destination, copied) {
174
+ source = realpathSync(source);
175
+ mkdirSync(dirname(destination), { recursive: true });
176
+ const previous = copied.get(source);
177
+ if (previous) {
178
+ // Windows junctions reuse snapshot directories without symlink privileges.
179
+ symlinkSync(previous, destination, process.platform === 'win32' ? 'junction' : 'dir');
180
+ return;
181
+ }
182
+ copied.set(source, destination);
183
+ cpSync(source, destination, {
184
+ recursive: true,
185
+ dereference: true,
186
+ filter: (path) => {
187
+ const parts = relative(source, path).split(/[\\/]/);
188
+ if (parts.some((p) => [
189
+ 'node_modules',
190
+ '.git',
191
+ '.npmrc',
192
+ '.pnpmrc',
193
+ '.yarnrc',
194
+ '.yarnrc.yml',
195
+ ].includes(p) ||
196
+ p === '.env' ||
197
+ p.startsWith('.env.')))
198
+ return false;
199
+ const real = realpathSync(path), rel = relative(source, real);
200
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
201
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', 'SDK package contains external symbolic links');
202
+ return true;
203
+ },
204
+ });
205
+ const pkg = JSON.parse(readFileSync(join(source, 'package.json'), 'utf8'));
206
+ for (const name of Object.keys(pkg.dependencies ?? {}))
207
+ snapshotPackage(resolvePackage(name, source), join(destination, 'node_modules', name), copied);
208
+ }
@@ -0,0 +1,75 @@
1
+ /** meta.json declarations; calendar and timezone semantics belong to deployment. */
2
+ export declare const triggerDeclarationsSchema: {
3
+ type: string;
4
+ items: {
5
+ type: string;
6
+ additionalProperties: boolean;
7
+ required: string[];
8
+ properties: {
9
+ id: {
10
+ type: string;
11
+ pattern: string;
12
+ };
13
+ type: {
14
+ const: string;
15
+ };
16
+ enabled: {
17
+ type: string;
18
+ };
19
+ input: {
20
+ type: string;
21
+ };
22
+ timer: {
23
+ type: string;
24
+ additionalProperties: boolean;
25
+ required: string[];
26
+ properties: {
27
+ startAt: {
28
+ type: string;
29
+ minLength: number;
30
+ };
31
+ timezone: {
32
+ type: string;
33
+ minLength: number;
34
+ };
35
+ endDate: {
36
+ type: string;
37
+ minLength: number;
38
+ };
39
+ repeat: {
40
+ type: string;
41
+ additionalProperties: boolean;
42
+ required: string[];
43
+ properties: {
44
+ unit: {
45
+ enum: string[];
46
+ };
47
+ interval: {
48
+ type: string;
49
+ minimum: number;
50
+ maximum: number;
51
+ };
52
+ };
53
+ allOf: {
54
+ if: {
55
+ properties: {
56
+ unit: {
57
+ enum: string[];
58
+ };
59
+ };
60
+ };
61
+ then: {
62
+ properties: {
63
+ interval: {
64
+ const: number;
65
+ };
66
+ };
67
+ };
68
+ }[];
69
+ };
70
+ };
71
+ };
72
+ };
73
+ };
74
+ };
75
+ export declare function validateTriggerDeclarations(value: unknown, inputSchema: Record<string, unknown>, path: string, seen: Set<string>): void;
@@ -0,0 +1,73 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ /** meta.json declarations; calendar and timezone semantics belong to deployment. */
3
+ export const triggerDeclarationsSchema = {
4
+ type: 'array',
5
+ items: {
6
+ type: 'object',
7
+ additionalProperties: false,
8
+ required: ['id', 'type', 'timer'],
9
+ properties: {
10
+ id: { type: 'string', pattern: '^[A-Za-z0-9_-]{1,64}$' },
11
+ type: { const: 'timer' },
12
+ enabled: { type: 'boolean' },
13
+ input: { type: 'object' },
14
+ timer: {
15
+ type: 'object',
16
+ additionalProperties: false,
17
+ required: ['startAt', 'timezone', 'repeat'],
18
+ properties: {
19
+ startAt: { type: 'string', minLength: 1 },
20
+ timezone: { type: 'string', minLength: 1 },
21
+ endDate: { type: 'string', minLength: 1 },
22
+ repeat: {
23
+ type: 'object',
24
+ additionalProperties: false,
25
+ required: ['unit', 'interval'],
26
+ properties: {
27
+ unit: {
28
+ enum: [
29
+ 'NONE',
30
+ 'MINUTE',
31
+ 'HOUR',
32
+ 'DAY',
33
+ 'WEEK',
34
+ 'MONTH',
35
+ 'YEAR',
36
+ 'WEEKDAY',
37
+ ],
38
+ },
39
+ interval: { type: 'integer', minimum: 1, maximum: 1000 },
40
+ },
41
+ allOf: [
42
+ {
43
+ if: { properties: { unit: { enum: ['NONE', 'WEEKDAY'] } } },
44
+ then: { properties: { interval: { const: 1 } } },
45
+ },
46
+ ],
47
+ },
48
+ },
49
+ },
50
+ },
51
+ },
52
+ };
53
+ const ajv = new Ajv2020({
54
+ allErrors: true,
55
+ strict: false,
56
+ validateFormats: false,
57
+ });
58
+ const validateDeclarations = ajv.compile(triggerDeclarationsSchema);
59
+ export function validateTriggerDeclarations(value, inputSchema, path, seen) {
60
+ if (value === undefined)
61
+ return;
62
+ if (!validateDeclarations(value))
63
+ throw new Error(`TRIGGER_INVALID: ${path}/triggers: ${ajv.errorsText(validateDeclarations.errors)}`);
64
+ const validateInput = ajv.compile(inputSchema);
65
+ for (const [index, trigger] of value.entries()) {
66
+ const location = `${path}/triggers/${index}`;
67
+ if (seen.has(trigger.id))
68
+ throw new Error(`TRIGGER_ID_DUPLICATE: ${location}/id: ${trigger.id}`);
69
+ seen.add(trigger.id);
70
+ if (!validateInput(trigger.input ?? {}))
71
+ throw new Error(`INPUT_INVALID: ${location}/input: ${ajv.errorsText(validateInput.errors)}`);
72
+ }
73
+ }