Headless 3D and VFX engine for agents. Research preview.
// Generate CLI implementation, dispatch and help from the SDK declarations.
import ts from 'typescript';
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
const modules = ['validate', 'constants', 'math', 'shapes', 'text', 'extrude'];
// Native loaders in crates/vork-std: only their help is generated here.
const native = ['text', 'extrude'];
const paths = modules.map(name => fileURLToPath(new URL(`src/lib/${name}.ts`, import.meta.url)));
const program = ts.createProgram(paths, {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, strict: true});
const checker = program.getTypeChecker();
let output = '// Generated by packages/ts/generate-std.mjs; edit the TypeScript sources.\n';
let help = "argument: JSON; '-'=stdin\nresult: JSON\nexpand: scene JSON → scene JSON with buffer geometry; font paths relative to working directory\ntypes: Scene,Node,Track,Layer,Material; JSON Schema\n";
function typeName(type) {
if (type.isIntersection() || ['Pick','Omit','Required'].includes(type.aliasSymbol?.name)) {
return '{'+checker.getPropertiesOfType(type).map(symbol => field(symbol.name,
checker.getTypeOfSymbolAtLocation(symbol,symbol.valueDeclaration ?? symbol.declarations[0]),
!!(symbol.flags & ts.SymbolFlags.Optional))).join(',')+'}';
}
return checker.typeToString(type).replace(/\s*\|\s*undefined/g, '').replace(/readonly /g, '')
.replace(/\bV2\b/g, 'vec2').replace(/\b(?:V3|Vec3)\b/g, 'vec3').replace(/\[number, number\]/g, 'vec2').replace(/\s*\|\s*/g,'|')
.replace(/\bTimes\b/g,'(number[]|buffer-name)').replace(/\bValues\b/g,'(value[]|buffer-name)');
}
function defaultValue(node) {
if (!node) return '';
if (ts.isIdentifier(node)) {
let symbol = checker.getSymbolAtLocation(node);
if (symbol?.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
return defaultValue(symbol?.valueDeclaration?.initializer);
}
return node.getText().replace(/\s+/g, '');
}
function field(name, type, optional, initializer) {
const value = defaultValue(initializer);
return `${name}${optional ? '?' : ''}:${typeName(type)}${value ? '='+value : ''}`;
}
function objectFields(parameter) {
return checker.getPropertiesOfType(checker.getTypeAtLocation(parameter)).map(symbol => {
const binding = ts.isObjectBindingPattern(parameter.name) ? parameter.name.elements.find(element =>
(element.propertyName ?? element.name).getText() === symbol.name) : undefined;
return field(jsonName(symbol.name), checker.getTypeOfSymbolAtLocation(symbol,parameter), !!(symbol.flags & ts.SymbolFlags.Optional),binding?.initializer);
});
}
function exportedFunctions(source) {
const result = [];
for (const statement of source.statements) {
if (!statement.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword)) continue;
if (ts.isFunctionDeclaration(statement)) result.push({fn:statement,name:statement.name.text});
if (ts.isVariableStatement(statement)) for (const declaration of statement.declarationList.declarations) {
if (!declaration.initializer || !ts.isObjectLiteralExpression(declaration.initializer)) continue;
for (const method of declaration.initializer.properties) if (ts.isMethodDeclaration(method)) {
result.push({fn:method,name:`${declaration.name.getText()}.${method.name.getText()}`});
}
}
}
return result;
}
const entries = [];
// CLI/std JSON keys retain snake_case; TypeScript parameter names are camelCase.
const jsonName = name => name.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase());
for (const [index, path] of paths.entries()) {
const source = program.getSourceFile(path);
if (!native.includes(modules[index])) output += ts.transpileModule(source.text, {compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext}}).outputText
.replace(/^import .*;\s*$/gm, '').replace(/^export \{\};\s*$/gm, '').replace(/\bexport /g, '') + '\n';
if (['validate', 'constants', 'math'].includes(modules[index])) continue;
for (const declaration of source.statements) {
if (ts.isTypeAliasDeclaration(declaration) && ['GeometryFragment'].includes(declaration.name.text)) {
const type = checker.getTypeAtLocation(declaration);
help += `${declaration.name.text}: {${checker.getPropertiesOfType(type).map(symbol => field(symbol.name,
checker.getTypeOfSymbolAtLocation(symbol,symbol.valueDeclaration ?? symbol.declarations[0]),
!!(symbol.flags & ts.SymbolFlags.Optional))).join(',')}}\n`;
}
}
for (const {fn,name: identifier} of exportedFunctions(source)) {
// vork tokens are snake_case; TS keeps its own identifier (roundedBox -> rounded_box).
const name = identifier;
const token = identifier.replace(/[A-Z]/g, letter => '_' + letter.toLowerCase());
const parameters = fn.parameters;
const namedOptions = parameters.some(p => ts.isObjectBindingPattern(p.name)) ||
(parameters.length === 2 && parameters[0].name.getText() === 'name' &&
checker.getPropertiesOfType(checker.getTypeAtLocation(parameters[1])).length > 0);
let allowed = [], signature = [], expression;
const props = parameter => checker.getPropertiesOfType(checker.getTypeAtLocation(parameter)).map(symbol => ({name:symbol.name, optional:!!(symbol.flags & ts.SymbolFlags.Optional)}));
if (parameters.length === 1 && (parameters[0].dotDotDotToken || checker.isArrayType(checker.getTypeAtLocation(parameters[0])))) {
allowed = null;
signature = [`${parameters[0].name.getText()} array`];
expression = `${name}(${parameters[0].dotDotDotToken ? '...' : ''}args)`;
} else if (parameters.length === 1 && parameters[0].name.getText() === 'options') {
const fields = props(parameters[0]);
allowed = fields.map(f => f.name); signature = fields.map(f => f.name+(f.optional?'?':''));
expression = `${name}(args)`;
} else if (namedOptions) {
const fields = props(parameters[1]);
allowed = ['name', ...fields.map(f => f.name)]; signature = [parameters[0].initializer ? 'name?' : 'name', ...fields.map(f => f.name+(f.optional?'?':''))];
expression = `(({name,...options}) => ${name}(name,options))(args)`;
} else {
allowed = parameters.map(p => jsonName(p.name.getText()));
signature = parameters.map(p => jsonName(p.name.getText())+(p.initializer || p.questionToken ? '?' : ''));
expression = `${name}(${allowed.map(key => `args[${JSON.stringify(key)}]`).join(',')})`;
}
let input;
if (allowed === null) input = typeName(checker.getTypeAtLocation(parameters[0]));
else if (parameters.length === 1 && parameters[0].name.getText() === 'options') input = `{${objectFields(parameters[0]).join(',')}}`;
else if (namedOptions) input = `{${field('name',checker.getTypeAtLocation(parameters[0]),!!parameters[0].initializer,parameters[0].initializer)},${objectFields(parameters[1]).join(',')}}`;
else input = `{${parameters.map(parameter => field(jsonName(parameter.name.getText()),checker.getTypeAtLocation(parameter),!!(parameter.initializer || parameter.questionToken),parameter.initializer)).join(',')}}`;
const returnType = checker.getReturnTypeOfSignature(checker.getSignatureFromDeclaration(fn));
const result = fn.type && ts.isTypeReferenceNode(fn.type) && fn.type.typeName.getText() === 'GeometryFragment'
? 'GeometryFragment' : typeName(returnType);
const facts = checker.getSymbolAtLocation(fn.name).getJsDocTags(checker).filter(tag => tag.name === 'help')
.map(tag => ts.displayPartsToString(tag.text));
help += `${token}: ${input} → ${result}${facts.map(fact => '; '+fact).join('')}\n`;
if (native.includes(modules[index])) continue;
entries.push(`${JSON.stringify(token)}: {keys:${JSON.stringify(allowed)}, required:${JSON.stringify(allowed===null ? [] : signature.filter(key => !key.endsWith('?')))}, invoke: args => ${expression}}`);
}
}
output += `const stdFunctions = {${entries.join(',\n')}};\nfunction stdEvaluate(name,args) {\n if (!Object.hasOwn(stdFunctions,name)) throw new Error('unknown standard-library function '+name+'; see vork help std');\n const fn=stdFunctions[name];\n if (fn.keys === null) { if (!Array.isArray(args)) throw new TypeError('argument must be an array'); }\n else { checkOptions(args,fn.keys); for (const key of fn.required) if (!Object.hasOwn(args,key)) throw new TypeError('missing option: '+key); }\n return fn.invoke(args);\n}\n`;
// The starting page keeps three builders; all other signatures live in the advanced std reference.
const shapeLines = help.split('\n').filter(line => /^(box|sphere|cylinder|cone|torus|capsule|rounded_box|grid|revolve|text|extrude):/.test(line));
const apiShapeLines = shapeLines.filter(line => /^(box|sphere|grid):/.test(line));
const indexPath = new URL('../../docs/help/index.md', import.meta.url);
const index = readFileSync(indexPath, 'utf8').replace(
/<!-- generated-shapes:start -->[\s\S]*?<!-- generated-shapes:end -->/,
'<!-- generated-shapes:start -->\n'+apiShapeLines.join('\n')+'\n<!-- generated-shapes:end -->');
if (process.argv.includes('--check')) {
if (readFileSync(indexPath, 'utf8') !== index) throw new Error('stale API shapes');
} else writeFileSync(indexPath, index);
const libraryPath = new URL('../../libraries/std/HELP.txt', import.meta.url);
const library = readFileSync(libraryPath, 'utf8').replace(
/<!-- generated-shapes:start -->[\s\S]*?<!-- generated-shapes:end -->/,
'<!-- generated-shapes:start -->\n'+shapeLines.filter(line => !apiShapeLines.includes(line)).join('\n')+'\n<!-- generated-shapes:end -->');
if (process.argv.includes('--check')) {
if (readFileSync(libraryPath, 'utf8') !== library) throw new Error('stale std reference shapes');
} else writeFileSync(libraryPath, library);
help = help.split('\n').filter(line => !shapeLines.includes(line) && !/^(argument:|result:|types:|GeometryFragment:)/.test(line)).join('\n');
for (const [file, content] of [['sdk.js',output],['help.txt',help]]) {
const path = new URL(`../../crates/vork-std/src/${file}`, import.meta.url);
if (process.argv.includes('--check')) {
if (readFileSync(path, 'utf8') !== content) throw new Error('stale std bundle: node packages/ts/generate-std.mjs');
} else writeFileSync(path,content);
}