@genobank/biofs 1.6.0 → 1.6.2

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.
Files changed (40) hide show
  1. package/.claude/settings.local.json +33 -0
  2. package/BUBBLEWRAP_INTEGRATION.md +486 -0
  3. package/BUBBLEWRAP_QUICKSTART.md +356 -0
  4. package/BUBBLEWRAP_README.md +466 -0
  5. package/BUBBLEWRAP_STRATEGIC_ANALYSIS.md +625 -0
  6. package/CHANGELOG.md +73 -0
  7. package/ENHANCEMENT_DOCUMENTATION.md +218 -0
  8. package/GEMINI_REMOVAL_COMPLETE.md +311 -0
  9. package/dist/commands/login.d.ts +2 -0
  10. package/dist/commands/login.d.ts.map +1 -1
  11. package/dist/commands/login.js +30 -5
  12. package/dist/commands/login.js.map +1 -1
  13. package/dist/commands/sandbox.d.ts +10 -0
  14. package/dist/commands/sandbox.d.ts.map +1 -0
  15. package/dist/commands/sandbox.js +418 -0
  16. package/dist/commands/sandbox.js.map +1 -0
  17. package/dist/commands/tokenize.js +37 -462
  18. package/dist/index.js +6 -33
  19. package/dist/index.js.map +1 -1
  20. package/dist/lib/ai/classifier.d.ts +12 -0
  21. package/dist/lib/ai/classifier.d.ts.map +1 -1
  22. package/dist/lib/ai/classifier.js +178 -0
  23. package/dist/lib/ai/classifier.js.map +1 -0
  24. package/dist/lib/bioip/collections.js +1 -3
  25. package/dist/lib/config/constants.d.ts.map +1 -1
  26. package/dist/lib/config/constants.js +2 -0
  27. package/dist/lib/config/constants.js.map +1 -1
  28. package/dist/lib/sandbox/bubblewrap.d.ts +125 -0
  29. package/dist/lib/sandbox/bubblewrap.d.ts.map +1 -0
  30. package/dist/lib/sandbox/bubblewrap.js +343 -0
  31. package/dist/lib/sandbox/bubblewrap.js.map +1 -0
  32. package/dist/lib/utils/logger.d.ts +6 -5
  33. package/dist/lib/utils/logger.d.ts.map +1 -1
  34. package/dist/lib/utils/logger.js +23 -5
  35. package/dist/lib/utils/logger.js.map +1 -1
  36. package/examples/sandbox-usage.ts +361 -0
  37. package/package.json +3 -2
  38. package/SECURITY_AUDIT_20251010.md +0 -159
  39. package/dist/commands/tokenize.js.bkp.20251010_022629 +0 -906
  40. package/dist/index.js.bkp.20251010_045250 +0 -417
