1/* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 20const path = require('path') 21 22const transCardArray = require('./templater/bind').transCardArray 23const resourceReferenceParsing = require('./resource-reference-script') 24 25import { logWarn } from './util' 26 27const REG_EVENT_STRING = /("\s*\$event\..+")|('\s*\$event\..+')/g 28const REG_EVENT = /\$event\.[\w]+/g 29const REG_THIS = /this\..*/g 30 31module.exports = function (source) { 32 this.cacheable && this.cacheable() 33 34 const extName = path.extname(this.resourcePath) 35 if (process.env.DEVICE_LEVEL === 'card') { 36 source = source.replace(/\/\*((\n|\r|.)*?)\*\//mg, "") 37 source = source.replace(/(\s|\;|^|\{|\})\/\/.*$/mg, "$1") 38 if (extName === '.js' || extName === '.json') { 39 if(source.trim().indexOf('export default') === 0) { 40 source = source.replace('export default', '') 41 } 42 source = resourceReferenceParsing(source) 43 source = source.replace(REG_EVENT_STRING, item => { 44 return item.slice(1,-1) 45 }) 46 source = source.replace(REG_EVENT, item => { 47 return '"' + item + '"' 48 }) 49 source = source.replace(REG_THIS, item => { 50 if (item.charAt(item.length-1) !== '\"' && 51 item.charAt(item.length-1) !== '\'' && 52 item.slice(-2) !== '\"\,' && 53 item.slice(-2) !== '\'\,') { 54 if (item.charAt(item.length-1) === ',') { 55 item = `"{{${transCardArray(item.slice(0, -1))}}}",`.replace(/this\./g, '') 56 } else { 57 item = `"{{${transCardArray(item)}}}"`.replace(/this\./g,'') 58 } 59 } 60 return item 61 }) 62 if (extName === '.js') { 63 try { 64 source = JSON.stringify(eval('(' + source + ')')) 65 } catch (e) { 66 logWarn(this, [{ 67 reason: 'ERROR: Failed to parse the file : ' + this.resourcePath + `\n${e}` 68 }]) 69 return `{}` 70 } 71 } else { 72 return source 73 } 74 } 75 } 76 return `module.exports = ${source}` 77} 78