Class: Condenser::RollupProcessor
- Inherits:
-
NodeProcessor
- Object
- NodeProcessor
- Condenser::RollupProcessor
- Defined in:
- lib/condenser/processors/rollup_processor.rb
Instance Attribute Summary collapse
-
#options ⇒ Object
Returns the value of attribute options.
Attributes inherited from NodeProcessor
Instance Method Summary collapse
- #build_tree(renderStack, from, to, visited: nil) ⇒ Object
- #call(environment, input) ⇒ Object
- #exec_runtime(script, input) ⇒ Object
-
#initialize(dir = nil, options = {}) ⇒ RollupProcessor
constructor
A new instance of RollupProcessor.
Methods inherited from NodeProcessor
#binary, call, #exec_runtime_error, #exec_syntax_error, #name, #npm_install, #npm_module_path, setup
Constructor Details
#initialize(dir = nil, options = {}) ⇒ RollupProcessor
Returns a new instance of RollupProcessor.
8 9 10 11 12 13 |
# File 'lib/condenser/processors/rollup_processor.rb', line 8 def initialize(dir = nil, = {}) super(dir) npm_install('rollup', '@rollup/plugin-commonjs', '@rollup/plugin-node-resolve') @options = .freeze end |
Instance Attribute Details
#options ⇒ Object
Returns the value of attribute options.
6 7 8 |
# File 'lib/condenser/processors/rollup_processor.rb', line 6 def @options end |
Instance Method Details
#build_tree(renderStack, from, to, visited: nil) ⇒ Object
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/condenser/processors/rollup_processor.rb', line 281 def build_tree(renderStack, from, to, visited: nil) visited ||= [] return if visited.include?(from) visited << from if renderStack[from].nil? || renderStack[from].empty? nil elsif renderStack[from].include?(to) from else renderStack[from].each do |dep| if tree = build_tree(renderStack, dep, to, visited: visited) return "#{from}\n└ #{tree.lines.each_with_index.map{|l, i| "#{i == 0 ? '' : ' '}#{l}"}.join("")}" end end nil end end |
#call(environment, input) ⇒ Object
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 |
# File 'lib/condenser/processors/rollup_processor.rb', line 15 def call(environment, input) @environment = environment @input = input Dir.mktmpdir do |output_dir| @entry = File.join(output_dir, 'entry.js') = { input: @entry } = { file: File.join(output_dir, 'result.js'), format: 'iife', # output: { sourcemap: true, format: 'iife' }, globals: [], sourcemap: true } if input[:source] =~ /export\s+{[^}]+};?\z/i [:name] = File.basename(input[:filename], ".*").capitalize # output_options[:output][:name] = File.basename(input[:filename], ".*").capitalize end exec_runtime(<<-JS, @entry) const fs = require('fs'); const path = require('path'); const stdin = process.stdin; module.paths.push("#{File.join(npm_path, 'node_modules')}") var buffer = ''; stdin.resume(); stdin.setEncoding('utf8'); function emitMessages(buffer) { try { var message = JSON.parse(buffer); stdin.emit('message' + message.rid, message); return ''; } catch(e) { if (e.name === "SyntaxError") { if (e.message.startsWith('Unexpected non-whitespace character after JSON at position ')) { var pos = parseInt(e.message.slice(59)); emitMessages(buffer.slice(0,pos)); return emitMessages(buffer.slice(pos)); } else if (e.message.startsWith('Unexpected token { in JSON at position ')) { // This can be removed, once dropping support for node <= v18 var pos = parseInt(e.message.slice(39)); emitMessages(buffer.slice(0,pos)); return emitMessages(buffer.slice(pos)); } else { return buffer; } } else { console.log(JSON.stringify({method: 'error', args: [e.name, e.message]}) + "\\n"); process.exit(1); } } } stdin.on('data', function (chunk) { buffer += chunk; buffer = emitMessages(buffer); }); const rollup = require("#{npm_module_path('rollup')}"); const commonjs = require("#{npm_module_path('@rollup/plugin-commonjs')}"); const nodeResolve = require("#{npm_module_path('@rollup/plugin-node-resolve')}").nodeResolve; var rid = 0; var renderStack = {}; var nodeResolver = null; function request(method, args) { var trid = rid; rid += 1; var promise = new Promise(function(resolve, reject) { stdin.once('message' + trid, function(message) { resolve(message['return']); }); }); console.log(JSON.stringify({ rid: trid, method: method, args: args }) + "\\n"); return promise; } if ('#{environment.npm_path}' !== '') { nodeResolver = nodeResolve({ mainFields: ['module', 'main'], // modulesOnly: true, // preferBuiltins: false, moduleDirectories: [], modulePaths: ['#{npm_module_path}'] }); } const inputOptions = #{JSON.generate()}; inputOptions.plugins = []; inputOptions.plugins.push({ name: 'condenser', resolveId: function (importee, importer, options) { if (importee.startsWith('\\0') || (importer && importer.startsWith('\\0'))) { return null; } if (!(importer in renderStack)) { renderStack[importer] = []; } return request('resolve', [importee, importer]).then((value) => { if (!(value === null || value === undefined) && !renderStack[importer].includes(value)) { renderStack[importer].push(value); } return value; }); }, load: function(id) { if (id.startsWith('\\0')) { return null; } return request('load', [id]).then(function(value) { return value; }); } }); inputOptions.plugins.push(nodeResolver); inputOptions.plugins.push(commonjs()); // inputOptions.plugins.push({ // name: 'nullHanlder', // resolveId: function (importee, importer, options) { // request('log', [importee, importer, options]) // // request('error', ["AssetNotFound", importee, importer, renderStack]).then(function(value) { // // process.exit(1); // // }); // } // }); const outputOptions = #{JSON.generate()}; async function build() { try { // inputOptions.cache = await JSON.parse(request('get_cache', [])); const bundle = await rollup.rollup(inputOptions); await bundle.write(outputOptions); // await request('set_cache', [JSON.stringify(bundle)]); process.exit(0); } catch(e) { await request('error', [e.name, e.message, e.stack]); process.exit(1); } } build(); JS input[:source] = File.read(File.join(output_dir, 'result.js')) input[:source].delete_suffix!("//# sourceMappingURL=result.js.map\n") # asset.map = File.read(File.join(output_dir, 'result.js.map')) end end |
#exec_runtime(script, input) ⇒ Object
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/condenser/processors/rollup_processor.rb', line 177 def exec_runtime(script, input) io = IO.popen([binary, '-e', script], 'r+') buffer = '' begin while IO.select([io]) && io_read = io.read_nonblock(1_024) buffer << io_read = buffer.split("\n\n") buffer = if buffer.end_with?("\n\n") '' else .pop end .each do || = JSON.parse() ret = case ['method'] when 'resolve' importee, importer = ['args'] if importer.nil? && importee == @entry @entry elsif importee.start_with?('@babel/runtime') || importee.start_with?('core-js-pure') || importee.start_with?('regenerator-runtime') x = File.join(npm_module_path, importee.gsub(/^\.\//, File.dirname(importer) + '/')).sub('/node_modules/regenerator-runtime', '/node_modules/regenerator-runtime/runtime.js') x = "#{x}.js" if !x.end_with?('.js', '.mjs') File.file?(x) ? x : (x.delete_suffix('.js') + "/index.js") elsif npm_module_path && importee&.start_with?(npm_module_path) x = importee.end_with?('.js', '.mjs') ? importee : "#{importee}.js" x = (x.delete_suffix('.js') + "/index.js") if !File.file?(x) x elsif importee.start_with?('.') && importer.start_with?(npm_module_path) x = File.(importee, File.dirname(importer)) x = "#{x}.js" if !x.end_with?('.js', '.mjs') File.file?(x) ? x : (x.delete_suffix('.js') + "/index.js") elsif importee.end_with?('*') File.join(File.dirname(importee), '*') else @environment.find(importee, importer ? (@entry == importer ? @input[:source_file] : importer) : nil, accept: @input[:content_types].last)&.source_file end when 'load' importee = ['args'].first if importee == @entry { code: @input[:source], map: @input[:map] } elsif importee.end_with?('*') importees = @environment.resolve(importee, importer ? File.dirname(@entry == importer ? @input[:source_file] : importer) : nil, accept: @input[:content_types].last) code = "" code_imports = []; importees.each_with_index.map do |f, i| if f.has_default_export? code << "import _#{i} from '#{f.source_file}';\n" code_imports << "_#{i}" elsif f.has_exports? code << "import * as _#{i} from '#{f.source_file}';\n" code_imports << "_#{i}" else code << "import '#{f.source_file}';\n" end end code += "export default [#{code_imports.join(', ')}];" { code: code, map: nil } else asset = @environment.find(importee, accept: @input[:content_types].last) if asset { code: asset.source, map: asset.sourcemap } else nil end end when 'error' io.write(JSON.generate({rid: ['rid'], return: nil})) case ['args'][0] when 'AssetNotFound' = "Could not find import \"#{['args'][1]}\" for \"#{['args'][2]}\".\n\n" << build_tree(['args'][3], input, ['args'][2]) raise exec_runtime_error() else raise exec_runtime_error(['args'][0] + ': ' + ['args'][1]) end # when 'set_cache' # @environment.cache.set('rollup', message['args'][0]) # io.write(JSON.generate({rid: message['rid'], return: true})) # when 'get_cache' # io.write(JSON.generate({rid: message['rid'], return: [(@environment.cache.get('rollup') || '{}')] })) end io.write(JSON.generate({rid: ['rid'], return: ret})) end end rescue Errno::EPIPE, EOFError end io.close if $?.success? true else raise exec_runtime_error(buffer) end end |