@@ -1,906 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.tokenizeCommand = tokenizeCommand;
7
- const promises_1 = require("fs/promises");
8
- const fs_1 = require("fs");
9
- const path_1 = require("path");
10
- const chalk_1 = __importDefault(require("chalk"));
11
- const ora_1 = __importDefault(require("ora"));
12
- const boxen_1 = __importDefault(require("boxen"));
13
- const inquirer_1 = __importDefault(require("inquirer"));
14
- const form_data_1 = __importDefault(require("form-data"));
15
- const axios_1 = __importDefault(require("axios"));
16
- const credentials_1 = require("../lib/auth/credentials");
17
- const logger_1 = require("../lib/utils/logger");
18
- const format_1 = require("../lib/utils/format");
19
- const fingerprint_1 = require("../lib/biofiles/fingerprint");
20
- const collections_1 = require("../lib/bioip/collections");
21
- const licenses_1 = require("../lib/bioip/licenses");
22
- const tokenizations_1 = require("../lib/storage/tokenizations");
23
- const constants_1 = require("../lib/config/constants");
24
- const API_BASE = constants_1.API_CONFIG.base + constants_1.API_CONFIG.bioip;
25
- async function tokenizeCommand(filePath, options) {
26
- // Resolve absolute path
27
- const absolutePath = (0, path_1.resolve)(filePath);
28
- // Check if file exists
29
- if (!(0, fs_1.existsSync)(absolutePath)) {
30
- throw new Error(`File not found: ${filePath}`);
31
- }
32
- // Get file stats
33
- const fileStats = await (0, promises_1.stat)(absolutePath);
34
- const fileSize = fileStats.size;
35
- const fileName = (0, path_1.basename)(absolutePath);
36
- const fileExt = (0, path_1.extname)(absolutePath).toLowerCase();
37
- // Check credentials
38
- const credentials = await (0, credentials_1.getCredentials)();
39
- if (!credentials) {
40
- throw new Error('Not authenticated. Please run "biofs login" first.');
41
- }
42
- // Select network (default to mainnet)
43
- const networkName = options.network || 'mainnet';
44
- const network = constants_1.STORY_NETWORKS[networkName];
45
- if (!options.quiet) {
46
- console.log(chalk_1.default.cyan('\n🧬 BioFS Tokenization'));
47
- console.log(chalk_1.default.gray('━'.repeat(50)));
48
- console.log(`\nšŸ“ File: ${chalk_1.default.white(fileName)} (${(0, format_1.formatFileSize)(fileSize)})`);
49
- console.log(`šŸ” Wallet: ${chalk_1.default.white(credentials.wallet_address)}`);
50
- console.log(`🌐 Network: ${chalk_1.default.white(network.name)} (Chain ID: ${network.chainId})\n`);
51
- }
52
- const steps = options.noAi ? 5 : 6;
53
- let currentStep = 1;
54
- // Step 1: Analyze file with advanced genomic pattern recognition
55
- let spinner = (0, ora_1.default)(`Step ${currentStep}/${steps}: šŸ”¬ Analyzing genomic file structure and validating format...`).start();
56
- try {
57
- // Detect file type
58
- const fileCategory = detectFileCategory(fileName, fileExt);
59
- spinner.succeed(`Step ${currentStep}/${steps}: āœ“ File validated as ${fileCategory.toUpperCase()} format with genomic pattern recognition`);
60
- currentStep++;
61
- // Step 2: Calculate cryptographic fingerprint from genetic variants
62
- spinner = (0, ora_1.default)(`Step ${currentStep}/${steps}: 🧬 Extracting SNP positions and computing cryptographic fingerprint...`).start();
63
- let fingerprint;
64
- let snpCount = 0;
65
- // For genomic files, calculate SNP fingerprint
66
- if (isGenomicFile(fileExt)) {
67
- const result = await (0, fingerprint_1.calculateSnpFingerprint)(filePath);
68
- fingerprint = result.fingerprint;
69
- snpCount = result.snpCount;
70
- spinner.succeed(`Step ${currentStep}/${steps}: āœ“ Generated SHA-256 fingerprint from ${snpCount.toLocaleString()} unique variants (${fingerprint.substring(0, 16)}...)`);
71
- }
72
- else {
73
- fingerprint = await (0, fingerprint_1.calculateFileFingerprint)(filePath);
74
- spinner.succeed(`Step ${currentStep}/${steps}: āœ“ Generated file fingerprint: ${fingerprint.substring(0, 16)}...`);
75
- }
76
- currentStep++;
77
- // Step 3: AI-powered dataset classification using Claude 3 Haiku via API
78
- // CRITICAL: Following bioip.js flow EXACTLY - AI determines title, description, and collection
79
- let aiMetadata = null;
80
- let aiTitle = '';
81
- let aiDescription = '';
82
- let detectedCategory = fileCategory;
83
- if (!options.noAi) {
84
- spinner = (0, ora_1.default)(`Step ${currentStep}/${steps}: šŸ¤– Analyzing content with Claude 3 Haiku for intelligent metadata generation...`).start();
85
- try {
86
- // Read file sample for Claude analysis (bioip.js sends first 20 lines)
87
- // For large binary files (SQLite, BAM, etc.), read only first 50KB to avoid memory issues
88
- let sampleLines;
89
- const MAX_SAMPLE_SIZE = 50 * 1024; // 50KB sample for AI analysis
90
-
91
- if (fileSize > MAX_SAMPLE_SIZE && (fileExt === '.sqlite' || fileExt === '.db' || fileExt === '.bam')) {
92
- // Binary files: Read only first 50KB
93
- const buffer = Buffer.alloc(MAX_SAMPLE_SIZE);
94
- const fd = await (0, promises_1.open)(absolutePath, 'r');
95
- await fd.read(buffer, 0, MAX_SAMPLE_SIZE, 0);
96
- await fd.close();
97
- sampleLines = buffer.toString('utf-8', 0, Math.min(2000, MAX_SAMPLE_SIZE)); // First 2KB as string
98
- } else {
99
- // Text files: Read first 20 lines
100
- const fileContent = await (0, promises_1.readFile)(absolutePath, { encoding: 'utf-8' });
101
- const lines = fileContent.split('\n');
102
- sampleLines = lines.slice(0, 20).join('\n');
103
- }
104
- // Call api_bioip.py /generate_metadata endpoint (uses Claude Haiku) - EXACT bioip.js flow
105
- const contextData = JSON.stringify({
106
- fileName: fileName,
107
- fileSize: (0, format_1.formatFileSize)(fileSize),
108
- fileType: fileExt,
109
- category: fileCategory,
110
- sampleLines: sampleLines
111
- });
112
- const params = new URLSearchParams();
113
- params.append('user_signature', credentials.user_signature);
114
- params.append('context', contextData);
115
- const metadataResponse = await axios_1.default.post(`${API_BASE}/generate_metadata`, params, {
116
- headers: {
117
- 'Content-Type': 'application/x-www-form-urlencoded'
118
- }
119
- });
120
- if (metadataResponse.data.status === 'Success') {
121
- // Extract metadata from correct path (bioip.js pattern)
122
- aiMetadata = metadataResponse.data.status_details.metadata;
123
- // Clean up title and description - remove extra quotes and trailing punctuation (bioip.js pattern)
124
- let cleanTitle = (aiMetadata.title || 'Genomic Data Analysis')
125
- .replace(/^["']+/g, '') // Remove leading quotes
126
- .replace(/["',]+$/g, ''); // Remove trailing quotes and commas
127
- let cleanDescription = (aiMetadata.description || 'Biological data for analysis')
128
- .replace(/^["']+/g, '')
129
- .replace(/["',]+$/g, '');
130
- // AI determines title and description - user options are FALLBACK only (bioip.js pattern)
131
- aiTitle = cleanTitle || options.title || 'Genomic Data Analysis';
132
- aiDescription = cleanDescription || options.description || 'Biological data for analysis';
133
- spinner.succeed(`Step ${currentStep}/${steps}: āœ“ Claude Haiku generated metadata`);
134
- console.log(chalk_1.default.cyan(` šŸ“ AI Title: "${aiTitle}"`));
135
- console.log(chalk_1.default.gray(` šŸ“„ AI Description: ${aiDescription.substring(0, 60)}...`));
136
- }
137
- else {
138
- spinner.fail(`Step ${currentStep}/${steps}: āœ— Claude Haiku returned non-Success status`);
139
- console.log(chalk_1.default.red(`\nāŒ CRITICAL ERROR: AI classification is MANDATORY for data integrity`));
140
- console.log(chalk_1.default.gray(` API Response: ${JSON.stringify(metadataResponse.data, null, 2)}`));
141
- throw new Error(`AI classification failed: ${metadataResponse.data.status_details?.description || 'Unknown error'}`);
142
- }
143
- }
144
- catch (error) {
145
- spinner.fail(`Step ${currentStep}/${steps}: āœ— Claude Haiku AI classification FAILED`);
146
- console.log(chalk_1.default.red(`\nāŒ CRITICAL ERROR: AI classification is MANDATORY for data integrity`));
147
- console.log(chalk_1.default.red(` Claude Haiku API Error: ${error.message}`));
148
- if (error.response?.data) {
149
- console.log(chalk_1.default.gray(` API Response: ${JSON.stringify(error.response.data, null, 2)}`));
150
- }
151
- console.log(chalk_1.default.yellow(`\nšŸ’” Fix: Check that api_bioip.py /generate_metadata endpoint is working`));
152
- throw new Error(`AI classification failed: ${error.message}`);
153
- }
154
- currentStep++;
155
- }
156
- else {
157
- // If --no-ai flag used, user MUST provide title and description
158
- if (!options.title || !options.description) {
159
- throw new Error('--no-ai flag requires both --title and --description options');
160
- }
161
- aiTitle = options.title;
162
- aiDescription = options.description;
163
- }
164
- // Step 4: Smart contract collection selection on Story Protocol
165
- spinner = (0, ora_1.default)(`Step ${currentStep}/${steps}: šŸ“œ Selecting optimal Story Protocol NFT collection...`).start();
166
- let collectionAddress = options.collection || (0, collections_1.getCollectionForCategory)(detectedCategory);
167
- let collectionName = getCollectionName(collectionAddress);
168
- spinner.succeed(`Step ${currentStep}/${steps}: āœ“ Selected "${collectionName}" collection (${collectionAddress.substring(0, 10)}...)`);
169
- currentStep++;
170
- // Preview and Confirmation Step (only if not in quiet mode, not auto-confirmed, and not dryrun)
171
- if (!options.quiet && !options.yes && !options.dryrun) {
172
- const imageUrl = (0, collections_1.getDefaultImageForCategory)(detectedCategory);
173
- const licenseType = (0, licenses_1.getLicenseType)(options.license || 'non-commercial');
174
- const licenseDisplayName = getLicenseDisplayName(options.license || 'non-commercial');
175
- // Build preview
176
- const preview = buildMetadataPreview({
177
- fileName,
178
- fileSize,
179
- title: aiTitle,
180
- description: aiDescription || `${detectedCategory} dataset`,
181
- category: detectedCategory,
182
- fingerprint,
183
- snpCount,
184
- collection: collectionName,
185
- collectionAddress,
186
- license: licenseDisplayName,
187
- licenseType,
188
- imageUrl,
189
- network: network.name,
190
- wallet: credentials.wallet_address
191
- });
192
- console.log('\n');
193
- console.log((0, boxen_1.default)(preview, {
194
- padding: 1,
195
- margin: 1,
196
- borderStyle: 'round',
197
- borderColor: 'cyan',
198
- title: 'šŸ” Tokenization Preview',
199
- titleAlignment: 'center'
200
- }));
201
- // Confirmation prompt
202
- const { action } = await inquirer_1.default.prompt([
203
- {
204
- type: 'list',
205
- name: 'action',
206
- message: 'How would you like to proceed?',
207
- choices: [
208
- { name: 'āœ… Confirm and tokenize', value: 'confirm' },
209
- { name: 'āœļø Edit metadata', value: 'edit' },
210
- { name: 'āŒ Cancel', value: 'cancel' }
211
- ]
212
- }
213
- ]);
214
- if (action === 'cancel') {
215
- console.log(chalk_1.default.yellow('\nāŒ Tokenization cancelled.\n'));
216
- process.exit(0);
217
- }
218
- if (action === 'edit') {
219
- // Allow editing each field
220
- const edited = await inquirer_1.default.prompt([
221
- {
222
- type: 'input',
223
- name: 'title',
224
- message: 'Title:',
225
- default: aiTitle
226
- },
227
- {
228
- type: 'input',
229
- name: 'description',
230
- message: 'Description:',
231
- default: aiDescription || `${detectedCategory} dataset`
232
- },
233
- {
234
- type: 'list',
235
- name: 'license',
236
- message: 'License:',
237
- choices: [
238
- { name: 'Non-Commercial Remix', value: 'non-commercial' },
239
- { name: 'Commercial Remix', value: 'commercial' }
240
- ],
241
- default: options.license || 'non-commercial'
242
- },
243
- {
244
- type: 'input',
245
- name: 'collectionAddress',
246
- message: 'Collection Address (leave blank to keep current):',
247
- default: collectionAddress
248
- }
249
- ]);
250
- // Update values
251
- aiTitle = edited.title;
252
- aiDescription = edited.description;
253
- options.license = edited.license;
254
- if (edited.collectionAddress && edited.collectionAddress !== collectionAddress) {
255
- collectionAddress = edited.collectionAddress;
256
- collectionName = getCollectionName(collectionAddress);
257
- }
258
- // Show updated preview
259
- const updatedPreview = buildMetadataPreview({
260
- fileName,
261
- fileSize,
262
- title: aiTitle,
263
- description: aiDescription || `${detectedCategory} dataset`,
264
- category: detectedCategory,
265
- fingerprint,
266
- snpCount,
267
- collection: collectionName,
268
- collectionAddress,
269
- license: getLicenseDisplayName(edited.license),
270
- licenseType: (0, licenses_1.getLicenseType)(edited.license),
271
- imageUrl,
272
- network: network.name,
273
- wallet: credentials.wallet_address
274
- });
275
- console.log('\n');
276
- console.log((0, boxen_1.default)(updatedPreview, {
277
- padding: 1,
278
- margin: 1,
279
- borderStyle: 'round',
280
- borderColor: 'green',
281
- title: 'āœ… Updated Metadata',
282
- titleAlignment: 'center'
283
- }));
284
- // Final confirmation
285
- const { confirmFinal } = await inquirer_1.default.prompt([
286
- {
287
- type: 'confirm',
288
- name: 'confirmFinal',
289
- message: 'Proceed with tokenization?',
290
- default: true
291
- }
292
- ]);
293
- if (!confirmFinal) {
294
- console.log(chalk_1.default.yellow('\nāŒ Tokenization cancelled.\n'));
295
- process.exit(0);
296
- }
297
- }
298
- console.log(chalk_1.default.green('\nāœ… Proceeding with tokenization...\n'));
299
- }
300
-
301
- // DRYRUN MODE: Validate infrastructure before stopping
302
- if (options.dryrun) {
303
- currentStep++;
304
- spinner = (0, ora_1.default)(`Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Validating infrastructure (S3, blockchain, wallet)...`).start();
305
-
306
- const validationResults = {
307
- s3Access: false,
308
- s3Bucket: false,
309
- awsCredentials: false,
310
- walletValid: false,
311
- rpcConnection: false,
312
- collectionExists: false,
313
- apiConnection: false
314
- };
315
-
316
- try {
317
- // 1. Validate AWS Credentials
318
- const AWS = require('aws-sdk');
319
- // Check if credentials are available
320
- if (!process.env.S3_ACCESS_KEY || !process.env.S3_SECRET_KEY) {
321
- validationResults.awsCredentials = false;
322
- validationResults.s3Bucket = false;
323
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - AWS credentials not found in environment`;
324
- } else {
325
- const s3 = new AWS.S3({
326
- accessKeyId: process.env.S3_ACCESS_KEY,
327
- secretAccessKey: process.env.S3_SECRET_KEY,
328
- region: 'us-west-1'
329
- });
330
-
331
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Checking AWS credentials...`;
332
- try {
333
- // Test credentials by listing buckets
334
- await s3.listBuckets().promise();
335
- validationResults.awsCredentials = true;
336
- } catch (e) {
337
- validationResults.awsCredentials = false;
338
- }
339
-
340
- // 2. Check S3 bucket existence
341
- const bucket = networkName === 'mainnet' ? 'test.vault.genoverse.io' : 'test.vault.genoverse.io';
342
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Checking S3 bucket: ${bucket}...`;
343
- try {
344
- await s3.headBucket({ Bucket: bucket }).promise();
345
- validationResults.s3Bucket = true;
346
- } catch (e) {
347
- validationResults.s3Bucket = false;
348
- }
349
- }
350
-
351
- // 3. Check S3 write access by testing path construction
352
- const testRegistrationId = `bioip_dryrun_${Date.now()}`;
353
- const testS3Path = `biowallet/${credentials.wallet_address}/bioip/${testRegistrationId}/test.txt`;
354
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Validating S3 path access...`;
355
- validationResults.s3Access = true; // Path is valid
356
-
357
- // 4. Validate wallet format
358
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Validating wallet address...`;
359
- validationResults.walletValid = /^0x[a-fA-F0-9]{40}$/.test(credentials.wallet_address);
360
-
361
- // 5. Check Story Protocol RPC connection
362
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Connecting to Story Protocol RPC...`;
363
- const https = require('https');
364
- const rpcUrl = networkName === 'mainnet' ? 'https://mainnet.storyrpc.io/' : 'https://aeneid.storyrpc.io/';
365
-
366
- try {
367
- await new Promise((resolve, reject) => {
368
- const postData = JSON.stringify({
369
- jsonrpc: '2.0',
370
- method: 'eth_blockNumber',
371
- params: [],
372
- id: 1
373
- });
374
-
375
- const url = new URL(rpcUrl);
376
- const options = {
377
- hostname: url.hostname,
378
- port: url.port || 443,
379
- path: url.pathname,
380
- method: 'POST',
381
- headers: {
382
- 'Content-Type': 'application/json',
383
- 'Content-Length': Buffer.byteLength(postData)
384
- },
385
- timeout: 5000
386
- };
387
-
388
- const req = https.request(options, (res) => {
389
- let data = '';
390
- res.on('data', (chunk) => { data += chunk; });
391
- res.on('end', () => {
392
- try {
393
- const parsed = JSON.parse(data);
394
- if (parsed.result) {
395
- validationResults.rpcConnection = true;
396
- resolve();
397
- } else {
398
- reject(new Error('No result from RPC'));
399
- }
400
- } catch (e) {
401
- reject(e);
402
- }
403
- });
404
- });
405
-
406
- req.on('error', reject);
407
- req.on('timeout', () => {
408
- req.destroy();
409
- reject(new Error('RPC timeout'));
410
- });
411
-
412
- req.write(postData);
413
- req.end();
414
- });
415
- } catch (e) {
416
- validationResults.rpcConnection = false;
417
- }
418
-
419
- // 6. Check collection exists on-chain (if collectionAddress provided)
420
- if (collectionAddress && collectionAddress !== '0x0000000000000000000000000000000000000000') {
421
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Verifying collection on-chain...`;
422
- try {
423
- await new Promise((resolve, reject) => {
424
- const postData = JSON.stringify({
425
- jsonrpc: '2.0',
426
- method: 'eth_getCode',
427
- params: [collectionAddress, 'latest'],
428
- id: 1
429
- });
430
-
431
- const url = new URL(rpcUrl);
432
- const options = {
433
- hostname: url.hostname,
434
- port: url.port || 443,
435
- path: url.pathname,
436
- method: 'POST',
437
- headers: {
438
- 'Content-Type': 'application/json',
439
- 'Content-Length': Buffer.byteLength(postData)
440
- },
441
- timeout: 5000
442
- };
443
-
444
- const req = https.request(options, (res) => {
445
- let data = '';
446
- res.on('data', (chunk) => { data += chunk; });
447
- res.on('end', () => {
448
- try {
449
- const parsed = JSON.parse(data);
450
- if (parsed.result && parsed.result !== '0x' && parsed.result !== '0x0') {
451
- validationResults.collectionExists = true;
452
- resolve();
453
- } else {
454
- reject(new Error('No contract code at address'));
455
- }
456
- } catch (e) {
457
- reject(e);
458
- }
459
- });
460
- });
461
-
462
- req.on('error', reject);
463
- req.on('timeout', () => {
464
- req.destroy();
465
- reject(new Error('RPC timeout'));
466
- });
467
-
468
- req.write(postData);
469
- req.end();
470
- });
471
- } catch (e) {
472
- validationResults.collectionExists = false;
473
- }
474
- } else {
475
- validationResults.collectionExists = true; // No specific collection, OK
476
- }
477
-
478
- // 7. Check API connectivity
479
- spinner.text = `Step ${currentStep}/${steps + 1}: 🧪 DRYRUN - Testing API endpoint connectivity...`;
480
- try {
481
- await new Promise((resolve, reject) => {
482
- const apiUrl = new URL('https://genobank.app/api_bioip/');
483
- const options = {
484
- hostname: apiUrl.hostname,
485
- port: apiUrl.port || 443,
486
- path: apiUrl.pathname,
487
- method: 'GET',
488
- timeout: 5000
489
- };
490
-
491
- const req = https.request(options, (res) => {
492
- validationResults.apiConnection = (res.statusCode === 200 || res.statusCode === 404);
493
- resolve();
494
- });
495
-
496
- req.on('error', () => {
497
- validationResults.apiConnection = false;
498
- resolve(); // Don't reject, just mark as failed
499
- });
500
-
501
- req.on('timeout', () => {
502
- req.destroy();
503
- validationResults.apiConnection = false;
504
- resolve();
505
- });
506
-
507
- req.end();
508
- });
509
- } catch (e) {
510
- validationResults.apiConnection = false;
511
- }
512
-
513
- spinner.succeed(`Step ${currentStep}/${steps + 1}: āœ“ Infrastructure validation complete`);
514
-
515
- } catch (error) {
516
- spinner.fail(`Step ${currentStep}/${steps + 1}: Infrastructure validation failed`);
517
- }
518
-
519
- // Display validation results
520
- console.log('\n');
521
- const imageUrl = (0, collections_1.getDefaultImageForCategory)(detectedCategory);
522
- const licenseType = (0, licenses_1.getLicenseType)(options.license || 'non-commercial');
523
- const licenseDisplayName = getLicenseDisplayName(options.license || 'non-commercial');
524
-
525
- // Build full preview for dryrun
526
- const preview = buildMetadataPreview({
527
- fileName,
528
- fileSize,
529
- title: aiTitle,
530
- description: aiDescription || `${detectedCategory} dataset`,
531
- category: detectedCategory,
532
- fingerprint,
533
- snpCount,
534
- collection: collectionName,
535
- collectionAddress,
536
- license: licenseDisplayName,
537
- licenseType,
538
- imageUrl,
539
- network: network.name,
540
- wallet: credentials.wallet_address
541
- });
542
-
543
- console.log((0, boxen_1.default)(preview, {
544
- padding: 1,
545
- margin: 1,
546
- borderStyle: 'round',
547
- borderColor: 'cyan',
548
- title: '🧪 DRY RUN - Metadata Preview',
549
- titleAlignment: 'center'
550
- }));
551
-
552
- // Display infrastructure validation results
553
- console.log('\n');
554
- const allValid = Object.values(validationResults).every(v => v === true);
555
- const validationColor = allValid ? 'green' : 'yellow';
556
-
557
- const statusIcon = (valid) => valid ? chalk_1.default.green('āœ…') : chalk_1.default.red('āŒ');
558
-
559
- const infrastructureStatus =
560
- chalk_1.default.bold.white('šŸ”§ Infrastructure Validation Results\n\n') +
561
- `${statusIcon(validationResults.awsCredentials)} AWS Credentials: ${validationResults.awsCredentials ? chalk_1.default.green('Valid') : chalk_1.default.red('Invalid')}\n` +
562
- `${statusIcon(validationResults.s3Bucket)} S3 Bucket Access: ${validationResults.s3Bucket ? chalk_1.default.green('test.vault.genoverse.io exists') : chalk_1.default.red('Bucket not found')}\n` +
563
- `${statusIcon(validationResults.s3Access)} S3 Path Validation: ${validationResults.s3Access ? chalk_1.default.green('Path structure valid') : chalk_1.default.red('Invalid path')}\n` +
564
- `${statusIcon(validationResults.walletValid)} Wallet Address: ${validationResults.walletValid ? chalk_1.default.green('Valid format') : chalk_1.default.red('Invalid format')}\n` +
565
- `${statusIcon(validationResults.rpcConnection)} Story Protocol RPC: ${validationResults.rpcConnection ? chalk_1.default.green('Connected') : chalk_1.default.red('Connection failed')}\n` +
566
- `${statusIcon(validationResults.collectionExists)} Collection On-Chain: ${validationResults.collectionExists ? chalk_1.default.green('Verified') : chalk_1.default.red('Not found')}\n` +
567
- `${statusIcon(validationResults.apiConnection)} API Endpoint: ${validationResults.apiConnection ? chalk_1.default.green('Accessible') : chalk_1.default.red('Not accessible')}\n\n` +
568
- (allValid
569
- ? chalk_1.default.green.bold('āœ… All infrastructure checks passed - Ready to tokenize!')
570
- : chalk_1.default.yellow.bold('āš ļø Some infrastructure checks failed - Fix issues before tokenizing'));
571
-
572
- console.log((0, boxen_1.default)(infrastructureStatus, {
573
- padding: 1,
574
- margin: 1,
575
- borderStyle: 'round',
576
- borderColor: validationColor,
577
- title: 'šŸ”§ Infrastructure Status',
578
- titleAlignment: 'center'
579
- }));
580
-
581
- console.log('\n');
582
- console.log((0, boxen_1.default)(chalk_1.default.cyan.bold('🧪 DRY RUN MODE COMPLETE\n\n') +
583
- chalk_1.default.white('All validation and AI classification steps completed!\n\n') +
584
- chalk_1.default.gray('āœ… File validated and fingerprinted\n') +
585
- chalk_1.default.gray('āœ… AI metadata generated by Claude Haiku\n') +
586
- chalk_1.default.gray('āœ… Collection and license configured\n') +
587
- chalk_1.default.gray(`${allValid ? 'āœ…' : 'āš ļø '} Infrastructure validation ${allValid ? 'passed' : 'has issues'}\n\n`) +
588
- chalk_1.default.yellow('āøļø Tokenization paused before data upload and blockchain minting\n\n') +
589
- chalk_1.default.white('To proceed with actual tokenization, run without --dryrun flag:\n\n') +
590
- chalk_1.default.cyan(`biofs tokenize "${absolutePath}" --network ${networkName} --license ${options.license || 'non-commercial'}`), {
591
- padding: 1,
592
- margin: 1,
593
- borderStyle: 'double',
594
- borderColor: 'cyan',
595
- title: '🧪 Dry Run Complete',
596
- titleAlignment: 'center'
597
- }));
598
- console.log('\n');
599
- return; // Exit without tokenizing
600
- }
601
-
602
- // Step 5: Upload to GenoBank with Web3 signature authentication
603
- spinner = (0, ora_1.default)(`Step ${currentStep}/${steps}: šŸ“¤ Uploading to secure GenoBank vault with Web3 authentication...`).start();
604
-
605
- // Check file size to determine upload method (fileSize already defined from fileStats at line 34)
606
- const CLOUDFLARE_LIMIT = 100 * 1024 * 1024; // 100MB CloudFlare limit
607
-
608
- let response;
609
- let s3Path;
610
-
611
- if (fileSize > CLOUDFLARE_LIMIT) {
612
- // Large file: Use direct S3 upload to bypass CloudFlare
613
- spinner.text = `Step ${currentStep}/${steps}: šŸ“¤ Large file detected (${(0, format_1.formatFileSize)(fileSize)}), uploading directly to S3...`;
614
-
615
- const AWS = require('aws-sdk');
616
-
617
- // Require AWS credentials from environment
618
- if (!process.env.S3_ACCESS_KEY || !process.env.S3_SECRET_KEY) {
619
- spinner.fail(`Step ${currentStep}/${steps}: āŒ AWS credentials not found`);
620
- console.error(chalk_1.default.red('\nāš ļø AWS credentials required for S3 upload'));
621
- console.error(chalk_1.default.yellow('Please set S3_ACCESS_KEY and S3_SECRET_KEY environment variables\n'));
622
- process.exit(1);
623
- }
624
-
625
- const s3 = new AWS.S3({
626
- accessKeyId: process.env.S3_ACCESS_KEY,
627
- secretAccessKey: process.env.S3_SECRET_KEY,
628
- region: 'us-west-1'
629
- });
630
-
631
- const bucket = networkName === 'mainnet' ? 'vault.genoverse.io' : 'test.vault.genoverse.io';
632
- const registrationId = `bioip_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
633
- s3Path = `biowallet/${credentials.wallet_address}/bioip/${registrationId}/${fileName}`;
634
-
635
- // Upload to S3 with progress
636
- const fileBuffer = await (0, promises_1.readFile)(absolutePath);
637
- await s3.upload({
638
- Bucket: bucket,
639
- Key: s3Path,
640
- Body: fileBuffer
641
- }).on('httpUploadProgress', (progress) => {
642
- const percentCompleted = Math.round((progress.loaded * 100) / progress.total);
643
- const progressBar = 'ā–“'.repeat(Math.floor(percentCompleted / 5)) + 'ā–‘'.repeat(20 - Math.floor(percentCompleted / 5));
644
- spinner.text = `Step ${currentStep}/${steps}: šŸ“¤ Uploading to S3 ${(0, format_1.formatFileSize)(progress.loaded)}/${(0, format_1.formatFileSize)(progress.total)} ${progressBar} ${percentCompleted}%`;
645
- }).promise();
646
-
647
- spinner.text = `Step ${currentStep}/${steps}: šŸ“¤ S3 upload complete, registering on blockchain...`;
648
-
649
- // Register with API using s3_path parameter (bypasses CloudFlare)
650
- const formDataS3 = new form_data_1.default();
651
- formDataS3.append('user_signature', credentials.user_signature);
652
- formDataS3.append('s3_path', s3Path);
653
- formDataS3.append('title', aiTitle);
654
- formDataS3.append('description', aiDescription || `${detectedCategory} dataset`);
655
- formDataS3.append('license_type', (0, licenses_1.getLicenseType)(options.license || 'non-commercial'));
656
- formDataS3.append('fingerprint', fingerprint);
657
- formDataS3.append('file_category', detectedCategory);
658
- formDataS3.append('collection_address', collectionAddress);
659
- formDataS3.append('image_url', (0, collections_1.getDefaultImageForCategory)(detectedCategory));
660
- formDataS3.append('network', networkName);
661
-
662
- response = await axios_1.default.post(`${API_BASE}/register_bioip`, formDataS3, {
663
- headers: {
664
- ...formDataS3.getHeaders()
665
- }
666
- });
667
- } else {
668
- // Small file: Use standard upload through CloudFlare
669
- const fileBuffer = await (0, promises_1.readFile)(absolutePath);
670
- const formData = new form_data_1.default();
671
- formData.append('user_signature', credentials.user_signature);
672
- formData.append('file', fileBuffer, fileName);
673
- formData.append('title', aiTitle);
674
- formData.append('description', aiDescription || `${detectedCategory} dataset`);
675
- formData.append('license_type', (0, licenses_1.getLicenseType)(options.license || 'non-commercial'));
676
- formData.append('fingerprint', fingerprint);
677
- formData.append('file_category', detectedCategory);
678
- formData.append('collection_address', collectionAddress);
679
- formData.append('image_url', (0, collections_1.getDefaultImageForCategory)(detectedCategory));
680
- formData.append('network', networkName);
681
-
682
- response = await axios_1.default.post(`${API_BASE}/register_bioip`, formData, {
683
- headers: {
684
- ...formData.getHeaders()
685
- },
686
- maxBodyLength: Infinity,
687
- maxContentLength: Infinity,
688
- onUploadProgress: (progressEvent) => {
689
- if (progressEvent.total) {
690
- const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
691
- const progressBar = 'ā–“'.repeat(Math.floor(percentCompleted / 5)) + 'ā–‘'.repeat(20 - Math.floor(percentCompleted / 5));
692
- spinner.text = `Step ${currentStep}/${steps}: šŸ“¤ Uploading ${(0, format_1.formatFileSize)(progressEvent.loaded)}/${(0, format_1.formatFileSize)(progressEvent.total)} ${progressBar} ${percentCompleted}%`;
693
- }
694
- }
695
- });
696
- }
697
-
698
- spinner.succeed(`Step ${currentStep}/${steps}: āœ“ Uploaded to encrypted S3 vault & registered in MongoDB`);
699
- currentStep++;
700
- // Debug: Log the response structure
701
- logger_1.Logger.debug(`API Response: ${JSON.stringify(response.data, null, 2)}`);
702
- // Step 6: Mint IP Asset on Story Protocol blockchain
703
- spinner = (0, ora_1.default)(`Step ${currentStep}/${steps}: ā›“ļø Minting IP Asset NFT on Story Protocol ${network.name}...`).start();
704
- // Extract response data - handle different response formats
705
- const responseData = response.data.status_details?.data ||
706
- response.data.status_details ||
707
- response.data.data ||
708
- response.data;
709
- // Check for IP ID in multiple possible locations
710
- const ipId = responseData.ip_id ||
711
- responseData.ipId ||
712
- responseData.ip_asset_id ||
713
- responseData.registration_id; // Sometimes used as temporary ID
714
- if (!ipId && response.data.status === 'Success') {
715
- // If successful but no IP ID, it might be pending blockchain confirmation
716
- console.log('\nāš ļø Transaction submitted but IP ID pending blockchain confirmation');
717
- }
718
- else if (!ipId) {
719
- throw new Error('No IP ID returned from tokenization');
720
- }
721
- spinner.succeed(`Step ${currentStep}/${steps}: āœ“ Smart contract executed successfully - IP Asset minted on-chain!`);
722
- // Generate BioCID
723
- const bioCID = generateBioCID(credentials.wallet_address, detectedCategory, fileName);
724
- // Display results
725
- console.log(chalk_1.default.gray('\n' + '━'.repeat(50)));
726
- console.log(chalk_1.default.green.bold('šŸŽ‰ BioIP Tokenization Complete!'));
727
- console.log(chalk_1.default.gray('━'.repeat(50) + '\n'));
728
- if (ipId) {
729
- console.log(`${chalk_1.default.cyan('šŸ“¦ IP Asset ID:')} ${chalk_1.default.white(ipId)}`);
730
- }
731
- console.log(`${chalk_1.default.cyan('šŸ”— BioCID:')} ${chalk_1.default.white(bioCID)}`);
732
- console.log(`${chalk_1.default.cyan('šŸ›ļø PIL License:')} ${chalk_1.default.white(getLicenseDisplayName(options.license || 'non-commercial'))}`);
733
- console.log(`${chalk_1.default.cyan('šŸ“Š Collection:')} ${chalk_1.default.white(collectionName)}`);
734
- console.log(`${chalk_1.default.cyan('🌐 Network:')} ${chalk_1.default.white(network.name)} (Chain ID: ${network.chainId})`);
735
- const txHash = responseData.tx_hash || responseData.txHash || responseData.transaction_hash;
736
- if (txHash) {
737
- console.log(`${chalk_1.default.cyan('šŸ” Transaction:')} ${chalk_1.default.white(txHash)}`);
738
- }
739
- if (snpCount) {
740
- console.log(`${chalk_1.default.cyan('🧬 Fingerprint:')} ${chalk_1.default.gray(snpCount.toLocaleString() + ' SNPs analyzed')}`);
741
- }
742
- if (ipId) {
743
- console.log(`\n${chalk_1.default.cyan('🌐 View on Block Explorer:')}`);
744
- console.log(chalk_1.default.white(` ${network.explorer}/ipa/${ipId}`));
745
- }
746
- // Save tokenization record
747
- const recordPath = await (0, tokenizations_1.saveTokenizationRecord)({
748
- fileName,
749
- filePath: absolutePath,
750
- ipId: ipId || 'pending',
751
- bioCID,
752
- collection: collectionAddress,
753
- license: options.license || 'non-commercial',
754
- title: aiTitle,
755
- description: aiDescription || `${detectedCategory} dataset`,
756
- fingerprint,
757
- snpCount,
758
- txHash: txHash || '',
759
- timestamp: new Date().toISOString(),
760
- wallet: credentials.wallet_address,
761
- network: networkName
762
- });
763
- console.log(`\nšŸ’¾ Details saved to: ${chalk_1.default.gray(recordPath)}`);
764
- }
765
- catch (error) {
766
- spinner.fail(`Step ${currentStep}/${steps}: Failed`);
767
- // Check for duplicate error
768
- if (error.response?.data?.status_details?.description?.includes('already tokenized') ||
769
- error.response?.data?.status_details?.description?.includes('already been registered')) {
770
- if (networkName === 'mainnet') {
771
- throw new Error('This genomic profile has already been tokenized on mainnet (duplicate fingerprint detected)');
772
- }
773
- // For testnet, this shouldn't happen - pass through the original error
774
- throw new Error(error.response.data.status_details.description);
775
- }
776
- // Check for API error
777
- if (error.response?.data?.status_details?.description) {
778
- throw new Error(error.response.data.status_details.description);
779
- }
780
- // Log debug info if available
781
- if (error.response?.data) {
782
- logger_1.Logger.debug(`API Response: ${JSON.stringify(error.response.data)}`);
783
- }
784
- throw error;
785
- }
786
- }
787
- function detectFileCategory(fileName, fileExt) {
788
- // Check by extension
789
- const extMap = {
790
- '.vcf': 'vcf',
791
- '.vcf.gz': 'vcf',
792
- '.bam': 'alignment',
793
- '.sam': 'alignment',
794
- '.fastq': 'sequence',
795
- '.fq': 'sequence',
796
- '.fastq.gz': 'sequence',
797
- '.fq.gz': 'sequence',
798
- '.fasta': 'sequence',
799
- '.fa': 'sequence',
800
- '.txt': 'dtc', // Assume text files are 23andMe/Ancestry
801
- '.csv': 'gwas',
802
- '.tsv': 'gwas',
803
- '.bed': 'annotation',
804
- '.gff': 'annotation',
805
- '.gtf': 'annotation',
806
- '.dcm': 'medical_imaging',
807
- '.dicom': 'medical_imaging'
808
- };
809
- // Check compound extensions first
810
- for (const [ext, category] of Object.entries(extMap)) {
811
- if (fileName.toLowerCase().endsWith(ext)) {
812
- return category;
813
- }
814
- }
815
- // Check simple extension
816
- const category = extMap[fileExt];
817
- if (category)
818
- return category;
819
- // Default to genomic
820
- return 'genomic';
821
- }
822
- function isGenomicFile(fileExt) {
823
- const genomicExtensions = ['.vcf', '.vcf.gz', '.txt', '.csv', '.tsv'];
824
- return genomicExtensions.includes(fileExt.toLowerCase());
825
- }
826
- function getCollectionName(address) {
827
- const collections = {
828
- '0x5021F7438ea502b0c346cB59F8E92B749Ecd74B5': 'Genomic Data',
829
- '0x19A615224D03487AaDdC43e4520F9D83923d9512': 'VCF Analysis',
830
- '0xB8d03f2E1C02e4cC5b5fe1613c575c01BDD12269': 'Alignment Data',
831
- '0x88Ed5b47ea8f609Ee14ac60968C3f76f9138a171': 'Sequence Data',
832
- '0x29853ed299B8FBBe16568840F3Bb2A8E40dc7401': 'SNP/Microarray',
833
- '0x495B1E8C54b572d78B16982BFb97908823C9358A': 'ML Analytics'
834
- };
835
- return collections[address] || 'Custom Collection';
836
- }
837
- function getLicenseDisplayName(license) {
838
- const licenses = {
839
- 'commercial': 'Commercial Remix',
840
- 'non-commercial': 'Non-Commercial Remix'
841
- };
842
- return licenses[license] || license;
843
- }
844
- function generateBioCID(wallet, category, filename) {
845
- // Format: biocid://wallet/category/filename
846
- return `biocid://${wallet.toLowerCase()}/${category}/${filename}`;
847
- }
848
- function buildMetadataPreview(data) {
849
- const lines = [];
850
- lines.push(chalk_1.default.bold.white('šŸ“ FILE INFORMATION'));
851
- lines.push(chalk_1.default.gray('─'.repeat(50)));
852
- lines.push(`${chalk_1.default.cyan('Name:')} ${chalk_1.default.white(data.fileName)}`);
853
- lines.push(`${chalk_1.default.cyan('Size:')} ${chalk_1.default.white((0, format_1.formatFileSize)(data.fileSize))}`);
854
- lines.push(`${chalk_1.default.cyan('Category:')} ${chalk_1.default.white(data.category)}`);
855
- lines.push('');
856
- lines.push(chalk_1.default.bold.white('šŸ·ļø NFT METADATA'));
857
- lines.push(chalk_1.default.gray('─'.repeat(50)));
858
- lines.push(`${chalk_1.default.cyan('Title:')} ${chalk_1.default.white(data.title)}`);
859
- lines.push(`${chalk_1.default.cyan('Description:')} ${chalk_1.default.white(data.description.length > 45 ? data.description.substring(0, 45) + '...' : data.description)}`);
860
- if (data.description.length > 45) {
861
- // Show full description in gray
862
- const wrapped = wrapText(data.description, 45);
863
- wrapped.slice(1).forEach(line => {
864
- lines.push(` ${chalk_1.default.gray(line)}`);
865
- });
866
- }
867
- lines.push('');
868
- lines.push(chalk_1.default.bold.white('šŸ” BLOCKCHAIN DETAILS'));
869
- lines.push(chalk_1.default.gray('─'.repeat(50)));
870
- lines.push(`${chalk_1.default.cyan('Network:')} ${chalk_1.default.white(data.network)}`);
871
- lines.push(`${chalk_1.default.cyan('Collection:')} ${chalk_1.default.white(data.collection)}`);
872
- lines.push(`${chalk_1.default.cyan('Address:')} ${chalk_1.default.gray(data.collectionAddress.substring(0, 20) + '...')}`);
873
- lines.push(`${chalk_1.default.cyan('License:')} ${chalk_1.default.white(data.license)}`);
874
- lines.push(`${chalk_1.default.cyan('Owner:')} ${chalk_1.default.gray(data.wallet.substring(0, 20) + '...')}`);
875
- lines.push('');
876
- lines.push(chalk_1.default.bold.white('šŸ”¬ GENOMIC DATA'));
877
- lines.push(chalk_1.default.gray('─'.repeat(50)));
878
- lines.push(`${chalk_1.default.cyan('Fingerprint:')} ${chalk_1.default.white(data.fingerprint.substring(0, 16) + '...')}`);
879
- if (data.snpCount) {
880
- lines.push(`${chalk_1.default.cyan('SNPs:')} ${chalk_1.default.white(data.snpCount.toLocaleString())} variants`);
881
- }
882
- lines.push('');
883
- lines.push(chalk_1.default.bold.white('šŸ–¼ļø NFT IMAGE'));
884
- lines.push(chalk_1.default.gray('─'.repeat(50)));
885
- lines.push(`${chalk_1.default.cyan('Image URL:')} ${chalk_1.default.gray(data.imageUrl.substring(0, 45) + '...')}`);
886
- return lines.join('\n');
887
- }
888
- function wrapText(text, maxLength) {
889
- const words = text.split(' ');
890
- const lines = [];
891
- let currentLine = '';
892
- for (const word of words) {
893
- if ((currentLine + ' ' + word).trim().length <= maxLength) {
894
- currentLine = (currentLine + ' ' + word).trim();
895
- }
896
- else {
897
- if (currentLine)
898
- lines.push(currentLine);
899
- currentLine = word;
900
- }
901
- }
902
- if (currentLine)
903
- lines.push(currentLine);
904
- return lines;
905
- }
906
- //# sourceMappingURL=tokenize.js.map