UNPKG

strictencode

Version:

Deterministic binary encoding for RGB protocol compliance - JavaScript implementation of StrictEncode

66 lines (56 loc) 2.43 kB
/** * Build CommonJS version of the package */ import fs from 'fs'; import path from 'path'; const files = ['index.js', 'rgb20.js']; files.forEach(file => { const esm = fs.readFileSync(file, 'utf-8'); // Convert ES module syntax to CommonJS let cjs = esm .replace(/export\s+{([^}]+)}\s*;?/g, (match, exports) => { const exportList = exports.split(',').map(e => e.trim()).filter(e => e); return exportList.map(exp => { const [name, alias] = exp.split(' as ').map(s => s.trim()); const exportName = alias || name; return `module.exports.${exportName} = ${name};`; }).join('\n'); }) .replace(/export\s+(class|const|function)\s+(\w+)/g, (match, type, name) => { return `${type} ${name}`; }) .replace(/export\s+default\s+/g, 'module.exports = ') .replace(/import\s+{([^}]+)}\s+from\s+['"]([^'"]+)['"];?/g, (match, imports, from) => { if (from.startsWith('./')) { const cjsFrom = from.replace(/\.js$/, '.cjs'); return `const {${imports}} = require('${cjsFrom}');`; } return `const {${imports}} = require('${from}');`; }) .replace(/import\s+(\w+)\s+from\s+['"]([^'"]+)['"];?/g, (match, name, from) => { if (from.startsWith('./')) { const cjsFrom = from.replace(/\.js$/, '.cjs'); return `const ${name} = require('${cjsFrom}');`; } return `const ${name} = require('${from}');`; }); // Add exports at the end for classes and functions that were exported const exports = []; // Find exported classes const classMatches = esm.matchAll(/export\s+class\s+(\w+)/g); for (const match of classMatches) { exports.push(`module.exports.${match[1]} = ${match[1]};`); } // Find exported constants/functions const constMatches = esm.matchAll(/export\s+(const|function)\s+(\w+)/g); for (const match of constMatches) { exports.push(`module.exports.${match[2]} = ${match[2]};`); } if (exports.length > 0) { cjs += '\n\n// Exports\n' + exports.join('\n'); } const cjsFile = file.replace('.js', '.cjs'); fs.writeFileSync(cjsFile, cjs); console.log(`Generated ${cjsFile}`); }); console.log('CommonJS build complete');