@edenapp/genesis 0.4.0 → 0.5.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.
package/dist/bundler.js CHANGED
@@ -15,570 +15,517 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
35
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
27
  };
38
28
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.GenesisBundler = void 0;
40
- const fs = __importStar(require("fs/promises"));
41
- const fs_1 = require("fs");
42
- const path = __importStar(require("path"));
43
- const crypto = __importStar(require("crypto"));
44
- const child_process_1 = require("child_process");
45
- const util_1 = require("util");
46
- const tar = __importStar(require("tar"));
29
+ exports.executeBuild = executeBuild;
30
+ exports.validateManifest = validateManifest;
31
+ exports.verifyFiles = verifyFiles;
32
+ exports.bundle = bundle;
33
+ exports.getInfo = getInfo;
34
+ exports.extract = extract;
35
+ const node_child_process_1 = require("node:child_process");
36
+ const crypto = __importStar(require("node:crypto"));
37
+ const node_fs_1 = require("node:fs");
38
+ const fs = __importStar(require("node:fs/promises"));
39
+ const path = __importStar(require("node:path"));
40
+ const node_util_1 = require("node:util");
47
41
  const cli_progress_1 = __importDefault(require("cli-progress"));
42
+ const tar = __importStar(require("tar"));
48
43
  const compression_1 = require("./compression");
49
- const execAsync = (0, util_1.promisify)(child_process_1.exec);
44
+ const execAsync = (0, node_util_1.promisify)(node_child_process_1.exec);
50
45
  // Archive format version for forward compatibility
51
46
  const ARCHIVE_FORMAT_VERSION = 1;
