pomljs
Version:
Prompt Orchestration Markup Language
193 lines (190 loc) • 6.34 kB
JavaScript
import * as React from 'react';
import { readFileSync, writeFileSync } from 'fs';
import path__default from 'path';
import { EnvironmentDispatcher } from './writer.js';
import { ErrorCollection, SystemError, StyleSheetProvider } from './base.js';
export { richContentFromSourceMap } from './base.js';
import { PomlFile } from './file.js';
import './presentation.js';
import './essentials.js';
import './components/table.js';
import './components/instructions.js';
import './components/utils.js';
import './components/document.js';
import './components/message.js';
import './components/tree.js';
import './components/webpage.js';
import { reactRender } from './util/reactRender.js';
import { setTrace, parseJsonWithBuffers, isTracing, dumpTrace } from './util/trace.js';
export { clearTrace } from './util/trace.js';
const read = async (element, options, context, stylesheet, sourcePath) => {
let readElement;
if (typeof element === 'string') {
readElement = new PomlFile(element, options, sourcePath).react(context);
}
else {
if (options || context) {
console.warn('Options and context are ignored when element is React.ReactElement');
}
readElement = element;
}
if (stylesheet) {
readElement = React.createElement(StyleSheetProvider, { stylesheet }, readElement);
}
return await reactRender(readElement);
};
/**
* Entry point for turning a parsed IR string into rich content or a list of
* speaker messages. The heavy lifting is done by `EnvironmentDispatcher`.
*/
function write(ir, options) {
const writer = new EnvironmentDispatcher();
if (options?.speaker) {
return writer.writeMessages(ir);
}
else {
return writer.write(ir);
}
}
/**
* Variant of {@link write} that also exposes a source map describing the
* mapping between input indices and output content.
*/
function writeWithSourceMap(ir, options) {
const writer = new EnvironmentDispatcher();
if (options?.speaker) {
return writer.writeMessagesWithSourceMap(ir);
}
else {
return writer.writeWithSourceMap(ir);
}
}
const poml = async (element) => {
ErrorCollection.clear();
const readResult = await read(element);
const result = write(readResult);
if (!ErrorCollection.empty()) {
throw ErrorCollection.first();
}
return result;
};
async function commandLine(args) {
const readOptions = {
trim: args.trim,
};
if (args.traceDir) {
setTrace(true, args.traceDir);
}
// Determine the working directory
let workingDirectory;
if (args.cwd) {
workingDirectory = path__default.resolve(args.cwd);
}
else {
workingDirectory = process.cwd();
}
let input;
let sourcePath;
if (args.input && args.file) {
throw new Error('Cannot specify both input and file');
}
else if (args.input) {
input = args.input;
}
else if (args.file) {
const filePath = path__default.resolve(workingDirectory, args.file);
input = readFileSync(filePath, { encoding: 'utf8' });
sourcePath = filePath;
}
else {
throw new Error('Must specify either input or file');
}
let context = {};
if (args.context) {
for (const pair of args.context) {
if (!pair.includes('=')) {
throw new Error(`Invalid context variable, must include one '=': ${pair}`);
}
const [key, value] = pair.split('=', 2);
context[key] = value;
}
}
else if (args.contextFile) {
const contextFilePath = path__default.resolve(workingDirectory, args.contextFile);
const contextFromFile = parseJsonWithBuffers(readFileSync(contextFilePath, { encoding: 'utf8' }));
context = { ...context, ...contextFromFile };
}
let stylesheet = {};
if (args.stylesheetFile) {
const stylesheetFilePath = path__default.resolve(workingDirectory, args.stylesheetFile);
stylesheet = { ...stylesheet, ...parseJsonWithBuffers(readFileSync(stylesheetFilePath, { encoding: 'utf8' })) };
}
if (args.stylesheet) {
stylesheet = { ...stylesheet, ...JSON.parse(args.stylesheet) };
}
ErrorCollection.clear();
const ir = await read(input, readOptions, context, stylesheet, sourcePath);
const speakerMode = args.speakerMode === true || args.speakerMode === undefined;
const prettyPrint = args.prettyPrint === true;
let output = '';
let result;
if (prettyPrint) {
if (speakerMode) {
result = write(ir, { speaker: true });
const outputs = result.map((message) => {
return `===== ${message.speaker} =====\n\n${renderContent(message.content)}`;
});
output = outputs.join('\n\n');
}
else {
result = write(ir);
output = renderContent(result);
}
}
else {
result = write(ir, { speaker: speakerMode });
output = JSON.stringify(result);
}
if (isTracing()) {
try {
dumpTrace(input, context, stylesheet, result, sourcePath);
}
catch (err) {
ErrorCollection.add(new SystemError('Failed to dump trace', { cause: err }));
}
}
if (args.strict === true || args.strict === undefined) {
if (!ErrorCollection.empty()) {
throw ErrorCollection.first();
}
}
if (args.output) {
const outputPath = path__default.resolve(workingDirectory, args.output);
writeFileSync(outputPath, output);
}
else {
process.stdout.write(output);
}
}
const renderContent = (content) => {
if (typeof content === 'string') {
return content;
}
const outputs = content.map((part) => {
if (typeof part === 'string') {
return part;
}
else {
const media = JSON.stringify(part);
if (media.length > 100) {
return media.slice(0, 100) + '...';
}
else {
return media;
}
}
});
return outputs.join('\n\n');
};
export { commandLine, dumpTrace, parseJsonWithBuffers, poml, read, setTrace, write, writeWithSourceMap };
//# sourceMappingURL=index.js.map