|
274 | 274 | }
|
275 | 275 |
|
276 | 276 | let strict = /^(\s|\/\/.*)*["']use strict['"]/.test(code), ast
|
277 |
| - try { ast = acorn.parse(code) } |
| 277 | + try { ast = acorn.parse(code, {sourceType: detectSourceType(code)}) } |
278 | 278 | catch(e) { return code }
|
279 | 279 | let patches = []
|
280 | 280 | let backJump = "if (++__c % 1000 === 0) __sandbox.tick();"
|
|
293 | 293 | ForInStatement: loop,
|
294 | 294 | WhileStatement: loop,
|
295 | 295 | DoWhileStatement: loop,
|
| 296 | + ImportDeclaration(node) { |
| 297 | + dependencies.push(node.source.value) |
| 298 | + let req = "require(" + node.source.raw + ")", text |
| 299 | + if (node.specifiers.length == 0) { |
| 300 | + text = req |
| 301 | + } else if (node.specifiers.length > 1 || node.specifiers[0].type == "ImportDefaultSpecifier") { |
| 302 | + let name = modVar(node.source.value) |
| 303 | + text = "var " + name + " = " + req |
| 304 | + node.specifiers.forEach(spec => { |
| 305 | + if (spec.type == "ImportDefaultSpecifier") |
| 306 | + text += ", " + spec.local.name + " = " + name + ".default || " + name |
| 307 | + else if (name != null) |
| 308 | + text += ", " + spec.local.name + " = " + name + "." + spec.imported.name |
| 309 | + }) |
| 310 | + } else { |
| 311 | + text = "var " |
| 312 | + node.specifiers.forEach(spec => { |
| 313 | + if (spec.type == "ImportNamespaceSpecifier") |
| 314 | + text += spec.local.name + " = " + req |
| 315 | + else |
| 316 | + text += spec.local.name + " = " + req + "." + spec.imported.name |
| 317 | + }) |
| 318 | + } |
| 319 | + patches.push({from: node.start, to: node.end, text: text + ";"}) |
| 320 | + }, |
296 | 321 | CallExpression(node) {
|
297 | 322 | if (node.callee.type == "Identifier" && node.callee.name == "require" &&
|
298 | 323 | node.arguments.length == 1 && node.arguments[0].type == "Literal" &&
|
|
324 | 349 | pos = patch.to || patch.from
|
325 | 350 | }
|
326 | 351 | out += code.slice(pos, code.length)
|
| 352 | + console.log(out) |
327 | 353 | out += "\n//# sourceURL=code" + randomID()
|
328 | 354 | return {code: (strict ? '"use strict";' : "") + out, dependencies}
|
329 | 355 | }
|
330 | 356 |
|
| 357 | + function detectSourceType(code) { |
| 358 | + return /(^|\n)\s*(im|ex)port\b/.test(code) ? "module" : "script" |
| 359 | + } |
| 360 | + |
331 | 361 | function randomID() {
|
332 | 362 | return Math.floor(Math.random() * 0xffffffff).toString(16)
|
333 | 363 | }
|
|
0 commit comments