Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 3x 3x 1x 5x 5x 5x 1x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 1x 30x 30x 30x 30x 30x 30x 27x 3x 3x 30x 30x 30x 27x 30x 30x 30x 30x 30x 3x 2x 1x 27x 27x 27x 27x 2x 25x 25x 31x 31x 1x 30x 30x 2x 30x 29x 29x 1x 1x | import { promises as fs } from 'fs';
import { exec } from 'child_process';
import { promisify } from 'util';
import * as path from 'path';
import { generateDeckId } from './deck-id';
import { replaceTemplatePlaceholders } from './template-processor';
const execAsync = promisify(exec);
/**
* Result of deck generation
*/
export interface GenerateDeckResult {
deckId: string;
deckUrl: string;
}
/**
* Options for deck generation
*/
export interface GenerateDeckOptions {
/** Template ID to use (e.g., 'starter') */
templateId: string;
/** Data to replace placeholders in the template */
data: Record<string, any>;
/** Session ID for tracking (not used for now, reserved for Stream C) */
sessionId?: string;
/** Build timeout in milliseconds (default: 60000) */
buildTimeout?: number;
/** Base URL for slides (default: 'https://slides.buzztrail.ai') */
baseUrl?: string;
}
/**
* Error thrown when template is not found
*/
export class TemplateNotFoundError extends Error {
constructor(templateId: string) {
super(`Template not found: ${templateId}`);
this.name = 'TemplateNotFoundError';
}
}
/**
* Error thrown when build times out
*/
export class BuildTimeoutError extends Error {
constructor(timeout: number) {
super(`Slidev build timed out after ${timeout}ms`);
this.name = 'BuildTimeoutError';
}
}
/**
* Error thrown when build fails
*/
export class BuildError extends Error {
constructor(message: string, public originalError?: Error) {
super(message);
this.name = 'BuildError';
}
}
/**
* Generate a Slidev deck from a template
*
* This function orchestrates the full pipeline:
* 1. Load template from apps/slidev-templates/src/default/{templateId}/slides.md
* 2. Replace placeholders with provided data
* 3. Create temp build directory (/tmp/slidev-build-{deckId})
* 4. Build Slidev with correct base path (--base /d/{deckId})
* 5. Copy built files to apps/slide-server/assets/decks/{deckId}
* 6. Clean up temp directory (even on errors)
*
* Note: Supabase integration will be added in Stream C
*
* @param options - Configuration for deck generation
* @returns Promise with deckId and deckUrl
* @throws {TemplateNotFoundError} If template doesn't exist
* @throws {BuildTimeoutError} If build exceeds timeout
* @throws {BuildError} If build fails for other reasons
*
* @example
* const result = await generateDeck({
* templateId: 'starter',
* data: {
* COMPANY_NAME: 'Acme Corp',
* INDUSTRY: 'Technology'
* },
* sessionId: 'session-123'
* });
* console.log(result.deckUrl); // https://slides.buzztrail.ai/d/a3b2-c5d9-e7f1
*/
export async function generateDeck(
options: GenerateDeckOptions
): Promise<GenerateDeckResult> {
const {
templateId,
data,
buildTimeout = 60000,
baseUrl = 'https://slides.buzztrail.ai',
} = options;
// Generate unique deck ID
const deckId = generateDeckId();
// Get absolute paths - resolve relative to project root
const projectRoot = path.resolve(__dirname, '../..');
const templatePath = path.join(
projectRoot,
'apps/slidev-templates/src/default',
templateId
);
const slidesPath = path.join(templatePath, 'slides.md');
const outputPath = path.join(
projectRoot,
'apps/slide-server/assets/decks',
deckId
);
const tempDir = `/tmp/slidev-build-${deckId}`;
try {
// 1. Validate template exists
try {
await fs.access(slidesPath);
} catch (error) {
throw new TemplateNotFoundError(templateId);
}
// 2. Load template
const templateContent = await fs.readFile(slidesPath, 'utf-8');
// 3. Replace placeholders
const processedContent = replaceTemplatePlaceholders(templateContent, data);
// 4. Create temp build directory
await fs.mkdir(tempDir, { recursive: true });
// 5. Copy template files to temp directory
// We need to copy package.json and other necessary files
const packageJsonPath = path.join(templatePath, 'package.json');
try {
await fs.access(packageJsonPath);
await fs.copyFile(
packageJsonPath,
path.join(tempDir, 'package.json')
);
} catch (error) {
// If no package.json, create a minimal one
const minimalPackageJson = {
name: `slidev-deck-${deckId}`,
type: 'module',
scripts: {
build: 'slidev build',
},
};
await fs.writeFile(
path.join(tempDir, 'package.json'),
JSON.stringify(minimalPackageJson, null, 2)
);
}
// Copy setup directory if it exists
const setupDir = path.join(templatePath, 'setup');
try {
await fs.access(setupDir);
await execAsync(`cp -r "${setupDir}" "${tempDir}/setup"`);
} catch (error) {
// Setup directory is optional
}
// Write processed slides.md
await fs.writeFile(path.join(tempDir, 'slides.md'), processedContent);
// 6. Build Slidev with timeout
const basePath = `/d/${deckId}`;
const buildCommand = `cd "${tempDir}" && pnpx slidev build --base "${basePath}" --out dist`;
try {
await execWithTimeout(buildCommand, buildTimeout);
} catch (error) {
if (error instanceof BuildTimeoutError) {
throw error;
}
throw new BuildError(
`Slidev build failed: ${error instanceof Error ? error.message : String(error)}`,
error instanceof Error ? error : undefined
);
}
// 7. Copy built files to assets folder
await fs.mkdir(outputPath, { recursive: true });
const distPath = path.join(tempDir, 'dist');
// Verify dist directory was created
try {
await fs.access(distPath);
} catch (error) {
throw new BuildError('Build completed but dist directory was not created');
}
await execAsync(`cp -r "${distPath}"/* "${outputPath}"/`);
// 8. Return result (without Supabase call - that's Stream C)
return {
deckId,
deckUrl: `${baseUrl}/d/${deckId}`,
};
} finally {
// 9. Cleanup temp directory (even on errors)
try {
await fs.rm(tempDir, { recursive: true, force: true });
} catch (error) {
// Log but don't throw - cleanup errors shouldn't fail the operation
console.error(`Failed to cleanup temp directory ${tempDir}:`, error);
}
}
}
/**
* Execute a command with timeout
*
* @param command - Command to execute
* @param timeoutMs - Timeout in milliseconds
* @returns Promise with command output
* @throws {BuildTimeoutError} If command exceeds timeout
*/
async function execWithTimeout(
command: string,
timeoutMs: number
): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new BuildTimeoutError(timeoutMs));
}, timeoutMs);
execAsync(command)
.then(result => {
clearTimeout(timeout);
resolve(result);
})
.catch(error => {
clearTimeout(timeout);
reject(error);
});
});
}
|