52
- /**
53
- * Genesis Bundler
54
- * Packages Eden apps into .edenite format
55
- */
56
- class GenesisBundler {
57
- /**
58
- * Initialize compression library
59
- */
60
- static async initCompressor() {
61
- if (this.isInitialized)
62
- return;
63
- await this.compressor.initialize();
64
- this.isInitialized = true;
47
+ const compressor = compression_1.DEFAULT_COMPRESSOR;
48
+ let isInitialized = false;
49
+ async function initCompressor() {
50
+ if (isInitialized)
51
+ return;
52
+ await compressor.initialize();
53
+ isInitialized = true;
54
+ }
55
+ function isRemoteEntry(entry) {
56
+ return !!entry && /^https?:\/\//i.test(entry);
57
+ }
58
+ function calculateChecksum(data) {
59
+ return crypto.createHash("sha256").update(data).digest("hex");
60
+ }
61
+ async function executeBuild(appDirectory, manifest, verbose) {
62
+ if (!manifest.build?.command) {
63
+ return { success: true }; // No build command defined, skip
65
64
  }
66
- static isRemoteEntry(entry) {
67
- return !!entry && /^https?:\/\//i.test(entry);
65
+ try {
66
+ const buildCwd = manifest.build.cwd
67
+ ? path.join(appDirectory, manifest.build.cwd)
68
+ : appDirectory;
69
+ if (verbose) {
70
+ console.log(`🔨 Running build command: ${manifest.build.command}`);
71
+ console.log(` Working directory: ${buildCwd}`);
72
+ }
73
+ const { stdout, stderr } = await execAsync(manifest.build.command, {
74
+ cwd: buildCwd,
75
+ env: { ...process.env },
76
+ });
77
+ if (verbose && stdout) {
78
+ console.log(` ${stdout.trim()}`);
79
+ }
80
+ if (stderr && verbose) {
81
+ console.log(` ${stderr.trim()}`);
82
+ }
83
+ if (verbose) {
84
+ console.log("✓ Build completed successfully");
85
+ }
86
+ return { success: true };
68
87
  }
69
- /**
70
- * Calculate SHA256 checksum of data
71
- */
72
- static calculateChecksum(data) {
73
- return crypto.createHash("sha256").update(data).digest("hex");
88
+ catch (error) {
89
+ return {
90
+ success: false,
91
+ error: `Build failed: ${error.message}`,
92
+ };
74
93
  }
75
- /**
76
- * Execute build command if defined in manifest
77
- */
78
- static async executeBuild(appDirectory, manifest, verbose) {
79
- if (!manifest.build?.command) {
80
- return { success: true }; // No build command defined, skip
94
+ }
95
+ async function validateManifest(manifestPath) {
96
+ const errors = [];
97
+ try {
98
+ const content = await fs.readFile(manifestPath, "utf-8");
99
+ const manifest = JSON.parse(content);
100
+ // Required fields
101
+ if (!manifest.id)
102
+ errors.push("Missing required field: id");
103
+ if (!manifest.name)
104
+ errors.push("Missing required field: name");
105
+ if (!manifest.version)
106
+ errors.push("Missing required field: version");
107
+ // Validate ID format
108
+ if (manifest.id && !/^[a-z0-9.-]+$/.test(manifest.id)) {
109
+ errors.push("Invalid ID format. Use lowercase letters, numbers, dots, and hyphens only.");
81
110
  }
82
- try {
83
- const buildCwd = manifest.build.cwd
84
- ? path.join(appDirectory, manifest.build.cwd)
85
- : appDirectory;
86
- if (verbose) {
87
- console.log(`🔨 Running build command: ${manifest.build.command}`);
88
- console.log(` Working directory: ${buildCwd}`);
89
- }
90
- const { stdout, stderr } = await execAsync(manifest.build.command, {
91
- cwd: buildCwd,
92
- env: { ...process.env },
93
- });
94
- if (verbose && stdout) {
95
- console.log(` ${stdout.trim()}`);
96
- }
97
- if (stderr && verbose) {
98
- console.log(` ${stderr.trim()}`);
99
- }
100
- if (verbose) {
101
- console.log("✓ Build completed successfully");
102
- }
103
- return { success: true };
111
+ // Backend validation (optional, but ensure entry if provided)
112
+ if (manifest.backend && !manifest.backend.entry) {
113
+ errors.push("Missing required field: backend.entry");
104
114
  }
105
- catch (error) {
106
- return {
107
- success: false,
108
- error: `Build failed: ${error.message}`,
109
- };
115
+ // Frontend validation (optional, but entry required if frontend exists)
116
+ if (manifest.frontend && !manifest.frontend.entry) {
117
+ errors.push("Missing required field: frontend.entry");
118
+ }
119
+ else if (manifest.frontend &&
120
+ !isRemoteEntry(manifest.frontend.entry) &&
121
+ manifest.frontend.entry.startsWith("http")) {
122
+ errors.push("Invalid frontend.entry URL");
123
+ }
124
+ // Must have at least frontend or backend
125
+ if (!manifest.frontend && !manifest.backend) {
126
+ errors.push("App must have at least a frontend or backend entry");
110
127
  }
128
+ return {
129
+ valid: errors.length === 0,
130
+ errors,
131
+ manifest: errors.length === 0 ? manifest : undefined,
132
+ };
111
133
  }
112
- /**
113
- * Validate an app manifest
114
- */
115
- static async validateManifest(manifestPath) {
116
- const errors = [];
134
+ catch (error) {
135
+ errors.push(`Failed to read/parse manifest: ${error.message}`);
136
+ return { valid: false, errors };
137
+ }
138
+ }
139
+ async function verifyFiles(appDirectory, manifest) {
140
+ const errors = [];
141
+ // Check backend entry if defined
142
+ if (manifest.backend?.entry) {
143
+ const backendPath = path.join(appDirectory, manifest.backend.entry);
117
144
  try {
118
- const content = await fs.readFile(manifestPath, "utf-8");
119
- const manifest = JSON.parse(content);
120
- // Required fields
121
- if (!manifest.id)
122
- errors.push("Missing required field: id");
123
- if (!manifest.name)
124
- errors.push("Missing required field: name");
125
- if (!manifest.version)
126
- errors.push("Missing required field: version");
127
- // Validate ID format
128
- if (manifest.id && !/^[a-z0-9\.\-]+$/.test(manifest.id)) {
129
- errors.push("Invalid ID format. Use lowercase letters, numbers, dots, and hyphens only.");
130
- }
131
- // Backend validation (optional, but ensure entry if provided)
132
- if (manifest.backend && !manifest.backend.entry) {
133
- errors.push("Missing required field: backend.entry");
134
- }
135
- // Frontend validation (optional, but entry required if frontend exists)
136
- if (manifest.frontend && !manifest.frontend.entry) {
137
- errors.push("Missing required field: frontend.entry");
138
- }
139
- else if (manifest.frontend &&
140
- !this.isRemoteEntry(manifest.frontend.entry) &&
141
- manifest.frontend.entry.startsWith("http")) {
142
- errors.push("Invalid frontend.entry URL");
143
- }
144
- // Must have at least frontend or backend
145
- if (!manifest.frontend && !manifest.backend) {
146
- errors.push("App must have at least a frontend or backend entry");
147
- }
148
- return {
149
- valid: errors.length === 0,
150
- errors,
151
- manifest: errors.length === 0 ? manifest : undefined,
152
- };
145
+ await fs.access(backendPath);
153
146
  }
154
- catch (error) {
155
- errors.push(`Failed to read/parse manifest: ${error.message}`);
156
- return { valid: false, errors };
147
+ catch {
148
+ errors.push(`Backend entry file not found: ${manifest.backend.entry}`);
157
149
  }
158
150
  }
159
- /**
160
- * Verify that required files exist
161
- */
162
- static async verifyFiles(appDirectory, manifest) {
163
- const errors = [];
164
- // Check backend entry if defined
165
- if (manifest.backend?.entry) {
166
- const backendPath = path.join(appDirectory, manifest.backend.entry);
167
- try {
168
- await fs.access(backendPath);
169
- }
170
- catch {
171
- errors.push(`Backend entry file not found: ${manifest.backend.entry}`);
172
- }
151
+ // Check frontend entry if defined and not a remote URL
152
+ if (manifest.frontend?.entry && !isRemoteEntry(manifest.frontend.entry)) {
153
+ const frontendPath = path.join(appDirectory, manifest.frontend.entry);
154
+ try {
155
+ await fs.access(frontendPath);
173
156
  }
174
- // Check frontend entry if defined and not a remote URL
175
- if (manifest.frontend?.entry &&
176
- !this.isRemoteEntry(manifest.frontend.entry)) {
177
- const frontendPath = path.join(appDirectory, manifest.frontend.entry);
178
- try {
179
- await fs.access(frontendPath);
180
- }
181
- catch {
182
- errors.push(`Frontend entry file not found: ${manifest.frontend.entry}`);
183
- }
157
+ catch {
158
+ errors.push(`Frontend entry file not found: ${manifest.frontend.entry}`);
184
159
  }
185
- // Check icon if specified (warn but don't fail)
186
- if (manifest.icon) {
187
- const iconPath = path.join(appDirectory, manifest.icon);
188
- try {
189
- await fs.access(iconPath);
190
- }
191
- catch {
192
- // Icon is optional, so just warn in verbose mode
193
- // Don't add to errors array
194
- }
160
+ }
161
+ // Check icon if specified (warn but don't fail)
162
+ if (manifest.icon) {
163
+ const iconPath = path.join(appDirectory, manifest.icon);
164
+ try {
165
+ await fs.access(iconPath);
166
+ }
167
+ catch {
168
+ // Icon is optional, so just warn in verbose mode
169
+ // Don't add to errors array
195
170
  }
196
- return { valid: errors.length === 0, errors };
197
171
  }
198
- /**
199
- * Check if a file path should be excluded from bundling
200
- */
201
- static shouldExcludeFile(filePath, manifest) {
202
- // Check if this path is explicitly included via manifest
203
- if (manifest?.include) {
204
- for (const includePath of manifest.include) {
205
- // Normalize paths for comparison
206
- const normalizedInclude = includePath.replace(/\\/g, "/");
207
- const normalizedFile = filePath.replace(/\\/g, "/");
208
- // Check if the file path starts with or equals the include path
209
- if (normalizedFile === normalizedInclude ||
210
- normalizedFile.startsWith(normalizedInclude + "/")) {
211
- console.log(`DEBUG: Including explicitly: ${normalizedFile} (matched ${normalizedInclude})`);
212
- return false; // Don't exclude - explicitly included
213
- }
172
+ return { valid: errors.length === 0, errors };
173
+ }
174
+ function shouldExcludeFile(filePath, manifest) {
175
+ // Check if this path is explicitly included via manifest
176
+ if (manifest?.include) {
177
+ for (const includePath of manifest.include) {
178
+ // Normalize paths for comparison
179
+ const normalizedInclude = includePath.replace(/\\/g, "/");
180
+ const normalizedFile = filePath.replace(/\\/g, "/");
181
+ // Check if the file path starts with or equals the include path
182
+ if (normalizedFile === normalizedInclude ||
183
+ normalizedFile.startsWith(`${normalizedInclude}/`)) {
184
+ return false; // Don't exclude - explicitly included
214
185
  }
215
186
  }
216
- const excludePatterns = [
217
- // Dependencies
218
- /^node_modules\//,
219
- /^node_modules$/,
220
- // Source files (we only want the built output)
221
- /^src\//,
222
- /^src$/,
223
- // Config files
224
- /^tsconfig\.json$/,
225
- /^tsconfig\..+\.json$/,
226
- /^vite\.config\..+$/,
227
- /^\.eslintrc/,
228
- /^\.prettierrc/,
229
- /^\.gitignore$/,
230
- /^\.git\//,
231
- /^\.DS_Store$/,
232
- // Lock files
233
- /^package-lock\.json$/,
234
- /^pnpm-lock\.yaml$/,
235
- /^yarn\.lock$/,
236
- // Build artifacts that shouldn't be included
237
- /^\.vite\//,
238
- /^\.cache\//,
239
- // Test files
240
- /^__tests__\//,
241
- /\.test\.[jt]sx?$/,
242
- /\.spec\.[jt]sx?$/,
243
- ];
244
- return excludePatterns.some((pattern) => pattern.test(filePath));
245
187
  }
246
- /**
247
- * Extract app files directly to a directory (no compression)
248
- */
249
- static async extractToDirectory(appDirectory, targetDir, manifest, verbose) {
250
- const resolvedTarget = path.resolve(targetDir);
251
- if (verbose)
252
- console.log(`📁 Copying files to: ${resolvedTarget}`);
253
- // Ensure target directory exists
254
- await fs.mkdir(resolvedTarget, { recursive: true });
255
- // Copy all files from the app directory (excluding development files)
256
- const files = await fs.readdir(appDirectory, { recursive: true });
257
- let copiedCount = 0;
258
- let skippedCount = 0;
259
- for (const file of files) {
260
- const fileStr = file;
261
- // Skip excluded files
262
- if (this.shouldExcludeFile(fileStr, manifest)) {
263
- skippedCount++;
264
- continue;
265
- }
266
- const sourcePath = path.join(appDirectory, fileStr);
267
- const stat = await fs.stat(sourcePath);
268
- if (stat.isFile()) {
269
- const targetPath = path.join(resolvedTarget, fileStr);
270
- const targetFileDir = path.dirname(targetPath);
271
- // Ensure subdirectory exists
272
- await fs.mkdir(targetFileDir, { recursive: true });
273
- // Copy file
274
- await fs.copyFile(sourcePath, targetPath);
275
- copiedCount++;
276
- if (verbose)
277
- console.log(` + ${fileStr}`);
278
- }
188
+ const excludePatterns = [
189
+ // Dependencies
190
+ /^node_modules\//,
191
+ /^node_modules$/,
192
+ // Source files (we only want the built output)
193
+ /^src\//,
194
+ /^src$/,
195
+ // Config files
196
+ /^tsconfig\.json$/,
197
+ /^tsconfig\..+\.json$/,
198
+ /^vite\.config\..+$/,
199
+ /^\.eslintrc/,
200
+ /^\.prettierrc/,
201
+ /^\.gitignore$/,
202
+ /^\.git\//,
203
+ /^\.DS_Store$/,
204
+ // Lock files
205
+ /^package-lock\.json$/,
206
+ /^pnpm-lock\.yaml$/,
207
+ /^yarn\.lock$/,
208
+ // Build artifacts that shouldn't be included
209
+ /^\.vite\//,
210
+ /^\.cache\//,
211
+ // Test files
212
+ /^__tests__\//,
213
+ /\.test\.[jt]sx?$/,
214
+ /\.spec\.[jt]sx?$/,
215
+ ];
216
+ return excludePatterns.some((pattern) => pattern.test(filePath));
217
+ }
218
+ async function extractToDirectory(appDirectory, targetDir, manifest, verbose) {
219
+ const resolvedTarget = path.resolve(targetDir);
220
+ if (verbose)
221
+ console.log(`📁 Copying files to: ${resolvedTarget}`);
222
+ // Ensure target directory exists
223
+ await fs.mkdir(resolvedTarget, { recursive: true });
224
+ // Copy all files from the app directory (excluding development files)
225
+ const files = await fs.readdir(appDirectory, { recursive: true });
226
+ let copiedCount = 0;
227
+ let skippedCount = 0;
228
+ for (const file of files) {
229
+ const fileStr = file;
230
+ // Skip excluded files
231
+ if (shouldExcludeFile(fileStr, manifest)) {
232
+ skippedCount++;
233
+ continue;
279
234
  }
280
- if (verbose) {
281
- console.log(`✓ Files copied to: ${resolvedTarget}`);
282
- console.log(` Copied: ${copiedCount} files, Skipped: ${skippedCount} (dev files)`);
235
+ const sourcePath = path.join(appDirectory, fileStr);
236
+ const stat = await fs.stat(sourcePath);
237
+ if (stat.isFile()) {
238
+ const targetPath = path.join(resolvedTarget, fileStr);
239
+ const targetFileDir = path.dirname(targetPath);
240
+ // Ensure subdirectory exists
241
+ await fs.mkdir(targetFileDir, { recursive: true });
242
+ // Copy file
243
+ await fs.copyFile(sourcePath, targetPath);
244
+ copiedCount++;
245
+ if (verbose)
246
+ console.log(` + ${fileStr}`);
283
247
  }
284
248
  }
285
- /**
286
- * Create a TAR archive and compress with Zstandard
287
- */
288
- static async createArchive(appDirectory, manifest, outputPath, verbose, compressionLevel = 11) {
289
- await this.initCompressor();
290
- const finalOutputPath = outputPath ||
291
- path.join(process.cwd(), `${manifest.id}-${manifest.version}.edenite`);
292
- // Create temporary tar file
293
- const tempTarPath = `${finalOutputPath}.tmp.tar`;
294
- if (verbose)
295
- console.log("📦 Creating TAR archive...");
296
- let progressBar = null;
297
- // Get file list for progress tracking (excluding development files)
298
- const allFiles = await fs.readdir(appDirectory, { recursive: true });
299
- const fileList = [];
300
- if (verbose) {
301
- console.log(`DEBUG: Found ${allFiles.length} files in app directory`);
302
- console.log(`DEBUG: Manifest include: ${JSON.stringify(manifest.include)}`);
249
+ if (verbose) {
250
+ console.log(`✓ Files copied to: ${resolvedTarget}`);
251
+ console.log(` Copied: ${copiedCount} files, Skipped: ${skippedCount} (dev files)`);
252
+ }
253
+ }
254
+ async function createArchive(appDirectory, manifest, outputPath, verbose, compressionLevel = 11) {
255
+ await initCompressor();
256
+ const finalOutputPath = outputPath ||
257
+ path.join(process.cwd(), `${manifest.id}-${manifest.version}.edenite`);
258
+ // Create temporary tar file
259
+ const tempTarPath = `${finalOutputPath}.tmp.tar`;
260
+ if (verbose)
261
+ console.log("📦 Creating TAR archive...");
262
+ let progressBar = null;
263
+ // Get file list for progress tracking (excluding development files)
264
+ const allFiles = await fs.readdir(appDirectory, { recursive: true });
265
+ const fileList = [];
266
+ for (const file of allFiles) {
267
+ const fileStr = file;
268
+ // Skip excluded files
269
+ if (shouldExcludeFile(fileStr, manifest)) {
270
+ continue;
271
+ }
272
+ const filePath = path.join(appDirectory, fileStr);
273
+ const stat = await fs.stat(filePath);
274
+ if (stat.isFile()) {
275
+ fileList.push(fileStr);
303
276
  }
304
- for (const file of allFiles) {
305
- const fileStr = file;
306
- // Skip excluded files
307
- if (this.shouldExcludeFile(fileStr, manifest)) {
308
- // console.log(`DEBUG: Excluding ${fileStr}`);
309
- continue;
277
+ }
278
+ if (verbose && fileList.length > 50) {
279
+ progressBar = new cli_progress_1.default.SingleBar({
280
+ format: " Progress |{bar}| {percentage}% | {value}/{total} files",
281
+ barCompleteChar: "\u2588",
282
+ barIncompleteChar: "\u2591",
283
+ hideCursor: true,
284
+ });
285
+ progressBar.start(fileList.length, 0);
286
+ }
287
+ let processedFiles = 0;
288
+ // Create TAR archive
289
+ await tar.create({
290
+ file: tempTarPath,
291
+ cwd: appDirectory,
292
+ gzip: false,
293
+ portable: true,
294
+ filter: (entryPath, stat) => {
295
+ if (verbose && progressBar) {
296
+ processedFiles++;
297
+ progressBar.update(processedFiles);
310
298
  }
311
- const filePath = path.join(appDirectory, fileStr);
312
- const stat = await fs.stat(filePath);
313
- if (stat.isFile()) {
314
- fileList.push(fileStr);
299
+ else if (verbose) {
300
+ console.log(` + ${entryPath}`);
315
301
  }
302
+ return true;
303
+ },
304
+ }, fileList);
305
+ if (progressBar) {
306
+ progressBar.stop();
307
+ }
308
+ if (verbose)
309
+ console.log("🗜️ Compressing with Zstandard...");
310
+ // Create temporary file for compressed output
311
+ const tempCompressedPath = `${tempTarPath}.zst`;
312
+ // Compress with configured compressor using streaming to disk
313
+ const { checksum } = await compressor.compressFileStreaming(tempTarPath, tempCompressedPath, compressionLevel);
314
+ // Create metadata
315
+ const metadata = {
316
+ version: ARCHIVE_FORMAT_VERSION,
317
+ checksum,
318
+ created: new Date().toISOString(),
319
+ manifest,
320
+ };
321
+ // Combine metadata + compressed data
322
+ // Format: [4 bytes metadata length][metadata JSON][compressed stream]
323
+ const metadataJson = JSON.stringify(metadata);
324
+ const metadataBuffer = Buffer.from(metadataJson, "utf-8");
325
+ const metadataLength = Buffer.alloc(4);
326
+ metadataLength.writeUInt32BE(metadataBuffer.length, 0);
327
+ const finalWriteStream = (0, node_fs_1.createWriteStream)(finalOutputPath);
328
+ // Write metadata length and buffer
329
+ finalWriteStream.write(metadataLength);
330
+ finalWriteStream.write(metadataBuffer);
331
+ // Stream compressed content to final file
332
+ const compressedReadStream = (0, node_fs_1.createReadStream)(tempCompressedPath);
333
+ await new Promise((resolve, reject) => {
334
+ compressedReadStream.pipe(finalWriteStream);
335
+ compressedReadStream.on("error", reject);
336
+ finalWriteStream.on("error", reject);
337
+ finalWriteStream.on("finish", resolve);
338
+ });
339
+ // Get stats for logging
340
+ const tarStats = await fs.stat(tempTarPath);
341
+ const finalStats = await fs.stat(finalOutputPath);
342
+ // Clean up temp files
343
+ await fs.unlink(tempTarPath);
344
+ await fs.unlink(tempCompressedPath);
345
+ if (verbose) {
346
+ const originalSize = tarStats.size;
347
+ const finalSize = finalStats.size;
348
+ const metadataSize = metadataLength.length + metadataBuffer.length;
349
+ const compressedSize = finalSize - metadataSize; // Approximate
350
+ console.log(`✓ Archive created: ${finalOutputPath}`);
351
+ console.log(` Original size: ${(originalSize / 1024).toFixed(2)} KB`);
352
+ console.log(` Compressed size: ${(compressedSize / 1024).toFixed(2)} KB`);
353
+ console.log(` Compression ratio: ${((1 - compressedSize / originalSize) * 100).toFixed(1)}%`);
354
+ console.log(` SHA256: ${checksum}`);
355
+ }
356
+ return {
357
+ path: finalOutputPath,
358
+ checksum,
359
+ size: finalStats.size,
360
+ };
361
+ }
362
+ async function bundle(options) {
363
+ const { appDirectory, outputPath, extractToDirectory: extractTarget, verbose, dryRun = false, compressionLevel = 11, } = options;
364
+ try {
365
+ // Initialize compressor
366
+ await initCompressor();
367
+ if (verbose)
368
+ console.log(`📦 Bundling app from: ${appDirectory}`);
369
+ // Check if directory exists
370
+ try {
371
+ await fs.access(appDirectory);
316
372
  }
317
- if (verbose && fileList.length > 50) {
318
- progressBar = new cli_progress_1.default.SingleBar({
319
- format: " Progress |{bar}| {percentage}% | {value}/{total} files",
320
- barCompleteChar: "\u2588",
321
- barIncompleteChar: "\u2591",
322
- hideCursor: true,
323
- });
324
- progressBar.start(fileList.length, 0);
373
+ catch {
374
+ return {
375
+ success: false,
376
+ error: `App directory not found: ${appDirectory}`,
377
+ };
325
378
  }
326
- let processedFiles = 0;
327
- // Create TAR archive
328
- await tar.create({
329
- file: tempTarPath,
330
- cwd: appDirectory,
331
- gzip: false,
332
- portable: true,
333
- filter: (path, stat) => {
334
- if (verbose && progressBar) {
335
- processedFiles++;
336
- progressBar.update(processedFiles);
337
- }
338
- else if (verbose) {
339
- console.log(` + ${path}`);
340
- }
341
- return true;
342
- },
343
- }, fileList);
344
- if (progressBar) {
345
- progressBar.stop();
379
+ // Read and validate manifest
380
+ const manifestPath = path.join(appDirectory, "manifest.json");
381
+ const validation = await validateManifest(manifestPath);
382
+ if (!validation.valid) {
383
+ return {
384
+ success: false,
385
+ error: `Invalid manifest:\n${validation.errors.join("\n")}`,
386
+ };
346
387
  }
347
- if (verbose)
348
- console.log("🗜️ Compressing with Zstandard...");
349
- // Create temporary file for compressed output
350
- const tempCompressedPath = `${tempTarPath}.zst`;
351
- // Compress with configured compressor using streaming to disk
352
- const { checksum } = await this.compressor.compressFileStreaming(tempTarPath, tempCompressedPath, compressionLevel);
353
- // Create metadata
354
- const metadata = {
355
- version: ARCHIVE_FORMAT_VERSION,
356
- checksum,
357
- created: new Date().toISOString(),
358
- manifest,
359
- };
360
- // Combine metadata + compressed data
361
- // Format: [4 bytes metadata length][metadata JSON][compressed stream]
362
- const metadataJson = JSON.stringify(metadata);
363
- const metadataBuffer = Buffer.from(metadataJson, "utf-8");
364
- const metadataLength = Buffer.alloc(4);
365
- metadataLength.writeUInt32BE(metadataBuffer.length, 0);
366
- const finalWriteStream = (0, fs_1.createWriteStream)(finalOutputPath);
367
- // Write metadata length and buffer
368
- finalWriteStream.write(metadataLength);
369
- finalWriteStream.write(metadataBuffer);
370
- // Stream compressed content to final file
371
- const compressedReadStream = (0, fs_1.createReadStream)(tempCompressedPath);
372
- await new Promise((resolve, reject) => {
373
- compressedReadStream.pipe(finalWriteStream);
374
- compressedReadStream.on("error", reject);
375
- finalWriteStream.on("error", reject);
376
- finalWriteStream.on("finish", resolve);
377
- });
378
- // Get stats for logging
379
- const tarStats = await fs.stat(tempTarPath);
380
- const finalStats = await fs.stat(finalOutputPath);
381
- // Clean up temp files
382
- await fs.unlink(tempTarPath);
383
- await fs.unlink(tempCompressedPath);
388
+ const manifest = validation.manifest;
384
389
  if (verbose) {
385
- const originalSize = tarStats.size;
386
- const finalSize = finalStats.size;
387
- const metadataSize = metadataLength.length + metadataBuffer.length;
388
- const compressedSize = finalSize - metadataSize; // Approximate
389
- console.log(`✓ Archive created: ${finalOutputPath}`);
390
- console.log(` Original size: ${(originalSize / 1024).toFixed(2)} KB`);
391
- console.log(` Compressed size: ${(compressedSize / 1024).toFixed(2)} KB`);
392
- console.log(` Compression ratio: ${((1 - compressedSize / originalSize) *
393
- 100).toFixed(1)}%`);
394
- console.log(` SHA256: ${checksum}`);
390
+ console.log(`✓ Manifest valid: ${manifest.name} v${manifest.version}`);
395
391
  }
396
- return {
397
- path: finalOutputPath,
398
- checksum,
399
- size: finalStats.size,
400
- };
401
- }
402
- /**
403
- * Bundle an app into .edenite format or extract to directory
404
- */
405
- static async bundle(options) {
406
- const { appDirectory, outputPath, extractToDirectory, verbose, dryRun = false, compressionLevel = 11, } = options;
407
- try {
408
- // Initialize compressor
409
- await this.initCompressor();
392
+ // If dry run, stop here
393
+ if (dryRun) {
410
394
  if (verbose)
411
- console.log(`📦 Bundling app from: ${appDirectory}`);
412
- // Check if directory exists
413
- try {
414
- await fs.access(appDirectory);
415
- }
416
- catch {
417
- return {
418
- success: false,
419
- error: `App directory not found: ${appDirectory}`,
420
- };
421
- }
422
- // Read and validate manifest
423
- const manifestPath = path.join(appDirectory, "manifest.json");
424
- const validation = await this.validateManifest(manifestPath);
425
- if (!validation.valid) {
426
- return {
427
- success: false,
428
- error: `Invalid manifest:\n${validation.errors.join("\n")}`,
429
- };
430
- }
431
- const manifest = validation.manifest;
432
- if (verbose) {
433
- console.log(`✓ Manifest valid: ${manifest.name} v${manifest.version}`);
434
- }
435
- // If dry run, stop here
436
- if (dryRun) {
437
- if (verbose)
438
- console.log("✓ Dry run successful - no files created");
439
- return {
440
- success: true,
441
- manifest,
442
- };
443
- }
444
- // Execute build command if defined (before verifying files, as build may create them)
445
- const buildResult = await this.executeBuild(appDirectory, manifest, verbose);
446
- if (!buildResult.success) {
447
- return {
448
- success: false,
449
- error: buildResult.error,
450
- };
451
- }
452
- // Verify required files exist (after build)
453
- const fileCheck = await this.verifyFiles(appDirectory, manifest);
454
- if (!fileCheck.valid) {
455
- return {
456
- success: false,
457
- error: `Missing files:\n${fileCheck.errors.join("\n")}`,
458
- };
459
- }
460
- if (verbose)
461
- console.log("✓ All required files present");
462
- // If extractToDirectory is provided, copy files directly
463
- if (extractToDirectory) {
464
- await this.extractToDirectory(appDirectory, extractToDirectory, manifest, verbose);
465
- return {
466
- success: true,
467
- outputPath: path.resolve(extractToDirectory),
468
- manifest,
469
- };
470
- }
471
- // Otherwise, create compressed archive
472
- const result = await this.createArchive(appDirectory, manifest, outputPath, verbose, compressionLevel);
395
+ console.log("✓ Dry run successful - no files created");
473
396
  return {
474
397
  success: true,
475
- outputPath: result.path,
476
398
  manifest,
477
- checksum: result.checksum,
478
- size: result.size,
479
399
  };
480
400
  }
481
- catch (error) {
401
+ // Execute build command if defined (before verifying files, as build may create them)
402
+ const buildResult = await executeBuild(appDirectory, manifest, verbose);
403
+ if (!buildResult.success) {
482
404
  return {
483
405
  success: false,
484
- error: `Bundle failed: ${error.message}`,
406
+ error: buildResult.error,
485
407
  };
486
408
  }
487
- }
488
- /**
489
- * Extract info from an .edenite file
490
- */
491
- static async getInfo(edenitePath) {
492
- try {
493
- await this.initCompressor();
494
- // Read the .edenite file
495
- const data = await fs.readFile(edenitePath);
496
- // Read metadata length (first 4 bytes)
497
- const metadataLength = data.readUInt32BE(0);
498
- // Read metadata
499
- const metadataBuffer = data.subarray(4, 4 + metadataLength);
500
- const metadata = JSON.parse(metadataBuffer.toString("utf-8"));
409
+ // Verify required files exist (after build)
410
+ const fileCheck = await verifyFiles(appDirectory, manifest);
411
+ if (!fileCheck.valid) {
501
412
  return {
502
- success: true,
503
- manifest: metadata.manifest,
504
- checksum: metadata.checksum,
413
+ success: false,
414
+ error: `Missing files:\n${fileCheck.errors.join("\n")}`,
505
415
  };
506
416
  }
507
- catch (error) {
417
+ if (verbose)
418
+ console.log("✓ All required files present");
419
+ // If extractToDirectory is provided, copy files directly
420
+ if (extractTarget) {
421
+ await extractToDirectory(appDirectory, extractTarget, manifest, verbose);
508
422
  return {
509
- success: false,
510
- error: `Failed to read archive: ${error.message}`,
423
+ success: true,
424
+ outputPath: path.resolve(extractTarget),
425
+ manifest,
511
426
  };
512
427
  }
428
+ // Otherwise, create compressed archive
429
+ const result = await createArchive(appDirectory, manifest, outputPath, verbose, compressionLevel);
430
+ return {
431
+ success: true,
432
+ outputPath: result.path,
433
+ manifest,
434
+ checksum: result.checksum,
435
+ size: result.size,
436
+ };
513
437
  }
514
- /**
515
- * Extract an .edenite file to a directory
516
- */
517
- static async extract(options) {
518
- const { edenitePath, outputDirectory, verbose, verifyChecksum = true, } = options;
519
- try {
520
- await this.initCompressor();
521
- if (verbose)
522
- console.log(`📂 Extracting: ${edenitePath}`);
523
- // Read the .edenite file
524
- const data = await fs.readFile(edenitePath);
525
- // Read metadata length (first 4 bytes)
526
- const metadataLength = data.readUInt32BE(0);
527
- // Read metadata
528
- const metadataBuffer = data.subarray(4, 4 + metadataLength);
529
- const metadata = JSON.parse(metadataBuffer.toString("utf-8"));
530
- if (verbose) {
531
- console.log(`✓ Archive format version: ${metadata.version}`);
532
- console.log(`✓ Created: ${metadata.created}`);
533
- }
534
- // Read compressed data
535
- const compressedData = data.subarray(4 + metadataLength);
536
- // Verify checksum if requested
537
- if (verifyChecksum) {
538
- const actualChecksum = this.calculateChecksum(Buffer.from(compressedData));
539
- if (actualChecksum !== metadata.checksum) {
540
- return {
541
- success: false,
542
- error: `Checksum mismatch! Archive may be corrupted.\nExpected: ${metadata.checksum}\nActual: ${actualChecksum}`,
543
- };
544
- }
545
- if (verbose)
546
- console.log("✓ Checksum verified");
438
+ catch (error) {
439
+ return {
440
+ success: false,
441
+ error: `Bundle failed: ${error.message}`,
442
+ };
443
+ }
444
+ }
445
+ async function getInfo(edenitePath) {
446
+ try {
447
+ await initCompressor();
448
+ // Read the .edenite file
449
+ const data = await fs.readFile(edenitePath);
450
+ // Read metadata length (first 4 bytes)
451
+ const metadataLength = data.readUInt32BE(0);
452
+ // Read metadata
453
+ const metadataBuffer = data.subarray(4, 4 + metadataLength);
454
+ const metadata = JSON.parse(metadataBuffer.toString("utf-8"));
455
+ return {
456
+ success: true,
457
+ manifest: metadata.manifest,
458
+ checksum: metadata.checksum,
459
+ };
460
+ }
461
+ catch (error) {
462
+ return {
463
+ success: false,
464
+ error: `Failed to read archive: ${error.message}`,
465
+ };
466
+ }
467
+ }
468
+ async function extract(options) {
469
+ const { edenitePath, outputDirectory, verbose, verifyChecksum = true, } = options;
470
+ try {
471
+ await initCompressor();
472
+ if (verbose)
473
+ console.log(`📂 Extracting: ${edenitePath}`);
474
+ // Read the .edenite file
475
+ const data = await fs.readFile(edenitePath);
476
+ // Read metadata length (first 4 bytes)
477
+ const metadataLength = data.readUInt32BE(0);
478
+ // Read metadata
479
+ const metadataBuffer = data.subarray(4, 4 + metadataLength);
480
+ const metadata = JSON.parse(metadataBuffer.toString("utf-8"));
481
+ if (verbose) {
482
+ console.log(`✓ Archive format version: ${metadata.version}`);
483
+ console.log(`✓ Created: ${metadata.created}`);
484
+ }
485
+ // Read compressed data
486
+ const compressedData = data.subarray(4 + metadataLength);
487
+ // Verify checksum if requested
488
+ if (verifyChecksum) {
489
+ const actualChecksum = calculateChecksum(Buffer.from(compressedData));
490
+ if (actualChecksum !== metadata.checksum) {
491
+ return {
492
+ success: false,
493
+ error: `Checksum mismatch! Archive may be corrupted.\nExpected: ${metadata.checksum}\nActual: ${actualChecksum}`,
494
+ };
547
495
  }
548
496
  if (verbose)
549
- console.log("🗜️ Decompressing...");
550
- // Decompress with configured compressor
551
- const decompressedBuffer = await this.compressor.decompress(Buffer.from(compressedData));
552
- // Write to temporary tar file
553
- const tempTarPath = path.join(outputDirectory, `temp-${Date.now()}.tar`);
554
- await fs.mkdir(outputDirectory, { recursive: true });
555
- await fs.writeFile(tempTarPath, decompressedBuffer);
556
- if (verbose)
557
- console.log("📦 Extracting TAR archive...");
558
- // Extract TAR
559
- await tar.extract({
560
- file: tempTarPath,
561
- cwd: outputDirectory,
562
- });
563
- // Clean up temp tar file
564
- await fs.unlink(tempTarPath);
565
- if (verbose) {
566
- console.log(`✓ Extracted to: ${outputDirectory}`);
567
- }
568
- return {
569
- success: true,
570
- manifest: metadata.manifest,
571
- };
497
+ console.log("✓ Checksum verified");
572
498
  }
573
- catch (error) {
574
- return {
575
- success: false,
576
- error: `Extraction failed: ${error.message}`,
577
- };
499
+ if (verbose)
500
+ console.log("🗜️ Decompressing...");
501
+ // Decompress with configured compressor
502
+ const decompressedBuffer = await compressor.decompress(Buffer.from(compressedData));
503
+ // Write to temporary tar file
504
+ const tempTarPath = path.join(outputDirectory, `temp-${Date.now()}.tar`);
505
+ await fs.mkdir(outputDirectory, { recursive: true });
506
+ await fs.writeFile(tempTarPath, decompressedBuffer);
507
+ if (verbose)
508
+ console.log("📦 Extracting TAR archive...");
509
+ // Extract TAR
510
+ await tar.extract({
511
+ file: tempTarPath,
512
+ cwd: outputDirectory,
513
+ });
514
+ // Clean up temp tar file
515
+ await fs.unlink(tempTarPath);
516
+ if (verbose) {
517
+ console.log(`✓ Extracted to: ${outputDirectory}`);
578
518
  }
519
+ return {
520
+ success: true,
521
+ manifest: metadata.manifest,
522
+ };
523
+ }
524
+ catch (error) {
525
+ return {
526
+ success: false,
527
+ error: `Extraction failed: ${error.message}`,
528
+ };
579
529
  }
580
530
  }
581
- exports.GenesisBundler = GenesisBundler;
582
- GenesisBundler.compressor = compression_1.DEFAULT_COMPRESSOR;
583
- GenesisBundler.isInitialized = false;
584
531
  //# sourceMappingURL=bundler.js.map