diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 000000000..56342361d --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,36 @@ +### 议题类别 + + +- [ ] 错误报告 +- [ ] 功能请求 +- [ ] 支持问题 +- [ ] 其他问题 + +## 议题描述 + +## 议题信息 + + +### 使用的命令或代码 + + +### 使用的环境、平台、设备 + + + + +### 版本信息 + + + + +## 检查清单 + + +- [ ] 此问题没有在其他issue(议题)中出现 +- [ ] 我已将无名杀本体更新为最新版本 +- [ ] 我已将所有扩展更新为最新版本 +- [ ] 我填写了上面所有必要的信息 \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/其他问题.md b/.github/ISSUE_TEMPLATE/其他问题.md new file mode 100644 index 000000000..6f42fa6db --- /dev/null +++ b/.github/ISSUE_TEMPLATE/其他问题.md @@ -0,0 +1,32 @@ +--- +name: 其他问题 +about: 其他问题 +--- +## 问题描述 + +## 问题信息 + + +### 使用的命令或代码 + + +### 使用的环境、平台、设备 + + + + +### 版本信息 + + + + +## 检查清单 + + +- [ ] 此问题没有在其他issue(议题)中出现 +- [ ] 我已将无名杀本体更新为最新版本 +- [ ] 我已将所有扩展更新为最新版本 +- [ ] 我填写了上面所有必要的信息 \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/功能请求.md b/.github/ISSUE_TEMPLATE/功能请求.md new file mode 100644 index 000000000..00403ada7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/功能请求.md @@ -0,0 +1,29 @@ +--- +name: 功能请求 +about: 编写扩展或本体代码时,需要主分支来添加或修改某些功能代码的实现 +--- +## 功能描述 + +## 功能信息 + + +### 使用的环境、平台、设备 + + + + +### 版本信息 + + + + +## 检查清单 + + +- [ ] 此问题没有在其他issue(议题)中出现 +- [ ] 我已将无名杀本体更新为最新版本 +- [ ] 我已将所有扩展更新为最新版本 +- [ ] 我填写了上面所有必要的信息 \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/支持问题.md b/.github/ISSUE_TEMPLATE/支持问题.md new file mode 100644 index 000000000..90a785cf5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/支持问题.md @@ -0,0 +1,32 @@ +--- +name: 支持问题 +about: 某些接口对客户端的兼容性有问题 +--- +## 问题描述 + +## 问题信息 + + +### 使用的命令或代码 + + +### 使用的环境、平台、设备 + + + + +### 版本信息 + + + + +## 检查清单 + + +- [ ] 此问题没有在其他issue(议题)中出现 +- [ ] 我已将无名杀本体更新为最新版本 +- [ ] 我已将所有扩展更新为最新版本 +- [ ] 我填写了上面所有必要的信息 \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/错误报告.md b/.github/ISSUE_TEMPLATE/错误报告.md new file mode 100644 index 000000000..72e237754 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/错误报告.md @@ -0,0 +1,32 @@ +--- +name: 错误报告 +about: 游戏中遇到的错误弹窗,或是遇到技能卡牌结算不对 +--- +## 错误描述 + +## 错误信息 + + +### 使用的命令或代码 + + +### 使用的环境、平台、设备 + + + + +### 版本信息 + + + + +## 检查清单 + + +- [ ] 此问题没有在其他issue(议题)中出现 +- [ ] 我已将无名杀本体更新为最新版本 +- [ ] 我已将所有扩展更新为最新版本 +- [ ] 我填写了上面所有必要的信息 \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..3941a586b --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,34 @@ + + +### PR受影响的平台 + + + +### 诱因和背景 + + + + + +### PR描述 + + + + +### PR测试 + + + + +### 扩展适配 + + + + +### 检查清单 + +- [ ] 我已经进行了充足的测试,且现有的测试都已通过 +- [ ] 如果此次PR涉及到新功能的添加,我已在`PR描述`中写入详细文档 +- [ ] 如果此次PR需要扩展跟进,我已在`扩展适配`中写入详细文档 +- [ ] 如果这个PR解决了一个issue,我在`诱因和背景`中明确链接到该issue +- [ ] 我保证该PR中没有随意修改换行符等内容,没有制造出大量的Diff \ No newline at end of file diff --git a/audio/die/caofang.mp3 b/audio/die/caofang.mp3 new file mode 100644 index 000000000..dcead5311 Binary files /dev/null and b/audio/die/caofang.mp3 differ diff --git a/audio/die/tw_wenchou.mp3 b/audio/die/tw_wenchou.mp3 new file mode 100644 index 000000000..9a3a30ddc Binary files /dev/null and b/audio/die/tw_wenchou.mp3 differ diff --git a/audio/die/tw_yanliang.mp3 b/audio/die/tw_yanliang.mp3 new file mode 100644 index 000000000..97a355584 Binary files /dev/null and b/audio/die/tw_yanliang.mp3 differ diff --git a/audio/die/tw_yuantan.mp3 b/audio/die/tw_yuantan.mp3 new file mode 100644 index 000000000..5946ed144 Binary files /dev/null and b/audio/die/tw_yuantan.mp3 differ diff --git a/audio/skill/dcjujian1.mp3 b/audio/skill/dcjujian1.mp3 new file mode 100644 index 000000000..01acd1404 Binary files /dev/null and b/audio/skill/dcjujian1.mp3 differ diff --git a/audio/skill/dcjujian2.mp3 b/audio/skill/dcjujian2.mp3 new file mode 100644 index 000000000..15f07a8a6 Binary files /dev/null and b/audio/skill/dcjujian2.mp3 differ diff --git a/audio/skill/dczhimin1.mp3 b/audio/skill/dczhimin1.mp3 new file mode 100644 index 000000000..c302de8fd Binary files /dev/null and b/audio/skill/dczhimin1.mp3 differ diff --git a/audio/skill/dczhimin2.mp3 b/audio/skill/dczhimin2.mp3 new file mode 100644 index 000000000..db679995e Binary files /dev/null and b/audio/skill/dczhimin2.mp3 differ diff --git a/audio/skill/gztongduo1.mp3 b/audio/skill/gztongduo1.mp3 new file mode 100644 index 000000000..fcc33e4e0 Binary files /dev/null and b/audio/skill/gztongduo1.mp3 differ diff --git a/audio/skill/gztongduo2.mp3 b/audio/skill/gztongduo2.mp3 new file mode 100644 index 000000000..aec506e65 Binary files /dev/null and b/audio/skill/gztongduo2.mp3 differ diff --git a/audio/skill/twbaizu1.mp3 b/audio/skill/twbaizu1.mp3 new file mode 100644 index 000000000..66b76d5fd Binary files /dev/null and b/audio/skill/twbaizu1.mp3 differ diff --git a/audio/skill/twbaizu2.mp3 b/audio/skill/twbaizu2.mp3 new file mode 100644 index 000000000..a4743e777 Binary files /dev/null and b/audio/skill/twbaizu2.mp3 differ diff --git a/audio/skill/twduwang1.mp3 b/audio/skill/twduwang1.mp3 new file mode 100644 index 000000000..bf4c8173a Binary files /dev/null and b/audio/skill/twduwang1.mp3 differ diff --git a/audio/skill/twduwang2.mp3 b/audio/skill/twduwang2.mp3 new file mode 100644 index 000000000..8b9860e63 Binary files /dev/null and b/audio/skill/twduwang2.mp3 differ diff --git a/audio/skill/twjuexing1.mp3 b/audio/skill/twjuexing1.mp3 new file mode 100644 index 000000000..2d8ded5df Binary files /dev/null and b/audio/skill/twjuexing1.mp3 differ diff --git a/audio/skill/twjuexing2.mp3 b/audio/skill/twjuexing2.mp3 new file mode 100644 index 000000000..5ccaa619f Binary files /dev/null and b/audio/skill/twjuexing2.mp3 differ diff --git a/audio/skill/twqiaosi1.mp3 b/audio/skill/twqiaosi1.mp3 new file mode 100644 index 000000000..2ff639aea Binary files /dev/null and b/audio/skill/twqiaosi1.mp3 differ diff --git a/audio/skill/twqiaosi2.mp3 b/audio/skill/twqiaosi2.mp3 new file mode 100644 index 000000000..63375b5ad Binary files /dev/null and b/audio/skill/twqiaosi2.mp3 differ diff --git a/audio/skill/twxiayong1.mp3 b/audio/skill/twxiayong1.mp3 new file mode 100644 index 000000000..1bd635ea2 Binary files /dev/null and b/audio/skill/twxiayong1.mp3 differ diff --git a/audio/skill/twxiayong2.mp3 b/audio/skill/twxiayong2.mp3 new file mode 100644 index 000000000..1cd33b543 Binary files /dev/null and b/audio/skill/twxiayong2.mp3 differ diff --git a/audio/skill/twxiayong_tw_yanliang1.mp3 b/audio/skill/twxiayong_tw_yanliang1.mp3 new file mode 100644 index 000000000..b79596b1a Binary files /dev/null and b/audio/skill/twxiayong_tw_yanliang1.mp3 differ diff --git a/audio/skill/twxiayong_tw_yanliang2.mp3 b/audio/skill/twxiayong_tw_yanliang2.mp3 new file mode 100644 index 000000000..f7d92a941 Binary files /dev/null and b/audio/skill/twxiayong_tw_yanliang2.mp3 differ diff --git a/audio/skill/twylyanshi1.mp3 b/audio/skill/twylyanshi1.mp3 new file mode 100644 index 000000000..02c82e988 Binary files /dev/null and b/audio/skill/twylyanshi1.mp3 differ diff --git a/audio/skill/twylyanshi2.mp3 b/audio/skill/twylyanshi2.mp3 new file mode 100644 index 000000000..37bd5f7a7 Binary files /dev/null and b/audio/skill/twylyanshi2.mp3 differ diff --git a/card/extra.js b/card/extra.js index df068778b..519ada0a6 100644 --- a/card/extra.js +++ b/card/extra.js @@ -577,7 +577,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ player.loseToSpecial(cards,'muniu'); "step 1" for(var i=0;i1||get.mode()=='guozhan') player.loseHp(); + if(player.hp>1) player.loseHp(); } }, yuxi:{ @@ -1855,7 +1855,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ feilongduofeng_info:'①当你使用【杀】指定目标后,你可令目标角色弃置一张牌。②当你因使用【杀】而令其他角色进入濒死状态时,你可以获得其一张手牌。', taipingyaoshu:'太平要术', taipingyaoshu_info:'锁定技。①当你即将受到属性伤害时,取消之。②你的手牌上限+X(X为场上势力数-1)。③当你失去装备区里的【太平要术】时,你摸两张牌,然后若你的体力值大于1,你失去1点体力。', - taipingyaoshu_info_guozhan:'锁定技。①当你即将受到属性伤害时,取消之。②你的手牌上限+X(X为与你势力相同的角色数)。③当你失去装备区里的【太平要术】时,你摸两张牌,然后你失去1点体力。', + taipingyaoshu_info_guozhan:'锁定技。①当你即将受到属性伤害时,取消之。②你的手牌上限+X(X为与你势力相同的角色数)。③当你失去装备区里的【太平要术】时,你摸两张牌,然后若你的体力值大于1,你失去1点体力。', yuxi_skill:'玉玺', yuxi_skill2:'玉玺', yuxi:'玉玺', diff --git a/card/standard.js b/card/standard.js index 6c6e26e84..1aea5bef8 100644 --- a/card/standard.js +++ b/card/standard.js @@ -157,11 +157,10 @@ game.import('card',function(lib,game,ui,get,ai,_status){ if(target.hasSkillTag('useShan',null,event)) return true; if(target.isLinked()&&game.hasNature(event.card)&&get.attitude(target,player._trueMe||player)>0) return false; if(event.baseDamage+event.extraDamage<=0&&!game.hasNature(event.card,'ice')) return false; - if(target.hasSkillTag('freeShan',false,event,true)) return true; - if(event.shanRequired>1&&target.mayHaveShan(target,'use',null,'count')=target.hp+ ((player.hasSkillTag('jueqing',false,target)||target.hasSkill('gangzhi'))?target.hujia:0)) return true; if(!game.hasNature(event.card,'ice')&&get.damageEffect(target,player,target,get.nature(event.card))>=0) return false; + if(event.shanRequired>1&&target.mayHaveShan(target,'use',null,'count'){ - if(player===_status.currentPhase&&player.hasSkillTag('nokeep',true,{ - card:card, - target:target - },true)) return 2; let mode = get.mode(), taos = player.getCards('hs',i=>get.name(i)==='tao'&&lib.filter.cardEnabled(i,target,'forceEnable')); - if(target.hp>0){ - if(!player.isPhaseUsing()) return 0; + if(target!==_status.event.dying){ + if(!player.isPhaseUsing() || player.hasSkillTag('nokeep',true,{ + card:card, + target:target + },true)) return 2; let min = 7.2-4*player.hp/player.maxHp, nd = player.needsToDiscard(0,(i,player)=>{ return !player.canIgnoreHandcard(i)&&(taos.includes(i)||get.value(i)>=min); @@ -1536,7 +1534,9 @@ game.import('card',function(lib,game,ui,get,ai,_status){ if (get.damageEffect(target, player, target) >= 0) return 0; let pd = get.damageEffect(player, target, player), att = get.attitude(player, target); if (att > 0 && get.damageEffect(target, player, player) > pd) return 0; - let ts = target.mayHaveSha(player, 'respond', null, 'count'), ps = player.mayHaveSha(player, 'respond', null, 'count'); + let ts = target.mayHaveSha(player, 'respond', null, 'count'), ps = player.mayHaveSha(player, 'respond', player.getCards('h', i => { + return card === i || card.cards && card.cards.includes(i) || ui.selected.cards.includes(i); + }), 'count'); if (ts < 1 && ts << 3 < Math.pow(player.hp, 2)) return 0; if (att > 0) { if (ts < 1) return 0; @@ -1555,7 +1555,9 @@ game.import('card',function(lib,game,ui,get,ai,_status){ if (td >= 0) return td / get.attitude(target, target); let pd = get.damageEffect(player, target, player), att = get.attitude(player, target); if (att > 0 && get.damageEffect(target, player, player) > pd) return -2; - let ts = target.mayHaveSha(player, 'respond', null, 'count'), ps = player.mayHaveSha(player, 'respond', null, 'count'); + let ts = target.mayHaveSha(player, 'respond', null, 'count'), ps = player.mayHaveSha(player, 'respond', player.getCards('h', i => { + return card === i || card.cards && card.cards.includes(i) || ui.selected.cards.includes(i); + }), 'count'); if (ts < 1) return -1.5; if (att > 0) return -2; if (ts - ps < 1) return -2 - ts; @@ -2494,7 +2496,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ }, icesha_skill:{ inherit:'hanbing_skill', - trigger:{source:'damageBegin2'}, + trigger:{source:'damageBegin3'}, equipSkill:false, ruleSkill:true, filter:function(event){ @@ -2908,14 +2910,19 @@ game.import('card',function(lib,game,ui,get,ai,_status){ }, audio:true, check:function(event,player){ - if(event&&(event.ai||event.ai1)){ - var ai=event.ai||event.ai1; + if(!event) return true; + if(event.ai){ + var ai=event.ai; var tmp=_status.event; _status.event=event; var result=ai({name:'shan'},_status.event.player,event); _status.event=tmp; return result>0; } + let evt=event.getParent(); + if(player.hasSkillTag('noShan',null,evt)) return false; + if(!evt||!evt.card||!evt.player||player.hasSkillTag('useShan',null,evt)) return true; + if(evt.card&&evt.player&&player.isLinked()&&game.hasNature(evt.card)&&get.attitude(player,evt.player._trueMe||evt.player)>0) return false; return true; }, content:function(){ @@ -2940,8 +2947,6 @@ game.import('card',function(lib,game,ui,get,ai,_status){ if(!arg||!arg.player) return true; if(arg.player.hasSkillTag('unequip',false,{ target:player - })||arg.player.hasSkillTag('unequip_ai',false,{ - target:player })) return false; return true; }, @@ -2982,6 +2987,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ return true; }, forceLoad:true, + forceDie:true, content:function(){ 'step 0' delete event.wuxieresult; diff --git a/card/swd.js b/card/swd.js index 5d10daaf9..bb5764f0b 100644 --- a/card/swd.js +++ b/card/swd.js @@ -2418,7 +2418,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ if(card&&card.storage.shouna&&card.storage.shouna.length){ return '共有'+get.cnNumber(card.storage.shouna.length)+'张牌'; } - return '共有〇张牌'; + return '共有零张牌'; }, mark:function(dialog,storage,player){ var card=player.getEquip('lianyaohu'); @@ -2426,7 +2426,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ dialog.addAuto(card.storage.shouna); } else{ - return '共有〇张牌'; + return '共有零张牌'; } }, markcount:function(storage,player){ @@ -3099,7 +3099,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ event.hu=hu; } 'step 1' - if(!event.card.destroyed){ + if(!event.card._selfDestroyed){ event.hu.storage.shouna.push(event.card); player.updateMarks(); } @@ -4588,7 +4588,7 @@ game.import('card',function(lib,game,ui,get,ai,_status){ content:function(){ "step 0" if(event.isMine()){ - event.longfan=ui.create.control('〇','〇','〇','〇',function(){ + event.longfan=ui.create.control('零','零','零','零',function(){ event.longfan.status--; }); event.longfan.status=4; diff --git a/character/clan.js b/character/clan.js index f330b635b..368646427 100644 --- a/character/clan.js +++ b/character/clan.js @@ -20,21 +20,181 @@ game.import('character',function(lib,game,ui,get,ai,_status){ clan_wanghun:['male','jin',3,['clanfuxun','clanchenya','clanzhongliu'],['clan:太原王氏']], clan_zhonghui:['male','wei','3/4',['clanyuzhi','clanxieshu','clanbaozu'],['clan:颍川钟氏']], clan_zhongyu:['male','wei',3,['clanjiejian','clanhuanghan','clanbaozu'],['clan:颍川钟氏']], - clan_wanglun:['male','wei',3,['clanqiuxin','clanjianyuan','clanzhongliu'],['clan:太原王氏']], + clan_wanglun:['male','jin',3,['clanqiuxin','clanjianyuan','clanzhongliu'],['clan:太原王氏']], clan_xunyou:['male','wei',3,['clanbaichu','clandaojie'],['clan:颍川荀氏']], clan_wuqiao:['male','jin',4,['clanqiajue','clanmuyin'],['clan:陈留吴氏']], + clan_wangguang:['male','wei',3,['clanlilun','clanjianji','clanzhongliu'],['clan:太原王氏']], }, characterSort:{ clan:{ clan_wu:['clan_wuxian','clan_wuban','clan_wukuang','clan_wuqiao'], clan_xun:['clan_xunshu','clan_xunchen','clan_xuncai','clan_xuncan','clan_xunyou'], clan_han:['clan_hanshao','clan_hanrong'], - clan_wang:['clan_wangling','clan_wangyun','clan_wanghun','clan_wanglun'], + clan_wang:['clan_wangling','clan_wangyun','clan_wanghun','clan_wanglun','clan_wangguang'], clan_zhong:['clan_zhongyan','clan_zhonghui','clan_zhongyu'], }, }, /** @type { importCharacterConfig['skill'] } */ skill:{ + //族贝斯塔[doge] + clanlilun:{ + audio:2, + enable:'phaseUse', + filter(event,player){ + return player.hasCard(card=>get.info('clanlilun').filterCard(card,player),'h'); + }, + filterCard(card,player){ + if(player.getStorage('clanlilun').includes(card.name)) return false; + if(ui.selected.cards.length&&ui.selected.cards[0].name!=card.name) return false; + const cards=player.getCards('h',cardx=>player.canRecast(cardx)); + return cards.includes(card)&&cards.filter(i=>i.name==card.name).length>1; + }, + selectCard:2, + position:'h', + check(card){ + const player=get.event('player'); + const value=function(card,player){ + const num=player.getUseValue(card); + return num>0?(num+(1/(get.value(card)||0.5))+7):7-get.value(card); + }; + if(ui.selected.cards.length&&value(card,player){ + player.unmarkSkill('clanlilun'); + delete player.storage.clanlilun; + }); + } + player.markAuto('clanlilun',event.cards.slice().map(card=>card.name)); + const cards=event.cards.filterInD('d'); + if(cards.some(card=>player.hasUseTarget(card))){ + const {result:{bool,links}}=await player.chooseButton(['离论:是否使用其中的一张牌?',cards]).set('filterButton',button=>{ + return get.event('player').hasUseTarget(button.link); + }).set('ai',button=>{ + return get.event('player').getUseValue(button.link); + }); + if(bool){ + const card=links[0]; + player.$gain2(card,false); + await game.asyncDelayx(); + await player.chooseUseTarget(true,card,false); + } + } + }, + onremove:true, + intro:{content:'本回合已重铸过$'}, + ai:{ + order(item,player){ + let cards=player.getCards('h',card=>get.info('clanlilun').filterCard(card,player)&&player.getUseValue(card)>0); + cards=cards.filter(card=>cards.filter(i=>i.name==card.name).length>1); + if(!cards.length) return 1; + cards.sort((a,b)=>get.order(b)-get.order(a)); + return get.order(cards[0])-0.001; + }, + result:{player:1}, + }, + }, + clanjianji:{ + unique:true, + limited:true, + audio:2, + trigger:{global:'phaseJieshuBegin'}, + filter(event,player){ + if(!event.player.isIn()) return false; + const targets=game.filterPlayer(target=>{ + return event.player.getPrevious()==target||event.player.getNext()==target; + }); + if(!targets.length) return false; + const card=new lib.element.VCard({name:'sha'}); + return !targets.some(target=>{ + return target.getHistory('useCard').length; + })||(player.hasUseTarget(card)&&!targets.some(target=>{ + return game.hasPlayer2(current=>{ + return current.getHistory('useCard',evt=>{ + return evt.targets&&evt.targets.includes(target); + }).length; + }); + })); + }, + skillAnimation:true, + animationColor:'watar', + prompt2(event,player){ + let str=''; + const card=new lib.element.VCard({name:'sha'}); + const targets=game.filterPlayer(target=>{ + return event.player.getPrevious()==target||event.player.getNext()==target; + }),bool=(!targets.some(target=>{ + return target.getHistory('useCard').length; + })),goon=(player.hasUseTarget(card)&&!targets.some(target=>{ + return game.hasPlayer2(current=>{ + return current.getHistory('useCard',evt=>{ + return evt.targets&&evt.targets.includes(target); + }).length; + }); + })); + if(bool){ + if(goon) str+='你可以'; + str+='与'+get.translation(get.translation(event.player))+'各摸一张牌'; + } + if(goon){ + if(bool) str+=',然后你可以'; + str+='视为使用一张【杀】'; + } + return str; + }, + check(event,player){ + const card=new lib.element.VCard({name:'sha'}); + const targets=game.filterPlayer(target=>{ + return event.player.getPrevious()==target||event.player.getNext()==target; + }),bool=(!targets.some(target=>{ + return target.getHistory('useCard').length; + })),goon=(player.hasUseTarget(card)&&!targets.some(target=>{ + return game.hasPlayer2(current=>{ + return current.getHistory('useCard',evt=>{ + return evt.targets&&evt.targets.includes(target); + }).length; + }); + })); + return (bool&&(get.attitude(player,event.player)>0||event.player.countCards('h')>player.countCards('h')))||(goon&&player.hasValueTarget(card)); + }, + logTarget:'player', + async content(event,trigger,player){ + player.awakenSkill('clanjianji'); + const card=new lib.element.VCard({name:'sha'}); + const targets=game.filterPlayer(target=>{ + return trigger.player.getPrevious()==target||trigger.player.getNext()==target; + }),boolx=(!targets.some(target=>{ + return target.getHistory('useCard').length; + })),goon=(player.hasUseTarget(card)&&!targets.some(target=>{ + return game.hasPlayer2(current=>{ + return current.getHistory('useCard',evt=>{ + return evt.targets&&evt.targets.includes(target); + }).length; + }); + })); + if(boolx){ + let draw=false; + if(goon){ + const {result:{bool}}=await player.chooseBool('是否与'+get.translation(trigger.player)+'各摸一张牌?').set('choice',get.attitude(player,trigger.player)>0||trigger.player.countCards('h')>player.countCards('h')); + if(bool) draw=true; + } + else draw=true; + if(draw){ + await player.draw('nodelay'); + await trigger.player.draw(); + } + } + if(goon) await player.chooseUseTarget(card,false,!boolx); + }, + }, //族吴乔 clanqiajue:{ audio:2, @@ -447,17 +607,15 @@ game.import('character',function(lib,game,ui,get,ai,_status){ 'step 2' if(!player.countCards('h')) event.finish(); 'step 3' - player.chooseCard('迂志:请展示一张手牌','摸此牌牌名字数的牌。下一轮开始时,若本轮你使用的牌数或上一轮你以此法摸的牌数小于此牌牌名字数,则你失去1点体力。',true,function(card,player){ + player.chooseToDiscard('迂志:请弃置一张手牌','摸此牌牌名字数的牌。下一轮开始时,若本轮你使用的牌数或上一轮你以此法摸的牌数小于此牌牌名字数,则你失去1点体力。',true,function(card,player){ var num=get.cardNameLength(card); return typeof num=='number'&&num>0; - }).set('ai',function(card){ + }).set('logSkill','clanyuzhi').set('ai',function(card){ if(_status.event.dying&&_status.event.num>0&&get.cardNameLength(card)>_status.event.num) return 1/get.cardNameLength(card);//怂 return get.cardNameLength(card);//勇 }).set('dying',player.hp+player.countCards('hs',{name:['tao','jiu']})<1).set('num',event.num1); 'step 4' if(result.bool){ - player.logSkill('clanyuzhi'); - player.showCards(result.cards,get.translation(player)+'发动了【迂志】'); player.draw(get.cardNameLength(result.cards[0])); player.storage.clanyuzhi=get.cardNameLength(result.cards[0]); player.markSkill('clanyuzhi'); @@ -474,7 +632,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ audio:2, trigger:{player:'damageEnd',source:'damageSource'}, filter(event,player){ - if(!event.card) return false; + if(!event.card||player.isLinked()) return false; + if(game.getGlobalHistory('everything',evt=>{ + if(evt.name!='damage'||!evt.card) return false; + return evt.player==player||(evt.source&&evt.source==player); + }).indexOf(event)!=0) return false; var num=get.cardNameLength(event.card); return typeof num=='number'&&num>0&&player.countCards('he')>0; }, @@ -483,7 +645,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ 'step 0' var num=get.cardNameLength(trigger.card),str=''; if(player.getDamagedHp()>0) str+=('并摸'+get.cnNumber(player.getDamagedHp())+'张牌'); - player.chooseToDiscard(get.prompt('clanxieshu'),'弃置'+get.cnNumber(num)+'张牌'+str,'he',num).set('ai',function(card){ + player.chooseToDiscard(get.prompt('clanxieshu'),'横置武将牌,弃置'+get.cnNumber(num)+'张牌'+str,'he',num).set('ai',function(card){ var player=_status.event.player; var num=_status.event.num; var num2=player.getDamagedHp(); @@ -492,7 +654,10 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return 0; }).set('num',num).logSkill='clanxieshu'; 'step 1' - if(result.bool&&player.getDamagedHp()>0) player.draw(player.getDamagedHp()); + if(result.bool){ + player.link(true); + if(player.getDamagedHp()>0) player.draw(player.getDamagedHp()); + } }, ai:{threaten:3}, }, @@ -1075,8 +1240,8 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } } }, - prompt(result){ - if(result.index>0) return '点击“确定”以观看牌堆顶牌'; + prompt(result,player){ + if(!player.storage.clanguangu) return '点击“确定”以观看牌堆顶牌'; return '观骨:选择观看牌的目标'; }, }, @@ -1231,7 +1396,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, clanzhongliu:{ audio:2, - audioname:['clan_wangling','clan_wangyun','clan_wanghun','clan_wanglun'], + audioname:['clan_wangling','clan_wangyun','clan_wanghun','clan_wanglun','clan_wangguang'], trigger:{player:'useCard'}, forced:true, clanSkill:true, @@ -2315,6 +2480,10 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, clandianzhan:{ audio:2, + intro:{ + content:'已使用过的花色:$', + onunmark:true + }, trigger:{player:'useCardAfter'}, forced:true, filter(event,player){ @@ -2333,13 +2502,50 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, content(){ 'step 0' - if(trigger.targets&&trigger.targets.length==1){ + if(trigger.targets&&trigger.targets.length==1&&!trigger.targets[0].isLinked()){ trigger.targets[0].link(true); + event.link=true; } var cards=player.getCards('h',card=>get.suit(card)==get.suit(trigger.card)&&player.canRecast(card)); - if(cards.length>0) player.recast(cards); + if(cards.length>0){ + player.recast(cards); + event.recast=true; + } 'step 1' - player.draw(); + if(event.link&&event.recast) player.draw(); + }, + group:['clandianzhan_count','clandianzhan_clear'], + subSkill:{ + count:{ + trigger:{player:'useCardAfter'}, + filter(event,player){ + let suit=get.suit(event.card); + return lib.suits.includes(suit)&&!player.getStorage('clandianzhan').includes(suit); + }, + silent:true, + charlotte:true, + content(){ + player.storage.clandianzhan=[]; + for(let i=player.actionHistory.length-1; i>=0; i--){ + let history=player.actionHistory[i].useCard; + for(let evt of history){ + player.storage.clandianzhan.add(get.suit(evt.card)); + } + if(player.actionHistory[i].isRound) break; + } + player.markSkill('clandianzhan'); + }, + sub:true + }, + clear:{ + trigger:{global:'roundStart'}, + silent:true, + charlotte:true, + content(){ + player.unmarkSkill('clandianzhan'); + }, + sub:true + } } }, clanhuanyin:{ @@ -2622,6 +2828,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ zhongyu:'钟毓(?-263年),字稚叔,颍川长社(今河南长葛市)人。三国时期魏国大臣,太傅钟繇之子、司徒钟会之兄。出身颍川钟氏,机灵敏捷,有其父之遗风。十四岁时,起家散骑侍郎。太和初年,迁黄门侍郎,袭封定陵县侯。正始年间,拜散骑常侍,迁魏郡太守,入为侍中、御史中丞、廷尉 [5] 。随平诸葛诞的淮南叛乱,拜青州刺史、后将军,都督徐州、荆州诸军事。景元四年(263年),去世,追赠车骑将军,谥号为惠,著有文集五卷(见《隋书·经籍志》及《两唐书·经籍志》),传于世。', wanglun:'王沦(233年-257年)字太冲,出身太原晋阳王姓世族(今山西省太原市),王昶三子,王浑、王深之弟,王湛之兄。醇粹简远,崇尚老庄之学,心思平淡。二十多时被举荐为孝廉,没有前往,后任大将军参军。257年,诸葛诞不满司马氏篡权而在寿春起义,王沦跟随司马昭征讨,遭遇疾疫去世,时年二十五,时人惜之,司马昭为他流泪。其兄著诔文《表德论》,表述其德行,说“因为畏惧帝王的典章制度,不能写墓志铭,于是撰写过往的事迹,刻在墓的背面。”', wuqiao:'吴乔,西晋人物,蜀车骑将军吴懿之孙。李雄建立成汉政权,他沦落益州,长达三十年,始终不向李雄屈服。', + clan_wangguang:'王广,三国时期曹魏太原祁县人,哲学家。东汉司徒王允从孙,魏太尉王凌之子。有志尚学,官至尚书。魏时随父亲在朝作官,屯骑校尉,机智有谋。当得知司马懿篡夺曹魏政权时,王凌与外甥令狐愚合谋立楚王为魏主,王广劝其父不可,王凌没有接受儿子的谏言,结果计谋泄而被害。', }, dynamicTranslate:{ clanlianzhu(player){ @@ -2679,7 +2886,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ clanlieshi:'烈誓', clanlieshi_info:'出牌阶段,你可以选择一项:1.废除判定区并受到你造成的1点火焰伤害;2.弃置所有【闪】;3.弃置所有【杀】。然后令一名其他角色从你未选择的选项中选择一项。', clandianzhan:'点盏', - clandianzhan_info:'锁定技。当你每轮第一次使用一种花色的牌后:若此牌的目标数为1,你横置此牌目标;若你有此花色的手牌,你重铸这些牌。然后你摸一张牌。', + clandianzhan_info:'锁定技。当你每轮第一次使用一种花色的牌后:若此牌的目标数为1且目标未横置,你横置此牌目标;若你有此花色的手牌,你重铸这些牌。均执行后你摸一张牌。', clanhuanyin:'还阴', clanhuanyin_info:'锁定技。当你进入濒死状态时,将手牌补至四张。', clan_xunchen:'族荀谌', @@ -2733,9 +2940,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ clanchenya_info:'当一名角色发动“出牌阶段限一次”的技能后,你可以令其重铸任意张牌名字数为X的牌(X为其手牌数)。', clan_zhonghui:'族钟会', clanyuzhi:'迂志', - clanyuzhi_info:'锁定技。新的一轮开始时,你依次执行以下项:①若你上一轮使用的牌数或你上上轮因〖迂志〗摸的牌数小于你上轮因〖迂志〗摸的牌数,你失去1点体力或失去〖保族〗。②你展示一张手牌,然后摸X张牌(X为此牌牌名字数)。', + clanyuzhi_info:'锁定技。新的一轮开始时,你依次执行以下项:①若你上一轮使用的牌数或你上上轮因〖迂志〗摸的牌数小于你上轮因〖迂志〗摸的牌数,你失去1点体力或失去〖保族〗。②你弃置一张手牌,然后摸X张牌(X为此牌牌名字数)。', clanxieshu:'挟术', - clanxieshu_info:'当你使用牌造成伤害后,或受到来自牌造成的伤害后,你可以弃置Y张牌并摸你已损失体力值张牌(Y为此牌牌名字数)。', + clanxieshu_info:'当你每回合首次因牌造成或受到伤害后,你可以横置武将牌,然后弃置Y张牌并摸你已损失体力值张牌(Y为此牌牌名字数)。', clan_zhongyu:'族钟毓', clanjiejian:'捷谏', clanjiejian_info:'当你于一回合使用第X张牌指定第一个目标后,若此牌不为装备牌,则你可以令一名目标角色摸X张牌。(X为此牌牌名字数)', @@ -2752,6 +2959,12 @@ game.import('character',function(lib,game,ui,get,ai,_status){ clan_wuqiao:'族吴乔', clanqiajue:'跒倔', clanqiajue_info:'摸牌阶段开始时,你可以弃置一张黑色牌。若如此做,此阶段结束时,你展示手牌,若这些牌的点数和大于30,你的手牌上限-2,否则你执行一个额外的摸牌阶段。', + clan_wangguang:'族王广', + clan_wangguang_prefix:'族', + clanlilun:'离论', + clanlilun_info:'出牌阶段限一次,你可以重铸两张手牌(不能是你本回合以此法重铸过的牌名的牌),然后使用其中的一张牌。', + clanjianji:'见机', + clanjianji_info:'限定技,一名角色的结束阶段,若其上下家均未于本回合:使用过牌,则你可以与其各摸一张牌;成为过牌的目标,则你可以视为使用一张【杀】。', clan_wu:'陈留·吴氏', clan_xun:'颍川·荀氏', diff --git a/character/ddd.js b/character/ddd.js index b437eb13f..493032017 100644 --- a/character/ddd.js +++ b/character/ddd.js @@ -1630,185 +1630,140 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, }, dddzhengjun:{ - trigger:{ - global:['loseAfter','equipAfter','addJudgeAfter','gainAfter','loseAsyncAfter','addToExpansionAfter'], - }, + trigger:{global:['damageEnd','loseHpEnd','recoverEnd','loseAfter','equipAfter','addJudgeAfter','gainAfter','loseAsyncAfter','addToExpansionAfter']}, filter(event,player){ if(!player.isPhaseUsing()) return false; - var boolh=!player.hasSkill('dddzhengjun_handcard',null,false,false),boole=(!player.hasSkill('dddzhengjun_equip')&&player.canMoveCard(null,true)); - var hs=player.countCards('h'),es=player.countCards('e'); - return game.hasPlayer(function(current){ - // if(player==current) return false; - if(boolh&¤t.countCards('h')==hs){ - var num=event.getl(current).hs.length; - if(event.getg) num-=event.getg(current).length; - if(num!=0) return game.hasPlayer(current=>{ - if(player==current) return false; - return current.countCards('h')==player.countCards('h'); - }); - } - if(boole&¤t.countCards('e')==es){ - var num=event.getl(current).es.length; - if(event.name=='equip'&¤t==event.player) num--; - if(num!=0) return game.hasPlayer(current=>{ - if(player==current) return false; - return current.countCards('e')==player.countCards('e'); - }); - } - return false; + if(event.name=='damage'||event.name=='loseHp'||event.name=='recover'){ + if(player.hasSkill('dddzhengjun_hp')) return false; + return event.player.getHp()==player.getHp(); + } + const info=get.info('dddzhengjun'); + const hs_check=info.hs_check,es_check=info.es_check; + return game.hasPlayer(target=>{ + if(event.getg&&event.getg(target)&&event.getg(target).length&&hs_check(player,target)) return true; + const evt=event.getl(target); + if(evt&&evt.hs&&evt.hs.length&&hs_check(player,target)) return true; + if(event.name=='equip'&&event.player==target&&(!evt||evt.cards.length!=1)&&es_check(player,target)) return true; + return evt&&evt.es&&evt.es.length&&es_check(player,target); }); }, - direct:true, - *content(event,map){ - var player=map.player,trigger=map.trigger; - var boolh=!player.hasSkill('dddzhengjun_handcard',null,false,false),hs=player.countCards('h'); - if(boolh&&game.hasPlayer(function(current){ - // if(player==current) return false; - if(boolh&¤t.countCards('h')==hs){ - var num=trigger.getl(current).hs.length; - if(trigger.getg) num-=trigger.getg(current).length; - if(num!=0) return game.hasPlayer(current=>{ - if(player==current) return false; - return current.countCards('h')==player.countCards('h'); - }); - } - return false; - })){ - var result=yield player.chooseTarget(get.prompt('dddzhengjun'),'令一名手牌数与你相等的其他角色摸或弃置一张牌',(card,player,target)=>{ - return player.countCards('h')==target.countCards('h')&&player!=target; - }).set('ai',target=>{ - var player=get.player(); - return Math.max(get.effect(target,{name:'draw'},player,player),get.effect(target,{name:'guohe'},player,player)/2); - }); - if(result.bool){ - var target=result.targets[0]; - var choices=['摸牌']; - if(target.countCards('he')) choices.push('弃牌'); - result=yield player.chooseControl(choices).set('prompt',`整军:请选择一项`).set('prompt2',`令${get.translation(target)}摸一张牌或弃置一张牌`).set('ai',()=>{ - return get.event('choice'); - }).set('choice',get.attitude(player,target)>0||!choices.includes('弃牌')?0:1); - player.logSkill('dddzhengjun',target); - player.addTempSkill('dddzhengjun_handcard','phaseUseAfter'); - if(result.control=='摸牌') target.draw(); - else target.chooseToDiscard('he',true); - } - } - var boole=(!player.hasSkill('dddzhengjun_equip')&&player.canMoveCard(null,true)),es=player.countCards('h'); - if(boolh&&game.hasPlayer(function(current){ - // if(player==current) return false; - if(boole&¤t.countCards('e')==es){ - var num=trigger.getl(current).es.length; - if(trigger.name=='equip'&&trigger.player==current) num--; - if(num!=0) return game.hasPlayer(current=>{ - if(player==current) return false; - return current.countCards('e')==player.countCards('e'); - }); - } - return false; - })){ - var result=yield player.chooseBool(get.prompt('dddzhengjun'),'移动一名装备区牌数与你相等的其他角色装备区里的一张牌').set('ai',function(){ - var targets=game.filterPlayer(target=>player.countCards('e')==target.countCards('e')&&player!=target); - return get.player().canMoveCard(true,true,targets); - }); - if(result.bool){ - player.logSkill('dddzhengjun'); - player.addTempSkill('dddzhengjun_equip','phaseUseAfter'); - player.moveCard(true,true,game.filterPlayer(target=>player.countCards('e')==target.countCards('e')&&player!=target)); - } - } + hs_check(player,target){ + return !player.hasSkill('dddzhengjun_hs')&&target.countCards('h')==player.countCards('h'); }, - content_old(){ - 'step 0' - var boolh=!player.hasSkill('dddzhengjun_handcard',null,false,false),hs=player.countCards('h'); - if(boolh&&game.hasPlayer(function(current){ - if(player==current) return false; - if(boolh&¤t.countCards('h')==hs){ - var num=trigger.getl(current).hs.length; - if(trigger.getg) num-=trigger.getg(current).length; - if(num!=0) return true; - } - return false; - })){ - player.chooseTarget('整军:是否令一名角色摸一张牌?').set('ai',function(target){ - var player=_status.event.player; - return get.effect(target,{name:'draw'},player,player); - }); - } - else event.goto(2); - 'step 1' - if(result.bool){ - var target=result.targets[0]; - player.logSkill('dddzhengjun',target); - player.addTempSkill('dddzhengjun_handcard','phaseUseAfter'); - target.draw(); - } - 'step 2' - var boole=(!player.hasSkill('dddzhengjun_equip')&&player.canMoveCard(null,true)),es=player.countCards('h'); - if(boolh&&game.hasPlayer(function(current){ - if(player==current) return false; - if(boole&¤t.countCards('e')==es){ - var num=trigger.getl(current).es.length; - if(trigger.name=='equip'&&trigger.player==current) num--; - if(num!=0) return true; - } - return false; - })){ - player.chooseBool('整军:是否移动场上的一张装备牌?').set('ai',function(){ - return _status.event.player.canMoveCard(true,true); - }) - } - else event.finish(); - 'step 3' - if(result.bool){ - player.logSkill('dddzhengjun'); - player.addTempSkill('dddzhengjun_equip','phaseUseAfter'); - player.moveCard(true).set('nojudge',true); - } + es_check(player,target){ + return !player.hasSkill('dddzhengjun_es')&&target.countCards('e')==player.countCards('e'); }, - group:'dddzhengjun_hp', - subSkill:{ - equip:{charlotte:true}, - handcard:{charlotte:true}, - hp:{ - trigger:{global:['damageEnd','loseHpEnd','recoverEnd']}, - direct:true, - filter(event,player){ - if(player.hp!=event.player.hp) return false; - if(event.hujia&&event.hujia==event.num) return false; - if(!game.hasPlayer(current=>current.getHp()==player.getHp()&¤t!=player)) return false; - var evt=event.getParent('phaseUse'); - if(!evt||evt.player!=player) return false; - return !player.hasHistory('useSkill',function(evt){ - if(evt.skill=='dddzhengjun_hp'){ - if(evt.event.getParent('phaseUse')==event) return true; - } - return false; - }); - }, - content(){ - 'step 0' - player.chooseTarget(get.prompt('dddzhengjun'),'令一名体力值与你相等的其他角色回复或失去1点体力',function(card,player,target){ - return target.getHp()==player.getHp()&&player!=target; - }).set('ai',target=>{ - var player=get.player(); - return Math.max(get.recoverEffect(target,player,player),get.effect(target,{name:'losehp'},player,player)); - }); - 'step 1' - if(result.bool){ - var target=result.targets[0]; - event.target=target; - var choices=['失去体力']; - if(target.isDamaged()) choices.push('回复体力'); - player.chooseControl(choices).set('prompt',`整军:请选择一项`).set('prompt2',`令${get.translation(target)}失去1点体力或回复1点体力`).set('ai',()=>{ - return get.event('choice'); - }).set('choice',get.recoverEffect(target,player,player)>0&&target.isDamaged()?1:0); + async cost(event,trigger,player){ + if(trigger.name=='damage'||trigger.name=='loseHp'||trigger.name=='recover'){ + let list=['失去体力','cancel2']; + if(trigger.player.isDamaged()) list.unshift('回复体力'); + const {result:{control}}=await player.chooseControl(list) + .set('prompt',get.prompt('dddzhengjun',trigger.player)) + .set('prompt2','令'+get.translation(event.player)+'执行其中一项') + .set('ai',()=>{ + const player=get.event('player'),target=get.event().getTrigger().player; + if(get.event('controls').includes('回复体力')&&get.recoverEffect(target,player,player)>0) return '回复体力'; + return get.effect(target,{name:'losehp'},player,player)>0?'失去体力':'cancel2'; + }); + event.result={ + bool:control!='cancel2', + targets:[trigger.player], + cost_data:control, + }; + } + else{ + let map={}; + const hs_targets=game.filterPlayer(target=>{ + if(!get.info('dddzhengjun').hs_check(player,target)) return false; + if(trigger.getg&&trigger.getg(target)&&trigger.getg(target).length) return true; + const evt=trigger.getl(target); + return evt&&evt.hs&&evt.hs.length; + }); + const es_targets=game.filterPlayer(target=>{ + if(!get.info('dddzhengjun').es_check(player,target)) return false; + const evt=trigger.getl(target); + if(trigger.name=='equip'&&trigger.player==target&&(!evt||evt.cards.length!=1)) return true; + return evt&&evt.es&&evt.es.length; + }); + if(hs_targets.length){ + let target; + if(hs_targets.length==1) target=hs_targets[0]; + else{ + let targets=await player.chooseTarget(get.prompt('dddzhengjun'),'令其中一名角色摸一张牌或弃置一张牌',(card,player,target)=>{ + return get.event('targets').includes(target); + }).set('ai',target=>{ + const player=get.event('player'); + return Math.max(get.effect(target,{name:'guohe_copy2'},target,player),get.effect(target,{name:'draw'},player,player)); + }).set('targets',hs_targets).forResultTargets(); + if(targets&&targets.length) target=targets[0]; + } + if(target){ + let list=['摸牌']; + if(target.countCards('h')) list.push('弃牌'); + const {result:{control}}=await player.chooseControl(list,'cancel2') + .set('prompt',get.prompt('dddzhengjun',target)) + .set('prompt2','令'+get.translation(target)+'执行其中一项') + .set('ai',()=>{ + const player=get.event('player'),target=get.event().getTrigger().player; + if(get.event('controls').includes('弃牌')&&get.effect(target,{name:'guohe_copy2'},player,player)>0) return '弃牌'; + return get.effect(target,{name:'draw'},player,player)>0?'摸牌':'cancel2'; + }); + if(control!='cancel2'){ + map.hs_target=[target,control]; + } } - else event.finish(); - 'step 2' - player.logSkill('dddzhengjun_hp',target); - target[result.control=='失去体力'?'loseHp':'draw'](); } - }, + if(es_targets.length){ + let target; + if(hs_targets.length==1){ + const {result:{bool}}=await player.chooseBool() + .set('prompt',get.prompt('dddzhengjun',hs_targets[0])) + .set('prompt2','移动'+get.translation(hs_targets[0])+'的一张装备牌') + .set('choice',()=>player.canMoveCard(true,true,hs_targets[0])); + if(bool) target=hs_targets[0]; + } + else{ + let targets=await player.chooseTarget(get.prompt('dddzhengjun'),'移动其中一名角色的一张装备牌',(card,player,target)=>{ + return get.event('targets').includes(target); + }).set('ai',target=>{ + const player=get.event('player'); + return player.canMoveCard(true,true,target)?(1+Math.random()):0; + }).set('targets',es_targets).forResultTargets(); + if(targets&&targets.length) target=targets[0]; + } + if(target){ + map.es_target=target; + } + } + event.result={ + bool:(map.hs_target||map.es_target), + targets:[(map.hs_target||[])[0]].concat(map.es_target?[map.es_target]:[]), + cost_data:map, + }; + } + }, + async content(event,trigger,player){ + const data=event.cost_data; + if(trigger.name=='damage'||trigger.name=='loseHp'||trigger.name=='recover'){ + player.addTempSkill('dddzhengjun_hp','phaseUseAfter'); + await trigger.player[data=='回复体力'?'recover':'loseHp'](); + } + else{ + if(data.hs_target){ + player.addTempSkill('dddzhengjun_hs','phaseUseAfter'); + if(data.hs_target[1]=='摸牌') await data.hs_target[0].draw(); + else await data.hs_target[0].chooseToDiscard('he',true); + } + if(data.es_target){ + player.addTempSkill('dddzhengjun_es','phaseUseAfter'); + await player.moveCard(true,data.es_target); + } + } + }, + subSkill:{ + hs:{charlotte:true}, + es:{charlotte:true}, + hp:{charlotte:true}, }, }, dddxianxi:{ diff --git a/character/diy.js b/character/diy.js index bc32b2d9a..c9cd5422f 100755 --- a/character/diy.js +++ b/character/diy.js @@ -3420,7 +3420,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return get.itemtype(player.storage.mia_qianmeng)=='card'; }, async cost(event, trigger, player){ - event.result = await + event.result = await player.chooseTarget(get.prompt('mia_qianmeng'),'令一名角色获得牌堆中所有点数为'+player.storage.mia_qianmeng.number+'的牌',lib.filter.notMe).forResult(); }, async content(event, trigger, player){ @@ -6689,7 +6689,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ var next=get.copy(lib.skill.kud_qiaoshou_backupx); next.cardname=links[0][2]; return next; - }, + }, prompt(links){ return '将一张手牌置于武将牌上,然后视为装备'+get.translation(links[0][2]); }, @@ -9357,7 +9357,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if (result.bool) event.result = { bool: true, cards: result.links, - } + } }, logTarget: 'player', async content(event, trigger, player){ @@ -17676,22 +17676,23 @@ game.import('character',function(lib,game,ui,get,ai,_status){ trigger:{player:'useCard'}, forced:true, filter(event,player){ - return event.card.name=='sha'||get.type(event.card,null,false)=='trick'; + return event.card.name=='sha' || get.type(event.card,null,false)=='trick'; }, - content(){ - 'step 0' - var filter1=function(card){ - return get.name(card)=='sha'; - },filter2=function(card){ - return get.type(card)=='trick'; - }; - var num1=player.countCards('h',filter1),num2=player.countCards('h',filter2); - if(num1!=num2){ - var delta=num1-num2; - player.chooseToDiscard('h',true,Math.abs(delta),delta>0?filter1:filter2,'驭衡:请弃置'+get.cnNumber(Math.abs(delta))+'张'+(delta>0?'【杀】':'普通锦囊牌')); + async content(event, trigger, player){ + const cards1 = player.getCards('h', card => get.name(card) === 'sha'), cards2 = player.getCards('h', card => get.type(card) === 'trick'); + if (cards1.length !== cards2.length){ + const num = cards1.length - cards2.length, cards = num > 0 ? cards1 : cards2; + let i = 0; + cards.forEach(card => { + if (i < Math.abs(num) && lib.filter.cardDiscardable(card, player, 'junkquandao')) i++; + }); + if (i > 0) { + await player.chooseToDiscard(i, true, + `权道:请弃置${ get.cnNumber(i) }张${ num > 0 ? '杀' : '普通锦囊牌' }`, + num > 0 ? (card => get.name(card) === 'sha') : (card => get.type(card) === 'trick')) + } } - 'step 1' - player.draw(); + await player.draw(); }, }, junkchigang:{ @@ -17765,7 +17766,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.chooseButton(2,[ '蛮智:请选择让下列等式成立的A与B的值', '
目标等式
', - `0.5 × A² + 2.5 × B - ${game.roundNumber} = ${game.countPlayer()}`, + `0.5 × A2 + 2.5 × B - ${game.roundNumber} = ${game.countPlayer()}`, '
A的可选值
', [nums.map(i=>{ return [ @@ -17803,7 +17804,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(i[0]=='A') a=parseInt(i.slice(2)); else b=parseInt(i.slice(2)); } - equals=`0.5×${a}²+2.5×${b}-${game.roundNumber}=${game.countPlayer()}`; + equals=`0.5×${a}2+2.5×${b}-${game.roundNumber}=${game.countPlayer()}`; player.logSkill('nsmanzhi'); player.chat(equals); game.log(player,'的计算结果为',equals); @@ -18847,7 +18848,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ junkshengzhi:'圣质', junkshengzhi_info:'锁定技。当你发动非锁定技后,你令你本回合使用的下一张牌无距离和次数限制。', junkquandao:'权道', - junkquandao_info:'锁定技。当你使用【杀】或普通锦囊牌时,若你手牌中的【杀】或普通锦囊牌的数量之差X不为0,则你弃置X张数量较多的一种牌,然后你摸一张牌。', + junkquandao_info:'锁定技。当你使用【杀】或普通锦囊牌时,{若你手牌中的【杀】或普通锦囊牌的数量之差X不为0,则你弃置X张数量较多的一种牌},然后你摸一张牌。', junkchigang:'持纲', junkchigang_info:'转换技,锁定技。判定阶段开始前,你取消此阶段。然后你获得一个额外的:阴,摸牌阶段;阳,出牌阶段。', junkrende:'仁德', @@ -18889,7 +18890,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ ns_mengyou_prefix:'数学', ns_mengyou_ab:'孟优', nsmanzhi:'蛮智', - nsmanzhi_info:'准备阶段或结束阶段开始时,你可以将场上出现的数字代入等式中的A和B。若此等式成立,你摸Y张牌。(等式为Y=0.5A²+2.5B-X,其中X为游戏轮数,Y为存活人数)', + nsmanzhi_info:'准备阶段或结束阶段开始时,你可以将场上出现的数字代入等式中的A和B。若此等式成立,你摸Y张牌。(等式为Y=0.5A2+2.5B-X,其中X为游戏轮数,Y为存活人数)', ns_chengpu:'铁索程普', ns_chengpu_prefix:'铁索', ns_chengpu_ab:'程普', diff --git a/character/extra.js b/character/extra.js index 19dc20260..c85d11811 100755 --- a/character/extra.js +++ b/character/extra.js @@ -357,7 +357,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ node.link=item; const func=function(node,item){ - if(item!='unknown') node.setBackground(item,'character'); + const currentPlayer=game.findPlayer(current=>current.getSeatNum()==seat); + if(currentPlayer.classList.contains('unseen_show')) node.setBackground('hidden_image','character'); + else if(item!='unknown') node.setBackground(item,'character'); if(node.node){ node.node.name.remove(); node.node.hp.remove(); @@ -370,7 +372,6 @@ game.import('character',function(lib,game,ui,get,ai,_status){ group:ui.create.div('.identity',node), intro:ui.create.div('.intro',node), }; - const currentPlayer=game.findPlayer(current=>current.getSeatNum()==seat); const infoitem=[currentPlayer.sex,currentPlayer.group,`${currentPlayer.hp}/${currentPlayer.maxHp}/${currentPlayer.hujia}`]; node.node.name.innerHTML=get.slimName(item); if(lib.config.buttoncharacter_style=='default'||lib.config.buttoncharacter_style=='simple'){ diff --git a/character/huicui.js b/character/huicui.js index 2906d8a92..0689c9478 100644 --- a/character/huicui.js +++ b/character/huicui.js @@ -2859,7 +2859,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.logSkill('dcmanzhi',target); if(result.control=='选项一'){ player.addTempSkill('dcmanzhi_1'); - target.chooseCard(2,'he','蛮智:请交给'+get.translation(player)+'两张牌',true); + target.chooseCard(Math.min(2,target.countCards('he')),'he','蛮智:请交给'+get.translation(player)+'两张牌',true); } else{ player.addTempSkill('dcmanzhi_2'); @@ -4474,7 +4474,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } } return Math.random(); - }); + }).set('complexTarget', true); } 'step 1' if(result.bool){ @@ -5337,10 +5337,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ check:function(event,player){ var num=player.getDamagedHp()-1; if(num<=0) return false; - var list=game.filterPlayer().map(target=>{ - return get.attitude(player,target)*Math.pow(Math.max(0,target.maxHp-target.countCards('h')-1),2); - }).sort((a,b)=>b-a); - return list.slice(0,num).reduce((p,c)=>p+c,0)>0; + return game.hasPlayer(target=>{ + return get.attitude(player,target)>0&&target.maxHp-target.countCards('h')>1; + }); }, content:function(){ 'step 0' @@ -5348,7 +5347,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ 'step 1' var num=player.getDamagedHp(); if(!player.isIn()||!num) event.finish(); - else player.chooseTarget('御关:令'+get.cnNumber(num)+'名角色将手牌摸至体力上限',Math.min(game.countPlayer(),num),true).set('ai',target=>{ + else player.chooseTarget('御关:令'+get.cnNumber(num)+'名角色将手牌摸至体力上限',Math.min(game.countPlayer(),[1,num]),true).set('ai',target=>{ return get.attitude(_status.event.player,target)*Math.max(0.1,target.maxHp-target.countCards('h')); }); 'step 2' @@ -7096,6 +7095,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ content:function(){ 'step 0' player.showCards(cards,get.translation(player)+'发动了【数合】'); + player.addMark('dcliehou',1); 'step 1' event.cards2=[]; var num1=get.number(cards[0],player); @@ -7136,7 +7136,6 @@ game.import('character',function(lib,game,ui,get,ai,_status){ var target=result.targets[0]; player.line(target,'green'); player.give(cards,target); - player.addMark('dcliehou',1); } }, ai:{ @@ -9947,11 +9946,19 @@ game.import('character',function(lib,game,ui,get,ai,_status){ intro:{content:'不能使用手牌'}, charlotte:true, mod:{ - cardEnabled:function(card){ - if(get.position(card)=='h') return false; + cardEnabled:function(card,player){ + let hs=player.getCards('h'),cards=[card]; + if(Array.isArray(card.cards)) cards.addArray(card.cards); + for(let i of cards){ + if(hs.includes(i)) return false; + } }, - cardSavable:function(card){ - if(get.position(card)=='h') return false; + cardSavable:function(card,player){ + let hs=player.getCards('h'),cards=[card]; + if(Array.isArray(card.cards)) cards.addArray(card.cards); + for(let i of cards){ + if(hs.includes(i)) return false; + } }, }, }, @@ -11901,7 +11908,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ 'step 0' var target=trigger.player; event.target=target; - if(target.getHistory('sourceDamage').length>0&&player.canUse('juedou',target)){ + if(target.getHistory('useCard',evt=>get.color(evt.card)=='black').length>0&&player.canUse('juedou',target)){ player.useCard({name:'juedou',isCard:true},target,'dcxunji_effect'); } 'step 1' @@ -12413,7 +12420,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ furongfuqian:'傅肜(?-222年),义阳(今湖北枣阳)人,三国时蜀汉将领。刘备攻伐吴国时,傅肜为别督。后刘备被陆逊击败,傅肜率部断后,奋战至死。死前怒斥道:“吴狗!何有汉将军降者!”
傅佥[qiān] ( ? ~263年),义阳(治今湖北省枣阳市)人,蜀汉将领傅彤之子,三国时期蜀汉名将。金长于谋略,并颇有胆勇,姜维甚爱之。傅佥官至关中都督。魏国攻伐蜀汉时,傅佥和蒋舒防守阳安关,兵败战死。', qinlang:'秦朗(生卒年不详),字元明,小字阿蘇(一作阿鳔),新兴(治今山西忻州)云中人。三国时期曹魏将领,官至骁骑将军、给事中,曾率兵讨伐鲜卑轲比能和步度根的叛军。', xianglang:'向朗(约167年—247年),字巨达。襄阳郡宜城县(今湖北宜城)人,三国时期蜀汉官员、藏书家、学者。向朗早年师从于司马徽,并被荆州牧刘表任命为临沮县长。后随刘备入蜀,历任巴西、牂牁、房陵太守,并拜步兵校尉,领丞相长史,随丞相诸葛亮北伐。因包庇马谡被免职,后为光禄勋,转左将军、特进,封显明亭侯。曾代理丞相册封张皇后及太子刘璿。晚年专心研究典籍,诱导青年学习,家中藏书丰富,受到举国尊重。延熙十年(247年),向朗去世。《全三国文》收录有一篇《遗言戒子》', - yuantanyuanxiyuanshang:'袁谭袁尚介绍请移步「袁谭袁尚」,此处为袁熙的介绍。
袁熙(?-207年),字显奕(《后汉书》、《东光世系》作显雍),汝南郡汝阳县(今河南商水)人,是东汉末年占据河北的军阀袁绍次子,袁绍打败公孙瓒后,令袁熙为幽州刺史。袁绍官渡兵败后不久病死,其兄长袁谭、弟弟袁尚各自独立,互相攻伐,曹操趁机进攻袁谭、袁尚,并逐渐占河北。袁熙接纳兵败的袁尚后,因为属下叛变而逃往乌桓,被曹操击败后,逃往辽东太守公孙康帐下,却被公孙康杀死,二人首级被献给曹操。', + yuantanyuanxiyuanshang:'袁谭、袁尚的武将介绍请移步「袁谭袁尚」,此处为袁熙的介绍。
袁熙(?-207年),字显奕(《后汉书》、《东光世系》作显雍),汝南郡汝阳县(今河南商水)人,是东汉末年占据河北的军阀袁绍次子,袁绍打败公孙瓒后,令袁熙为幽州刺史。袁绍官渡兵败后不久病死,其兄长袁谭、弟弟袁尚各自独立,互相攻伐,曹操趁机进攻袁谭、袁尚,并逐渐占河北。袁熙接纳兵败的袁尚后,因为属下叛变而逃往乌桓,被曹操击败后,逃往辽东太守公孙康帐下,却被公孙康杀死,二人首级被献给曹操。', zhanghu:'张虎,生卒年不详,雁门马邑(今山西朔城区大夫庄)人。张辽之子,三国时期曹魏武将。官至偏将军,封晋阳侯,有一子张统。', mengjie:'孟节,南中蛮王孟获之兄。是小说《三国演义》中杜撰的人物,史上并无记载。诸葛亮南征孟获之时,帐下军士因误饮哑泉之水失语。当地山神告知诸葛亮,言万安溪畔有一高士隐居彼处,号“万安隐者”。其草庵后有一泉,名安乐泉,可解哑泉之毒。庵前生有一草,名薤叶芸香,可防瘴气之染。诸葛亮于是带人连夜前往其隐居之处,求得泉水草叶解毒防瘴,拜求隐士姓名,方知其名为孟节,由此而叹:“方信盗跖、下惠之事,今亦有之。”诸葛亮欲申奏刘禅,立其为王,孟节辞之。又以金帛赠之,孟节坚辞不受。诸葛亮嗟叹不已,拜别而回。', peiyuanshao:'裴元绍,《三国演义》人物,原黄巾军之武将。黄巾起义失败之后,与周仓一同率领残部在山中落草当山贼。公元200年,在关羽欲返刘备旗下,在突破曹操的五道关卡后路过其落草之地,与周仓一同向关羽要求能以期成为关羽家臣。但此时仅周仓同行,其他弟兄则于山中等待。不久后,因其欲夺偶然路过的赵云之马,反遭讨伐战败身死。', @@ -12537,7 +12544,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ recangchu:'仓储', recangchu2:'仓储', recangchu3:'仓储', - recangchu_info:'锁定技,游戏开始时,你获得3个“粮”。你的手牌上限+X(X为“粮”数)。当你于回合外得到后时,你获得一个“粮”。(你的“粮”数不能超过存活角色数)', + recangchu_info:'锁定技。①游戏开始时,你获得3个“粮”。你的手牌上限+X(X为“粮”数)。②每回合限一次,当你于回合外得到牌后,你获得一个“粮”。(你的“粮”数不能超过存活角色数)', reliangying:'粮营', reliangying_info:'弃牌阶段开始时,你可以摸至多X张牌,然后交给等量的角色各一张牌。(X为你的“粮”数)', reshishou:'失守', @@ -12551,7 +12558,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ zhuangdan_info:'锁定技,其他角色的回合结束时,若你的手牌数为全场唯一最多,则你令〖裂胆〗失效直到你下回合结束。', dc_caiyang:'蔡阳', dcxunji:'寻嫉', - dcxunji_info:'出牌阶段限一次,你可以选择一名其他角色。该角色的下个结束阶段开始时,若其于该回合内造成过伤害,则你视为对其使用一张【决斗】,且当此【决斗】对其造成伤害后,其对你造成等量的伤害。', + dcxunji_info:'出牌阶段限一次,你可以选择一名其他角色。该角色的下个结束阶段开始时,若其此回合使用过黑色牌,则你视为对其使用一张【决斗】,且当此【决斗】对其造成伤害后,其对你造成等量的伤害。', dcjiaofeng:'交锋', dcjiaofeng_info:'锁定技。每回合限一次,当你造成伤害时,若你本回合内未造成过其他伤害且你已损失的体力值:大于0,则你摸一张牌;大于1,则此伤害+1;大于2,则你回复1点体力。', zhoushan:'周善', @@ -12716,7 +12723,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ xingchong:'幸宠', xingchong_info:'一轮游戏开始时,你可声明两个自然数X和Y,且(X+Y)≤min(5, 你的体力上限)。你摸X张牌并展示Y张手牌。若如此做,当你于本轮内失去一张以此法展示的牌后,你摸两张牌。', liunian:'流年', - liunian_info:'锁定技。回合结束时,若本回合内进行了本次游戏的第一次洗牌,则你加1点体力上限;若本回合内进行了本次游戏的第二次洗牌,则你于本回合结束时回复1点体力,且本局游戏内的手牌上限+10。', + liunian_info:'锁定技。一名角色的回合结束时,若本回合内进行了本次游戏的第一次洗牌,则你加1点体力上限;若本回合内进行了本次游戏的第二次洗牌,则你于本回合结束时回复1点体力,且本局游戏内的手牌上限+10。', caimaozhangyun:'蔡瑁张允', lianzhou:'连舟', lianzhou_info:'锁定技。准备阶段,你横置你的武将牌。然后你可横置任意名体力值等于你的角色。', @@ -12751,7 +12758,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ qinbao_info:'锁定技。当你使用【杀】或普通锦囊牌时,你令所有手牌数不小于你的角色不能响应此牌。', dc_lvkuanglvxiang:'吕旷吕翔', dcshuhe:'数合', - dcshuhe_info:'出牌阶段限一次,你可以展示一张手牌。若场上有与此牌点数相同的牌,则你获得这些牌;否则你将此牌交给一名其他角色并获得一枚“爵”。', + dcshuhe_info:'出牌阶段限一次,你可以展示一张手牌并获得一枚“爵”。若场上有与此牌点数相同的牌,则你获得这些牌;否则你将此牌交给一名其他角色。', dcliehou:'列侯', dcliehou_info:'锁定技。摸牌阶段开始时,你令额定摸牌数+X;然后此摸牌阶段结束时,你选择一项:⒈弃置X张牌。⒉失去1点体力(X为你的“爵”数+1且至多为5)。', yinfuren:'尹夫人', @@ -12828,7 +12835,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ dcxuewei:'血卫', dcxuewei_info:'结束阶段,你可以选择一名体力值不大于你的角色,然后你获得如下效果直到你的下回合开始时:当其受到伤害时,防止此伤害,然后你失去1点体力,你与其各摸一张牌(若该角色为你,则改为你摸一张牌)。', dcyuguan:'御关', - dcyuguan_info:'一名角色的回合结束时,若你已损失的体力值为全场最多,你可以减1点体力上限,然后令X名角色将手牌摸至体力上限(X为你已损失的体力值)。', + dcyuguan_info:'一名角色的回合结束时,若你已损失的体力值为全场最多,你可以减1点体力上限,然后令至多X名角色将手牌摸至体力上限(X为你已损失的体力值)。', qinlang:'秦朗', dchaochong:'昊宠', dchaochong_info:'当你使用牌后,你可以将手牌摸至或弃置至你的手牌上限数(至多摸五张)。然后若你以此法:得到牌,你的手牌上限-1;失去牌,你的手牌上限+1。', diff --git a/character/mobile.js b/character/mobile.js index c9db5834b..4c86ae3e3 100644 --- a/character/mobile.js +++ b/character/mobile.js @@ -459,7 +459,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ delete player.storage.mbxuetu_used; }); } - player.markAuto('mbxuetu_used', storage); + player.markAuto('mbxuetu_used',[status===0?storage:(!event.cards.length)]); if (status === 0 && !storage || status === 1 && event.cards.length) { await target.recover(); } @@ -718,7 +718,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(gains.length) player.gain(gains.randomGets(Math.min(gains.length,num)),'gain2'); }, getNum:function(player,event){ - let num=3; + let num=(get.mode()=='identity'?3:4); const history=game.getAllGlobalHistory('everything'); for(let i=history.length-1;i>=0;i--){ const evt=history[i]; @@ -743,8 +743,15 @@ game.import('character',function(lib,game,ui,get,ai,_status){ filter:function(event,player,name){ if(name=='damageSource'&&player.getHistory('sourceDamage').indexOf(event)!=0) return false; return game.hasPlayer(target=>{ - if(name=='damageEnd') return get.distance(player,target)>2; - return get.distance(player,target)<=2; + if(get.mode()!='doudizhu'){ + if(name=='damageEnd'&&get.distance(player,target)<=2) return false; + if(name=='damageSource'&&get.distance(player,target)>2) return false; + } + const zhoufa=player.storage.zhoulin_zhoufa; + if(!zhoufa) return true; + if(zhoufa=='豹'||zhoufa=='兔') return true; + if(zhoufa=='鹰') return target.countCards('he'); + return target.countDiscardableCards(player,'e'); }); }, direct:true, @@ -756,10 +763,13 @@ game.import('character',function(lib,game,ui,get,ai,_status){ '你随机弃置其装备区的一张牌', '令其摸一张牌', ][['豹','鹰','熊','兔'].indexOf(zhoufa)]:'令其随机执行一个效果'; - const {result:{bool,targets}}=await player.chooseTarget(get.prompt('shoufa'),'选择一名距离'+(event.triggername=='damageEnd'?'':'不')+'大于2的角色,'+str,(card,player,target)=>{ + const nodoudizhu=(get.mode()=='doudizhu'?'':('距离'+(event.triggername=='damageEnd'?'':'不')+'大于2的')); + const {result:{bool,targets}}=await player.chooseTarget(get.prompt('shoufa'),'选择一名'+nodoudizhu+'角色,'+str,(card,player,target)=>{ const name=_status.event.triggername; - if(name=='damageEnd'&&get.distance(player,target)<=2) return false; - if(name=='damageSource'&&get.distance(player,target)>2) return false; + if(get.mode()!='doudizhu'){ + if(name=='damageEnd'&&get.distance(player,target)<=2) return false; + if(name=='damageSource'&&get.distance(player,target)>2) return false; + } const zhoufa=player.storage.zhoulin_zhoufa; if(!zhoufa) return true; if(zhoufa=='豹'||zhoufa=='兔') return true; @@ -3819,7 +3829,6 @@ game.import('character',function(lib,game,ui,get,ai,_status){ ai:{ order:1, threaten:1.14, - unequip:true, unequip_ai:true, skillTagFilter:function(player,tag,arg){ if(arg&&arg.name=='sha'&&arg.card&&arg.card.storage&&arg.card.storage.mbguli) return true; @@ -3846,8 +3855,25 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.loseHp(); 'step 1' player.drawTo(player.maxHp); - } - } + }, + group:'mbguli_unequip', + }, + unequip:{ + trigger:{ + player:'useCardToPlayered', + }, + filter:function({card}){ + return card.name=='sha' && card.storage && card.storage.mbguli; + }, + forced:true, + popup:false, + logTarget:'target', + content:function(){ + trigger.target.addTempSkill('qinggang2'); + trigger.target.storage.qinggang2.add(trigger.card); + trigger.target.markSkill('qinggang2'); + }, + }, }, }, mbaosi:{ @@ -7218,11 +7244,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ delay:false, check:function(card){ var player=_status.event.player; - if(!player.storage.jueyong||player.storage.jueyong[0].length0; - }).length)) return -1; + })||!player.storage.jueyong[0].some(function(card){ + return get.effect(player,card,player.storage.jueyong[1][player.storage.jueyong[0].indexOf(card)],player)<0; + })) return -1; return 20-get.value(card); }, content:function(){ @@ -15848,8 +15874,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, shoufa:function(player){ const zhoufa=player.storage.zhoulin_zhoufa; - if(!zhoufa) return '当你受到伤害后/于一回合首次造成伤害后,你可以选择一名与你距离大于/不大于2的角色,令其随机执行以下一项:豹,令其受到1点无来源伤害;鹰,你随机获得其一张牌;熊,你随机弃置其装备区的一张牌;兔,令其摸一张牌。'; - let str='当你受到伤害后/于一回合首次造成伤害后,你可以选择一名与你距离大于/不大于2的角色,'; + const nodoudizhu=(get.mode()=='doudizhu'?'':'与你距离大于/不大于2的'); + if(!zhoufa) return '当你受到伤害后/于一回合首次造成伤害后,你可以选择一名'+nodoudizhu+'角色,令其随机执行以下一项:豹,令其受到1点无来源伤害;鹰,你随机获得其一张牌;熊,你随机弃置其装备区的一张牌;兔,令其摸一张牌。'; + let str='当你受到伤害后/于一回合首次造成伤害后,你可以选择一名'+nodoudizhu+'角色,'; str+=[ '令其受到1点无来源伤害', '你随机获得其一张牌', @@ -16742,6 +16769,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ muludawang:'木鹿大王', shoufa:'兽法', shoufa_info:'当你受到伤害后/于一回合首次造成伤害后,你可以选择一名与你距离大于/不大于2的角色,令其随机执行以下一项:豹,令其受到1点无来源伤害;鹰,你随机获得其一张牌;熊,你随机弃置其装备区的一张牌;兔,令其摸一张牌。', + shoufa_info_doudizhu:'当你受到伤害后/于一回合首次造成伤害后,你可以选择一名角色,令其随机执行以下一项:豹,令其受到1点无来源伤害;鹰,你随机获得其一张牌;熊,你随机弃置其装备区的一张牌;兔,令其摸一张牌。', yuxiang:'御象', yuxiang_info:'锁定技,若你有护甲值,则:①你计算与其他角色的距离-1,其他角色计算与你的距离+1;②当你受到火焰伤害时,此伤害+1。', zhoulin:'咒鳞', @@ -16751,7 +16779,8 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sidai:'伺怠', sidai_info:'限定技,出牌阶段,你可以将手牌区内的所有基本牌当做【杀】使用。若此牌对应的实体牌中:包含【闪】,则目标角色成为此牌的目标后,需弃置一张基本牌,否则不可响应此牌;包含【桃】,则当目标角色受到此牌的伤害后,其减1点体力上限。', jieyu:'竭御', - jieyu_info:'结束阶段,你可以从弃牌堆中获得共X张不同牌名的基本牌(X为3-你上次发动〖竭御〗至今你成为其他角色使用伤害类卡牌目标的次数,且X至少为1)。', + jieyu_info:'结束阶段,你可以从弃牌堆中获得共X张不同牌名的基本牌(X为4-你上次发动〖竭御〗至今你成为其他角色使用伤害类卡牌目标的次数,且X至少为1)。', + jieyu_info_identity:'结束阶段,你可以从弃牌堆中获得共X张不同牌名的基本牌(X为3-你上次发动〖竭御〗至今你成为其他角色使用伤害类卡牌目标的次数,且X至少为1)。', yangfeng:'杨奉', mbxuetu:'血途', mbxuetu_info:'转换技。出牌阶段限一次,阴:你可以弃置一张牌,然后令一名角色回复1点体力;阳:你可以失去1点体力,然后令一名角色摸两张牌。', diff --git a/character/onlyOL.js b/character/onlyOL.js index e8b12c46c..d19a3af1a 100644 --- a/character/onlyOL.js +++ b/character/onlyOL.js @@ -14,11 +14,12 @@ game.import('character',function(lib,game,ui,get,ai,_status){ ol_sb_yuanshao:['male','qun',4,['olsbhetao','olsbshenli','olsbyufeng','olsbshishou'],['zhu']], ol_yufan:['male','wu',3,['olzongxuan','olzhiyan'],['tempname:re_yufan','die_audio:re_yufan']], ol_chengpu:['male','wu',4,['dclihuo','olchunlao'],['tempname:xin_chengpu','die_audio:xin_chengpu']], + ol_wangyi:['female','wei',3,['olzhenlie','olmiji']], }, characterSort:{ onlyOL:{ onlyOL_yijiang1:['ol_jianyong','ol_lingtong','ol_gaoshun'], - onlyOL_yijiang2:['ol_caozhang','ol_chengpu'], + onlyOL_yijiang2:['ol_caozhang','ol_chengpu','ol_wangyi'], onlyOL_yijiang3:['ol_yufan'], onlyOL_sb:['ol_sb_jiangwei','ol_sb_guanyu','ol_sb_taishici','ol_sb_yuanshao'], }, @@ -51,6 +52,101 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, }, skill:{ + //王异 + olzhenlie:{ + audio:2, + inherit:'zhenlie', + async content(event,trigger,player){ + const target=trigger.player; + if(get.attitude(player,target)<0&&target.countDiscardableCards(player,'he')) player.addTempSkill('zhenlie_lose'); + await player.loseHp(); + player.removeSkill('zhenlie_lose'); + trigger.getParent().excluded.add(player); + if(!player.isIn()) return; + const goon=target.hasCard(card=>{ + if(get.position(card)=='h') return true; + return lib.filter.canBeGained(card,player,target); + },'he'); + if(goon||player.isDamaged()){ + let result; + if(goon&&player.isDamaged()) result=await player.chooseControl().set('choiceList',[ + '获得'+get.translation(target)+'的一张牌', + '发动一次〖秘计〗', + ]).set('ai',()=>{ + const player=get.event('player'),target=get.event().getTrigger().player; + return get.effect(target,{name:'shunshou_copy2'},player,player)>get.effect(player,{name:'draw'},player,player)*player.getDamagedHp()?0:1 + }).forResult(); + else result={index:goon?0:1}; + if(result.index==0){ + await player.gainPlayerCard(target,'he',true); + } + else{ + await player.useSkill('olmiji'); + } + } + }, + }, + olmiji:{ + audio:2, + trigger:{player:'phaseJieshuBegin'}, + filter(event,player){ + return player.isDamaged(); + }, + async content(event,trigger,player){ + let num=player.getDamagedHp(); + await player.draw(num); + if(player.countCards('he')&&game.hasPlayer(target=>target!=player)){ + if(_status.connectMode) game.broadcastAll(()=>_status.noclearcountdown=true); + let given_map=[]; + while(num>0&&player.hasCard(card=>!card.hasGaintag('olsujian_given'),'he')){ + const {result:{bool,cards,targets}}=await player.chooseCardTarget({ + filterCard(card,player){ + return !card.hasGaintag('olsujian_given'); + }, + selectCard:[1,num], + position:'he', + filterTarget:lib.filter.notMe, + prompt:'秘计:请选择要分配的卡牌和目标', + prompt2:'(还可分配'+num+'张)', + ai1(card){ + return (!ui.selected.cards.length&&card.name=='du')?1:0; + }, + ai2(target){ + const player=get.event('player'); + const card=ui.selected.cards[0]; + if(card) return get.value(card,target)*get.attitude(player,target); + return 0; + }, + }); + if(bool){ + num-=cards.length; + const target=targets[0]; + if(given_map.some(i=>i[0]==target)){ + given_map[given_map.indexOf(given_map.find(i=>i[0]==target))][1].addArray(cards); + } + else given_map.push([target,cards]); + player.addGaintag(cards,'olsujian_given'); + } + else break; + } + if(_status.connectMode){ + game.broadcastAll(()=>{ + delete _status.noclearcountdown; + game.stopCountChoose(); + }); + } + if(given_map.length){ + await game.loseAsync({ + gain_list:given_map, + player:player, + cards:given_map.slice().map(list=>list[1]), + giver:player, + animate:'giveAuto', + }).setContent('gaincardMultiple'); + } + } + }, + }, //程普 dclihuo:{ audio:'relihuo', @@ -721,8 +817,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } if(get.type(trigger.card)=='basic'&&player.getHistory('useCard',evt=>get.type(evt.card)=='basic').indexOf(trigger)==0){ game.log(trigger.card,'不计入次数上限'); - trigger.addCount=false; - if(player.stat[player.stat.length-1].card.sha>0) player.stat[player.stat.length-1].card.sha--; + if (trigger.addCount !== false) { + trigger.addCount=false; + const stat = player.stat[player.stat.length-1].card; + if (typeof stat[trigger.card.name] === 'number') stat[trigger.card.name]--; + } } } }, @@ -907,11 +1006,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ const goon1=player.countCards('h',card=>get.name(card,player)=='sha')>=player.countCards('h',card=>get.name(card,player)!='sha'); const goon2=player.countCards('h',card=>get.name(card,player)!='sha')>=player.countCards('h',card=>get.name(card,player)=='sha'); if((goon1&&control=='【杀】更多')||(goon2&&control=='非【杀】更多')){ - target.popup('判断正确','wood'); + target.popup('洗具'); game.log(target,'猜测','#g正确'); } else{ - target.popup('判断错误','fire'); + target.popup('杯具'); game.log(target,'猜测','#y错误'); trigger.increase('num'); } @@ -1267,7 +1366,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ ol_sb_taishici:'OL谋太史慈', ol_sb_taishici_prefix:'OL谋', olsbdulie:'笃烈', - olsbdulie_info:'每回合限一次,当你成为其他角色使用基本牌或普通锦囊牌的目标时,你可以令此牌额外结算一次。若如此做,此牌结算完毕后,你摸X张牌(X为你的攻击范围且至多为5)。', + olsbdulie_info:'每回合限一次,当你成为其他角色使用基本牌或普通锦囊牌的唯一目标时,你可以令此牌额外结算一次。若如此做,此牌结算完毕后,你摸X张牌(X为你的攻击范围且至多为5)。', olsbdouchan:'斗缠', olsbdouchan_info:'锁定技,准备阶段,你从牌堆中获得一张【决斗】,若牌堆没有【决斗】,则你的攻击范围和出牌阶段使用【杀】的次数上限+1(增加次数不超过游戏人数)。', olsbweilin:'威临', @@ -1305,6 +1404,12 @@ game.import('character',function(lib,game,ui,get,ai,_status){ dclihuo_info:'①你使用的非火【杀】可以改为火【杀】,若如此做,此牌结算完毕后,若此牌造成过伤害,则你弃置一张牌或失去1点体力。②你使用火【杀】可以额外指定一个目标。', olchunlao:'醇醪', olchunlao_info:'①当你的【杀】因弃置进入弃牌堆后,你将位于弃牌堆的这些牌称为“醇”置于武将牌上。②一名角色处于濒死状态时,你可以将一张“醇”置入弃牌堆,然后令其视为使用一张【酒】。', + ol_wangyi:'OL界王异', + ol_wangyi_prefix:'OL界', + olzhenlie:'贞烈', + olzhenlie_info:'当你成为其他角色使用【杀】或普通锦囊牌的目标后,你可以失去1点体力并令此牌对你无效,然后你选择一项:①获得使用者的一张牌;②发动一次〖秘计〗。', + olmiji:'秘计', + olmiji_info:'结束阶段,若你已受伤,则你可以摸X张牌,然后你可以将至多X张牌任意分配给其他角色(X为你已损失的体力值)。', onlyOL_yijiang1:'OL专属·将1', onlyOL_yijiang2:'OL专属·将2', diff --git a/character/rank.js b/character/rank.js index f97e8e9ab..1c658a254 100644 --- a/character/rank.js +++ b/character/rank.js @@ -137,6 +137,7 @@ window.noname_character_rank={ 'xia_yuzhenzi', 'dc_simashi', 'dc_sb_simayi', + 'caofang', ], a:[ 'star_caoren', @@ -684,6 +685,8 @@ window.noname_character_rank={ 'ol_sb_guanyu', 'gongsunxiu', 'dc_caoshuang', + 'clan_wangling', + 'clan_wangguang', ], bp:[ 'xin_huojun', @@ -1076,6 +1079,8 @@ window.noname_character_rank={ 'yangfeng', 'sb_xiahoudun', 'sb_gaoshun', + 're_wangyi', + 'ol_wangyi', ], b:[ 'junk_guanyu', @@ -2175,8 +2180,11 @@ window.noname_character_rank={ 'xia_shitao', 'bailingyun', 'dc_sb_simayi', + 'caofang', ], rare:[ + 're_wangyi', + 'ol_wangyi', 'tw_yanliang', 'tw_wenchou', 'tw_yuantan', @@ -2653,6 +2661,7 @@ window.noname_character_rank={ 'furongfuqian', 'zhenghun', 'clan_wangling', + 'clan_wangguang', 'clan_wangyun', 'quhuang', 'ol_wenqin', diff --git a/character/refresh.js b/character/refresh.js index 43463f8ea..005ca5042 100755 --- a/character/refresh.js +++ b/character/refresh.js @@ -1356,7 +1356,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, olkanpo:{ audio:'rekanpo', - audioname:['ol_sp_zhugeliang'], + audioname:['ol_sp_zhugeliang','ol_pangtong'], trigger:{player:'useCard'}, forced:true, locked:false, @@ -5448,40 +5448,44 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } return true; }, - direct:true, - content:function(){ - "step 0" - if(lib.skill.rebingyi.filtery(player)) event.draw=true; - if(lib.skill.rebingyi.filterx(player)){ - player.chooseTarget(get.prompt('xinbingyi'),'展示所有手牌,并选择至多'+get.cnNumber(player.countCards('h'))+'名角色各摸一张牌',[0,player.countCards('h')],function(card,player,target){ - return true; - }).set('ai',function(target){ - return get.attitude(_status.event.player,target); - }); + async cost(event, trigger, player){ + const selfDraw = lib.skill.rebingyi.filtery(player), asyncDraw = lib.skill.rebingyi.filterx(player); + if (asyncDraw) { + const num = player.countCards('h'); + const result = await player.chooseTarget( + get.prompt('xinbingyi'), + `展示所有手牌,并选择至多${get.cnNumber(num)}名角色各摸一张牌${selfDraw ? '' : ',然后你摸一张牌'}`, + [0,num] + ).set('ai', function(target){ + return get.attitude(get.player(), target); + }).forResult(); + if(result.bool) event.result = { + bool: result.bool, + cost_data: { + asyncDraw, + selfDraw, + targets: result.targets + }, + } } - else player.chooseBool(get.prompt('bingyi'),'展示所有手牌').ai=function(){return false}; - "step 1" - if(result.bool){ - player.logSkill('rebingyi'); - player.showHandcards(get.translation(player)+'发动了【秉壹】'); - event.targets=result.targets; + else { + event.result = await player.chooseBool(get.prompt('bingyi'),`展示所有手牌${selfDraw ? '' : ',然后你摸一张牌'}`) + .set('choice', selfDraw) + .set('ai',()=>get.event().choice) + .forResult(); + event.result.cost_data = {selfDraw}; } - else{ - event.finish(); - } - "step 2" - if(targets&&targets.length){ - player.line(targets,'green'); - targets.sortBySeat(); + }, + async content(event, trigger, player){ + await player.showHandcards(get.translation(player)+'发动了【秉壹】') + const data = event.cost_data; + if (data.asyncDraw && data.targets && data.targets.length){ + const targets = data.targets.sortBySeat(); game.asyncDraw(targets); } - else event.finish(); - if(event.draw){ + if (data.selfDraw) { player.draw(); - event.finish(); } - "step 3" - game.delayx(); }, }, //钟会 @@ -11744,7 +11748,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ event.num-=res.length if(!event.given_map[target]) event.given_map[target]=[]; event.given_map[target].addArray(res); - if(event.num>0) event.goto(2); + if(event.num>0) event.goto(1); } else if(event.num==2){ if(_status.connectMode){ @@ -13568,42 +13572,43 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } }, rejianxiong_old:{ - audio:2, + audio:'rejianxiong', + audioname2:{ + gz_caocao:'jianxiong', + }, trigger:{player:'damageEnd'}, - direct:true, - content:function(){ - "step 0" - if(get.itemtype(trigger.cards)=='cards'&&get.position(trigger.cards[0],true)=='o'){ - player.chooseControl('rejianxiong_mopai','rejianxiong_napai','cancel2').set('prompt',get.prompt('rejianxiong')).ai=function(){ - var trigger=_status.event.getTrigger(); - if(trigger.cards.length==1&&trigger.cards[0].name=='sha') return 0; - return 1; - }; - } - else{ - player.chooseControl('rejianxiong_mopai','cancel2').set('prompt',get.prompt('rejianxiong')); - } - "step 1" - if(result.control=='rejianxiong_napai'){ - player.logSkill('rejianxiong'); - player.gain(trigger.cards); - player.$gain2(trigger.cards); - } - else if(result.control=='rejianxiong_mopai'){ - player.logSkill('rejianxiong'); - player.draw(); + async cost(event,trigger,player){ + let list=['摸牌']; + if(get.itemtype(trigger.cards)=='cards'&&trigger.cards.filterInD().length){ + list.push('拿牌'); } + list.push('cancel2'); + const {result:{control}}=await player.chooseControl(list).set('prompt',get.prompt2('rejianxiong_old')).set('ai',()=>{ + const player=get.event('player'),trigger=get.event().getTrigger(); + const cards=trigger.cards.filterInD(); + if(get.event().controls.includes('拿牌')){ + if(cards.reduce((sum,card)=>{ + return sum+(card.name=='du'?-1:1); + },0)>1||player.getUseValue(cards[0])>6) return '拿牌'; + } + return '摸牌'; + }); + event.result={bool:(control!='cancel2'),cost_data:control}; + }, + async content(event,trigger,player){ + if(event.cost_data=='摸牌') await player.draw(); + else await player.gain(trigger.cards.filterInD(),'gain2'); }, ai:{ maixie:true, maixie_hp:true, effect:{ - target:function(card,player,target){ + target(card,player,target){ if(player.hasSkillTag('jueqing',false,target)) return [1,-1]; if(get.tag(card,'damage')&&player!=target) return [1,0.6]; - } - } - } + }, + }, + }, }, reyiji:{ audio:2, @@ -15452,7 +15457,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ dcmieji:'灭计', dcmieji_info:'出牌阶段限一次,你可以展示一张武器牌或黑色锦囊牌。你将此牌置于牌堆顶,然后令一名有手牌的其他角色选择一项:⒈弃置一张锦囊牌;⒉依次弃置两张非锦囊牌。', dcfencheng:'焚城', - dcfencheng_info:'限定技。出牌阶段,你可以指定一名其他角色,令从其开始的其他角色依次选择一项:⒈弃置至少X张牌(X为上一名角色弃置的牌数+1)。⒉你对其造成2点伤害。', + dcfencheng_info:'限定技。出牌阶段,你可以指定一名其他角色,令从其开始的其他角色依次选择一项:⒈弃置至少X张牌(X为上一名角色弃置的牌数+1)。⒉你对其造成2点火焰伤害。', oljiang:'激昂', oljiang_info:'①当你使用【决斗】或红色【杀】指定第一个目标后,或成为【决斗】或红色【杀】的目标后,你可以摸一张牌。②当有【决斗】或红色【杀】于每回合内首次因弃置而进入弃牌堆后,你可以失去1点体力并获得这些牌。', re_xunyou:'界荀攸', @@ -15577,6 +15582,8 @@ game.import('character',function(lib,game,ui,get,ai,_status){ re_lidian_prefix:'界', re_xushu:'界徐庶', re_xushu_prefix:'界', + rejianxiong_old:'奸雄', + rejianxiong_old_info:'当你受到伤害后,你可以摸一张牌或获得对你造成伤害的牌。', refresh_standard:'界限突破·标', refresh_feng:'界限突破·风', diff --git a/character/sb.js b/character/sb.js index fc12a6506..a252e5a31 100644 --- a/character/sb.js +++ b/character/sb.js @@ -55,7 +55,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sb_tong:['liucheng','sp_yangwan','sb_xiahoushi','sb_zhangfei','sb_zhaoyun','sb_sunce','sb_zhurong','sb_xiaoqiao','sb_xiahoudun'], sb_yu:['sb_yujin','sb_lvmeng','sb_huangzhong','sb_huanggai','sb_zhouyu','sb_caoren','sb_ganning','sb_yl_luzhi','sb_huangyueying'], sb_neng:['sb_huaxiong','sb_sunshangxiang','sb_jiangwei','sb_yuanshao','sb_menghuo','sb_guanyu','sb_gaoshun'], - sb_waitforsort:[], + // sb_waitforsort:[], } }, characterSubstitute:{ @@ -742,11 +742,15 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sbxingshang:{ audio:2, trigger:{global:['die','damageEnd']}, - usable:1, + filter(event,player){ + if(player.countMark('sbxingshang')>=get.info('sbxingshang').getLimit) return false; + return event.name=='die'||!player.getHistory('custom',evt=>evt.sbxingshang).length; + }, forced:true, locked:false, async content(event,trigger,player){ - player.addMark('sbxingshang',1); + player.addMark('sbxingshang',Math.min(2,get.info('sbxingshang').getLimit-player.countMark('sbxingshang'))); + if(trigger.name=='damage') player.getHistory('custom').push({sbxingshang:true}); }, marktext:'颂', intro:{ @@ -754,37 +758,89 @@ game.import('character',function(lib,game,ui,get,ai,_status){ content:'mark', }, ai:{threaten:2.5}, + getLimit:9, + getNum(num){ + if(typeof num!='number'||!Array.from({length:9}).map((_,i)=>i+1).includes(num)) return 0; + return [2,2,5,5,1,2,2,3,3][num-1]; + }, + getEffect(player,num){ + if(!player||typeof num!='number') return 0; + switch(num){ + //行殇选项 + case 1://-2,重置武将牌 + if(game.hasPlayer(target=>{ + return get.attitude(player,target)>0&&target.isTurnedOver(); + })) return 10; + return 0; + case 2://-2,摸min(5,max(1,阵亡角色数))的牌 + return Math.min(5,(Math.max(1,game.dead.length))); + case 3://-5,加上限加血+复原装备栏 + if(!game.hasPlayer(target=>{ + return get.attitude(player,target)>0&&target.maxHp<10; + })) return 0; + return 5+(game.hasPlayer(target=>{ + return get.attitude(player,target)>0&&target.hasDisabledSlot(); + })?1:0); + case 4://-5,劝封/化萍 + return 0; + //放逐选项 + case 5://-1,封印基本牌外的手牌 + if(game.hasPlayer(target=>{ + return get.attitude(player,target)<0; + })) return 1; + return 0; + case 6://-2,白板到结束 + if(game.hasPlayer(target=>{ + if(target.hasSkill('sbfangzhu_ban')||target.hasSkill('fengyin')||target.hasSkill('baiban')) return false; + return get.attitude(player,target)<0&&['name','name1','name2'].reduce((sum,name)=>{ + if(target[name]&&(name!='name1'||target.name!=target.name1)){ + if(get.character(target[name])) sum+get.rank(target[name],true); + } + return sum; + },0)>5; + })) return 6; + return 0; + case 7://-2,强命到结束 + return 0; + case 8://-3,翻面 + if(game.hasPlayer(target=>{ + return get.attitude(player,target)<0&&!target.isTurnedOver(); + })) return 8; + return 0; + case 9://-3,封印装备牌外的手牌 + if(game.hasPlayer(target=>{ + return get.attitude(player,target)<0; + })) return 2.5; + return 0; + default://其他 + return 0; + } + }, group:'sbxingshang_use', subSkill:{ use:{ audio:'sbxingshang', enable:'phaseUse', - filter:function(event,player){ + filter(event,player){ return game.hasPlayer(target=>{ if(player.countMark('sbxingshang')>1) return true; return player.countMark('sbxingshang')&&(target.isLinked()||target.isTurnedOver()); }); }, - usable:1, + usable:2, chooseButton:{ - dialog:function(){ - var dialog=ui.create.dialog( - '行殇:请选择你要执行的一项', - [[ - [1,'   ⒈复原一名角色的武将牌   '], - [2,'   ⒉令一名角色摸'+Math.min(5,Math.max(1,game.dead.length))+'张牌   '], - ],'tdnodes'], - [[ - [3,'   ⒊令一名体力上限小于10的角色加1点体力上限并回复1点体力,然后随机恢复一个被废除的装备栏   '], - ],'tdnodes'], - [[ - [4,'   ⒋获得一名已阵亡角色的所有技能,然后失去武将牌上的所有技能   '], - ],'tdnodes'] - ); + dialog(){ + var dialog=ui.create.dialog('行殇:请选择你要执行的一项','hidden'); + dialog.add([[ + [1,'移去2个“颂”标记,复原一名角色的武将牌'], + [2,'移去2个“颂”标记,令一名角色摸'+get.cnNumber(Math.min(5,Math.max(1,game.dead.length)))+'张牌'], + [3,'移去5个“颂”标记,令一名体力上限小于10的角色加1点体力上限并回复1点体力,然后随机恢复一个被废除的装备栏'], + [4,'移去5个“颂”标记,获得一名已阵亡角色的所有技能,然后失去〖行殇〗〖放逐〗〖颂威〗'], + ],'textbutton']); return dialog; }, - filter:function(button,player){ - if(button.link>player.countMark('sbxingshang')) return false; + filter(button,player){ + if(player.countMark('sbxingshang')target.isLinked()||target.isTurnedOver()); @@ -796,39 +852,20 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return game.dead.length; } }, - check:function(button){ - let player=_status.event.player; - switch(button.link){ - case 1: - return game.filterPlayer(current=>get.attitude(player,current)>0).reduce((list,target)=>{ - let num=0; - if(target.isLinked()) num+=0.5; - if(target.isTurnedOver()) num+=10; - list.push(num); - return list; - },[]).sort((a,b)=>b-a)[0]; - case 2: - return Math.min(5,Math.max(1,game.dead.length)); - case 3: - return game.filterPlayer().reduce((list,target)=>{ - list.push(get.recoverEffect(target,player,player)); - return list; - },[]).sort((a,b)=>b-a)[0]; - case 4: - return game.dead.reduce((list,target)=>{ - let num=0; - if(target.name&&lib.character[target.name]) num+=get.rank(target.name,true); - if(target.name2&&lib.character[target.name2]) num+=get.rank(target.name2,true); - list.push(num); - return list; - },[]).sort((a,b)=>b-a)[0]; - } + check(button){ + const player=get.event('player'),info=get.info('sbxingshang'); + let list=Array.from({length:4}).map((_,i)=>i+1); + list=list.filter(num=>player.countMark('sbxingshang')>=info.getNum(num)); + const num=list.sort((a,b)=>info.getEffect(player,b)-info.getEffect(player,a))[0]; + return (button.link==num)?10:0; }, - backup:function(links,player){ + backup(links,player){ return { num:links[0], audio:'sbxingshang', - filterTarget:function(card,player,target){ + filterCard:()=>false, + selectCard:-1, + filterTarget(card,player,target){ switch(lib.skill.sbxingshang_use_backup.num){ case 1: return target=>target.isLinked()||target.isTurnedOver(); @@ -882,24 +919,24 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.line(target2); game.log(player,'选择了',target2); const skills=target2.getStockSkills(true,true); - const skills2=player.getStockSkills(true,true); + const skills2=['sbxingshang','sbfangzhu','sbsongwei']; player.changeSkills(skills,skills2); } } }, ai:{ result:{ - target:function(player,target){ + target(player,target){ switch(lib.skill.sbxingshang_use_backup.num){ case 1: let num=0; - if(target.isLinked()) num+=0.5; + if(target.isLinked()&&!target.hasSkill('nzry_jieying')) num+=0.5; if(target.isTurnedOver()) num+=10; return num; case 2: - return 1; + return get.effect(target,{name:'draw'},player,player); case 3: - return get.recoverEffect(target,player,player); + return Math.max(0,get.recoverEffect(target,player,player))+get.attitude(player,target); case 4: return 1; } @@ -908,21 +945,29 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, } }, - prompt:function(links,player){ + prompt(links,player){ + const str='###行殇###'; switch(links[0]){ case 1: - return '复原一名角色的武将牌'; + return str+'移去2个“颂”标记,复原一名角色的武将牌'; case 2: - return '令一名角色摸'+get.cnNumber(Math.min(5,Math.max(1,game.dead.length)))+'张牌'; + return str+'移去2个“颂”标记,令一名角色摸'+get.cnNumber(Math.min(5,Math.max(1,game.dead.length)))+'张牌'; case 3: - return '令一名体力上限小于10的角色加1点体力上限并回复1点体力,然后随机恢复一个被废除的装备栏'; + return str+'移去5个“颂”标记,令一名体力上限小于10的角色加1点体力上限并回复1点体力,然后随机恢复一个被废除的装备栏'; case 4: - return '获得一名已阵亡角色的所有技能,然后失去武将牌上的所有技能'; + return str+'移去5个“颂”标记,获得一名已阵亡角色的所有技能,然后失去武将牌上的所有技能'; } } }, ai:{ - order:9, + order(_,player){ + const info=get.info('sbxingshang'); + const goon=(player.hasSkill('sbfangzhu')&&(player.getStat('skill').sbfangzhu||0)<(get.info('sbfangzhu').usable||Infinity)); + let list=Array.from({length:goon?9:4}).map((_,i)=>i+1); + list=list.filter(num=>player.countMark('sbxingshang')>=info.getNum(num)); + list.sort((a,b)=>info.getEffect(player,b)-info.getEffect(player,a)); + return (Array.from({length:4}).map((_,i)=>i+1).includes(list[0])&&info.getEffect(player,list[0])>0)?1:0; + }, result:{player:1}, }, }, @@ -932,118 +977,122 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sbfangzhu:{ audio:2, enable:'phaseUse', - filter:function(event,player){ - return player.countMark('sbxingshang')>1; + filter(event,player){ + return player.hasMark('sbxingshang'); }, usable:1, chooseButton:{ - dialog:function(){ + dialog(){ var dialog=ui.create.dialog('放逐:请选择你要执行的一项','hidden'); dialog.add([[ - [1,'移去2个“颂”标记,令一名其他角色的非Charlotte技能失效直到其回合结束'], - [2,'移去2个“颂”标记,令一名其他角色不能响应除其外的角色使用的牌直到其回合结束'], - [3,'移去3个“颂”标记,令一名其他角色将武将牌翻面'], - [4,'移去3个“颂”标记,令一名其他角色只能使用你选择的一种类型的牌直到其回合结束'] + [1,'移去1个“颂”标记,令一名其他角色于手牌中只能使用基本牌直到其回合结束'], + [2,'移去2个“颂”标记,令一名其他角色的非Charlotte技能失效直到其回合结束'], + [3,'移去2个“颂”标记,令一名其他角色不能响应除其外的角色使用的牌直到其回合结束'], + [4,'移去3个“颂”标记,令一名其他角色将武将牌翻面'], + [5,'移去3个“颂”标记,令一名其他角色于手牌中只能使用装备牌直到其回合结束'] ],'textbutton']); return dialog; }, - filter:function(button,player){ - if(button.link>2&&player.countMark('sbxingshang')<3) return false; - if(button.link==4) return game.hasPlayer(target=>target!=player&&!target.hasSkill('sbfangzhu_ban')); - return true; + filter(button,player){ + if(player.countMark('sbxingshang'){ + if(target==player) return false; + const num=button.link,storage=target.getStorage('sbfangzhu_ban'); + return !((num==1&&storage.includes('basic'))||(num==5&&storage.includes('equip'))); + }); }, - check:function(button){ - let player=_status.event.player; - switch(button.link){ - case 1: - return game.filterPlayer(current=>get.attitude(player,current)<0).reduce((list,target)=>{ - let num=0; - if(target.name&&lib.character[target.name]) num+=get.rank(target.name,true); - if(target.name2&&lib.character[target.name2]) num+=get.rank(target.name2,true); - list.push(num); - return list; - },[]).sort((a,b)=>b-a)[0]; - case 2: - return 0; - case 3: - return game.filterPlayer(target=>target!=player&&!target.hasSkill('sbfangzhu_ban')).reduce((list,target)=>{ - if(get.attitude(player,target)>0&&target.isTurnedOver()) list.push(10*target.countCards('hs')+1); - else if(get.attitude(player,target)<0&&!target.isTurnedOver()) list.push(5*target.countCards('hs')+1); - else list.push(0); - return list; - },[]).sort((a,b)=>b-a)[0]; - case 4: - return 0; - } + check(button){ + const player=get.event('player'),info=get.info('sbxingshang'); + let list=Array.from({length:5}).map((_,i)=>i+1); + list=list.filter(num=>player.countMark('sbxingshang')>=info.getNum(num+4)); + const num=list.sort((a,b)=>info.getEffect(player,b+4)-info.getEffect(player,a+4))[0]-4; + return (button.link==num)?10:0; }, - backup:function(links,player){ + backup(links,player){ return { num:links[0], audio:'sbfangzhu', - filterTarget:lib.filter.notMe, + filterCard:()=>false, + selectCard:-1, + filterTarget(card,player,target){ + if(target==player) return false; + const num=lib.skill.sbfangzhu_backup.num,storage=target.getStorage('sbfangzhu_ban'); + return !((num==1&&storage.includes('basic'))||(num==5&&storage.includes('equip'))); + }, async content(event,trigger,player){ const target=event.target; const num=lib.skill.sbfangzhu_backup.num; - player.removeMark('sbxingshang',num>2?3:2); + player.removeMark('sbxingshang',get.info('sbxingshang').getNum(num+4)); switch(num){ case 1: + target.addTempSkill('sbfangzhu_ban',{player:'phaseEnd'}); + target.markAuto('sbfangzhu_ban',['basic']); + break; + case 2: target.removeSkill('baiban'); target.addTempSkill('baiban',{player:'phaseEnd'}); break; - case 2: + case 3: target.addTempSkill('sbfangzhu_kill',{player:'phaseEnd'}); break; - case 3: + case 4: target.turnOver(); break; - case 4: - const {result:{control}}=await player.chooseControl('basic','trick','equip').set('ai',()=>'equip').set('prompt','放逐:请选择'+get.translation(target)+'仅能使用的类别的牌'); - if(control){ - player.line(target); - player.popup(get.translation(control)+'牌'); - target.addTempSkill('sbfangzhu_ban',{player:'phaseEnd'}); - target.markAuto('sbfangzhu_ban',[control]); - } + case 5: + target.addTempSkill('sbfangzhu_ban',{player:'phaseEnd'}); + target.markAuto('sbfangzhu_ban',['equip']); + break; } }, ai:{ result:{ - target:function(player,target){ + target(player,target){ switch(lib.skill.sbfangzhu_backup.num){ case 1: - let num=0; - if(target.name&&lib.character[target.name]) num+=get.rank(target.name,true); - if(target.name2&&lib.character[target.name2]) num+=get.rank(target.name2,true); - return num; + return -target.countCards('h',card=>get.type(card)!='basic')-1; case 2: - return 0; + return -target.getSkills(null,null,false).reduce((sum,skill)=>{ + return sum+Math.max(get.skillRank(skill,'out'),get.skillRank(skill,'in')); + },0); case 3: + return 0; + case 4: if(get.attitude(player,target)>0&&target.isTurnedOver()) return 10*target.countCards('hs')+1; if(get.attitude(player,target)<0&&!target.isTurnedOver()) return -5*target.countCards('hs')+1; return 0; - case 4: - return 0; + case 5: + return -target.countCards('h',card=>get.type(card)!='equip')-3; } }, }, }, } }, - prompt:function(links,player){ + prompt(links,player){ + const str='###放逐###'; switch(links[0]){ case 1: - return '移去2个“颂”标记,令一名其他角色的非Charlotte技能失效直到其回合结束'; + return str+'移去1个“颂”标记,令一名其他角色于手牌中只能使用基本牌直到其回合结束'; case 2: - return '移去2个“颂”标记,令一名其他角色不能响应除其外的角色使用的牌直到其回合结束'; + return str+'移去2个“颂”标记,令一名其他角色的非Charlotte技能失效直到其回合结束'; case 3: - return '移去3个“颂”标记,令一名其他角色将武将牌翻面'; + return str+'移去2个“颂”标记,令一名其他角色不能响应除其外的角色使用的牌直到其回合结束'; case 4: - return '移去3个“颂”标记,令一名其他角色只能使用你选择的一种类型的牌直到其回合结束'; + return str+'移去3个“颂”标记,令一名其他角色将武将牌翻面'; + case 5: + return str+'移去3个“颂”标记,令一名其他角色于手牌中只能使用装备牌直到其回合结束'; } } }, ai:{ - order:9, + order(_,player){ + const info=get.info('sbxingshang'); + const goon=(player.hasSkill('sbxingshang')&&(player.getStat('skill').sbxingshang_use||0)<(info.subSkill.use.usable||Infinity)); + let list=Array.from({length:goon?9:5}).map((_,i)=>i+(goon?1:5)); + list=list.filter(num=>player.countMark('sbxingshang')>=info.getNum(num)); + list.sort((a,b)=>info.getEffect(player,b)-info.getEffect(player,a)); + return (Array.from({length:5}).map((_,i)=>i+5).includes(list[0])&&info.getEffect(player,list[0])>0)?1:0; + }, result:{player:1}, }, subSkill:{ @@ -1054,7 +1103,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ marktext:'禁', intro:{content:'不能响应其他角色使用的牌'}, trigger:{global:'useCard1'}, - filter:function(event,player){ + filter(event,player){ return event.player!=player; }, forced:true, @@ -1070,14 +1119,21 @@ game.import('character',function(lib,game,ui,get,ai,_status){ marktext:'禁', intro:{ markcount:()=>0, - content:'只能使用$牌', + content(storage){ + if(storage.length>1) return '不能使用手牌'; + return '于手牌中只能使用'+get.translation(storage[0])+'牌'; + }, }, mod:{ - cardEnabled:function(card,player){ - if(!player.getStorage('sbfangzhu_ban').includes(get.type2(card))) return false; + cardEnabled(card,player){ + const storage=player.getStorage('sbfangzhu_ban'); + if(get.itemtype(card)=='card'&&get.position(card)!='h') return; + if(storage.length>1||!storage.includes(get.type2(card))) return false; }, - cardSavable:function(card,player){ - if(!player.getStorage('sbfangzhu_ban').includes(get.type2(card))) return false; + cardSavable(card,player){ + const storage=player.getStorage('sbfangzhu_ban'); + if(get.itemtype(card)=='card'&&get.position(card)!='h') return; + if(storage.length>1||!storage.includes(get.type2(card))) return false; }, }, }, @@ -1085,39 +1141,40 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, sbsongwei:{ audio:2, - init:(player)=>{ - player.addSkill('sbsongwei_delete'); - }, trigger:{player:'phaseUseBegin'}, - filter:function(event,player){ + filter(event,player){ + if(player.countMark('sbxingshang')>=get.info('sbxingshang').getLimit) return false; return game.hasPlayer(target=>target.group=='wei'&&target!=player); }, zhuSkill:true, forced:true, locked:false, async content(event,trigger,player){ - player.addMark('sbxingshang',game.countPlayer(target=>target.group=='wei'&&target!=player)); + player.addMark('sbxingshang',Math.min(get.info('sbxingshang').getLimit-player.countMark('sbxingshang'),game.countPlayer(target=>target.group=='wei'&&target!=player))); }, + group:'sbsongwei_delete', subSkill:{ delete:{ audio:'sbsongwei', enable:'phaseUse', - filter:function(event,player){ + filter(event,player){ + if(player.storage.sbsongwei_delete) return false; return game.hasPlayer(target=>lib.skill.sbsongwei.subSkill.delete.filterTarget(null,player,target)); }, - filterTarget:function(card,player,target){ + filterTarget(card,player,target){ return target!=player&&target.group=='wei'&&target.getStockSkills(false,true).length; }, skillAnimation:true, animationColor:'thunder', async content(event,trigger,player){ + player.storage.sbsongwei_delete=true; player.awakenSkill('sbsongwei_delete'); event.target.removeSkills(event.target.getStockSkills(false,true)); }, ai:{ order:13, result:{ - target:function(player,target){ + target(player,target){ return -target.getStockSkills(false,true).length; }, }, @@ -2678,7 +2735,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sbguose:{ audio:2, enable:'phaseUse', - usable:4, + get usable(){ + return get.mode()=='identity'?4:2; + }, discard:false, lose:false, delay:false, @@ -3993,7 +4052,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ trigger:{player:'phaseUseEnd'}, zhuSkill:true, unique:true, - direct:true, + popup:false, filter:function(event,player){ if(!player.hasZhuSkill('sbjijiang')) return false; return game.hasPlayer(current=>{ @@ -4001,59 +4060,40 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return game.hasPlayer(currentx=>current.inRange(currentx)); }); }, - content:function(){ - 'step 0' - var next=player.chooseTarget(get.prompt2('sbjijiang'),2); - next.set('filterTarget',(card,player,target)=>{ - if(!ui.selected.targets.length) return true; + async cost(event,trigger,player){ + event.result=await player.chooseTarget(get.prompt2('sbjijiang'),2).set('filterTarget',(card,player,target)=>{ + if(!ui.selected.targets.length) return target.group=='shu'&&target.hp>=player.hp&&target!=player; var current=ui.selected.targets[0]; - if(current.group=='shu'&¤t.hp>=player.hp&¤t!=player){ - return current.inRange(target); - } - else{ - return target.group=='shu'&&target.hp>=player.hp&&target.inRange(current)&&target!=player; - } - }) - next.set('targetprompt',target=>{ - var player=_status.event.player; - if(target.group=='shu'&&target.hp>=player.hp&&target!=player&&!ui.selected.targets.some(i=>{ - return i!=target&&i.hp>=player.hp&&i.group=='shu'; - })) return '进行选择'; - return '出杀对象'; - }); - next.set('ai',target=>{ + return current.inRange(target); + }).set('targetprompt',['进行选择','出杀对象']).set('multitarget',true).set('ai',target=>{ var player=_status.event.player; if(ui.selected.targets.length){ var current=ui.selected.targets[0]; - if(current.group=='shu'&¤t.hp>=player.hp&¤t!=player){ - return -get.attitude(player,target); - } - return Math.abs(get.attitude(player,current)); + return get.effect(target,new lib.element.VCard({name:'sha'}),current,player); } - else{ - if(target.group=='shu'&&target.hp>=player.hp&&target!=player&&game.hasPlayer(current=>{ - return get.attitude(player,current)<0; - })) return 10; - return 1; + let curs=game.filterPlayer(current=>{ + return target!==current&&target.inRange(current)&&target.canUse({name:'sha',isCard:true},current,false); + }); + if(!curs.length){ + let att=get.attitude(player,target); + if(att>=0) return 0; + return -att*get.threaten(target,player); } - }) - 'step 1' - if(result.bool){ - var targets=result.targets; - event.targets=targets; - if(targets[0].group!='shu'||targets[0].hp{ - return _status.event.choice; - }).set('choice',get.effect(targets[1],{name:'sha'},targets[0],targets[0])>get.effect(targets[0],{name:'lebu'},targets[0],targets[0])?0:1); - } - else event.finish(); - 'step 2' + return curs.reduce((max,i)=>Math.max(max,get.effect(i,new lib.element.VCard({name:'sha'}),target,player)),-1); + }).forResult(); + }, + async content(event,trigger,player){ + let targets=event.targets; + player.logSkill('sbjijiang',targets,false); + player.line2(targets); + var choiceList=[ + '视为对'+get.translation(targets[1])+'使用一张【杀】', + '你的下一个出牌阶段开始前,跳过此阶段' + ],result; + if(!targets[0].canUse({name:'sha',isCard:true},targets[1],false)) result={index:1}; + else result=await targets[0].chooseControl().set('choiceList',choiceList).set('ai',()=>{ + return _status.event.choice; + }).set('choice',get.effect(targets[1],{name:'sha'},targets[0],targets[0])>get.effect(targets[0],{name:'lebu'},targets[0],targets[0])?0:1).forResult(); if(result.index==0){ targets[0].useCard({name:'sha',isCard:true},targets[1],false); } @@ -6967,7 +7007,8 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sbzhiba_info:'主公技,限定技。当你进入濒死状态时,你可以回复X-1点体力并修改〖激昂③〗为“出牌阶段限X次”(X为场上其他吴势力角色数+1)。然后其他吴势力角色依次受到1点无来源伤害,且当有角色因此死亡后,你摸三张牌。', sb_daqiao:'谋大乔', sbguose:'国色', - sbguose_info:'出牌阶段限四次。你可以选择一项:1.将一张♦牌当【乐不思蜀】使用;2.弃置场上一张【乐不思蜀】。然后你摸一张牌。', + sbguose_info:'出牌阶段限两次,你可以将一张♦牌当【乐不思蜀】使用或弃置场上一张【乐不思蜀】,然后你摸一张牌。', + sbguose_info_identity:'出牌阶段限四次,你可以将一张♦牌当【乐不思蜀】使用或弃置场上一张【乐不思蜀】,然后你摸一张牌。', sbliuli:'流离', sbliuli_info:'当你成为【杀】的目标时,你可以弃置一张牌并选择你攻击范围内的一名不为此【杀】使用者的角色,将此【杀】转移给该角色。若你以此法弃置了♥牌,则你可以令一名不为此【杀】使用者的其他角色获得“流离”标记,且移去场上所有其他的“流离”(每回合限一次)。有“流离”的角色回合开始时,其移去其“流离”并执行一个额外的出牌阶段。', sb_liubiao:'谋刘表', @@ -7028,9 +7069,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sb_caopi:'谋曹丕', sb_caopi_prefix:'谋', sbxingshang:'行殇', - sbxingshang_info:'①每回合限一次,当一名角色死亡时或受到伤害时,你获得1个“颂”标记。②出牌阶段限一次,你可以:1.移去1个“颂”标记,令一名角色复原武将牌;2.移去2个“颂”标记,令一名角色摸X张牌(X为场上阵亡角色数,且X至少为1,至多为5);3.移去3个“颂”标记,令一名体力上限小于10的角色加1点体力上限,回复1点体力,随机恢复一个已废除的装备栏;4.移去4个“颂”标记,获得一名阵亡角色武将牌上的所有技能,然后你失去武将牌上的所有技能。', + sbxingshang_info:'①当一名角色受到伤害后(每回合限一次)或死亡时,你获得2个“颂”标记(你至多拥有9个“颂”标记)。②出牌阶段限两次,你可以:1.移去2个“颂”标记,令一名角色复原武将牌;2.移去2个“颂”标记,令一名角色摸X张牌(X为场上阵亡角色数,且X至少为1,至多为5);3.移去5个“颂”标记,令一名体力上限小于10的角色加1点体力上限,回复1点体力,随机恢复一个已废除的装备栏;4.移去5个“颂”标记,获得一名阵亡角色武将牌上的所有技能,然后你失去〖行殇〗〖放逐〗〖颂威〗。', sbfangzhu:'放逐', - sbfangzhu_info:'出牌阶段限一次,你可以:1.移去2个“颂”标记,令一名其他角色的非Charlotte技能失效直到其回合结束;2.移去2个“颂”标记,令一名其他角色不能响应除其以外的角色使用的牌直到其回合结束;3.移去3个“颂”标记,令一名其他角色将武将牌翻面;4.移去3个“颂”标记,令一名其他角色只能使用你选择的一种类型的牌直到其回合结束。', + sbfangzhu_info:'出牌阶段限一次,你可以:1.移去1个“颂”标记,令一名其他角色于手牌中只能使用基本牌直到其回合结束;2.移去2个“颂”标记,令一名其他角色的非Charlotte技能失效直到其回合结束;3.移去2个“颂”标记,令一名其他角色不能响应除其以外的角色使用的牌直到其回合结束;4.移去3个“颂”标记,令一名其他角色将武将牌翻面;5.移去3个“颂”标记,令一名其他角色于手牌中只能使用装备牌直到其回合结束。', sbsongwei:'颂威', sbsongwei_info:'主公技。①出牌阶段开始时,你获得Y个“颂”标记(Y为场上其他魏势力角色数)。②每局游戏限一次,出牌阶段,你可以令一名其他魏势力角色失去所有武将牌的技能。', sb_xunyu:'谋荀彧', diff --git a/character/shenhua.js b/character/shenhua.js index 692e140bc..f6ff37797 100755 --- a/character/shenhua.js +++ b/character/shenhua.js @@ -5441,8 +5441,6 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(!arg||!arg.player) return true; if(arg.player.hasSkillTag('unequip',false,{ target:player - })||arg.player.hasSkillTag('unequip_ai',false,{ - target:player })) return false; return true; }, @@ -6208,8 +6206,8 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } "step 2" if(result.suit=='club'){ - event.target.damage('thunder'); player.recover(); + event.target.damage('thunder'); } else if(result.suit=='spade'){ event.target.damage(2,'thunder'); @@ -8048,7 +8046,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ quhu_info:'出牌阶段限一次,你可以与一名体力值大于你的角色拼点,若你赢,则该角色对其攻击范围内另一名由你指定的角色造成1点伤害。若你没赢,该角色对你造成1点伤害。', jieming_info:'当你受到1点伤害后,你可令一名角色将手牌摸至X张(X为其体力上限且至多为5)。', qiangxi_info:'出牌阶段限一次,你可以失去1点体力或弃置一张武器牌,然后对你攻击范围内的一名其他角色造成1点伤害。', - qiangxix_info:'出牌阶段限两次,你可以失去1点体力或弃置一张武器牌,然后一名本阶段内未成为过〖强袭〗的目标的其他角色造成1点伤害。', + qiangxix_info:'出牌阶段限两次,你可以失去1点体力或弃置一张武器牌,然后对一名本阶段内未成为过〖强袭〗的目标的其他角色造成1点伤害。', tianyi_info:'出牌阶段限一次,你可以和一名其他角色拼点。若你赢,你获得以下技能效果直到回合结束:你使用【杀】没有距离限制;可额外使用一张【杀】;使用【杀】时可额外指定一个目标。若你没赢,你不能使用【杀】直到回合结束。', shuangxiong_info:'摸牌阶段,你可以改为进行一次判定:你获得此判定牌,且你可以于此回合内将任意一张与此判定牌不同颜色的手牌当做【决斗】使用。', luanji_info:'出牌阶段,你可以将任意两张相同花色的手牌当做【万箭齐发】使用。', @@ -8113,7 +8111,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ xinkuanggu_info:'当你造成1点伤害后,若受伤角色受到此伤害时你与其的距离不大于1,则你可以回复1点体力或摸一张牌。', xinliegong_info:'①你使用【杀】可以选择你距离不大于此【杀】点数的角色为目标。②当你使用【杀】指定一个目标后,你可以根据下列条件执行相应的效果:1.其手牌数小于等于你的手牌数,此【杀】不可被响应,2.其体力值大于等于你的体力值,此【杀】伤害+1。', jiewei_info:'当你的武将牌翻面后,你可以摸一张牌。然后你可以使用一张锦囊牌或装备牌,并可以在此牌结算后弃置场上一张同类型的牌。', - releiji_info:'当你使用或打出一张【闪】时,你可令一名其他角色进行一次判定:若结果为梅花,其受到1点雷电伤害,然后你回复1点体力;若结果为黑桃,其受到2点雷电伤害。', + releiji_info:'当你使用或打出一张【闪】时,你可令一名其他角色进行一次判定:若结果为梅花,你回复1点体力,并对其造成1点雷电伤害;若结果为黑桃,你对其造成2点雷电伤害。', tiangong_info:'锁定技,你防止即将受到的雷电伤害。每当你造成雷电伤害时,你摸一张牌。', shensu_info:'你可以跳过判定阶段和摸牌阶段,或跳过出牌阶段并弃置一张装备牌。若如此做,则你可以视为对任意一名角色使用一张无距离限制的【杀】。', jushou_info:'结束阶段,你可以摸三张牌并翻面。', diff --git a/character/sp.js b/character/sp.js index 7ce5b7b63..acfcf080f 100755 --- a/character/sp.js +++ b/character/sp.js @@ -231,7 +231,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ xiahouxuan:'夏侯玄(209年~254年),字泰初(《三国志》等作太初),沛国谯县(今安徽省亳州市)人。三国时期曹魏大臣、思想家、文学家,征南大将军夏侯尚之子,大将军曹爽的表弟。夏侯玄少年有名望,仪表出众,时人称为“朗朗如日月之入怀”。魏文帝黄初六年(225年),袭封昌陵乡侯。魏明帝时,历任散骑黄门侍郎、羽林监。少帝曹芳继位后,拜散骑常侍、中护军,保卫皇宫。后任征西将军,任内与曹爽策划骆谷之役,大失人心。高平陵政变后,被夺去兵权,改任大鸿胪、太常卿。嘉平六年(254年),中书令李丰与外戚张缉密谋杀死大将军司马师,改以夏侯玄执政。事泄被杀,夷灭三族,夏侯玄死时年仅四十六岁。著有文集三卷,如今已佚。政治上,提出了“审官择人”、“除重官”、“改服制”等制度,被太傅司马懿评价“皆大善”。博学多识,才华出众,精通玄学,成为“四聪”之一,与何晏等人开创了魏晋玄学的先河,是早期的玄学领袖人物。', dengzhong:'邓忠(不详-264年),三国时期曹魏名将邓艾之子。景元五年(264年),钟会谋反事败,士兵哗变,钟会被杀,邓艾部将想追还邓艾父子,但卫瓘却派田续追邓艾,于绵竹西相遇,将邓艾和邓忠等人杀死。直至泰始九年(273年)才恢复名节。', wangyan:'王衍(256年~311年),字夷甫,琅邪郡临沂县(今山东省临沂市)人。西晋末年重臣,玄学清谈领袖,曹魏幽州刺史王雄之孙、平北将军王乂之子、司徒王戎堂弟。王衍出身琅琊王氏。外表清明俊秀,风姿安详文雅,笃好老庄学说,颇有时名。步入仕途后,历任黄门侍郎、中领军、尚书令、尚书仆射等职。光熙元年(307年),升任司空。次年,又任司徒。王衍位高权重,却不思为国,为保全自己,还让弟弟王澄、族弟王敦分任荆州、青州刺史,遭时人鄙夷。王弥进攻洛阳时,王衍率军抵抗。其后转任太尉兼尚书令,又兼领太傅军司。永嘉五年(311年),东海王司马越去世,王衍奉其灵柩返回东海,途中为羯人石勒所俘获。王衍在与石勒交谈时,仍推脱责任,并劝其称帝,石勒大怒,将其与西晋旧臣一同活埋,时年五十六岁。王衍工书法,尤擅行书,《宣和书谱》有其作品《尊夫人帖》。', - caoxiancaohua:'请分别查询参考「曹宪」和「曹华」的部武将介绍。', + caoxiancaohua:'请分别查看「曹宪」和「曹华」的武将介绍。', zhaoyǎn:'赵俨(171~245年),字伯然,颍川阳翟(今河南禹州市)。东汉末年颍川“四大名士”之一,三国时期魏国名臣。熟读经史,精明强干。建安二年,投靠大将军曹操之后,起家朗陵县令,历任司空府掾、司空主薄、都督护军、扶风太守等职。魏文帝曹丕继位后,历任魏国侍中、驸马都尉、河东太守、典农中郎将、度支尚书,封宜土亭侯。魏明帝曹睿时期,历任大司农、骠骑将军、大司空等职。正始六年,去世,时年七十五,谥号为穆。', ruiji:'芮姬,芮玄之女,太子孙登妃,黄武五年卒。', weizi:'卫兹(?-190年),字子许,(《三国演义》中其名为卫弘,当为误记),陈留襄邑(今河南睢县)人。曾举孝廉,先后被车骑将军何苗、司徒杨赐等召辟。中平六年(189年)十二月,曹操在陈留己吾募兵,而卫兹以家财资助曹操,使曹操顺利募得五千士兵。此后,卫兹与曹操共同讨伐董卓。初平元年(190年),卫兹在跟随曹操讨伐董卓途中,于荥阳汴水遭遇董卓军徐荣,力战终日,失利身亡。', @@ -248,7 +248,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ panshu:'潘淑(?-252年),会稽句章(今浙江省宁波市)人,是吴大帝孙权的皇后,吴少帝孙亮的母亲。和孙权是中国历代帝后中年龄差距较大的一对。潘淑少时与姐姐俱没入织室,容媚有宠,拜为夫人,生有一子孙亮。赤乌十三年(250年),孙权立孙亮为皇太子,翌年(251年)立潘淑为皇后。神凤元年(252年)暴崩,合葬蒋陵。世称潘淑为江东绝色,有神女之称。', zongyu:'宗预(?-264年),字德艳 ,荆州南阳郡安众县(今河南省南阳市)人。三国时期蜀汉官员、将领。曾随张飞入蜀助平益州,又受辟为丞相诸葛亮手下主簿,升任参军、右中郎将。诸葛亮逝世后,宗预受命出使孙吴,得到孙权的赞赏。迁后将军,出督永安,又升任征西大将军,并受封关内侯。公元258年(景耀元年),因病回成都,受任镇军大将军。蜀汉灭亡后,宗预随后主刘禅徙往洛阳,在中途病逝。宗预为人坦率耿直,多次出使孙吴并深得孙权的敬重,为吴、汉两国同盟的巩固作出了一定的贡献。', mengda:'孟达(?-228),字子度,本字子敬,因刘备的叔父名叫刘子敬,为避讳而改字。扶风郡郿人,三国时期人物。本为刘璋属下,后降刘备。关羽围樊城、襄阳时因不发兵救关羽而触怒刘备,于是投奔曹魏。此后,劝降刘封,未果。在魏官至散骑常侍、建武将军,封平阳亭侯。此后又欲反曹魏而归蜀汉,事败而死。', - wolongfengchu:'沙比武将,懒得复制粘贴,自己去看诸葛亮和庞统的介绍吧。', + wolongfengchu:'沙比武将,懒得复制粘贴,自己去看「诸葛亮」和「庞统」的介绍吧。', caoshuang:'曹爽(?-249年2月9日),字昭伯,沛国谯县(今安徽亳州市)人。三国时期魏国权臣,大司马曹真长子。曹爽体态肥胖,凭借宗室身份,出入宫廷,交好太子曹叡。魏明帝即位,起家员外散骑侍郎,累迁城门校尉、散骑常侍,转武卫将军。太和五年(231年),袭封邵陵侯。景初三年(239年),魏明帝曹叡病危,拜大将军、假黄钺,与司马懿并为托孤大臣。少帝曹芳即位,加侍中,改封武安侯。势倾四海,声震天下。任用私人,专权乱政,侵吞公产。伐蜀失败,虚耗国力。起居逾制,软禁郭太后。正始十年,太傅司马懿发动高平陵政变,掌握魏国大权。曹爽失去大将军职务,以谋反之罪处死,夷灭三族。', zhangling:'张道陵(34年2月22日—156年),字辅汉,原名陵,道教正一道实际创立者,汉朝东汉时期丰邑(今江苏徐州丰县)人。太上老君降临蜀地,“授以三天正法,命为天师”,张道陵整合当时的:黄老派、方仙道、文始派等先秦修道团体,创立道教称正一盟威之道。后世尊称为“老祖天师”、“正一真人”、“三天扶教大法师”、高明上帝、张天师。著作《老子想尔注》,弟子有3000多人,设立24治,奠基天师道。张道陵、葛玄、许逊、萨守坚合称四大天师。张道陵创建道教的背景:当时在巴蜀一带,原有巴人信奉原始巫教,大规模的淫祀而害民。而这些祀奉鬼妖(学名为:妖邪)的法教巫师聚众敛财,无恶不作。张天师携王长、赵升二位弟子和黄帝九鼎丹经,来到北邙山修行,平定了那些祸害百姓的巫妖之教。川渝一带流传的张天师以太上老君剑印符箓大破鬼兵的故事就是以此为原型的。', caiyang:'蔡阳(?-201年),又作蔡扬,东汉丞相曹操部下武将,汝南太守。于建安六年(201)奉曹操之命攻击与刘备联合的汝南贼龚都等人,兵败被刘备所杀。明代小说《三国演义》改编为“云长擂鼓斩蔡阳”。', @@ -288,7 +288,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ bianfuren:'武宣皇后卞氏(159年12月30日-230年7月9日),琅邪开阳(今山东临沂)人,魏武帝曹操的正妻(继室),魏文帝曹丕、任城威王曹彰、陈思王曹植、萧怀王曹熊的母亲。原本是倡家,即汉代专门从事音乐歌舞的乐人家庭,后来与曹操成婚,建安初年,原配丁夫人被废,卞夫人成为曹操的正妻。曹丕继位后尊其为皇太后,曹叡继位后尊其为太皇太后。卞后在太和四年去世,与魏武帝曹操合葬高陵。', shamoke:'沙摩柯(?-222年),东汉末三国时期五溪蛮首领。汉章武元年(221年)初,为报关羽被东吴杀害之仇,刘备亲自领兵攻孙权,以金锦爵赏诱沙摩柯助战。章武二年(222年),吴大都督陆逊以火攻破刘备,率诸军齐击,汉军四十多个营寨被攻破,沙摩柯在大乱中匹马奔逃,被乱军杀死。', lvfan:'吕范(?-228年),字子衡。汝南郡细阳县(今安徽太和)人。汉末至三国时期吴国重臣。吕范年轻为汝南县吏,后避难寿春,结识孙策。此后随孙策、孙权征伐四方,对稳固孙氏在江东的统治做出了杰出的贡献,孙权将其比之于东汉开国元勋吴汉。吴国建立后,吕范累官至前将军、假节、扬州牧,封南昌侯。黄武七年(228年),吕范被拜为大司马,未得授官,便已病逝。孙权悲痛不已,遣使赠其大司马印绶。孙权还都建业后,以太牢礼祭祀吕范。', - liqueguosi:"请分别参考武将【李傕】和【郭汜】各自的介绍。", + liqueguosi:"请分别查看「李傕」和「郭汜」的武将介绍。", maojie:"毛玠(?—216年),字孝先,陈留平丘(今河南封丘)人。东汉末年大臣。年少时为县吏,以清廉公正著称。因战乱而打算到荆州避乱,但中途知道刘表政令不严明,因而改往鲁阳。后来投靠曹操,提出“奉天子以令不臣,脩耕植,畜军资”的战略规划,得到曹操的欣赏。
毛玠与崔琰主持选举,所举用的都是清廉正直之士。而毛玠为人廉洁,激起天下廉洁之风,一改朝中奢华风气。曹操大为赞赏,曹丕也亲自去拜访他。
曹操获封魏公后,毛玠改任尚书仆射,再典选举。又密谏曹操应该立嫡长子曹丕为魏国太子。崔琰被杀后,毛玠十分不快。后来有人诬告毛玠,曹操大怒,将毛玠收于狱中。及后在桓阶、和洽营救下,只被免职,不久逝世于家中。曹操在他死后赐他棺材和钱帛。", huangfusong:'字义真。安定郡朝那县(今宁夏彭阳)人。于黄巾起义时,以中郎将身份讨伐黄巾,用火攻大破张梁、张宝。后接替董卓进攻张梁,连胜七阵。掘张角墓,拜左车骑将军、冀州牧,因拒绝贿赂宦官而被免职。 董卓死,王允命其与吕布等共至郿坞抄籍董卓家产、人口,皇甫嵩将坞中所藏良家子女,尽行释放。', @@ -297,7 +297,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ jiling:'东汉末年袁术帐下将领,勇猛非常,曾奉命率军攻打小沛的刘备,在吕布辕门射戟的调停下撤兵。', zoushi:'军阀张济之妻,张绣之婶。张绣降曹后,邹氏遂被曹操霸占。贾诩献计趁机诛杀曹操,险些得手。曹操在损失爱将典韦、侄子曹安民和长子曹昂后方才逃出生天。', ganfuren:'刘备起兵后,于沛城娶甘氏为妾。后来,甘夫人随刘备到荆州,生了阿斗(也就是后主刘禅)。223年四月,刘备病死于白帝城,追谥甘夫人为“昭烈皇后”。', - jiangfei:'请分别查阅【蒋琬】和【费袆】各自的介绍。', + jiangfei:'请分别查看「蒋琬」和「费袆」的武将介绍。', mifuren:'刘备夫人。徐州别驾糜竺之妹。长坂兵败,她怀抱年仅两岁的刘禅在乱军中走散,被赵云发现;但麋夫人因为赵云只有一匹马,不肯上马,在将阿斗托付给赵云后投井而亡。', chendong:'陈武,东吴将领,孙策攻打刘繇,陈武前来相助,孙策非常喜爱陈武,拜为校尉,使作先锋。陈武以十数骑兵力杀敌五十余人。后于赤壁等战役屡立功勋。董袭献上严虎的人头来降孙策。赤壁之战,董袭受周瑜命,分兵去汉阳,合肥会战时接应太史慈,逍遥津支援孙权。濡须口之战时,董袭在船上督战,船覆董袭坚守殉职。', jiangqing:'擅长弓术。与周泰原为活跃于长江一带的江贼,孙策脱离袁术下江东自立门户时,和周泰一起率众投靠。 孙策攻刘繇,并引出城中麾下的陈横、薛礼、张英三名将领,陈横后被蒋钦一箭射杀,后与韩当等将乘舟过江,乱箭射杀敌军。曾在赤壁之战与周泰,还有擅使长枪的韩当率领水军在三江口踏江破敌。', @@ -1219,10 +1219,10 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(result2.bool){ const card=result2.cards[0]; if(get.name(card,target)==event.result.card.name){ - player.popup('诿解成功'); + player.popup('洗具'); stop=true; } - else player.popup('诿解失败'); + else player.popup('杯具'); } } if(!stop){ @@ -1747,11 +1747,13 @@ game.import('character',function(lib,game,ui,get,ai,_status){ var {result:{bool,cards}}=await player.chooseToGive(get.prompt2('olxiangzuo',target),[1,num],'he').set('ai',card=>{ var player=_status.event.player,target=_status.event.target; if(player.getHistory('useSkill',evt=>{ - return (evt.skill=='olgongjie'||evt.skill=='olxiangxv')&&evt.targets.includes(target); + return evt.skill=='olgongjie'&&evt.targets.includes(target); + }).length&&player.getHistory('useSkill',evt=>{ + return evt.skill=='olxiangxv'&&evt.targets.includes(target); }).length){ if(get.attitude(player,target)>0) return 1; if(player.canSaveCard(card,player)) return 0; - if(ui.selected.cards.length+player.hp==player.maxHp) return 0; + if(ui.selected.cards.length+player.hp>=player.maxHp) return 0; return 20-get.value(card); } else{ @@ -1762,7 +1764,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(!bool) return; player.awakenSkill('olxiangzuo'); if(player.getHistory('useSkill',evt=>{ - return (evt.skill=='olgongjie'||evt.skill=='olxiangxv')&&evt.targets.includes(target); + return evt.skill=='olgongjie'&&evt.targets.includes(target); + }).length&&player.getHistory('useSkill',evt=>{ + return evt.skill=='olxiangxv'&&evt.targets.includes(target); }).length) player.recover(cards.length); }, }, @@ -3038,6 +3042,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ olcangxin:{ audio:2, trigger:{player:'damageBegin4'}, + filter(event,player){ + return game.getGlobalHistory('everything',evt=>{ + return evt.name=='damage'&&evt.player==player; + },event).indexOf(event)==0; + }, checkx:function(event,player){ var target=event.source; return get.damageEffect(player,target,target)<=0; @@ -3046,17 +3055,19 @@ game.import('character',function(lib,game,ui,get,ai,_status){ content:function(){ 'step 0' var cards=get.bottomCards(3,true); - player.chooseButton(['###藏心:请选择要弃置的牌###若以此法弃置了红桃牌,则防止此伤害',cards],[1,cards.length],true).set('ai',function(button){ + player.chooseButton(['###藏心:请选择要弃置的牌###若以此法弃置了红桃牌,则减少弃置红桃牌数的伤害',cards],[1,cards.length],true).set('ai',function(button){ if(!_status.event.bool&&get.suit(button.link,false)=='heart') return 0; if(get.suit(button.link,false)!='heart') return 1; - if(!ui.selected.buttons.some(but=>get.suit(but.link,false)=='heart')) return 1; + const num=get.event().getTrigger().num; + if(num>ui.selected.buttons.filter(but=>get.suit(but.link,false)=='heart').length) return 1; return 0; }).set('bool',lib.skill.olcangxin.checkx(trigger,player)); 'step 1' if(result.bool){ player.$throw(result.links,1000); game.cardsDiscard(result.links); - if(result.links.some(card=>get.suit(card,false)=='heart')) trigger.cancel(); + const num=result.links.filter(card=>get.suit(card,false)=='heart').length; + if(num) trigger.num-=Math.min(trigger.num,num); } else event.finish(); 'step 2' @@ -4761,7 +4772,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ event.goto(2); } else{ - var choices=['〇','一','二']; + var choices=['零','一','二']; player.chooseControl(choices).set('prompt','镇荧:请选择要将手牌调整至的张数').set('ai',()=>{ return [0,1,2].randomGet(); }); @@ -11526,12 +11537,15 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } else event.finish(); 'step 5' - player.chooseTarget('是否令一名手牌数小于自己的目标角色摸一张牌?',function(card,player,target){ - return _status.event.getParent().targets.includes(target)&&target.countCards('h')0&&targets.some(target=>target.isIn()&&target.countCards('h')player.canSaveCard(card,player))<=1) return 0; - const num=get.sgn(get.attitude(player,target)); - if(num*get.damageEffect(target,player,player)>0) return num*get.damageEffect(target,player,player); - if(target==player) return 0.00001; - return 0; + return get.damageEffect(target,player,target); }, }, }, @@ -261,6 +262,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ const num=player.countCards('h'); if(player.isMaxHandcard()&&num>0){ const maxNum=game.findPlayer(current=>{ + if(current===player) return false; return !game.hasPlayer(current2=>{ if(current2===player) return false; return current2.countCards('h')>current.countCards('h'); @@ -291,7 +293,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } } }, - + }, //星袁绍 starxiaoyan:{ @@ -716,8 +718,18 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } }, create:function(group,player){ - if(!lib.skill['starcanxi_'+group]){ - lib.skill['starcanxi_'+group]={ + const skill='starcanxi_'+group; + get.info('starcanxi').createSkill(skill); + if(!_status.postReconnect.starcanxi){ + _status.postReconnect.starcanxi=[get.info('starcanxi').createSkill,[]]; + } + _status.postReconnect.starcanxi[1].add(skill); + player.addSkill(skill); + }, + createSkill(skill){ + if(!lib.skill[skill]) game.broadcastAll(skill=>{ + const group=skill.slice('starcanxi_'.length); + lib.skill[skill]={ mark:true, charlotte:true, onremove:function(player){ @@ -725,11 +737,10 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, intro:{content:'玉玺的一角'}, }; - lib.translate['starcanxi_'+group]='残玺·'+get.translation(group+'2'); - lib.skill['starcanxi_'+group].marktext=get.translation(group); - lib.translate['starcanxi_'+group+'_bg']=get.translation(group); - } - player.addSkill('starcanxi_'+group); + lib.translate[skill]='残玺·'+get.translation(group+'2'); + lib.skill[skill].marktext=get.translation(group); + lib.translate[skill+'_bg']=get.translation(group); + },skill); }, subSkill:{ wangsheng:{ @@ -3272,7 +3283,10 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } else player.addTempSkill('piaoping_blocker'); }, - intro:{name2:'栗',content:'mark'}, + init(player){ + player.addMark('tuoxian',1,false); + }, + intro:{name2:'栗',content:'剩余可用#次'}, }, chuaili:{ audio:2, @@ -3288,8 +3302,8 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.changeZhuanhuanji('piaoping'); } else{ - player.addMark('tuoxian',1); - player.addTempSkill('chuaili_blocker'); + player.addMark('tuoxian',1,false); + if(player.countCards('tuoxian')>3) player.addTempSkill('chuaili_blocker'); } game.delayx(); }, @@ -4655,26 +4669,34 @@ game.import('character',function(lib,game,ui,get,ai,_status){ audio:'xinfu_xingluan', usable:1, trigger:{player:'useCardAfter'}, - direct:true, filter:function(event,player){ return player.isPhaseUsing(); }, - content:function(){ - 'step 0' - var list=['观看牌堆中两张点数为6的牌并获得其中一张']; - event.addIndex=1; - var bool2=false,bool3=game.hasPlayer(function(current){ - if(current!=player&¤t.countCards('he')>0) bool2=true; + async cost(event, trigger, player){ + const choiceList = [ + '观看牌堆中两张点数为6的牌并获得其中一张', + '令一名其他角色弃置一张点数为6的牌或交给你一张牌', + '获得场上一张点数为6的牌' + ], choices = ['选项一']; + if (game.hasPlayer(current => (current != player && current.countCards('he') > 0))) { + choices.push('选项二'); + } + else { + choiceList[1] = `${ choiceList[1] }`; + } + if (game.hasPlayer(current => { return current.hasCard(function(card){ return get.number(card)==6&&lib.filter.canBeGained(card,current,player); },'ej'); - }); - if(bool2){ - event.addIndex=0; - list.push('令一名其他角色弃置一张点数为6的牌或交给你一张牌'); + })) { + choices.push('选项三'); } - if(bool3) list.push('获得场上一张点数为6的牌'); - player.chooseControl('cancel2').set('choiceList',list).set('prompt',get.prompt('xinxingluan')).set('ai',function(){ + else { + choiceList[2] = `${ choiceList[2] }`; + } + const result = await player.chooseControl(choices, 'cancel2') + .set('choiceList',choiceList).set('prompt',get.prompt('xinxingluan')) + .set('ai',function(){ var player=_status.event.player; if(game.hasPlayer(function(current){ if(current==player) return false; @@ -4682,26 +4704,57 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return current.hasCard(function(card){ return get.number(card)==6&&lib.filter.canBeGained(card,current,player)&&get.sgn(get.useful(card,current))==att; },'ej'); - })) return 2-_status.event.getParent().addIndex; + })) return '选项三'; if(game.hasPlayer(function(target){ if(target==player) return false; var att=get.attitude(player,target); return att<0&&target.countCards('he')>0&&!target.hasCard(function(card){ return get.value(card,target)<=0; },'he'); - })) return 1; - return 0; - }); - 'step 1' - if(result.control!='cancel2'){ - if(result.index==0){ - player.logSkill('xinxingluan'); + })) return '选项二'; + return '选项一'; + }).forResult(); + if (result.control !== 'cancel2') { + const results = {bool: true, cost_data: {index: choices.indexOf(result.control)}}; + if(results.cost_data.index === 1) { + const {targets} = await player.chooseTarget('令一名其他角色弃置一张点数为6的牌,否则交给你一张牌',true,function(card,player,current){ + return current!=player&¤t.countCards('he')>0; + }).set('ai',function(target){ + var player=_status.event.player,att=get.attitude(player,target); + if(att>=0) return 0; + if(!target.hasCard(function(card){ + return get.value(card,target)<=0; + },'he')) return -att/Math.sqrt(target.countCards('he')); + return 0; + }).forResult(); + results.targets = targets; } - else if(result.index+event.addIndex==1) event.goto(6); - else event.goto(4); + else if(results.cost_data.index === 2){ + const {targets} = await player.chooseTarget('获得一名角色装备区或判定区内点数为6的牌',true,function(card,player,current){ + return current.hasCard(function(card){ + return get.number(card)==6&&lib.filter.canBeGained(card,current,player); + },'ej'); + }).set('ai',function(target){ + var player=_status.event.player,att=-get.sgn(get.attitude(player,target)-0.1),max=0,ej=target.getCards('ej',function(card){ + return get.number(card)==6&&lib.filter.canBeGained(card,target,player); + }); + for(var i of ej){ + var num=get.useful(i,target)*att; + if(num>max) max=num; + return max; + } + }).forResult(); + results.targets = targets; + } + event.result = results; } - else event.finish(); - 'step 2' + }, + content:function(){ + 'step 0' + var result = event.cost_data; + if(result.index === 1) event.goto(4); + else if(result.index === 2) event.goto(3); + 'step 1' var cards=[]; while(cards.length<2){ var card=get.cardPile2(function(card){ @@ -4720,62 +4773,29 @@ game.import('character',function(lib,game,ui,get,ai,_status){ else player.chooseButton(['兴乱:选择获得其中一张',cards],true).set('ai',function(button){ return get.value(button.link,_status.event.player); }); - 'step 3' + 'step 2' if(result.bool){ player.gain(result.links,'gain2'); } event.finish(); - 'step 4' - player.chooseTarget('获得一名角色装备区或判定区内点数为6的牌',true,function(card,player,current){ - return current.hasCard(function(card){ - return get.number(card)==6&&lib.filter.canBeGained(card,current,player); - },'ej'); - }).set('ai',function(target){ - var player=_status.event.player,att=-get.sgn(get.attitude(player,target)-0.1),max=0,ej=target.getCards('ej',function(card){ - return get.number(card)==6&&lib.filter.canBeGained(card,target,player); - }); - for(var i of ej){ - var num=get.useful(i,target)*att; - if(num>max) max=num; - return max; - } + 'step 3' + var target=targets[0]; + player.gainPlayerCard(target,'ej',true).set('filterButton',function(button){ + return get.number(button.link)==6; }); - 'step 5' - if(result.bool){ - var target=result.targets[0]; - player.logSkill('xinxingluan',target); - player.gainPlayerCard(target,'ej',true).set('filterButton',function(button){ - return get.number(button.link)==6; - }); - } event.finish(); - 'step 6' - if(!game.hasPlayer(current=>current!=player)) event.finish(); - else player.chooseTarget('令一名其他角色弃置一张点数为6的牌,否则交给你一张牌',true,function(card,player,current){ - return current!=player&¤t.countCards('he')>0; - }).set('ai',function(target){ - var player=_status.event.player,att=get.attitude(player,target); - if(att>=0) return 0; - if(!target.hasCard(function(card){ - return get.value(card,target)<=0; - },'he')) return -att/Math.sqrt(target.countCards('he')); - return 0; - }); - 'step 7' - if(result.bool){ - var target=result.targets[0]; - event.target=target; - player.logSkill('xinxingluan',target); - target.chooseToDiscard('he','弃置一张点数为6的牌,否则交给'+get.translation(player)+'一张牌',function(card){ - return get.number(card)==6; - }).ai=(card)=>(8-get.value(card)); - } - 'step 8' + 'step 4' + var target=targets[0]; + event.target=target; + target.chooseToDiscard('he','弃置一张点数为6的牌,否则交给'+get.translation(player)+'一张牌',function(card){ + return get.number(card)==6; + }).ai=(card)=>(8-get.value(card)); + 'step 5' if(!result.bool){ target.chooseCard('he',true,'交给'+get.translation(player)+'一张牌'); } else event.finish(); - 'step 9' + 'step 6' if(result.bool) target.give(result.cards,player,'giveAuto'); }, }, @@ -6599,16 +6619,16 @@ game.import('character',function(lib,game,ui,get,ai,_status){ direct:true, filter:function(event,player){ if(!game.hasPlayer(function(current){ - return current.hasSkill('cixiao_yizi'); + return current.hasSkill('panshi'); })) return true; return player.countCards('he')>=1&&game.hasPlayer(function(current){ - return current!=player&&!current.hasSkill('cixiao_yizi'); + return current!=player&&!current.hasSkill('panshi'); }); }, content:function(){ 'step 0' if(game.hasPlayer(function(current){ - return current.hasSkill('cixiao_yizi'); + return current.hasSkill('panshi'); })) event.goto(2); else player.chooseTarget(lib.filter.notMe,get.prompt('cixiao'),'令一名其他角色获得「义子」标记').set('ai',function(target){ var player=_status.event.player; @@ -6619,19 +6639,19 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(result.bool){ var target=result.targets[0]; player.logSkill('cixiao',target); - target.addSkills('cixiao_yizi'); + target.addSkills('panshi'); } event.finish(); 'step 2' var list=game.filterPlayer(function(current){ - return current.hasSkill('cixiao_yizi'); + return current.hasSkill('panshi'); }); player.chooseCardTarget({ prompt:get.prompt('cixiao'), prompt2:('弃置一张牌并将'+get.translation(list)+'的「义子」标记转移给其他角色'), position:'he', filterTarget:function(card,player,target){ - return player!=target&&!target.hasSkill('cixiao_yizi'); + return player!=target&&!target.hasSkill('panshi'); }, filterCard:lib.filter.cardDiscardable, ai1:function(card){ @@ -6654,12 +6674,12 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.logSkill('cixiao'); player.discard(result.cards).delay=false; player.line2(game.filterPlayer(function(current){ - if(current.hasSkill('cixiao_yizi')){ - current.removeSkills('cixiao_yizi'); + if(current.hasSkill('panshi')){ + current.removeSkills('panshi'); return true; } }).concat(result.targets),'green'); - target.addSkills('cixiao_yizi'); + target.addSkills('panshi'); } else event.finish(); 'step 4' @@ -6667,18 +6687,6 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, derivation:'panshi', ai:{threaten:8}, - subSkill: { - yizi: { - mark: true, - charlotte: true, - marktext: '子', - intro: { - name: '义子', - content: '具有〖叛弑〗' - }, - group: 'panshi' - } - } }, panshi:{ trigger:{player:'phaseZhunbeiBegin'}, @@ -6714,6 +6722,31 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.give(result.cards,target); } }, + mark:true, + marktext:'子', + intro:{ + name:'义子', + //content:'我是儿子', + //R·I·P——永远怀念:被棘手砍掉的“我是儿子” + content(_,player){ + const targets=game.filterPlayer2(target=>target.hasSkill('cixiao',null,null,false)).sortBySeat(player); + if(!targets.length) return '我义父呢?!'; + if(['name','name1','name2'].some(name=>{ + if(!player[name]||!get.character(player[name])||typeof get.translation(player[name])!='string') return false; + return player[name].includes('lvbu')&&get.translation(player[name]).includes('吕布'); + })) return '公若不弃,布愿拜为义父'; + return '我是'+get.translation(targets)+'的'+((player)=>{ + switch(player.sex){ + case 'female': + return '义女'; + case 'double': + return '义子义女'; + default: + return '义子'; + } + })(player); + }, + }, group:'panshi_damage', }, panshi_damage:{ @@ -6725,6 +6758,10 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, content:function(){ trigger.num++; + if(['name','name1','name2'].some(name=>{ + if(!player[name]||!get.character(player[name])||typeof get.translation(player[name])!='string') return false; + return player[name].includes('lvbu')&&get.translation(player[name]).includes('吕布'); + })) player.chat('吾堂堂丈夫,安肯为汝子乎!'); var evt=event.getParent('phaseUse'); if(evt&&evt.player==player) evt.skipped=true; }, @@ -11026,9 +11063,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return '转换技,锁定技。当你使用一张牌时,阴:你摸X张牌。阳:你弃置X张牌。(X为你本阶段内发动过〖漂萍〗的次数且至多等于你的体力值)'; }, chuaili:function(player){ - if(!player.hasSkill('piaoping',null,null,false)) return '锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你获得一枚“栗”,且令〖惴栗〗于本回合内失效。'; - if(player.storage.piaoping) return '锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你获得一枚“栗”,且令〖惴栗〗于本回合内失效。'; - return '锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你获得一枚“栗”,且令〖惴栗〗于本回合内失效。'; + if(!player.hasSkill('piaoping',null,null,false)) return '锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你令〖托献〗发动次数+1,然后若〖托献〗发动次数大于3,则〖惴栗〗于本回合内失效。'; + if(player.storage.piaoping) return '锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你令〖托献〗发动次数+1,然后若〖托献〗发动次数大于3,则〖惴栗〗于本回合内失效。'; + return '锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你令〖托献〗发动次数+1,然后若〖托献〗发动次数大于3,则〖惴栗〗于本回合内失效。'; }, dcdouzhen:function(player){ var str='锁定技。①转换技。你的回合内,'; @@ -11388,7 +11425,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ recuorui:'摧锐', recuorui_info:'限定技,出牌阶段,你可以依次获得至多X名角色的各一张手牌(X为你的体力值)。', reliewei:'裂围', - reliewei_info:'每回合限Y次,当有角色于你的回合内进入濒死状态时,你可以摸一张牌(Y为你的体力值,若当前回合角色为你,则Y为Infinity)。', + reliewei_info:'每回合限Y次,当有角色进入濒死状态时,你可以摸一张牌(Y为你的体力值,若当前回合角色为你,则Y为Infinity)。', duanwei:'段煨', langmie:'狼灭', langmie_damage:'狼灭', @@ -11484,7 +11521,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ quanjiu_info:'锁定技。①你手牌区中的【酒】的牌名视为【杀】。②你使用对应的实体牌为一张【酒】的非转化【杀】不计入次数限制。', re_pangdegong:'庞德公', heqia:'和洽', - heqia_info:'出牌阶段开始时,你可选择一项:①将任意张牌交给一名其他角色。②令一名有手牌的其他角色交给你任意张牌。然后以此法得到牌的角色可以视为使用一张基本牌,且当其声明使用此牌后,可以为此牌增加至至多X个目标(X为以此法移动的牌数)。', + heqia_info:'出牌阶段开始时,你可选择一项:①将任意张牌交给一名其他角色。②令一名有手牌的其他角色交给你任意张牌。然后以此法得到牌的角色可以将一张手牌当作任意基本牌使用,且当其声明使用此牌后,可以为此牌增加至至多X个目标(X为以此法移动的牌数)。', yinyi:'隐逸', yinyi_info:'锁定技。每回合限一次,当你受到非属性伤害时,若你的手牌数和体力值与伤害来源均不相同,则你防止此伤害。', haomeng:'郝萌', @@ -11492,7 +11529,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ xiongmang_info:'你可将任意张花色各不相同的手牌当做目标数上限为X的【杀】使用(X为此【杀】对应的实体牌数)。此【杀】使用结算结束后,若你未造成过渠道为此牌的伤害,则你减1点体力上限。', yanfuren:'严夫人', channi:'谗逆', - channi_info:'出牌阶段限一次。你可将任意张手牌交给一名其他角色,然后其可以将等量的手牌当做【决斗】使用。若其因此【决斗】造成了伤害,则其摸X张牌(X为此【决斗】对应的实体牌数)。若其因此【决斗】受到过伤害,则你弃置所有手牌。', + channi_info:'出牌阶段限一次。你可将任意张手牌交给一名其他角色,然后其可以将至多等量的手牌当做【决斗】使用。若其因此【决斗】造成了伤害,则其摸X张牌(X为此【决斗】对应的实体牌数)。若其因此【决斗】受到过伤害,则你弃置所有手牌。', nifu:'匿伏', nifu_info:'锁定技。一名角色的回合结束时,你将手牌摸至或弃置至三张。', licaiwei:'李采薇', @@ -11512,9 +11549,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ piaoping:'漂萍', piaoping_info:'转换技,锁定技。当你使用一张牌时,阴:你摸X张牌。阳:你弃置X张牌。(X为你本阶段内发动过〖漂萍〗的次数且至多等于你的体力值)', tuoxian:'托献', - tuoxian_info:'当你因执行〖漂萍〗的效果而弃置牌后,你可以弃置一枚“栗”并令一名其他角色获得这些牌,然后令该角色选择一项:⒈弃置区域内等量的牌。⒉令你的〖漂萍〗失效直到回合结束。', + tuoxian_info:'每局游戏限一次。当你因执行〖漂萍〗的效果而弃置牌后,你可令一名其他角色获得这些牌,然后令该角色选择一项:⒈弃置区域内等量的牌。⒉令你的〖漂萍〗失效直到回合结束。', chuaili:'惴栗', - chuaili_info:'锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你获得一枚“栗”,且令〖惴栗〗于本回合内失效。', + chuaili_info:'锁定技。当你成为其他角色使用黑色牌的目标后,若你的〖漂萍〗:处于阳状态,则你将〖漂萍〗转换至阴状态;处于阴状态,则你令〖托献〗发动次数+1,然后若〖托献〗发动次数大于3,则〖惴栗〗于本回合内失效。', fengfang:'冯方', dcditing:'谛听', dcditing_info:'其他角色的出牌阶段开始时,若你在该角色的攻击范围内,则你可以观看其的X张手牌(X为你的体力值)并选择其中一张,且获得如下效果:①当其使用对应实体牌包含此牌的牌指定你为目标后,你令此牌对你无效。②当其使用对应实体牌包含此牌的牌结算结束后,若你不是此牌的目标,则你摸两张牌。③其出牌阶段结束时,若此牌位于其的手牌区,则你获得此牌。', diff --git a/character/tw.js b/character/tw.js index be64325a2..33583336d 100644 --- a/character/tw.js +++ b/character/tw.js @@ -693,32 +693,47 @@ game.import('character',function(lib,game,ui,get,ai,_status){ twxiayong:{ audio:2, audioname:['tw_yanliang'], - trigger:{global:'damageBegin1'}, - filter(event,player){ - if(event.getParent().type!='card'||event.card.name!='juedou'||!event.player.isIn()) return false; - const evt=game.getGlobalHistory('useCard',evt=>evt.card==event.card)[0]; - if(evt&&evt.targets&&(event.player!=player||player.countCards('h'))){ - if(evt.player==player){ - return evt.targets.includes(event.player)&&event.player!=player; - } - return evt.targets.includes(player)&&evt.player!=player; - } - return false; - }, - forced:true, - logTarget:'player', - async content(event,trigger,player){ - if(trigger.player===player){ - const cards=player.getCards('h',card=>{ - return lib.filter.cardDiscardable(card,player,'twxiayong'); - }); - if(cards.length>0) player.discard(cards.randomGet()); - } - else{ - trigger.increase('num'); - } + locked:true, + group:'twxiayong_effect', + subSkill:{ + effect:{ + trigger:{global:'damageBegin1'}, + filter(event,player){ + if(event.getParent().type!='card'||event.card.name!='juedou'||!event.player.isIn()) return false; + const evt=game.getGlobalHistory('useCard',evt=>evt.card==event.card)[0]; + if(evt&&evt.targets&&(event.player!=player||player.countCards('h'))){ + if(evt.player==player){ + return evt.targets.includes(event.player)&&event.player!=player; + } + return evt.targets.includes(player)&&evt.player!=player; + } + return false; + }, + forced:true, + popup:false, + async content(event,trigger,player){ + player.logSkill('twxiayong'+(trigger.player===player?'1':'2'),trigger.player); + if(trigger.player===player){ + const cards=player.getCards('h',card=>{ + return lib.filter.cardDiscardable(card,player,'twxiayong'); + }); + if(cards.length>0) player.discard(cards.randomGet()); + } + else{ + trigger.increase('num'); + } + }, + }, }, }, + twxiayong1:{ + audio:true, + audioname:['tw_yanliang'], + sourceSkill:'twxiayong', + }, + twxiayong2:{ + inherit:'twxiayong1', + }, //袁谭 twqiaosi:{ audio:2, @@ -1374,7 +1389,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ const {result:{bool,links}}=await player.chooseButton([ '劫囚:请选择你要恢复的装备栏', [transList,'tdnodes'], - ],num,true).set('map',map) + ],Math.min(transList.length,num),true).set('map',map) .set('ai',button=>['equip5','equip4','equip1','equip3','equip2'].indexOf(get.event('map')[button.link])+2); if(bool) await player.enableEquip(links.slice().map(i=>map[i])); }, @@ -10594,6 +10609,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ card:trigger.card, })) damageNum=1; var yimie=function(){ + if(damageNum==1) return false; var hit=true; if(get.type(trigger.card)=='trick'&&trigger.player.countCards('hs',{name:'wuxie'})) hit=false; if(trigger.card.name=='huogong'&&trigger.player.countCards('h',function(card){ diff --git a/character/xianding.js b/character/xianding.js index 84e387b2a..45df206b7 100644 --- a/character/xianding.js +++ b/character/xianding.js @@ -4,6 +4,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ name:'xianding', connect:true, character:{ + caofang:['male','wei',4,['dczhimin','dcjujian'],['zhu']], dc_sb_simayi:['male','wei',3,['dcsbquanmou','dcsbpingliao']], chendong:['male','wu',4,['dcduanxie','fenming']], lvfan:['male','wu',3,['diaodu','diancai']], @@ -103,7 +104,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ sp2_huben:['chendong','wangshuang','wenyang','re_liuzan','dc_huangzu','wulan','leitong','chentai','dc_duyu','dc_wangjun','dc_xiahouba','old_huangfusong','huzun'], sp2_shengun:["puyuan","guanlu","gexuan",'wufan','re_zhangbao','dukui','zhaozhi','zhujianping','dc_zhouxuān','zerong'], sp2_bizhe:['dc_luotong','dc_wangchang','chengbing','dc_yangbiao','ruanji','cuimao'], - sp2_huangjia:['caomao','liubian','dc_liuyu','quanhuijie','dingshangwan','yuanji','xielingyu','sunyu','ganfurenmifuren','dc_ganfuren','dc_mifuren','dc_shixie'], + sp2_huangjia:['caomao','liubian','dc_liuyu','quanhuijie','dingshangwan','yuanji','xielingyu','sunyu','ganfurenmifuren','dc_ganfuren','dc_mifuren','dc_shixie','caofang'], sp2_zhangtai:['guozhao','fanyufeng','ruanyu','yangwan','re_panshu'], sp2_jinse:['caojinyu','re_sunyi','re_fengfangnv','caohua','laiyinger','zhangfen','zhugeruoxue','caoxian','dc_qinghegongzhu','zhugemengxue'], sp2_yinyu:['zhouyi','luyi','sunlingluan','caoyi'], @@ -122,6 +123,143 @@ game.import('character',function(lib,game,ui,get,ai,_status){ ], }, skill:{ + //曹芳 + dczhimin:{ + audio:2, + trigger:{global:'roundStart'}, + filter(event,player){ + return game.hasPlayer(current=>current!=player&¤t.countCards('h'))&&player.getHp()>0; + }, + forced:true, + group:['dczhimin_mark','dczhimin_draw'], + async content(event,trigger,player){ + const targets = await player.chooseTarget(`置民:请选择至多${get.cnNumber(player.getHp())}名其他角色`, '你获得这些角色各自手牌中的随机一张点数最小的牌', (card, player, target) => { + return target !== player && target.countCards('h'); + }, [1, player.getHp()], true).set('ai', target => { + const player = get.player(); + return get.effect(target, {name:'shunshou_copy', position: 'h'}, player, player) + 0.1; + }).forResultTargets(); + if (!targets || !targets.length) return; + targets.sortBySeat(trigger.player); + player.line(targets, 'thunder'); + const toGain = []; + for (const target of targets) { + const cards = target.getCards('h'), minNumber = cards.map(card => get.number(card)).sort((a, b) => a - b)[0]; + const gainableCards = cards.filter(card => { + return get.number(card) === minNumber && lib.filter.canBeGained(card, player, target); + }).randomSort(); + toGain.push(gainableCards[0]); + } + if (toGain.length) await player.gain(toGain, 'giveAuto'); + await game.asyncDelayx(); + }, + ai:{ + threaten:5.8, + }, + mod:{ + aiOrder(player,card,num){ + if(num>0&&get.itemtype(card)==='card'&&card.hasGaintag('dczhimin_tag')&&player.countCards('h',cardx=>{ + return cardx.hasGaintag('dczhimin_tag')&&cardx!==card; + })get.position(card)==='h'&&get.owner(card)===player)) return false; + return true; + }, + async content(event,trigger,player){ + player.addGaintag(trigger.getg(player).filter(card=>get.position(card)==='h'&&get.owner(card)===player), 'dczhimin_tag'); + }, + }, + draw:{ + audio:'dczhimin', + trigger:{ + player:'loseAfter', + global:['equipAfter','addJudgeAfter','gainAfter','loseAsyncAfter','addToExpansionAfter'], + }, + forced:true, + filter(event,player){ + const evt=event.getl(player); + if(!evt.hs.length) return false; + return Object.values(evt.gaintag_map).flat().includes('dczhimin_tag'); + }, + async content(event,trigger,player){ + const count = player.maxHp - player.countCards('h'); + if (count <= 0) return; + await player.draw(count); + } + }, + }, + }, + dcjujian:{ + audio:2, + enable:'phaseUse', + usable:1, + zhuSkill:true, + filter(event,player){ + return game.hasPlayer(current=>{ + return player.hasZhuSkill('dcjujian',current)&¤t.group==='wei'&¤t!==player; + }); + }, + filterTarget(_,player,target){ + return player.hasZhuSkill('dcjujian',target)&&target.group==='wei'&&target!==player; + }, + async content(event,trigger,player){ + const target = event.targets[0]; + await target.draw(); + target.addTempSkill('dcjujian_forbid', 'roundStart'); + target.markAuto('dcjujian_forbid', player); + }, + ai:{ + result:{ + target(player,target){ + const num=target.countCards('hs',card=>{ + return get.type(card)=='trick'&&target.canUse(card,player)&&get.effect(player,card,target,player)<-2; + }),att=get.attitude(player,target); + if(att<0) return -0.74*num; + return 1.5; + }, + }, + }, + subSkill:{ + forbid:{ + audio:'dcjujian', + trigger:{ + player:'useCardToBefore', + }, + filter(event,player){ + if(get.type(event.card)!=='trick') return false; + return player.getStorage('dcjujian_forbid').includes(event.target); + }, + forced:true, + charlotte:true, + onremove:true, + direct:true, + async content(event,trigger,player){ + await trigger.target.logSkill('dcjujian_forbid', player); + trigger.cancel(); + }, + intro:{ + content:'使用普通锦囊牌对$无效', + }, + ai:{ + effect:{ + player(card,player,target,current){ + if(get.type(card)=='trick'&&player.getStorage('dcjujian_forbid').includes(target)) return 'zeroplayertarget'; + }, + }, + }, + }, + }, + }, //谋司马懿 dcsbquanmou:{ audio:2, @@ -1282,14 +1420,14 @@ game.import('character',function(lib,game,ui,get,ai,_status){ zhuanhuanji:true, intro:{ content:function(storage){ - if(!storage) return '每回合限一次,当你得到其他角色的牌后,或其他角色得到你的牌后,你可以令该角色使用至多X张【杀】,且其每以此法造成1点伤害,其回复1点体力。(X为你的体力值)' - return '每回合限一次,当你得到其他角色的牌后,或其他角色得到你的牌后,你可令该角色打出至多X张【杀】,然后其失去Y点体力。(X为你的体力值,Y为X-其打出【杀】数)'; + if(!storage) return '每回合限一次,当你得到其他角色的牌后,或其他角色得到你的牌后,你可以令该角色使用至多X张【杀】,且其每以此法造成1点伤害,其回复1点体力。(X为你的体力上限)'; + return '每回合限一次,当你得到其他角色的牌后,或其他角色得到你的牌后,你可令该角色打出至多X张【杀】,然后其失去Y点体力。(X为你的体力上限,Y为X-其打出【杀】数)'; }, }, audio:2, trigger:{global:['gainAfter','loseAsyncAfter']}, filter:function(event,player){ - if(!player.getHp()) return false; + if(typeof player.maxHp!='number'||player.maxHp<=0) return false; if(event.name=='loseAsync'&&event.type!='gain') return false; if(player.hasSkill('dcsbmengmou_true')&&player.hasSkill('dcsbmengmou_false')) return false; var cards1=event.getl(player).cards2,cards2=event.getg(player); @@ -1308,7 +1446,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ var player=map.player,trigger=map.trigger; var storage=player.storage.dcsbmengmou; player.addTempSkill('dcsbmengmou_effect','dcsbmengmouAfter'); - var targets=[],num=player.getHp(); + var targets=[],num=player.maxHp; var cards1=trigger.getl(player).cards2; var cards2=trigger.getg(player); targets.addArray(game.filterPlayer(function(current){ @@ -1396,7 +1534,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ charlotte:true, trigger:{global:'damageSource'}, filter:function(event,player){ - if(event.getParent().type!='card') return false; + if(!event.source||event.getParent().type!='card') return false; if(event.source.isHealthy()||event.card.name!='sha') return false; return event.getParent(4).name=='dcsbmengmou'&&event.getParent(4).player==player; }, @@ -1525,14 +1663,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ audio:2, trigger:{player:'phaseJieshuBegin'}, direct:true, - filter:function(event,player){ - return game.hasPlayer(current=>current.countCards('e')); - }, content:function*(event,map){ const player=map.player; - let result=yield player.chooseTarget(get.prompt('dcnuanhui'),'选择一名装备区有牌的角色,该角色可以依次使用X张基本牌(X为其装备区牌数)。',(card,player,target)=>{ - return target.countCards('e'); - }).set('ai',target=>{ + let result=yield player.chooseTarget(get.prompt('dcnuanhui'),'选择一名装备区有牌的角色,该角色可以依次使用X张基本牌(X为其装备区牌数且至少为1)').set('ai',target=>{ return get.event('aiTarget')==target?10:0; }).set('aiTarget',(()=>{ const player=get.player(); @@ -1544,7 +1677,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(get.attitude(player,target)<=0) return -1; const toUse=[]; const hp=target.hp; - let eff=0,count=target.countCards('e'); + let eff=0,count=Math.max(1,target.countCards('e')); while(count--){ target.hp=Math.min(target.maxHp,target.hp+toUse.filter(card=>card.name=='tao').length); const listx=list.map(info=>{ @@ -1570,11 +1703,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } return eff; } - const playerList=game.filterPlayer(current=>{ - return current.countCards('e'); - }).map(current=>[current,getUseValue(current)]).sort((a,b)=>{ - return b[1]-a[1]; - }); + const playerList=game.filterPlayer().map(current=>[current,getUseValue(current)]).sort((a,b)=>b[1]-a[1]); if(playerList[0][1]<=0) return null; return playerList[0][0]; })()); @@ -1582,8 +1711,8 @@ game.import('character',function(lib,game,ui,get,ai,_status){ const target=result.targets[0]; player.logSkill('dcnuanhui',target); if(!target.isUnderControl(true)&&!target.isOnline()) game.delayx(); - const total=target.countCards('e'); - let count=0,forced=false; + const total=Math.max(1,target.countCards('e')); + let count=0,forced=false,used=[],discard=false; while(count{ return info[0]=='basic'&&target.hasUseTarget({name:info[2],nature:info[3],isCard:true}); @@ -1593,7 +1722,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ break; } const str=forced?'视为使用一张基本牌':'是否视为使用一张基本牌?'; - result=yield target.chooseButton([str,[basicList,'vcard']],forced).set('ai',button=>{ + const result=yield target.chooseButton([str,[basicList,'vcard']],forced).set('ai',button=>{ return get.player().getUseValue({name:button.link[2],nature:button.link[3],isCard:true}); }); if(!result.bool){ @@ -1602,10 +1731,14 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } forced=true; const card=new lib.element.VCard({name:result.links[0][2],nature:result.links[0][3],isCard:true}); - yield target.chooseUseTarget(card,true,false); + const result2=yield target.chooseUseTarget(card,true,false); + if(!discard&&result2.bool){ + if(used.includes(result.links[0][2])) discard=true; + else used.add(result.links[0][2]); + } count++; } - if(count>1){ + if(discard){ const cards=target.getCards('e',card=>{ return lib.filter.cardDiscardable(card,target,'dcnuanhui'); }); @@ -2495,7 +2628,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(same.length){ for(var suit of suits){ if(same.some(card=>get.suit(card,false)==suit)){ - list.push([get.type(name),get.translation(suit),name,undefined,suit]); + list.push([suit,'',name,undefined,suit]); } } } @@ -2504,7 +2637,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(same.length){ for(var suit of suits){ if(same.some(card=>get.suit(card,false)==suit)){ - list.push([get.type(name),get.translation(suit),name,nature,suit]); + list.push([suit,'',name,nature,suit]); } } } @@ -3129,7 +3262,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }); if(target.hasMark('dcchangqu_warshipx')){ var prompt2='是否交给'+get.translation(player)+get.cnNumber(num)+'张手牌?'+(nextPlayer?'若如此做,将“战舰”移动给'+get.translation(nextPlayer)+',':',')+'否则你下次受到的属性伤害值+'+num; - target.chooseCard(get.translation(player)+'对你发动了【长驱】',prompt2).set('ai',card=>{ + target.chooseCard(get.translation(player)+'对你发动了【长驱】',prompt2,num).set('ai',card=>{ if(_status.event.att>0) return 15-get.value(card); if(_status.event.take) return 0; return 8.2-0.8*Math.min(5,_status.event.target.hp+_status.event.target.hujia)-get.value(card); @@ -3770,7 +3903,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ rec:{ audio:'guixiu', trigger:{ - player:'logSkill', + player:'useSkillAfter', }, forced:true, filter:function(event,player){ @@ -7968,8 +8101,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ audio:2, getZhuanhuanji:function(player,bool){ var skills=player.getSkills(null,false,false).filter(function(i){ - const list=get.skillCategoriesOf(i); - return !list.includes('Charlotte')&&list.includes('转换技'); + return get.is.zhuanhuanji(i,player); }); if(!bool) return skills; if(!skills.length) return 'none'; @@ -7981,7 +8113,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, getState:function(player,skill){ var info=get.info(skill),zhuanhuan=info.zhuanhuanji; - if(zhuanhuan=='number') return (player.countMark(skill)%2==1); + if(zhuanhuan&&zhuanhuan=='number') return (player.countMark(skill)%2==1); return Boolean(player.storage[skill]); }, trigger:{ @@ -9535,7 +9667,24 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(changed2.includes(from.link)) return true; return changed.includes(to.link); }); + next.set('max',Math.min(hs.length,ts.length,player.getDamagedHp())); next.set('processAI',function(list){ + if(_status.event.max){ + let gain=list[0][1].sort((a,b)=>{ + return player.getUseValue(b,null,true)-player.getUseValue(a,null,true); + }).slice(0,_status.event.max),give=list[1][1].sort((a,b)=>{ + return get.value(a,player)-get.value(b,player); + }).slice(0,_status.event.max); + for(let i of gain){ + if(get.value(i,player){ return get.value(b,player)-get.value(a,player); }); - gain=pai.splice(0,player.getDamagedHp()); - bottom=pai; + gain = pai.splice(0,player.getDamagedHp()); + bottom = cards.slice(0); + bottom.removeArray(gain); return [bottom, gain]; } return [cards,cards.splice(0,player.getDamagedHp())]; @@ -14172,6 +14322,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ subtype:'equip1', distance:{attackFrom:-2}, skills:['pyzhuren_heart'], + onDestroy(card){ + if(_status.pyzhuren&&_status.pyzhuren[card.name]){ + delete _status.pyzhuren[card.name]; + } + }, ai:{ basic:{ equipValue:4 @@ -14185,6 +14340,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ subtype:'equip1', distance:{attackFrom:-1}, skills:['pyzhuren_diamond'], + onDestroy(card){ + if(_status.pyzhuren&&_status.pyzhuren[card.name]){ + delete _status.pyzhuren[card.name]; + } + }, ai:{ basic:{ equipValue:3 @@ -14198,6 +14358,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ subtype:'equip1', distance:{attackFrom:-1}, skills:['pyzhuren_club'], + onDestroy(card){ + if(_status.pyzhuren&&_status.pyzhuren[card.name]){ + delete _status.pyzhuren[card.name]; + } + }, ai:{ basic:{ equipValue:5 @@ -14223,6 +14388,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ type:'equip', subtype:'equip1', skills:['pyzhuren_spade'], + onDestroy(card){ + if(_status.pyzhuren&&_status.pyzhuren[card.name]){ + delete _status.pyzhuren[card.name]; + } + }, ai:{ basic:{ equipValue:3 @@ -14236,6 +14406,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){ subtype:'equip1', distance:{attackFrom:-3}, skills:['pyzhuren_shandian'], + onDestroy(card){ + if(_status.pyzhuren&&_status.pyzhuren[card.name]){ + delete _status.pyzhuren[card.name]; + } + }, ai:{ basic:{ equipValue:3 @@ -14284,7 +14459,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, }, characterIntro:{ - cuimao:'请分别查看“崔琰”和“毛玠”的武将介绍。', + cuimao:'请分别查看「崔琰」和「毛玠」的武将介绍。', bailingyun:'柏灵筠,女,是电视剧《大军师司马懿之军师联盟》、《虎啸龙吟》中的主要角色之一,由张钧甯饰演。20岁,是曹丕赏赐司马懿的美人,也是曹丕的眼线,被送入司马府中为妾室。柔弱美貌、心机极深。', caoxian:'曹宪(生卒年不详),女,沛国谯县(今安徽省亳州市)人。东汉末年历史人物,汉献帝刘协嫔妃,魏武帝曹操女儿。建安十八年,嫁给汉献帝刘协,受封为贵人。黄初元年(220年),兄弟曹丕称帝后,汉献帝成为山阳公,不知所终。', zhangjian:'张臶(136年-240年),字子明,钜鹿人。汉末三国时期隐士、音乐家,精通谶纬之学。张臶生活的年代从东汉一直到曹魏齐王时期,受到朝廷多次征召,一直回避,不愿做官。他活了一百零五岁,是三国时期有可靠记载的最长寿的人之一。', @@ -14421,7 +14596,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ if(storage) str+=''; str+='阳,你可令该角色打出至多X张【杀】,然后其失去Y点体力。'; if(storage) str+=''; - str+='(X为你的体力值,Y为X-其打出【杀】数)'; + str+='(X为你的体力上限,Y为X-其打出【杀】数)'; return str; }, dcsbyingmou:function(player){ @@ -14452,6 +14627,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ guozhao:['guozhao','xin_guozhao','jsrg_guozhao'], dingshangwan:['dingshangwan','ol_dingshangwan'], qinghegongzhu:['qinghegongzhu','dc_qinghegongzhu'], + caofang:['caofang','jsrg_caofang'], }, translate:{ puyuan:'蒲元', @@ -14945,7 +15121,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ dcqiongying:'琼英', dcqiongying_info:'出牌阶段限一次。你可以移动场上的一张牌,然后你弃置一张与此牌花色相同的手牌(若没有该花色的手牌则改为展示所有手牌)。', dcnuanhui:'暖惠', - dcnuanhui_info:'结束阶段,你可以选择一名装备区有牌的角色,其可以视为依次使用X张基本牌(X为其装备区牌数)。若其以此法使用了至少两张牌,其弃置装备区里的所有牌。', + dcnuanhui_info:'结束阶段,你可以选择一名装备区有牌的角色,其可以视为依次使用X张基本牌(X为其装备区牌数且至少为1)。若其此次以此法使用了同名牌,其弃置装备区里的所有牌。', zhangjian:'张臶', dc_zj_a:'技能', dc_zj_a_info:'锁定技。当你受到牌造成的伤害时,若此牌有点数,则你将此伤害值改为此牌点数,否则你防止此伤害。', @@ -14956,7 +15132,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ dcsbmingshi:'明势', dcsbmingshi_info:'摸牌阶段,你可以多摸两张牌,然后展示三张牌并令一名其他角色选择获得其中的一张牌。', dcsbmengmou:'盟谋', - dcsbmengmou_info:'转换技,每回合每项各限一次,当你得到其他角色的牌后,或其他角色得到你的牌后:阴,你可以令该角色使用至多X张【杀】,且其每以此法造成1点伤害,其回复1点体力;阳,你可令该角色打出至多X张【杀】,然后其失去Y点体力。(X为你的体力值,Y为X-其打出【杀】数)', + dcsbmengmou_info:'转换技,每回合每项各限一次,当你得到其他角色的牌后,或其他角色得到你的牌后:阴,你可以令该角色使用至多X张【杀】,且其每以此法造成1点伤害,其回复1点体力;阳,你可令该角色打出至多X张【杀】,然后其失去Y点体力。(X为你的体力上限,Y为X-其打出【杀】数)', dc_sb_zhouyu:'新杀谋周瑜', dc_sb_zhouyu_prefix:'新杀谋', dcsbronghuo:'融火', @@ -15010,6 +15186,12 @@ game.import('character',function(lib,game,ui,get,ai,_status){ dcsbquanmou_info:'转换技。出牌阶段每名角色限一次,你可以令一名攻击范围内的其他角色交给你一张牌。阴:当你于本阶段内下次对其造成伤害时,取消之;阳:当你于本阶段内下次对其造成伤害后,你可以选择除其外的至多三名其他角色,对这些角色依次造成1点伤害。', dcsbpingliao:'平辽', dcsbpingliao_info:'锁定技。当你声明使用【杀】时,你令此【杀】的目标对其他角色不可见,且你令攻击范围内的其他角色依次选择是否打出一张红色基本牌。所有角色选择完成后,此牌的目标角色中没有以此法打出牌的角色本回合内无法使用或打出手牌;若有不为此牌目标的角色以此法打出了牌,则你摸两张牌,且你本回合使用【杀】的次数上限+1。', + caofang:'曹芳', + dczhimin:'置民', + dczhimin_tag:'民', + dczhimin_info:'锁定技。①一轮游戏开始时,你选择至多X名其他角色(X为你的体力值),获得这些角色各自手牌中的随机一张点数最小的牌。②当你于你的回合外得到牌后,你将这些牌标记为“民”。③当你失去“民”后,你将手牌补至体力上限。', + dcjujian:'拒谏', + dcjujian_info:'主公技。出牌阶段限一次,你可以令一名其他魏势力角色摸一张牌,然后你令其于本轮内使用的普通锦囊牌对你无效。', sp2_yinyu:'隐山之玉', sp2_huben:'百战虎贲', diff --git a/character/xinghuoliaoyuan.js b/character/xinghuoliaoyuan.js index 35100865c..2ba3a9168 100755 --- a/character/xinghuoliaoyuan.js +++ b/character/xinghuoliaoyuan.js @@ -1365,7 +1365,10 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player:["useCardAfter","respond"], }, filter:function (event,player){ - if(get.itemtype(event.cards)!='cards') return false; + if(get.itemtype(event.cards)!=='cards'||!game.hasPlayer(current=>{ + if(current===player) return false; + return current.getHp()>player.getHp()||current.countCards('h')>player.countCards('h'); + })) return false; for(var i=0;iplayer.countCards('h')||Math.max(0,target.hp)>Math.max(0,player.hp); - }).set('ai',function(target){ + async cost(event, trigger, player){ + event.result = await player.chooseTarget(get.prompt2('xinfu_xunxian'),(card,player,target)=>{ + if(target===player) return false; + return target.getHp()>player.getHp()||target.countCards('h')>player.countCards('h'); + }).set('ai',(target)=>{ let att=get.attitude(_status.event.player,target),name=_status.event.cards[0].name; if(att<3) return 0; if(target.hasJudge('lebu')) att/=5; if(name==='sha'&&target.hasSha()) att/=5; if(name==='wuxie'&&target.needsToDiscard(_status.event.cards)) att/=5; return att/(1+get.distance(player,target,'absolute')); - }).set('cards',trigger.cards); - 'step 1' - if(result.bool){ - var list=[]; - for(var i=0;iget.type2(card)==type); var guessedNum=event.guessedNum; if(count==guessedNum){ - player.popup('猜测正确','wood'); + player.popup('洗具'); game.log(player,'猜测','#g正确'); if(player.countMark('zhenfeng')<5) player.addMark('zhenfeng',1,false); player.draw(player.countMark('zhenfeng')); if(player.canUse('sha',trigger.player,false)) player.useCard({name:'sha',isCard:true},trigger.player); } else{ - player.popup('猜测错误','fire'); + player.popup('杯具'); game.log(player,'猜测','#y错误'); player.clearMark('zhenfeng'); if(Math.abs(count-guessedNum)>1&&trigger.player.canUse('sha',player,false)){ @@ -843,6 +843,9 @@ game.import('character',function(lib,game,ui,get,ai,_status){ } }, mod:{ + ignoredHandcard:function(card,player){ + if(card.hasGaintag('cibei_mark')) return true; + }, cardDiscardable:function(card,player,name){ if(card.hasGaintag('cibei_mark')) return false; }, @@ -2292,7 +2295,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return get.distance(player,current)>1; })) return false; if(tag=='directHit_ai') return arg.card.name=='sha'; - if(arg.card.name!='sha'&&arg.card.name!='chuqibuyi') return false; + if(!arg||!arg.card||arg.card.name!='sha'&&arg.card.name!='chuqibuyi') return false; var card=arg.target.getEquip(2); if(card&&card.name.indexOf('bagua')!=-1) return true; if(player._xinbenxi_ai) return false; @@ -11828,36 +11831,90 @@ game.import('character',function(lib,game,ui,get,ai,_status){ return player.hp player !== i); + cards.forEach(i => { + let o = get.value(i, player), max = o, temp, t; + tars.forEach(tar => { + temp = get.value(i, tar); + if (temp > max) { + max = temp; + t = tar; + } + }); + if (t) res.cards.push([i, t, max - o]); + }); + if (res.cards.length < event.num) res.bool = false; + else if (res.cards.length > event.num) res.cards.sort((a, b) => { + return b[2] - a[2]; + }).slice(0, event.num); + return res; + }(); + 'step 1' player.chooseCardTarget({ - selectCard:event.num, - filterTarget:function(card,player,target){ - return player!=target; + filterCard(card){ + return get.itemtype(card)=='card'&&!card.hasGaintag('miji_tag'); }, - ai1:function(card){ - var player=_status.event.player; - if(player.maxHp-player.hp==1&&card.name=='du') return 30; - var check=_status.event.check; - if(check<1) return 0; - if(player.hp>1&&check<2) return 0; - return get.unuseful(card)+9; + filterTarget: lib.filter.notMe, + selectCard: [1,event.num], + prompt:'请选择要分配的卡牌和目标', + forced: event._forcing, + ai1(card){ + if (!_status.event.res.bool || ui.selected.cards.length) return 0; + for (let arr of _status.event.res.cards) { + if (arr[0] === card) return arr[2]; + } + return 0; }, - ai2:function(target){ - var att=get.attitude(_status.event.player,target); - if(ui.selected.cards.length==1&&ui.selected.cards[0].name=='du') return 1-att; - return att-2; + ai2(target){ + let card = ui.selected.cards[0]; + for (let arr of _status.event.res.cards) { + if (arr[0] === card) return get.attitude(player, target); + } + let val=target.getUseValue(card); + if(val>0) return val*get.attitude(player,target)*2; + return get.value(card,target)*get.attitude(player,target); }, - prompt:'将'+get.cnNumber(event.num)+'张手牌交给一名其他角色', - }).set('check',check); - "step 2" + res: event.aicheck + }); + 'step 2' if(result.bool){ - player.give(result.cards,result.targets[0]); - player.line(result.targets,'green'); + event._forcing = true; + var res=result.cards,target=result.targets[0].playerid; + player.addGaintag(res,'miji_tag'); + event.num-=res.length; + if(!event.given_map[target]) event.given_map[target]=[]; + event.given_map[target].addArray(res); + if(event.num>0) event.goto(1); } + 'step 3' + if(_status.connectMode){ + game.broadcastAll(function(){delete _status.noclearcountdown;game.stopCountChoose()}); + } + var map=[],cards=[]; + for(var i in event.given_map){ + var source=(_status.connectMode?lib.playerOL:game.playerMap)[i]; + player.line(source,'green'); + if(player!==source&&(get.mode()!=='identity'||player.identity!=='nei')) player.addExpose(0.18); + map.push([source,event.given_map[i]]); + cards.addArray(event.given_map[i]); + } + game.loseAsync({ + gain_list:map, + player:player, + cards:cards, + giver:player, + animate:'giveAuto', + }).setContent('gaincardMultiple'); }, ai:{ threaten:function(player,target){ @@ -13931,7 +13988,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ lingtong:['lingtong','xin_lingtong','ol_lingtong','re_lingtong','old_lingtong'], gaoshun:['gaoshun','xin_gaoshun','ol_gaoshun','re_gaoshun','sb_gaoshun','old_gaoshun'], zhonghui:['zhonghui','xin_zhonghui','re_zhonghui','old_zhonghui','pe_zhonghui'], - wangyi:['wangyi','re_wangyi','old_wangyi'], + wangyi:['wangyi','ol_wangyi','re_wangyi','old_wangyi'], caozhang:['caozhang','ol_caozhang','re_caozhang','xin_caozhang'], guanzhang:['guanzhang','re_guanzhang','old_guanzhang'], madai:['old_madai','re_madai','tw_madai','madai'], @@ -14440,6 +14497,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ oldrenxin:'仁心', zhenlie:'贞烈', miji:'秘计', + miji_tag:'已分配', zhiyan:'直言', zongxuan:'纵玄', anxu:'安恤', @@ -14500,7 +14558,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ old_anxu_info:'出牌阶段限一次,你可以选择两名手牌数不同的其他角色,令其中手牌少的角色获得手牌多的角色的一张手牌并展示之。然后若此牌不为黑桃,则你摸一张牌。', zongxuan_info:'当你的牌因弃置而进入弃牌堆后,你可以将其按任意顺序置于牌堆顶。', zhiyan_info:'结束阶段,你可以令一名角色摸一张牌并展示之,若为装备牌,其使用此牌并回复1点体力。', - miji_info:'结束阶段,若你已受伤,则可以摸X张牌,然后可以将等量的牌交给一名其他角色(X为你已损失的体力值)。', + miji_info:'结束阶段,若你已受伤,则可以摸X张牌,然后可以将等量的牌交给其他角色(X为你已损失的体力值)。', zhenlie_info:'当你成为其他角色使用【杀】或普通锦囊牌的目标后,你可以失去1点体力并令此牌对你无效,然后弃置对方一张牌。', chengxiang_info:'当你受到伤害后,你可以亮出牌堆顶的四张牌。然后获得其中任意数量点数之和不大于13的牌。', oldchengxiang_info:'当你受到伤害后,你可以亮出牌堆顶的四张牌。然后获得其中任意数量点数之和不大于12的牌。', @@ -14605,7 +14663,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ duwang:'独往', duwang_info:'锁定技。①游戏开始时,你从牌堆顶将五张不为【杀】的牌置于武将牌上,称为“刺”。②若你有牌名不为【杀】“刺”,你至其他角色或其他角色至你的距离+1。', cibei:'刺北', - cibei_info:'①当一名角色使用【杀】造成伤害且此牌对应的实体牌进入弃牌堆后,你可以将一张不为【杀】的“刺”置入弃牌堆,并将这些牌置入“刺”,然后弃置一名角色区域里的一张牌。②一名角色的回合结束时,若你的“刺”均为【杀】,你获得所有“刺”,且这些牌不能被弃置,且当你使用对应实体牌包含这些牌的牌时无次数和距离限制。', + cibei_info:'①当一名角色使用【杀】造成伤害且此牌对应的实体牌进入弃牌堆后,你可以将一张不为【杀】的“刺”置入弃牌堆,并将这些牌置入“刺”,然后弃置一名角色区域里的一张牌。②一名角色的回合结束时,若你的“刺”均为【杀】,你获得所有“刺”,且这些牌不能被弃置,不计入手牌上限,且当你使用对应实体牌包含这些牌的牌时无次数和距离限制。', wuanguo:'武安国', diezhang:'叠嶂', diezhang_info:'转换技。①出牌阶段,你使用杀的次数上限+1。②阴:当你使用牌被其他角色抵消后,你可以弃置一张牌,视为对其使用X张【杀】;阳:当其他角色使用牌被你抵消后,你可以摸X张牌,视为对其使用一张【杀】(X为1)。', diff --git a/character/yingbian.js b/character/yingbian.js index 5a88b5a82..382e2aaf8 100644 --- a/character/yingbian.js +++ b/character/yingbian.js @@ -2328,40 +2328,37 @@ game.import('character',function(lib,game,ui,get,ai,_status){ }, xianzhu:{ trigger:{player:'phaseUseBegin'}, - direct:true, locked:true, filter:function(event,player){ return player.getExpansions('qiaoyan').length>0; }, - content:function(){ - 'step 0' - event.cards=player.getExpansions('qiaoyan'); - player.chooseTarget(true,'请选择【献珠】的目标','将'+get.translation(event.cards)+'交给一名角色。若该角色不为你自己,则你令其视为对其攻击范围内的另一名角色使用【杀】').set('ai',function(target){ + async cost(event, trigger, player){ + event.cards = player.getExpansions('qiaoyan'); + event.result = await player.chooseTarget(true,'请选择【献珠】的目标','将'+get.translation(event.cards)+'交给一名角色。若该角色不为你自己,则你令其视为对其攻击范围内的另一名角色使用【杀】').set('ai',function(target){ var player=_status.event.player; var eff=get.sgn(get.attitude(player,target))*get.value(_status.event.getParent().cards[0],target); if(player!=target) eff+=Math.max.apply(null,game.filterPlayer(function(current){ - if(current!=target&&target.inRange(current)&&target.canUse('sha',current)) return true; + if(current!=target&&player.inRange(current)&&target.canUse('sha',current,false)) return true; }).map(function(current){ return get.effect(current,{name:'sha'},target,player); })); return eff; - }); + }).forResult(); + }, + content:function(){ + 'step 0' + event.cards = player.getExpansions('qiaoyan'); + event.target = targets[0]; 'step 1' - if(result.bool){ - var target=result.targets[0]; - event.target=target; - player.logSkill('xianzhu',target); - player.give(cards,target,'give'); - } - else event.finish(); + player.give(cards,target,'give'); 'step 2' if(player!=target&&target.isIn()&&player.isIn()&&game.hasPlayer(function(current){ - return current!=target&&target.inRange(current)&&target.canUse('sha',current); + return current!=target&&player.inRange(current)&&target.canUse('sha',current,false); })){ var str=get.translation(target); - player.chooseTarget(true,'选择'+str+'攻击范围内的一名角色,视为'+str+'对其使用【杀】',function(card,player,target){ + player.chooseTarget(true,'选择攻击范围内的一名角色,视为'+str+'对其使用【杀】',function(card,player,target){ var source=_status.event.target; - return source.inRange(target)&&source.canUse('sha',target); + return player.inRange(target)&&source.canUse('sha', target, false); }).set('target',target).set('ai',function(target){ var evt=_status.event; return get.effect(target,{name:'sha'},evt.target,evt.player) @@ -2692,24 +2689,35 @@ game.import('character',function(lib,game,ui,get,ai,_status){ game.updateRoundNumber(); } }, - group:'xinquanbian_count', + //group:'xinquanbian_count', + init:(player,skill)=>player.addSkill('xinquanbian_count'), + onremove:(player,skill)=>player.removeSkill('xinquanbian_count'), }, xinquanbian_count:{ - trigger:{player:'useCard1'}, + trigger:{ + player:['useCard0','phaseUseBefore','phaseUseAfter'] + }, silent:true, firstDo:true, + charlotte:true, filter:function(event,player){ + if (event.name === 'phaseUse') return true; return player.isPhaseUsing()&&lib.skill.quanbian.hasHand(event)&&get.type(event.card)!='equip'; }, content:function(){ var stat=player.getStat('skill'); - if(!stat.quanbian) stat.quanbian=0; - stat.quanbian++; + if (this.trigger.name === 'phaseUse') { + delete stat.xinquanbian; + } + else{ + if(!stat.xinquanbian) stat.xinquanbian=0; + stat.xinquanbian++; + } }, mod:{ cardEnabled2:function(card,player){ var stat=player.getStat('skill'); - if(stat.quanbian&&stat.quanbian>=player.maxHp&&get.position(card)=='h'&&get.type(card,player)!='equip') return false; + if(stat.xinquanbian&&stat.xinquanbian>=player.maxHp&&get.position(card)=='h'&&get.type(card,player)!='equip') return false; }, }, }, @@ -3339,14 +3347,14 @@ game.import('character',function(lib,game,ui,get,ai,_status){ player.addTempSkill('yanxi2'); var card2=result.links[0]; if(card2==card){ - player.popup('猜对了'); + player.popup('洗具'); cards.remove(card2); player.$gain2(cards); player.gain(cards,'log').gaintag.add('yanxi'); player.gain(card,target,'bySelf','give').gaintag.add('yanxi'); } else{ - player.popup('猜错了'); + player.popup('杯具'); player.gain(card2,'gain2').gaintag.add('yanxi'); } }, @@ -3981,7 +3989,7 @@ game.import('character',function(lib,game,ui,get,ai,_status){ qiaoyan:'巧言', qiaoyan_info:'锁定技,当你于回合外受到其他角色造成的伤害时,若你:有“珠”,则你令伤害来源获得“珠”;没有“珠”,则你防止此伤害,然后摸一张牌,并将一张牌正面朝上置于武将牌上,称为“珠”。', xianzhu:'献珠', - xianzhu_info:'锁定技,出牌阶段开始时,你令一名角色A获得“珠”。若A不为你自己,则你选择A攻击范围内的一名角色B,视为A对B使用一张【杀】。', + xianzhu_info:'锁定技,出牌阶段开始时,你令一名角色A获得“珠”。若A不为你自己,则你选择你攻击范围内的一名角色B,视为A对B使用一张【杀】。', chengjichengcui:'成济成倅', oltousui:'透髓', oltousui_info:'你可以将任意张牌置于牌堆底,视为使用一张需使用等量张【闪】抵消的【杀】。', diff --git a/game/canUse.ts b/game/canUse.ts new file mode 100644 index 000000000..4f3678080 --- /dev/null +++ b/game/canUse.ts @@ -0,0 +1,4 @@ +// apk每次安装后第一次启动加载Service Worker会失败 +// 所以每次导入这个ts判断是否会成功,失败的话重启一次 + +export const text: string = 'ts文件导入成功'; \ No newline at end of file diff --git a/game/codemirror.js b/game/codemirror.js index 71bd4b791..c25437c24 100644 --- a/game/codemirror.js +++ b/game/codemirror.js @@ -61,6 +61,10 @@ var sawReadOnlySpans = false, sawCollapsedSpans = false; // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . +/** + * @type { typeof import('codemirror/index') } + */ +// @ts-ignore var CodeMirror = (function () { // A CodeMirror instance represents an editor. This is the object diff --git a/game/compiler-sfc.browser.js b/game/compiler-sfc.browser.js deleted file mode 100644 index b90f0ddc2..000000000 --- a/game/compiler-sfc.browser.js +++ /dev/null @@ -1,48244 +0,0 @@ -"use strict"; -var sfc = (() => { - /** - * @vue/compiler-sfc v3.4.21 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **/ - function makeMap(str, expectsLowerCase) { - const set = new Set(str.split(",")); - return expectsLowerCase ? (val) => set.has(val.toLowerCase()) : (val) => set.has(val); - } - - const EMPTY_OBJ = Object.freeze({}); - const NOOP = () => { - }; - const NO = () => false; - const isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter - (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); - const extend = Object.assign; - const hasOwnProperty$3 = Object.prototype.hasOwnProperty; - const hasOwn = (val, key) => hasOwnProperty$3.call(val, key); - const isArray$3 = Array.isArray; - const isMap = (val) => toTypeString(val) === "[object Map]"; - const isSet = (val) => toTypeString(val) === "[object Set]"; - const isFunction$1 = (val) => typeof val === "function"; - const isString$2 = (val) => typeof val === "string"; - const isSymbol$1 = (val) => typeof val === "symbol"; - const isObject$2 = (val) => val !== null && typeof val === "object"; - const objectToString$1 = Object.prototype.toString; - const toTypeString = (value) => objectToString$1.call(value); - const isPlainObject = (val) => toTypeString(val) === "[object Object]"; - const isReservedProp = /* @__PURE__ */ makeMap( - // the leading comma is intentional so empty string "" is also included - ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" - ); - const isBuiltInDirective = /* @__PURE__ */ makeMap( - "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" - ); - const cacheStringFunction = (fn) => { - const cache = /* @__PURE__ */ Object.create(null); - return (str) => { - const hit = cache[str]; - return hit || (cache[str] = fn(str)); - }; - }; - const camelizeRE = /-(\w)/g; - const camelize = cacheStringFunction((str) => { - return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); - }); - const hyphenateRE = /\B([A-Z])/g; - const hyphenate = cacheStringFunction( - (str) => str.replace(hyphenateRE, "-$1").toLowerCase() - ); - const capitalize$1 = cacheStringFunction((str) => { - return str.charAt(0).toUpperCase() + str.slice(1); - }); - const toHandlerKey = cacheStringFunction((str) => { - const s = str ? `on${capitalize$1(str)}` : ``; - return s; - }); - const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/; - function genPropsAccessExp(name) { - return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`; - } - - const PatchFlagNames = { - [1]: `TEXT`, - [2]: `CLASS`, - [4]: `STYLE`, - [8]: `PROPS`, - [16]: `FULL_PROPS`, - [32]: `NEED_HYDRATION`, - [64]: `STABLE_FRAGMENT`, - [128]: `KEYED_FRAGMENT`, - [256]: `UNKEYED_FRAGMENT`, - [512]: `NEED_PATCH`, - [1024]: `DYNAMIC_SLOTS`, - [2048]: `DEV_ROOT_FRAGMENT`, - [-1]: `HOISTED`, - [-2]: `BAIL` - }; - - const slotFlagsText = { - [1]: "STABLE", - [2]: "DYNAMIC", - [3]: "FORWARDED" - }; - - const GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error"; - const isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED); - - const range = 2; - function generateCodeFrame(source, start = 0, end = source.length) { - let lines = source.split(/(\r?\n)/); - const newlineSequences = lines.filter((_, idx) => idx % 2 === 1); - lines = lines.filter((_, idx) => idx % 2 === 0); - let count = 0; - const res = []; - for (let i = 0; i < lines.length; i++) { - count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0); - if (count >= start) { - for (let j = i - range; j <= i + range || end > count; j++) { - if (j < 0 || j >= lines.length) - continue; - const line = j + 1; - res.push( - `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}` - ); - const lineLength = lines[j].length; - const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0; - if (j === i) { - const pad = start - (count - (lineLength + newLineSeqLength)); - const length = Math.max( - 1, - end > count ? lineLength - pad : end - start - ); - res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); - } else if (j > i) { - if (end > count) { - const length = Math.max(Math.min(end - count, lineLength), 1); - res.push(` | ` + "^".repeat(length)); - } - count += lineLength + newLineSeqLength; - } - } - break; - } - } - return res.join("\n"); - } - - function normalizeStyle(value) { - if (isArray$3(value)) { - const res = {}; - for (let i = 0; i < value.length; i++) { - const item = value[i]; - const normalized = isString$2(item) ? parseStringStyle(item) : normalizeStyle(item); - if (normalized) { - for (const key in normalized) { - res[key] = normalized[key]; - } - } - } - return res; - } else if (isString$2(value) || isObject$2(value)) { - return value; - } - } - const listDelimiterRE = /;(?![^(]*\))/g; - const propertyDelimiterRE = /:([^]+)/; - const styleCommentRE = /\/\*[^]*?\*\//g; - function parseStringStyle(cssText) { - const ret = {}; - cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => { - if (item) { - const tmp = item.split(propertyDelimiterRE); - tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); - } - }); - return ret; - } - function stringifyStyle(styles) { - let ret = ""; - if (!styles || isString$2(styles)) { - return ret; - } - for (const key in styles) { - const value = styles[key]; - const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); - if (isString$2(value) || typeof value === "number") { - ret += `${normalizedKey}:${value};`; - } - } - return ret; - } - function normalizeClass(value) { - let res = ""; - if (isString$2(value)) { - res = value; - } else if (isArray$3(value)) { - for (let i = 0; i < value.length; i++) { - const normalized = normalizeClass(value[i]); - if (normalized) { - res += normalized + " "; - } - } - } else if (isObject$2(value)) { - for (const name in value) { - if (value[name]) { - res += name + " "; - } - } - } - return res.trim(); - } - - const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; - const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; - const MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"; - const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; - const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); - const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); - const isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS); - const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); - - const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; - const isBooleanAttr = /* @__PURE__ */ makeMap( - specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` - ); - const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; - const attrValidationCache = {}; - function isSSRSafeAttrName(name) { - if (attrValidationCache.hasOwnProperty(name)) { - return attrValidationCache[name]; - } - const isUnsafe = unsafeAttrCharRE.test(name); - if (isUnsafe) { - console.error(`unsafe attribute name: ${name}`); - } - return attrValidationCache[name] = !isUnsafe; - } - const propsToAttrMap = { - acceptCharset: "accept-charset", - className: "class", - htmlFor: "for", - httpEquiv: "http-equiv" - }; - const isKnownHtmlAttr = /* @__PURE__ */ makeMap( - `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap` - ); - const isKnownSvgAttr = /* @__PURE__ */ makeMap( - `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan` - ); - - const escapeRE = /["'&<>]/; - function escapeHtml(string) { - const str = "" + string; - const match = escapeRE.exec(str); - if (!match) { - return str; - } - let html = ""; - let escaped; - let index; - let lastIndex = 0; - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: - escaped = """; - break; - case 38: - escaped = "&"; - break; - case 39: - escaped = "'"; - break; - case 60: - escaped = "<"; - break; - case 62: - escaped = ">"; - break; - default: - continue; - } - if (lastIndex !== index) { - html += str.slice(lastIndex, index); - } - lastIndex = index + 1; - html += escaped; - } - return lastIndex !== index ? html + str.slice(lastIndex, index) : html; - } - - const toDisplayString = (val) => { - return isString$2(val) ? val : val == null ? "" : isArray$3(val) || isObject$2(val) && (val.toString === objectToString$1 || !isFunction$1(val.toString)) ? JSON.stringify(val, replacer, 2) : String(val); - }; - const replacer = (_key, val) => { - if (val && val.__v_isRef) { - return replacer(_key, val.value); - } else if (isMap(val)) { - return { - [`Map(${val.size})`]: [...val.entries()].reduce( - (entries, [key, val2], i) => { - entries[stringifySymbol(key, i) + " =>"] = val2; - return entries; - }, - {} - ) - }; - } else if (isSet(val)) { - return { - [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)) - }; - } else if (isSymbol$1(val)) { - return stringifySymbol(val); - } else if (isObject$2(val) && !isArray$3(val) && !isPlainObject(val)) { - return String(val); - } - return val; - }; - const stringifySymbol = (v, i = "") => { - var _a; - return isSymbol$1(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v; - }; - - const FRAGMENT = Symbol(`Fragment`); - const TELEPORT = Symbol(`Teleport`); - const SUSPENSE = Symbol(`Suspense`); - const KEEP_ALIVE = Symbol(`KeepAlive`); - const BASE_TRANSITION = Symbol(`BaseTransition`); - const OPEN_BLOCK = Symbol(`openBlock`); - const CREATE_BLOCK = Symbol(`createBlock`); - const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock`); - const CREATE_VNODE = Symbol(`createVNode`); - const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode`); - const CREATE_COMMENT = Symbol(`createCommentVNode`); - const CREATE_TEXT = Symbol(`createTextVNode`); - const CREATE_STATIC = Symbol(`createStaticVNode`); - const RESOLVE_COMPONENT = Symbol(`resolveComponent`); - const RESOLVE_DYNAMIC_COMPONENT = Symbol( - `resolveDynamicComponent` - ); - const RESOLVE_DIRECTIVE = Symbol(`resolveDirective`); - const RESOLVE_FILTER = Symbol(`resolveFilter`); - const WITH_DIRECTIVES = Symbol(`withDirectives`); - const RENDER_LIST = Symbol(`renderList`); - const RENDER_SLOT = Symbol(`renderSlot`); - const CREATE_SLOTS = Symbol(`createSlots`); - const TO_DISPLAY_STRING = Symbol(`toDisplayString`); - const MERGE_PROPS = Symbol(`mergeProps`); - const NORMALIZE_CLASS = Symbol(`normalizeClass`); - const NORMALIZE_STYLE = Symbol(`normalizeStyle`); - const NORMALIZE_PROPS = Symbol(`normalizeProps`); - const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps`); - const TO_HANDLERS = Symbol(`toHandlers`); - const CAMELIZE = Symbol(`camelize`); - const CAPITALIZE = Symbol(`capitalize`); - const TO_HANDLER_KEY = Symbol(`toHandlerKey`); - const SET_BLOCK_TRACKING = Symbol(`setBlockTracking`); - const PUSH_SCOPE_ID = Symbol(`pushScopeId`); - const POP_SCOPE_ID = Symbol(`popScopeId`); - const WITH_CTX = Symbol(`withCtx`); - const UNREF = Symbol(`unref`); - const IS_REF = Symbol(`isRef`); - const WITH_MEMO = Symbol(`withMemo`); - const IS_MEMO_SAME = Symbol(`isMemoSame`); - const helperNameMap = { - [FRAGMENT]: `Fragment`, - [TELEPORT]: `Teleport`, - [SUSPENSE]: `Suspense`, - [KEEP_ALIVE]: `KeepAlive`, - [BASE_TRANSITION]: `BaseTransition`, - [OPEN_BLOCK]: `openBlock`, - [CREATE_BLOCK]: `createBlock`, - [CREATE_ELEMENT_BLOCK]: `createElementBlock`, - [CREATE_VNODE]: `createVNode`, - [CREATE_ELEMENT_VNODE]: `createElementVNode`, - [CREATE_COMMENT]: `createCommentVNode`, - [CREATE_TEXT]: `createTextVNode`, - [CREATE_STATIC]: `createStaticVNode`, - [RESOLVE_COMPONENT]: `resolveComponent`, - [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`, - [RESOLVE_DIRECTIVE]: `resolveDirective`, - [RESOLVE_FILTER]: `resolveFilter`, - [WITH_DIRECTIVES]: `withDirectives`, - [RENDER_LIST]: `renderList`, - [RENDER_SLOT]: `renderSlot`, - [CREATE_SLOTS]: `createSlots`, - [TO_DISPLAY_STRING]: `toDisplayString`, - [MERGE_PROPS]: `mergeProps`, - [NORMALIZE_CLASS]: `normalizeClass`, - [NORMALIZE_STYLE]: `normalizeStyle`, - [NORMALIZE_PROPS]: `normalizeProps`, - [GUARD_REACTIVE_PROPS]: `guardReactiveProps`, - [TO_HANDLERS]: `toHandlers`, - [CAMELIZE]: `camelize`, - [CAPITALIZE]: `capitalize`, - [TO_HANDLER_KEY]: `toHandlerKey`, - [SET_BLOCK_TRACKING]: `setBlockTracking`, - [PUSH_SCOPE_ID]: `pushScopeId`, - [POP_SCOPE_ID]: `popScopeId`, - [WITH_CTX]: `withCtx`, - [UNREF]: `unref`, - [IS_REF]: `isRef`, - [WITH_MEMO]: `withMemo`, - [IS_MEMO_SAME]: `isMemoSame` - }; - function registerRuntimeHelpers(helpers) { - Object.getOwnPropertySymbols(helpers).forEach((s) => { - helperNameMap[s] = helpers[s]; - }); - } - - const Namespaces = { - "HTML": 0, - "0": "HTML", - "SVG": 1, - "1": "SVG", - "MATH_ML": 2, - "2": "MATH_ML" - }; - const NodeTypes = { - "ROOT": 0, - "0": "ROOT", - "ELEMENT": 1, - "1": "ELEMENT", - "TEXT": 2, - "2": "TEXT", - "COMMENT": 3, - "3": "COMMENT", - "SIMPLE_EXPRESSION": 4, - "4": "SIMPLE_EXPRESSION", - "INTERPOLATION": 5, - "5": "INTERPOLATION", - "ATTRIBUTE": 6, - "6": "ATTRIBUTE", - "DIRECTIVE": 7, - "7": "DIRECTIVE", - "COMPOUND_EXPRESSION": 8, - "8": "COMPOUND_EXPRESSION", - "IF": 9, - "9": "IF", - "IF_BRANCH": 10, - "10": "IF_BRANCH", - "FOR": 11, - "11": "FOR", - "TEXT_CALL": 12, - "12": "TEXT_CALL", - "VNODE_CALL": 13, - "13": "VNODE_CALL", - "JS_CALL_EXPRESSION": 14, - "14": "JS_CALL_EXPRESSION", - "JS_OBJECT_EXPRESSION": 15, - "15": "JS_OBJECT_EXPRESSION", - "JS_PROPERTY": 16, - "16": "JS_PROPERTY", - "JS_ARRAY_EXPRESSION": 17, - "17": "JS_ARRAY_EXPRESSION", - "JS_FUNCTION_EXPRESSION": 18, - "18": "JS_FUNCTION_EXPRESSION", - "JS_CONDITIONAL_EXPRESSION": 19, - "19": "JS_CONDITIONAL_EXPRESSION", - "JS_CACHE_EXPRESSION": 20, - "20": "JS_CACHE_EXPRESSION", - "JS_BLOCK_STATEMENT": 21, - "21": "JS_BLOCK_STATEMENT", - "JS_TEMPLATE_LITERAL": 22, - "22": "JS_TEMPLATE_LITERAL", - "JS_IF_STATEMENT": 23, - "23": "JS_IF_STATEMENT", - "JS_ASSIGNMENT_EXPRESSION": 24, - "24": "JS_ASSIGNMENT_EXPRESSION", - "JS_SEQUENCE_EXPRESSION": 25, - "25": "JS_SEQUENCE_EXPRESSION", - "JS_RETURN_STATEMENT": 26, - "26": "JS_RETURN_STATEMENT" - }; - const ElementTypes = { - "ELEMENT": 0, - "0": "ELEMENT", - "COMPONENT": 1, - "1": "COMPONENT", - "SLOT": 2, - "2": "SLOT", - "TEMPLATE": 3, - "3": "TEMPLATE" - }; - const ConstantTypes = { - "NOT_CONSTANT": 0, - "0": "NOT_CONSTANT", - "CAN_SKIP_PATCH": 1, - "1": "CAN_SKIP_PATCH", - "CAN_HOIST": 2, - "2": "CAN_HOIST", - "CAN_STRINGIFY": 3, - "3": "CAN_STRINGIFY" - }; - const locStub = { - start: { line: 1, column: 1, offset: 0 }, - end: { line: 1, column: 1, offset: 0 }, - source: "" - }; - function createRoot(children, source = "") { - return { - type: 0, - source, - children, - helpers: /* @__PURE__ */ new Set(), - components: [], - directives: [], - hoists: [], - imports: [], - cached: 0, - temps: 0, - codegenNode: void 0, - loc: locStub - }; - } - function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) { - if (context) { - if (isBlock) { - context.helper(OPEN_BLOCK); - context.helper(getVNodeBlockHelper(context.inSSR, isComponent)); - } else { - context.helper(getVNodeHelper(context.inSSR, isComponent)); - } - if (directives) { - context.helper(WITH_DIRECTIVES); - } - } - return { - type: 13, - tag, - props, - children, - patchFlag, - dynamicProps, - directives, - isBlock, - disableTracking, - isComponent, - loc - }; - } - function createArrayExpression(elements, loc = locStub) { - return { - type: 17, - loc, - elements - }; - } - function createObjectExpression(properties, loc = locStub) { - return { - type: 15, - loc, - properties - }; - } - function createObjectProperty(key, value) { - return { - type: 16, - loc: locStub, - key: isString$2(key) ? createSimpleExpression(key, true) : key, - value - }; - } - function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0) { - return { - type: 4, - loc, - content, - isStatic, - constType: isStatic ? 3 : constType - }; - } - function createInterpolation(content, loc) { - return { - type: 5, - loc, - content: isString$2(content) ? createSimpleExpression(content, false, loc) : content - }; - } - function createCompoundExpression(children, loc = locStub) { - return { - type: 8, - loc, - children - }; - } - function createCallExpression(callee, args = [], loc = locStub) { - return { - type: 14, - loc, - callee, - arguments: args - }; - } - function createFunctionExpression(params, returns = void 0, newline = false, isSlot = false, loc = locStub) { - return { - type: 18, - params, - returns, - newline, - isSlot, - loc - }; - } - function createConditionalExpression(test, consequent, alternate, newline = true) { - return { - type: 19, - test, - consequent, - alternate, - newline, - loc: locStub - }; - } - function createCacheExpression(index, value, isVNode = false) { - return { - type: 20, - index, - value, - isVNode, - loc: locStub - }; - } - function createBlockStatement(body) { - return { - type: 21, - body, - loc: locStub - }; - } - function createTemplateLiteral(elements) { - return { - type: 22, - elements, - loc: locStub - }; - } - function createIfStatement(test, consequent, alternate) { - return { - type: 23, - test, - consequent, - alternate, - loc: locStub - }; - } - function createAssignmentExpression(left, right) { - return { - type: 24, - left, - right, - loc: locStub - }; - } - function createSequenceExpression(expressions) { - return { - type: 25, - expressions, - loc: locStub - }; - } - function createReturnStatement(returns) { - return { - type: 26, - returns, - loc: locStub - }; - } - function getVNodeHelper(ssr, isComponent) { - return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE; - } - function getVNodeBlockHelper(ssr, isComponent) { - return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK; - } - function convertToBlock(node, { helper, removeHelper, inSSR }) { - if (!node.isBlock) { - node.isBlock = true; - removeHelper(getVNodeHelper(inSSR, node.isComponent)); - helper(OPEN_BLOCK); - helper(getVNodeBlockHelper(inSSR, node.isComponent)); - } - } - - // Generated using scripts/write-decode-map.ts - var htmlDecodeTree = new Uint16Array( - // prettier-ignore - "\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c" - .split("") - .map((c) => c.charCodeAt(0))); - - // Generated using scripts/write-decode-map.ts - var xmlDecodeTree = new Uint16Array( - // prettier-ignore - "\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022" - .split("") - .map((c) => c.charCodeAt(0))); - - // Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 - var _a$1; - const decodeMap = new Map([ - [0, 65533], - // C1 Unicode control character reference replacements - [128, 8364], - [130, 8218], - [131, 402], - [132, 8222], - [133, 8230], - [134, 8224], - [135, 8225], - [136, 710], - [137, 8240], - [138, 352], - [139, 8249], - [140, 338], - [142, 381], - [145, 8216], - [146, 8217], - [147, 8220], - [148, 8221], - [149, 8226], - [150, 8211], - [151, 8212], - [152, 732], - [153, 8482], - [154, 353], - [155, 8250], - [156, 339], - [158, 382], - [159, 376], - ]); - /** - * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. - */ - const fromCodePoint = - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins - (_a$1 = String.fromCodePoint) !== null && _a$1 !== void 0 ? _a$1 : function (codePoint) { - let output = ""; - if (codePoint > 0xffff) { - codePoint -= 0x10000; - output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800); - codePoint = 0xdc00 | (codePoint & 0x3ff); - } - output += String.fromCharCode(codePoint); - return output; - }; - /** - * Replace the given code point with a replacement character if it is a - * surrogate or is outside the valid range. Otherwise return the code - * point unchanged. - */ - function replaceCodePoint(codePoint) { - var _a; - if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) { - return 0xfffd; - } - return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint; - } - - var CharCodes; - (function (CharCodes) { - CharCodes[CharCodes["NUM"] = 35] = "NUM"; - CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; - CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; - CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; - CharCodes[CharCodes["NINE"] = 57] = "NINE"; - CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; - CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; - CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; - CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; - CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; - CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; - CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; - })(CharCodes || (CharCodes = {})); - /** Bit that needs to be set to convert an upper case ASCII character to lower case */ - const TO_LOWER_BIT = 0b100000; - var BinTrieFlags; - (function (BinTrieFlags) { - BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; - BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; - BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; - })(BinTrieFlags || (BinTrieFlags = {})); - function isNumber$2(code) { - return code >= CharCodes.ZERO && code <= CharCodes.NINE; - } - function isHexadecimalCharacter(code) { - return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) || - (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F)); - } - function isAsciiAlphaNumeric(code) { - return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) || - (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) || - isNumber$2(code)); - } - /** - * Checks if the given character is a valid end character for an entity in an attribute. - * - * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. - * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state - */ - function isEntityInAttributeInvalidEnd(code) { - return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); - } - var EntityDecoderState; - (function (EntityDecoderState) { - EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; - EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; - EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; - EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; - EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; - })(EntityDecoderState || (EntityDecoderState = {})); - var DecodingMode; - (function (DecodingMode) { - /** Entities in text nodes that can end with any character. */ - DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; - /** Only allow entities terminated with a semicolon. */ - DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; - /** Entities in attributes have limitations on ending characters. */ - DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; - })(DecodingMode || (DecodingMode = {})); - /** - * Token decoder with support of writing partial entities. - */ - class EntityDecoder { - constructor( - /** The tree used to decode entities. */ - decodeTree, - /** - * The function that is called when a codepoint is decoded. - * - * For multi-byte named entities, this will be called multiple times, - * with the second codepoint, and the same `consumed` value. - * - * @param codepoint The decoded codepoint. - * @param consumed The number of bytes consumed by the decoder. - */ - emitCodePoint, - /** An object that is used to produce errors. */ - errors) { - this.decodeTree = decodeTree; - this.emitCodePoint = emitCodePoint; - this.errors = errors; - /** The current state of the decoder. */ - this.state = EntityDecoderState.EntityStart; - /** Characters that were consumed while parsing an entity. */ - this.consumed = 1; - /** - * The result of the entity. - * - * Either the result index of a numeric entity, or the codepoint of a - * numeric entity. - */ - this.result = 0; - /** The current index in the decode tree. */ - this.treeIndex = 0; - /** The number of characters that were consumed in excess. */ - this.excess = 1; - /** The mode in which the decoder is operating. */ - this.decodeMode = DecodingMode.Strict; - } - /** Resets the instance to make it reusable. */ - startEntity(decodeMode) { - this.decodeMode = decodeMode; - this.state = EntityDecoderState.EntityStart; - this.result = 0; - this.treeIndex = 0; - this.excess = 1; - this.consumed = 1; - } - /** - * Write an entity to the decoder. This can be called multiple times with partial entities. - * If the entity is incomplete, the decoder will return -1. - * - * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the - * entity is incomplete, and resume when the next string is written. - * - * @param string The string containing the entity (or a continuation of the entity). - * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - write(str, offset) { - switch (this.state) { - case EntityDecoderState.EntityStart: { - if (str.charCodeAt(offset) === CharCodes.NUM) { - this.state = EntityDecoderState.NumericStart; - this.consumed += 1; - return this.stateNumericStart(str, offset + 1); - } - this.state = EntityDecoderState.NamedEntity; - return this.stateNamedEntity(str, offset); - } - case EntityDecoderState.NumericStart: { - return this.stateNumericStart(str, offset); - } - case EntityDecoderState.NumericDecimal: { - return this.stateNumericDecimal(str, offset); - } - case EntityDecoderState.NumericHex: { - return this.stateNumericHex(str, offset); - } - case EntityDecoderState.NamedEntity: { - return this.stateNamedEntity(str, offset); - } - } - } - /** - * Switches between the numeric decimal and hexadecimal states. - * - * Equivalent to the `Numeric character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - stateNumericStart(str, offset) { - if (offset >= str.length) { - return -1; - } - if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { - this.state = EntityDecoderState.NumericHex; - this.consumed += 1; - return this.stateNumericHex(str, offset + 1); - } - this.state = EntityDecoderState.NumericDecimal; - return this.stateNumericDecimal(str, offset); - } - addToNumericResult(str, start, end, base) { - if (start !== end) { - const digitCount = end - start; - this.result = - this.result * Math.pow(base, digitCount) + - parseInt(str.substr(start, digitCount), base); - this.consumed += digitCount; - } - } - /** - * Parses a hexadecimal numeric entity. - * - * Equivalent to the `Hexademical character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - stateNumericHex(str, offset) { - const startIdx = offset; - while (offset < str.length) { - const char = str.charCodeAt(offset); - if (isNumber$2(char) || isHexadecimalCharacter(char)) { - offset += 1; - } - else { - this.addToNumericResult(str, startIdx, offset, 16); - return this.emitNumericEntity(char, 3); - } - } - this.addToNumericResult(str, startIdx, offset, 16); - return -1; - } - /** - * Parses a decimal numeric entity. - * - * Equivalent to the `Decimal character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - stateNumericDecimal(str, offset) { - const startIdx = offset; - while (offset < str.length) { - const char = str.charCodeAt(offset); - if (isNumber$2(char)) { - offset += 1; - } - else { - this.addToNumericResult(str, startIdx, offset, 10); - return this.emitNumericEntity(char, 2); - } - } - this.addToNumericResult(str, startIdx, offset, 10); - return -1; - } - /** - * Validate and emit a numeric entity. - * - * Implements the logic from the `Hexademical character reference start - * state` and `Numeric character reference end state` in the HTML spec. - * - * @param lastCp The last code point of the entity. Used to see if the - * entity was terminated with a semicolon. - * @param expectedLength The minimum number of characters that should be - * consumed. Used to validate that at least one digit - * was consumed. - * @returns The number of characters that were consumed. - */ - emitNumericEntity(lastCp, expectedLength) { - var _a; - // Ensure we consumed at least one digit. - if (this.consumed <= expectedLength) { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - // Figure out if this is a legit end of the entity - if (lastCp === CharCodes.SEMI) { - this.consumed += 1; - } - else if (this.decodeMode === DecodingMode.Strict) { - return 0; - } - this.emitCodePoint(replaceCodePoint(this.result), this.consumed); - if (this.errors) { - if (lastCp !== CharCodes.SEMI) { - this.errors.missingSemicolonAfterCharacterReference(); - } - this.errors.validateNumericCharacterReference(this.result); - } - return this.consumed; - } - /** - * Parses a named entity. - * - * Equivalent to the `Named character reference state` in the HTML spec. - * - * @param str The string containing the entity (or a continuation of the entity). - * @param offset The current offset. - * @returns The number of characters that were consumed, or -1 if the entity is incomplete. - */ - stateNamedEntity(str, offset) { - const { decodeTree } = this; - let current = decodeTree[this.treeIndex]; - // The mask is the number of bytes of the value, including the current byte. - let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - for (; offset < str.length; offset++, this.excess++) { - const char = str.charCodeAt(offset); - this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); - if (this.treeIndex < 0) { - return this.result === 0 || - // If we are parsing an attribute - (this.decodeMode === DecodingMode.Attribute && - // We shouldn't have consumed any characters after the entity, - (valueLength === 0 || - // And there should be no invalid characters. - isEntityInAttributeInvalidEnd(char))) - ? 0 - : this.emitNotTerminatedNamedEntity(); - } - current = decodeTree[this.treeIndex]; - valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; - // If the branch is a value, store it and continue - if (valueLength !== 0) { - // If the entity is terminated by a semicolon, we are done. - if (char === CharCodes.SEMI) { - return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); - } - // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. - if (this.decodeMode !== DecodingMode.Strict) { - this.result = this.treeIndex; - this.consumed += this.excess; - this.excess = 0; - } - } - } - return -1; - } - /** - * Emit a named entity that was not terminated with a semicolon. - * - * @returns The number of characters consumed. - */ - emitNotTerminatedNamedEntity() { - var _a; - const { result, decodeTree } = this; - const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; - this.emitNamedEntityData(result, valueLength, this.consumed); - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); - return this.consumed; - } - /** - * Emit a named entity. - * - * @param result The index of the entity in the decode tree. - * @param valueLength The number of bytes in the entity. - * @param consumed The number of characters consumed. - * - * @returns The number of characters consumed. - */ - emitNamedEntityData(result, valueLength, consumed) { - const { decodeTree } = this; - this.emitCodePoint(valueLength === 1 - ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH - : decodeTree[result + 1], consumed); - if (valueLength === 3) { - // For multi-byte values, we need to emit the second byte. - this.emitCodePoint(decodeTree[result + 2], consumed); - } - return consumed; - } - /** - * Signal to the parser that the end of the input was reached. - * - * Remaining data will be emitted and relevant errors will be produced. - * - * @returns The number of characters consumed. - */ - end() { - var _a; - switch (this.state) { - case EntityDecoderState.NamedEntity: { - // Emit a named entity if we have one. - return this.result !== 0 && - (this.decodeMode !== DecodingMode.Attribute || - this.result === this.treeIndex) - ? this.emitNotTerminatedNamedEntity() - : 0; - } - // Otherwise, emit a numeric entity if we have one. - case EntityDecoderState.NumericDecimal: { - return this.emitNumericEntity(0, 2); - } - case EntityDecoderState.NumericHex: { - return this.emitNumericEntity(0, 3); - } - case EntityDecoderState.NumericStart: { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - case EntityDecoderState.EntityStart: { - // Return 0 if we have no entity. - return 0; - } - } - } - } - /** - * Creates a function that decodes entities in a string. - * - * @param decodeTree The decode tree. - * @returns A function that decodes entities in a string. - */ - function getDecoder(decodeTree) { - let ret = ""; - const decoder = new EntityDecoder(decodeTree, (str) => (ret += fromCodePoint(str))); - return function decodeWithTrie(str, decodeMode) { - let lastIndex = 0; - let offset = 0; - while ((offset = str.indexOf("&", offset)) >= 0) { - ret += str.slice(lastIndex, offset); - decoder.startEntity(decodeMode); - const len = decoder.write(str, - // Skip the "&" - offset + 1); - if (len < 0) { - lastIndex = offset + decoder.end(); - break; - } - lastIndex = offset + len; - // If `len` is 0, skip the current `&` and continue. - offset = len === 0 ? lastIndex + 1 : lastIndex; - } - const result = ret + str.slice(lastIndex); - // Make sure we don't keep a reference to the final string. - ret = ""; - return result; - }; - } - /** - * Determines the branch of the current node that is taken given the current - * character. This function is used to traverse the trie. - * - * @param decodeTree The trie. - * @param current The current node. - * @param nodeIdx The index right after the current node and its value. - * @param char The current character. - * @returns The index of the next node, or -1 if no branch is taken. - */ - function determineBranch(decodeTree, current, nodeIdx, char) { - const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; - const jumpOffset = current & BinTrieFlags.JUMP_TABLE; - // Case 1: Single branch encoded in jump offset - if (branchCount === 0) { - return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; - } - // Case 2: Multiple branches encoded in jump table - if (jumpOffset) { - const value = char - jumpOffset; - return value < 0 || value >= branchCount - ? -1 - : decodeTree[nodeIdx + value] - 1; - } - // Case 3: Multiple branches encoded in dictionary - // Binary search for the character. - let lo = nodeIdx; - let hi = lo + branchCount - 1; - while (lo <= hi) { - const mid = (lo + hi) >>> 1; - const midVal = decodeTree[mid]; - if (midVal < char) { - lo = mid + 1; - } - else if (midVal > char) { - hi = mid - 1; - } - else { - return decodeTree[mid + branchCount]; - } - } - return -1; - } - const htmlDecoder = getDecoder(htmlDecodeTree); - getDecoder(xmlDecodeTree); - /** - * Decodes an HTML string. - * - * @param str The string to decode. - * @param mode The decoding mode. - * @returns The decoded string. - */ - function decodeHTML(str, mode = DecodingMode.Legacy) { - return htmlDecoder(str, mode); - } - - const defaultDelimitersOpen = new Uint8Array([123, 123]); - const defaultDelimitersClose = new Uint8Array([125, 125]); - function isTagStartChar(c) { - return c >= 97 && c <= 122 || c >= 65 && c <= 90; - } - function isWhitespace$1(c) { - return c === 32 || c === 10 || c === 9 || c === 12 || c === 13; - } - function isEndOfTagSection(c) { - return c === 47 || c === 62 || isWhitespace$1(c); - } - function toCharCodes(str) { - const ret = new Uint8Array(str.length); - for (let i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret; - } - const Sequences = { - Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]), - // CDATA[ - CdataEnd: new Uint8Array([93, 93, 62]), - // ]]> - CommentEnd: new Uint8Array([45, 45, 62]), - // `-->` - ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]), - // `<\/script` - StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]), - // ` this.emitCodePoint(cp, consumed) - ); - } - } - get inSFCRoot() { - return this.mode === 2 && this.stack.length === 0; - } - reset() { - this.state = 1; - this.mode = 0; - this.buffer = ""; - this.sectionStart = 0; - this.index = 0; - this.baseState = 1; - this.inRCDATA = false; - this.currentSequence = void 0; - this.newlines.length = 0; - this.delimiterOpen = defaultDelimitersOpen; - this.delimiterClose = defaultDelimitersClose; - } - /** - * Generate Position object with line / column information using recorded - * newline positions. We know the index is always going to be an already - * processed index, so all the newlines up to this index should have been - * recorded. - */ - getPos(index) { - let line = 1; - let column = index + 1; - for (let i = this.newlines.length - 1; i >= 0; i--) { - const newlineIndex = this.newlines[i]; - if (index > newlineIndex) { - line = i + 2; - column = index - newlineIndex; - break; - } - } - return { - column, - line, - offset: index - }; - } - peek() { - return this.buffer.charCodeAt(this.index + 1); - } - stateText(c) { - if (c === 60) { - if (this.index > this.sectionStart) { - this.cbs.ontext(this.sectionStart, this.index); - } - this.state = 5; - this.sectionStart = this.index; - } else if (c === 38) { - this.startEntity(); - } else if (!this.inVPre && c === this.delimiterOpen[0]) { - this.state = 2; - this.delimiterIndex = 0; - this.stateInterpolationOpen(c); - } - } - stateInterpolationOpen(c) { - if (c === this.delimiterOpen[this.delimiterIndex]) { - if (this.delimiterIndex === this.delimiterOpen.length - 1) { - const start = this.index + 1 - this.delimiterOpen.length; - if (start > this.sectionStart) { - this.cbs.ontext(this.sectionStart, start); - } - this.state = 3; - this.sectionStart = start; - } else { - this.delimiterIndex++; - } - } else if (this.inRCDATA) { - this.state = 32; - this.stateInRCDATA(c); - } else { - this.state = 1; - this.stateText(c); - } - } - stateInterpolation(c) { - if (c === this.delimiterClose[0]) { - this.state = 4; - this.delimiterIndex = 0; - this.stateInterpolationClose(c); - } - } - stateInterpolationClose(c) { - if (c === this.delimiterClose[this.delimiterIndex]) { - if (this.delimiterIndex === this.delimiterClose.length - 1) { - this.cbs.oninterpolation(this.sectionStart, this.index + 1); - if (this.inRCDATA) { - this.state = 32; - } else { - this.state = 1; - } - this.sectionStart = this.index + 1; - } else { - this.delimiterIndex++; - } - } else { - this.state = 3; - this.stateInterpolation(c); - } - } - stateSpecialStartSequence(c) { - const isEnd = this.sequenceIndex === this.currentSequence.length; - const isMatch = isEnd ? ( - // If we are at the end of the sequence, make sure the tag name has ended - isEndOfTagSection(c) - ) : ( - // Otherwise, do a case-insensitive comparison - (c | 32) === this.currentSequence[this.sequenceIndex] - ); - if (!isMatch) { - this.inRCDATA = false; - } else if (!isEnd) { - this.sequenceIndex++; - return; - } - this.sequenceIndex = 0; - this.state = 6; - this.stateInTagName(c); - } - /** Look for an end tag. For and <textarea>, also decode entities. */ - stateInRCDATA(c) { - if (this.sequenceIndex === this.currentSequence.length) { - if (c === 62 || isWhitespace$1(c)) { - const endOfText = this.index - this.currentSequence.length; - if (this.sectionStart < endOfText) { - const actualIndex = this.index; - this.index = endOfText; - this.cbs.ontext(this.sectionStart, endOfText); - this.index = actualIndex; - } - this.sectionStart = endOfText + 2; - this.stateInClosingTagName(c); - this.inRCDATA = false; - return; - } - this.sequenceIndex = 0; - } - if ((c | 32) === this.currentSequence[this.sequenceIndex]) { - this.sequenceIndex += 1; - } else if (this.sequenceIndex === 0) { - if (this.currentSequence === Sequences.TitleEnd || this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot) { - if (c === 38) { - this.startEntity(); - } else if (c === this.delimiterOpen[0]) { - this.state = 2; - this.delimiterIndex = 0; - this.stateInterpolationOpen(c); - } - } else if (this.fastForwardTo(60)) { - this.sequenceIndex = 1; - } - } else { - this.sequenceIndex = Number(c === 60); - } - } - stateCDATASequence(c) { - if (c === Sequences.Cdata[this.sequenceIndex]) { - if (++this.sequenceIndex === Sequences.Cdata.length) { - this.state = 28; - this.currentSequence = Sequences.CdataEnd; - this.sequenceIndex = 0; - this.sectionStart = this.index + 1; - } - } else { - this.sequenceIndex = 0; - this.state = 23; - this.stateInDeclaration(c); - } - } - /** - * When we wait for one specific character, we can speed things up - * by skipping through the buffer until we find it. - * - * @returns Whether the character was found. - */ - fastForwardTo(c) { - while (++this.index < this.buffer.length) { - const cc = this.buffer.charCodeAt(this.index); - if (cc === 10) { - this.newlines.push(this.index); - } - if (cc === c) { - return true; - } - } - this.index = this.buffer.length - 1; - return false; - } - /** - * Comments and CDATA end with `-->` and `]]>`. - * - * Their common qualities are: - * - Their end sequences have a distinct character they start with. - * - That character is then repeated, so we have to check multiple repeats. - * - All characters but the start character of the sequence can be skipped. - */ - stateInCommentLike(c) { - if (c === this.currentSequence[this.sequenceIndex]) { - if (++this.sequenceIndex === this.currentSequence.length) { - if (this.currentSequence === Sequences.CdataEnd) { - this.cbs.oncdata(this.sectionStart, this.index - 2); - } else { - this.cbs.oncomment(this.sectionStart, this.index - 2); - } - this.sequenceIndex = 0; - this.sectionStart = this.index + 1; - this.state = 1; - } - } else if (this.sequenceIndex === 0) { - if (this.fastForwardTo(this.currentSequence[0])) { - this.sequenceIndex = 1; - } - } else if (c !== this.currentSequence[this.sequenceIndex - 1]) { - this.sequenceIndex = 0; - } - } - startSpecial(sequence, offset) { - this.enterRCDATA(sequence, offset); - this.state = 31; - } - enterRCDATA(sequence, offset) { - this.inRCDATA = true; - this.currentSequence = sequence; - this.sequenceIndex = offset; - } - stateBeforeTagName(c) { - if (c === 33) { - this.state = 22; - this.sectionStart = this.index + 1; - } else if (c === 63) { - this.state = 24; - this.sectionStart = this.index + 1; - } else if (isTagStartChar(c)) { - this.sectionStart = this.index; - if (this.mode === 0) { - this.state = 6; - } else if (this.inSFCRoot) { - this.state = 34; - } else if (!this.inXML) { - if (c === 116) { - this.state = 30; - } else { - this.state = c === 115 ? 29 : 6; - } - } else { - this.state = 6; - } - } else if (c === 47) { - this.state = 8; - } else { - this.state = 1; - this.stateText(c); - } - } - stateInTagName(c) { - if (isEndOfTagSection(c)) { - this.handleTagName(c); - } - } - stateInSFCRootTagName(c) { - if (isEndOfTagSection(c)) { - const tag = this.buffer.slice(this.sectionStart, this.index); - if (tag !== "template") { - this.enterRCDATA(toCharCodes(`</` + tag), 0); - } - this.handleTagName(c); - } - } - handleTagName(c) { - this.cbs.onopentagname(this.sectionStart, this.index); - this.sectionStart = -1; - this.state = 11; - this.stateBeforeAttrName(c); - } - stateBeforeClosingTagName(c) { - if (isWhitespace$1(c)); else if (c === 62) { - { - this.cbs.onerr(14, this.index); - } - this.state = 1; - this.sectionStart = this.index + 1; - } else { - this.state = isTagStartChar(c) ? 9 : 27; - this.sectionStart = this.index; - } - } - stateInClosingTagName(c) { - if (c === 62 || isWhitespace$1(c)) { - this.cbs.onclosetag(this.sectionStart, this.index); - this.sectionStart = -1; - this.state = 10; - this.stateAfterClosingTagName(c); - } - } - stateAfterClosingTagName(c) { - if (c === 62) { - this.state = 1; - this.sectionStart = this.index + 1; - } - } - stateBeforeAttrName(c) { - if (c === 62) { - this.cbs.onopentagend(this.index); - if (this.inRCDATA) { - this.state = 32; - } else { - this.state = 1; - } - this.sectionStart = this.index + 1; - } else if (c === 47) { - this.state = 7; - if (this.peek() !== 62) { - this.cbs.onerr(22, this.index); - } - } else if (c === 60 && this.peek() === 47) { - this.cbs.onopentagend(this.index); - this.state = 5; - this.sectionStart = this.index; - } else if (!isWhitespace$1(c)) { - if (c === 61) { - this.cbs.onerr( - 19, - this.index - ); - } - this.handleAttrStart(c); - } - } - handleAttrStart(c) { - if (c === 118 && this.peek() === 45) { - this.state = 13; - this.sectionStart = this.index; - } else if (c === 46 || c === 58 || c === 64 || c === 35) { - this.cbs.ondirname(this.index, this.index + 1); - this.state = 14; - this.sectionStart = this.index + 1; - } else { - this.state = 12; - this.sectionStart = this.index; - } - } - stateInSelfClosingTag(c) { - if (c === 62) { - this.cbs.onselfclosingtag(this.index); - this.state = 1; - this.sectionStart = this.index + 1; - this.inRCDATA = false; - } else if (!isWhitespace$1(c)) { - this.state = 11; - this.stateBeforeAttrName(c); - } - } - stateInAttrName(c) { - if (c === 61 || isEndOfTagSection(c)) { - this.cbs.onattribname(this.sectionStart, this.index); - this.handleAttrNameEnd(c); - } else if (c === 34 || c === 39 || c === 60) { - this.cbs.onerr( - 17, - this.index - ); - } - } - stateInDirName(c) { - if (c === 61 || isEndOfTagSection(c)) { - this.cbs.ondirname(this.sectionStart, this.index); - this.handleAttrNameEnd(c); - } else if (c === 58) { - this.cbs.ondirname(this.sectionStart, this.index); - this.state = 14; - this.sectionStart = this.index + 1; - } else if (c === 46) { - this.cbs.ondirname(this.sectionStart, this.index); - this.state = 16; - this.sectionStart = this.index + 1; - } - } - stateInDirArg(c) { - if (c === 61 || isEndOfTagSection(c)) { - this.cbs.ondirarg(this.sectionStart, this.index); - this.handleAttrNameEnd(c); - } else if (c === 91) { - this.state = 15; - } else if (c === 46) { - this.cbs.ondirarg(this.sectionStart, this.index); - this.state = 16; - this.sectionStart = this.index + 1; - } - } - stateInDynamicDirArg(c) { - if (c === 93) { - this.state = 14; - } else if (c === 61 || isEndOfTagSection(c)) { - this.cbs.ondirarg(this.sectionStart, this.index + 1); - this.handleAttrNameEnd(c); - { - this.cbs.onerr( - 27, - this.index - ); - } - } - } - stateInDirModifier(c) { - if (c === 61 || isEndOfTagSection(c)) { - this.cbs.ondirmodifier(this.sectionStart, this.index); - this.handleAttrNameEnd(c); - } else if (c === 46) { - this.cbs.ondirmodifier(this.sectionStart, this.index); - this.sectionStart = this.index + 1; - } - } - handleAttrNameEnd(c) { - this.sectionStart = this.index; - this.state = 17; - this.cbs.onattribnameend(this.index); - this.stateAfterAttrName(c); - } - stateAfterAttrName(c) { - if (c === 61) { - this.state = 18; - } else if (c === 47 || c === 62) { - this.cbs.onattribend(0, this.sectionStart); - this.sectionStart = -1; - this.state = 11; - this.stateBeforeAttrName(c); - } else if (!isWhitespace$1(c)) { - this.cbs.onattribend(0, this.sectionStart); - this.handleAttrStart(c); - } - } - stateBeforeAttrValue(c) { - if (c === 34) { - this.state = 19; - this.sectionStart = this.index + 1; - } else if (c === 39) { - this.state = 20; - this.sectionStart = this.index + 1; - } else if (!isWhitespace$1(c)) { - this.sectionStart = this.index; - this.state = 21; - this.stateInAttrValueNoQuotes(c); - } - } - handleInAttrValue(c, quote) { - if (c === quote || false) { - this.cbs.onattribdata(this.sectionStart, this.index); - this.sectionStart = -1; - this.cbs.onattribend( - quote === 34 ? 3 : 2, - this.index + 1 - ); - this.state = 11; - } else if (c === 38) { - this.startEntity(); - } - } - stateInAttrValueDoubleQuotes(c) { - this.handleInAttrValue(c, 34); - } - stateInAttrValueSingleQuotes(c) { - this.handleInAttrValue(c, 39); - } - stateInAttrValueNoQuotes(c) { - if (isWhitespace$1(c) || c === 62) { - this.cbs.onattribdata(this.sectionStart, this.index); - this.sectionStart = -1; - this.cbs.onattribend(1, this.index); - this.state = 11; - this.stateBeforeAttrName(c); - } else if (c === 34 || c === 39 || c === 60 || c === 61 || c === 96) { - this.cbs.onerr( - 18, - this.index - ); - } else if (c === 38) { - this.startEntity(); - } - } - stateBeforeDeclaration(c) { - if (c === 91) { - this.state = 26; - this.sequenceIndex = 0; - } else { - this.state = c === 45 ? 25 : 23; - } - } - stateInDeclaration(c) { - if (c === 62 || this.fastForwardTo(62)) { - this.state = 1; - this.sectionStart = this.index + 1; - } - } - stateInProcessingInstruction(c) { - if (c === 62 || this.fastForwardTo(62)) { - this.cbs.onprocessinginstruction(this.sectionStart, this.index); - this.state = 1; - this.sectionStart = this.index + 1; - } - } - stateBeforeComment(c) { - if (c === 45) { - this.state = 28; - this.currentSequence = Sequences.CommentEnd; - this.sequenceIndex = 2; - this.sectionStart = this.index + 1; - } else { - this.state = 23; - } - } - stateInSpecialComment(c) { - if (c === 62 || this.fastForwardTo(62)) { - this.cbs.oncomment(this.sectionStart, this.index); - this.state = 1; - this.sectionStart = this.index + 1; - } - } - stateBeforeSpecialS(c) { - if (c === Sequences.ScriptEnd[3]) { - this.startSpecial(Sequences.ScriptEnd, 4); - } else if (c === Sequences.StyleEnd[3]) { - this.startSpecial(Sequences.StyleEnd, 4); - } else { - this.state = 6; - this.stateInTagName(c); - } - } - stateBeforeSpecialT(c) { - if (c === Sequences.TitleEnd[3]) { - this.startSpecial(Sequences.TitleEnd, 4); - } else if (c === Sequences.TextareaEnd[3]) { - this.startSpecial(Sequences.TextareaEnd, 4); - } else { - this.state = 6; - this.stateInTagName(c); - } - } - startEntity() { - { - this.baseState = this.state; - this.state = 33; - this.entityStart = this.index; - this.entityDecoder.startEntity( - this.baseState === 1 || this.baseState === 32 ? DecodingMode.Legacy : DecodingMode.Attribute - ); - } - } - stateInEntity() { - { - const length = this.entityDecoder.write(this.buffer, this.index); - if (length >= 0) { - this.state = this.baseState; - if (length === 0) { - this.index = this.entityStart; - } - } else { - this.index = this.buffer.length - 1; - } - } - } - /** - * Iterates through the buffer, calling the function corresponding to the current state. - * - * States that are more likely to be hit are higher up, as a performance improvement. - */ - parse(input) { - this.buffer = input; - while (this.index < this.buffer.length) { - const c = this.buffer.charCodeAt(this.index); - if (c === 10) { - this.newlines.push(this.index); - } - switch (this.state) { - case 1: { - this.stateText(c); - break; - } - case 2: { - this.stateInterpolationOpen(c); - break; - } - case 3: { - this.stateInterpolation(c); - break; - } - case 4: { - this.stateInterpolationClose(c); - break; - } - case 31: { - this.stateSpecialStartSequence(c); - break; - } - case 32: { - this.stateInRCDATA(c); - break; - } - case 26: { - this.stateCDATASequence(c); - break; - } - case 19: { - this.stateInAttrValueDoubleQuotes(c); - break; - } - case 12: { - this.stateInAttrName(c); - break; - } - case 13: { - this.stateInDirName(c); - break; - } - case 14: { - this.stateInDirArg(c); - break; - } - case 15: { - this.stateInDynamicDirArg(c); - break; - } - case 16: { - this.stateInDirModifier(c); - break; - } - case 28: { - this.stateInCommentLike(c); - break; - } - case 27: { - this.stateInSpecialComment(c); - break; - } - case 11: { - this.stateBeforeAttrName(c); - break; - } - case 6: { - this.stateInTagName(c); - break; - } - case 34: { - this.stateInSFCRootTagName(c); - break; - } - case 9: { - this.stateInClosingTagName(c); - break; - } - case 5: { - this.stateBeforeTagName(c); - break; - } - case 17: { - this.stateAfterAttrName(c); - break; - } - case 20: { - this.stateInAttrValueSingleQuotes(c); - break; - } - case 18: { - this.stateBeforeAttrValue(c); - break; - } - case 8: { - this.stateBeforeClosingTagName(c); - break; - } - case 10: { - this.stateAfterClosingTagName(c); - break; - } - case 29: { - this.stateBeforeSpecialS(c); - break; - } - case 30: { - this.stateBeforeSpecialT(c); - break; - } - case 21: { - this.stateInAttrValueNoQuotes(c); - break; - } - case 7: { - this.stateInSelfClosingTag(c); - break; - } - case 23: { - this.stateInDeclaration(c); - break; - } - case 22: { - this.stateBeforeDeclaration(c); - break; - } - case 25: { - this.stateBeforeComment(c); - break; - } - case 24: { - this.stateInProcessingInstruction(c); - break; - } - case 33: { - this.stateInEntity(); - break; - } - } - this.index++; - } - this.cleanup(); - this.finish(); - } - /** - * Remove data that has already been consumed from the buffer. - */ - cleanup() { - if (this.sectionStart !== this.index) { - if (this.state === 1 || this.state === 32 && this.sequenceIndex === 0) { - this.cbs.ontext(this.sectionStart, this.index); - this.sectionStart = this.index; - } else if (this.state === 19 || this.state === 20 || this.state === 21) { - this.cbs.onattribdata(this.sectionStart, this.index); - this.sectionStart = this.index; - } - } - } - finish() { - if (this.state === 33) { - this.entityDecoder.end(); - this.state = this.baseState; - } - this.handleTrailingData(); - this.cbs.onend(); - } - /** Handle any trailing data. */ - handleTrailingData() { - const endIndex = this.buffer.length; - if (this.sectionStart >= endIndex) { - return; - } - if (this.state === 28) { - if (this.currentSequence === Sequences.CdataEnd) { - this.cbs.oncdata(this.sectionStart, endIndex); - } else { - this.cbs.oncomment(this.sectionStart, endIndex); - } - } else if (this.state === 6 || this.state === 11 || this.state === 18 || this.state === 17 || this.state === 12 || this.state === 13 || this.state === 14 || this.state === 15 || this.state === 16 || this.state === 20 || this.state === 19 || this.state === 21 || this.state === 9); else { - this.cbs.ontext(this.sectionStart, endIndex); - } - } - emitCodePoint(cp, consumed) { - { - if (this.baseState !== 1 && this.baseState !== 32) { - if (this.sectionStart < this.entityStart) { - this.cbs.onattribdata(this.sectionStart, this.entityStart); - } - this.sectionStart = this.entityStart + consumed; - this.index = this.sectionStart - 1; - this.cbs.onattribentity( - fromCodePoint(cp), - this.entityStart, - this.sectionStart - ); - } else { - if (this.sectionStart < this.entityStart) { - this.cbs.ontext(this.sectionStart, this.entityStart); - } - this.sectionStart = this.entityStart + consumed; - this.index = this.sectionStart - 1; - this.cbs.ontextentity( - fromCodePoint(cp), - this.entityStart, - this.sectionStart - ); - } - } - } - }; - - const CompilerDeprecationTypes = { - "COMPILER_IS_ON_ELEMENT": "COMPILER_IS_ON_ELEMENT", - "COMPILER_V_BIND_SYNC": "COMPILER_V_BIND_SYNC", - "COMPILER_V_BIND_OBJECT_ORDER": "COMPILER_V_BIND_OBJECT_ORDER", - "COMPILER_V_ON_NATIVE": "COMPILER_V_ON_NATIVE", - "COMPILER_V_IF_V_FOR_PRECEDENCE": "COMPILER_V_IF_V_FOR_PRECEDENCE", - "COMPILER_NATIVE_TEMPLATE": "COMPILER_NATIVE_TEMPLATE", - "COMPILER_INLINE_TEMPLATE": "COMPILER_INLINE_TEMPLATE", - "COMPILER_FILTERS": "COMPILER_FILTERS" - }; - const deprecationData = { - ["COMPILER_IS_ON_ELEMENT"]: { - message: `Platform-native elements with "is" prop will no longer be treated as components in Vue 3 unless the "is" value is explicitly prefixed with "vue:".`, - link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html` - }, - ["COMPILER_V_BIND_SYNC"]: { - message: (key) => `.sync modifier for v-bind has been removed. Use v-model with argument instead. \`v-bind:${key}.sync\` should be changed to \`v-model:${key}\`.`, - link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html` - }, - ["COMPILER_V_BIND_OBJECT_ORDER"]: { - message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript object spread: it will now overwrite an existing non-mergeable attribute that appears before v-bind in the case of conflict. To retain 2.x behavior, move v-bind to make it the first attribute. You can also suppress this warning if the usage is intended.`, - link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html` - }, - ["COMPILER_V_ON_NATIVE"]: { - message: `.native modifier for v-on has been removed as is no longer necessary.`, - link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html` - }, - ["COMPILER_V_IF_V_FOR_PRECEDENCE"]: { - message: `v-if / v-for precedence when used on the same element has changed in Vue 3: v-if now takes higher precedence and will no longer have access to v-for scope variables. It is best to avoid the ambiguity with <template> tags or use a computed property that filters v-for data source.`, - link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html` - }, - ["COMPILER_NATIVE_TEMPLATE"]: { - message: `<template> with no special directives will render as a native template element instead of its inner content in Vue 3.` - }, - ["COMPILER_INLINE_TEMPLATE"]: { - message: `"inline-template" has been removed in Vue 3.`, - link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html` - }, - ["COMPILER_FILTERS"]: { - message: `filters have been removed in Vue 3. The "|" symbol will be treated as native JavaScript bitwise OR operator. Use method calls or computed properties instead.`, - link: `https://v3-migration.vuejs.org/breaking-changes/filters.html` - } - }; - function getCompatValue(key, { compatConfig }) { - const value = compatConfig && compatConfig[key]; - if (key === "MODE") { - return value || 3; - } else { - return value; - } - } - function isCompatEnabled(key, context) { - const mode = getCompatValue("MODE", context); - const value = getCompatValue(key, context); - return mode === 3 ? value === true : value !== false; - } - function checkCompatEnabled(key, context, loc, ...args) { - const enabled = isCompatEnabled(key, context); - if (enabled) { - warnDeprecation(key, context, loc, ...args); - } - return enabled; - } - function warnDeprecation(key, context, loc, ...args) { - const val = getCompatValue(key, context); - if (val === "suppress-warning") { - return; - } - const { message, link } = deprecationData[key]; - const msg = `(deprecation ${key}) ${typeof message === "function" ? message(...args) : message}${link ? ` - Details: ${link}` : ``}`; - const err = new SyntaxError(msg); - err.code = key; - if (loc) - err.loc = loc; - context.onWarn(err); - } - - function defaultOnError(error) { - throw error; - } - function defaultOnWarn(msg) { - console.warn(`[Vue warn] ${msg.message}`); - } - function createCompilerError(code, loc, messages, additionalMessage) { - const msg = (messages || errorMessages$1)[code] + (additionalMessage || ``); - const error = new SyntaxError(String(msg)); - error.code = code; - error.loc = loc; - return error; - } - const ErrorCodes = { - "ABRUPT_CLOSING_OF_EMPTY_COMMENT": 0, - "0": "ABRUPT_CLOSING_OF_EMPTY_COMMENT", - "CDATA_IN_HTML_CONTENT": 1, - "1": "CDATA_IN_HTML_CONTENT", - "DUPLICATE_ATTRIBUTE": 2, - "2": "DUPLICATE_ATTRIBUTE", - "END_TAG_WITH_ATTRIBUTES": 3, - "3": "END_TAG_WITH_ATTRIBUTES", - "END_TAG_WITH_TRAILING_SOLIDUS": 4, - "4": "END_TAG_WITH_TRAILING_SOLIDUS", - "EOF_BEFORE_TAG_NAME": 5, - "5": "EOF_BEFORE_TAG_NAME", - "EOF_IN_CDATA": 6, - "6": "EOF_IN_CDATA", - "EOF_IN_COMMENT": 7, - "7": "EOF_IN_COMMENT", - "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT": 8, - "8": "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT", - "EOF_IN_TAG": 9, - "9": "EOF_IN_TAG", - "INCORRECTLY_CLOSED_COMMENT": 10, - "10": "INCORRECTLY_CLOSED_COMMENT", - "INCORRECTLY_OPENED_COMMENT": 11, - "11": "INCORRECTLY_OPENED_COMMENT", - "INVALID_FIRST_CHARACTER_OF_TAG_NAME": 12, - "12": "INVALID_FIRST_CHARACTER_OF_TAG_NAME", - "MISSING_ATTRIBUTE_VALUE": 13, - "13": "MISSING_ATTRIBUTE_VALUE", - "MISSING_END_TAG_NAME": 14, - "14": "MISSING_END_TAG_NAME", - "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES": 15, - "15": "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES", - "NESTED_COMMENT": 16, - "16": "NESTED_COMMENT", - "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME": 17, - "17": "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME", - "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE": 18, - "18": "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE", - "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME": 19, - "19": "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME", - "UNEXPECTED_NULL_CHARACTER": 20, - "20": "UNEXPECTED_NULL_CHARACTER", - "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME": 21, - "21": "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME", - "UNEXPECTED_SOLIDUS_IN_TAG": 22, - "22": "UNEXPECTED_SOLIDUS_IN_TAG", - "X_INVALID_END_TAG": 23, - "23": "X_INVALID_END_TAG", - "X_MISSING_END_TAG": 24, - "24": "X_MISSING_END_TAG", - "X_MISSING_INTERPOLATION_END": 25, - "25": "X_MISSING_INTERPOLATION_END", - "X_MISSING_DIRECTIVE_NAME": 26, - "26": "X_MISSING_DIRECTIVE_NAME", - "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END": 27, - "27": "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END", - "X_V_IF_NO_EXPRESSION": 28, - "28": "X_V_IF_NO_EXPRESSION", - "X_V_IF_SAME_KEY": 29, - "29": "X_V_IF_SAME_KEY", - "X_V_ELSE_NO_ADJACENT_IF": 30, - "30": "X_V_ELSE_NO_ADJACENT_IF", - "X_V_FOR_NO_EXPRESSION": 31, - "31": "X_V_FOR_NO_EXPRESSION", - "X_V_FOR_MALFORMED_EXPRESSION": 32, - "32": "X_V_FOR_MALFORMED_EXPRESSION", - "X_V_FOR_TEMPLATE_KEY_PLACEMENT": 33, - "33": "X_V_FOR_TEMPLATE_KEY_PLACEMENT", - "X_V_BIND_NO_EXPRESSION": 34, - "34": "X_V_BIND_NO_EXPRESSION", - "X_V_ON_NO_EXPRESSION": 35, - "35": "X_V_ON_NO_EXPRESSION", - "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET": 36, - "36": "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET", - "X_V_SLOT_MIXED_SLOT_USAGE": 37, - "37": "X_V_SLOT_MIXED_SLOT_USAGE", - "X_V_SLOT_DUPLICATE_SLOT_NAMES": 38, - "38": "X_V_SLOT_DUPLICATE_SLOT_NAMES", - "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN": 39, - "39": "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN", - "X_V_SLOT_MISPLACED": 40, - "40": "X_V_SLOT_MISPLACED", - "X_V_MODEL_NO_EXPRESSION": 41, - "41": "X_V_MODEL_NO_EXPRESSION", - "X_V_MODEL_MALFORMED_EXPRESSION": 42, - "42": "X_V_MODEL_MALFORMED_EXPRESSION", - "X_V_MODEL_ON_SCOPE_VARIABLE": 43, - "43": "X_V_MODEL_ON_SCOPE_VARIABLE", - "X_V_MODEL_ON_PROPS": 44, - "44": "X_V_MODEL_ON_PROPS", - "X_INVALID_EXPRESSION": 45, - "45": "X_INVALID_EXPRESSION", - "X_KEEP_ALIVE_INVALID_CHILDREN": 46, - "46": "X_KEEP_ALIVE_INVALID_CHILDREN", - "X_PREFIX_ID_NOT_SUPPORTED": 47, - "47": "X_PREFIX_ID_NOT_SUPPORTED", - "X_MODULE_MODE_NOT_SUPPORTED": 48, - "48": "X_MODULE_MODE_NOT_SUPPORTED", - "X_CACHE_HANDLER_NOT_SUPPORTED": 49, - "49": "X_CACHE_HANDLER_NOT_SUPPORTED", - "X_SCOPE_ID_NOT_SUPPORTED": 50, - "50": "X_SCOPE_ID_NOT_SUPPORTED", - "X_VNODE_HOOKS": 51, - "51": "X_VNODE_HOOKS", - "X_V_BIND_INVALID_SAME_NAME_ARGUMENT": 52, - "52": "X_V_BIND_INVALID_SAME_NAME_ARGUMENT", - "__EXTEND_POINT__": 53, - "53": "__EXTEND_POINT__" - }; - const errorMessages$1 = { - // parse errors - [0]: "Illegal comment.", - [1]: "CDATA section is allowed only in XML context.", - [2]: "Duplicate attribute.", - [3]: "End tag cannot have attributes.", - [4]: "Illegal '/' in tags.", - [5]: "Unexpected EOF in tag.", - [6]: "Unexpected EOF in CDATA section.", - [7]: "Unexpected EOF in comment.", - [8]: "Unexpected EOF in script.", - [9]: "Unexpected EOF in tag.", - [10]: "Incorrectly closed comment.", - [11]: "Incorrectly opened comment.", - [12]: "Illegal tag name. Use '<' to print '<'.", - [13]: "Attribute value was expected.", - [14]: "End tag name was expected.", - [15]: "Whitespace was expected.", - [16]: "Unexpected '<!--' in comment.", - [17]: `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<).`, - [18]: "Unquoted attribute value cannot contain U+0022 (\"), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).", - [19]: "Attribute name cannot start with '='.", - [21]: "'<?' is allowed only in XML context.", - [20]: `Unexpected null character.`, - [22]: "Illegal '/' in tags.", - // Vue-specific parse errors - [23]: "Invalid end tag.", - [24]: "Element is missing end tag.", - [25]: "Interpolation end sign was not found.", - [27]: "End bracket for dynamic directive argument was not found. Note that dynamic directive argument cannot contain spaces.", - [26]: "Legal directive name was expected.", - // transform errors - [28]: `v-if/v-else-if is missing expression.`, - [29]: `v-if/else branches must use unique keys.`, - [30]: `v-else/v-else-if has no adjacent v-if or v-else-if.`, - [31]: `v-for is missing expression.`, - [32]: `v-for has invalid expression.`, - [33]: `<template v-for> key should be placed on the <template> tag.`, - [34]: `v-bind is missing expression.`, - [52]: `v-bind with same-name shorthand only allows static argument.`, - [35]: `v-on is missing expression.`, - [36]: `Unexpected custom directive on <slot> outlet.`, - [37]: `Mixed v-slot usage on both the component and nested <template>. When there are multiple named slots, all slots should use <template> syntax to avoid scope ambiguity.`, - [38]: `Duplicate slot names found. `, - [39]: `Extraneous children found when component already has explicitly named default slot. These children will be ignored.`, - [40]: `v-slot can only be used on components or <template> tags.`, - [41]: `v-model is missing expression.`, - [42]: `v-model value must be a valid JavaScript member expression.`, - [43]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`, - [44]: `v-model cannot be used on a prop, because local prop bindings are not writable. -Use a v-bind binding combined with a v-on listener that emits update:x event instead.`, - [45]: `Error parsing JavaScript expression: `, - [46]: `<KeepAlive> expects exactly one child component.`, - [51]: `@vnode-* hooks in templates are no longer supported. Use the vue: prefix instead. For example, @vnode-mounted should be changed to @vue:mounted. @vnode-* hooks support has been removed in 3.4.`, - // generic errors - [47]: `"prefixIdentifiers" option is not supported in this build of compiler.`, - [48]: `ES module mode is not supported in this build of compiler.`, - [49]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`, - [50]: `"scopeId" option is only supported in module mode.`, - // just to fulfill types - [53]: `` - }; - - function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var f = n.default; - if (typeof f == "function") { - var a = function a() { - if (this instanceof a) { - return Reflect.construct(f, arguments, this.constructor); - } - return f.apply(this, arguments); - }; - a.prototype = f.prototype; - } else a = {}; - Object.defineProperty(a, '__esModule', { value: true }); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; - } - - var lib = {}; - - Object.defineProperty(lib, '__esModule', { - value: true - }); - function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - return target; - } - class Position { - constructor(line, col, index) { - this.line = void 0; - this.column = void 0; - this.index = void 0; - this.line = line; - this.column = col; - this.index = index; - } - } - class SourceLocation { - constructor(start, end) { - this.start = void 0; - this.end = void 0; - this.filename = void 0; - this.identifierName = void 0; - this.start = start; - this.end = end; - } - } - function createPositionWithColumnOffset(position, columnOffset) { - const { - line, - column, - index - } = position; - return new Position(line, column + columnOffset, index + columnOffset); - } - const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"; - var ModuleErrors = { - ImportMetaOutsideModule: { - message: `import.meta may appear only with 'sourceType: "module"'`, - code - }, - ImportOutsideModule: { - message: `'import' and 'export' may appear only with 'sourceType: "module"'`, - code - } - }; - const NodeDescriptions = { - ArrayPattern: "array destructuring pattern", - AssignmentExpression: "assignment expression", - AssignmentPattern: "assignment expression", - ArrowFunctionExpression: "arrow function expression", - ConditionalExpression: "conditional expression", - CatchClause: "catch clause", - ForOfStatement: "for-of statement", - ForInStatement: "for-in statement", - ForStatement: "for-loop", - FormalParameters: "function parameter list", - Identifier: "identifier", - ImportSpecifier: "import specifier", - ImportDefaultSpecifier: "import default specifier", - ImportNamespaceSpecifier: "import namespace specifier", - ObjectPattern: "object destructuring pattern", - ParenthesizedExpression: "parenthesized expression", - RestElement: "rest element", - UpdateExpression: { - true: "prefix operation", - false: "postfix operation" - }, - VariableDeclarator: "variable declaration", - YieldExpression: "yield expression" - }; - const toNodeDescription = ({ - type, - prefix - }) => type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[String(prefix)] : NodeDescriptions[type]; - var StandardErrors = { - AccessorIsGenerator: ({ - kind - }) => `A ${kind}ter cannot be a generator.`, - ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", - AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", - AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", - AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", - AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", - AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.", - AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", - AwaitNotInAsyncFunction: "'await' is only allowed within async functions.", - BadGetterArity: "A 'get' accessor must not have any formal parameters.", - BadSetterArity: "A 'set' accessor must have exactly one formal parameter.", - BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.", - ConstructorClassField: "Classes may not have a field named 'constructor'.", - ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", - ConstructorIsAccessor: "Class constructor may not be an accessor.", - ConstructorIsAsync: "Constructor can't be an async function.", - ConstructorIsGenerator: "Constructor can't be a generator.", - DeclarationMissingInitializer: ({ - kind - }) => `Missing initializer in ${kind} declaration.`, - DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.", - DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.", - DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.", - DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", - DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.", - DecoratorSemicolon: "Decorators must not be followed by a semicolon.", - DecoratorStaticBlock: "Decorators can't be used with a static block.", - DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.', - DeletePrivateField: "Deleting a private field is not allowed.", - DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", - DuplicateConstructor: "Duplicate constructor in the same class.", - DuplicateDefaultExport: "Only one default export allowed per module.", - DuplicateExport: ({ - exportName - }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`, - DuplicateProto: "Redefinition of __proto__ property.", - DuplicateRegExpFlags: "Duplicate regular expression flag.", - DynamicImportPhaseRequiresImportExpressions: ({ - phase - }) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`, - ElementAfterRest: "Rest element must be last element.", - EscapedCharNotAnIdentifier: "Invalid Unicode escape.", - ExportBindingIsString: ({ - localName, - exportName - }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`, - ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", - ForInOfLoopInitializer: ({ - type - }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`, - ForInUsing: "For-in loop may not start with 'using' declaration.", - ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", - ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", - GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", - IllegalBreakContinue: ({ - type - }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`, - IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", - IllegalReturn: "'return' outside of function.", - ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedAssertSyntax: true` option in the import attributes plugin to suppress this error.", - ImportBindingIsString: ({ - importName - }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`, - ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.", - ImportCallArity: ({ - maxArgumentCount - }) => `\`import()\` requires exactly ${maxArgumentCount === 1 ? "one argument" : "one or two arguments"}.`, - ImportCallNotNewExpression: "Cannot use new with import(...).", - ImportCallSpreadArgument: "`...` is not allowed in `import()`.", - ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.", - ImportReflectionHasAssertion: "`import module x` cannot have assertions.", - ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.', - IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.", - InvalidBigIntLiteral: "Invalid BigIntLiteral.", - InvalidCodePoint: "Code point out of bounds.", - InvalidCoverInitializedName: "Invalid shorthand property initializer.", - InvalidDecimal: "Invalid decimal.", - InvalidDigit: ({ - radix - }) => `Expected number in radix ${radix}.`, - InvalidEscapeSequence: "Bad character escape sequence.", - InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", - InvalidEscapedReservedWord: ({ - reservedWord - }) => `Escape sequence in keyword ${reservedWord}.`, - InvalidIdentifier: ({ - identifierName - }) => `Invalid identifier ${identifierName}.`, - InvalidLhs: ({ - ancestor - }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`, - InvalidLhsBinding: ({ - ancestor - }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`, - InvalidLhsOptionalChaining: ({ - ancestor - }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`, - InvalidNumber: "Invalid number.", - InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", - InvalidOrUnexpectedToken: ({ - unexpected - }) => `Unexpected character '${unexpected}'.`, - InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", - InvalidPrivateFieldResolution: ({ - identifierName - }) => `Private name #${identifierName} is not defined.`, - InvalidPropertyBindingPattern: "Binding member expression.", - InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.", - InvalidRestAssignmentPattern: "Invalid rest operator's argument.", - LabelRedeclaration: ({ - labelName - }) => `Label '${labelName}' is already declared.`, - LetInLexicalBinding: "'let' is disallowed as a lexically bound name.", - LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", - MalformedRegExpFlags: "Invalid regular expression flag.", - MissingClassName: "A class name is required.", - MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", - MissingSemicolon: "Missing semicolon.", - MissingPlugin: ({ - missingPlugin - }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, - MissingOneOfPlugins: ({ - missingPlugin - }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, - MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", - MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", - ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.", - ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", - ModuleAttributesWithDuplicateKeys: ({ - key - }) => `Duplicate key "${key}" is not allowed in module attributes.`, - ModuleExportNameHasLoneSurrogate: ({ - surrogateCharCode - }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`, - ModuleExportUndefined: ({ - localName - }) => `Export '${localName}' is not defined.`, - MultipleDefaultsInSwitch: "Multiple default clauses.", - NewlineAfterThrow: "Illegal newline after throw.", - NoCatchOrFinally: "Missing catch or finally clause.", - NumberIdentifier: "Identifier directly after number.", - NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", - ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", - OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", - OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", - OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", - ParamDupe: "Argument name clash.", - PatternHasAccessor: "Object pattern can't contain getter or setter.", - PatternHasMethod: "Object pattern can't contain methods.", - PrivateInExpectedIn: ({ - identifierName - }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`, - PrivateNameRedeclaration: ({ - identifierName - }) => `Duplicate private name #${identifierName}.`, - RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", - RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", - RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", - RecordNoProto: "'__proto__' is not allowed in Record expressions.", - RestTrailingComma: "Unexpected trailing comma after rest element.", - SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.", - SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", - SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.', - StaticPrototype: "Classes may not have static property named prototype.", - SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", - SuperPrivateField: "Private fields can't be accessed on super.", - TrailingDecorator: "Decorators must be attached to a class element.", - TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", - TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", - TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", - UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", - UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.', - UnexpectedDigitAfterHash: "Unexpected digit after hash token.", - UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", - UnexpectedKeyword: ({ - keyword - }) => `Unexpected keyword '${keyword}'.`, - UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", - UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", - UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", - UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", - UnexpectedPrivateField: "Unexpected private name.", - UnexpectedReservedWord: ({ - reservedWord - }) => `Unexpected reserved word '${reservedWord}'.`, - UnexpectedSuper: "'super' is only allowed in object methods and classes.", - UnexpectedToken: ({ - expected, - unexpected - }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`, - UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", - UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.", - UnsupportedBind: "Binding should be performed on object property.", - UnsupportedDecoratorExport: "A decorated export must export a class declaration.", - UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", - UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", - UnsupportedMetaProperty: ({ - target, - onlyValidPropertyName - }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`, - UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", - UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", - UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", - UnterminatedComment: "Unterminated comment.", - UnterminatedRegExp: "Unterminated regular expression.", - UnterminatedString: "Unterminated string constant.", - UnterminatedTemplate: "Unterminated template.", - UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", - VarRedeclaration: ({ - identifierName - }) => `Identifier '${identifierName}' has already been declared.`, - YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", - YieldInParameter: "Yield expression is not allowed in formal parameters.", - ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." - }; - var StrictModeErrors = { - StrictDelete: "Deleting local variable in strict mode.", - StrictEvalArguments: ({ - referenceName - }) => `Assigning to '${referenceName}' in strict mode.`, - StrictEvalArgumentsBinding: ({ - bindingName - }) => `Binding '${bindingName}' in strict mode.`, - StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", - StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", - StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", - StrictWith: "'with' in strict mode." - }; - const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); - var PipelineOperatorErrors = { - PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.", - PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', - PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", - PipeTopicUnconfiguredToken: ({ - token - }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`, - PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", - PipeUnparenthesizedBody: ({ - type - }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({ - type - })}; please wrap it in parentheses.`, - PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.', - PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.", - PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.", - PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.", - PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.", - PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.' - }; - const _excluded = ["toMessage"], - _excluded2 = ["message"]; - function defineHidden(obj, key, value) { - Object.defineProperty(obj, key, { - enumerable: false, - configurable: true, - value - }); - } - function toParseErrorConstructor(_ref) { - let { - toMessage - } = _ref, - properties = _objectWithoutPropertiesLoose(_ref, _excluded); - return function constructor(loc, details) { - const error = new SyntaxError(); - Object.assign(error, properties, { - loc, - pos: loc.index - }); - if ("missingPlugin" in details) { - Object.assign(error, { - missingPlugin: details.missingPlugin - }); - } - defineHidden(error, "clone", function clone(overrides = {}) { - var _overrides$loc; - const { - line, - column, - index - } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc; - return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details)); - }); - defineHidden(error, "details", details); - Object.defineProperty(error, "message", { - configurable: true, - get() { - const message = `${toMessage(details)} (${loc.line}:${loc.column})`; - this.message = message; - return message; - }, - set(value) { - Object.defineProperty(this, "message", { - value, - writable: true - }); - } - }); - return error; - }; - } - function ParseErrorEnum(argument, syntaxPlugin) { - if (Array.isArray(argument)) { - return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]); - } - const ParseErrorConstructors = {}; - for (const reasonCode of Object.keys(argument)) { - const template = argument[reasonCode]; - const _ref2 = typeof template === "string" ? { - message: () => template - } : typeof template === "function" ? { - message: template - } : template, - { - message - } = _ref2, - rest = _objectWithoutPropertiesLoose(_ref2, _excluded2); - const toMessage = typeof message === "string" ? () => message : message; - ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({ - code: "BABEL_PARSER_SYNTAX_ERROR", - reasonCode, - toMessage - }, syntaxPlugin ? { - syntaxPlugin - } : {}, rest)); - } - return ParseErrorConstructors; - } - const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors)); - const { - defineProperty - } = Object; - const toUnenumerable = (object, key) => defineProperty(object, key, { - enumerable: false, - value: object[key] - }); - function toESTreeLocation(node) { - node.loc.start && toUnenumerable(node.loc.start, "index"); - node.loc.end && toUnenumerable(node.loc.end, "index"); - return node; - } - var estree = superClass => class ESTreeParserMixin extends superClass { - parse() { - const file = toESTreeLocation(super.parse()); - if (this.options.tokens) { - file.tokens = file.tokens.map(toESTreeLocation); - } - return file; - } - parseRegExpLiteral({ - pattern, - flags - }) { - let regex = null; - try { - regex = new RegExp(pattern, flags); - } catch (e) { } - const node = this.estreeParseLiteral(regex); - node.regex = { - pattern, - flags - }; - return node; - } - parseBigIntLiteral(value) { - let bigInt; - try { - bigInt = BigInt(value); - } catch (_unused) { - bigInt = null; - } - const node = this.estreeParseLiteral(bigInt); - node.bigint = String(node.value || value); - return node; - } - parseDecimalLiteral(value) { - const decimal = null; - const node = this.estreeParseLiteral(decimal); - node.decimal = String(node.value || value); - return node; - } - estreeParseLiteral(value) { - return this.parseLiteral(value, "Literal"); - } - parseStringLiteral(value) { - return this.estreeParseLiteral(value); - } - parseNumericLiteral(value) { - return this.estreeParseLiteral(value); - } - parseNullLiteral() { - return this.estreeParseLiteral(null); - } - parseBooleanLiteral(value) { - return this.estreeParseLiteral(value); - } - directiveToStmt(directive) { - const expression = directive.value; - delete directive.value; - expression.type = "Literal"; - expression.raw = expression.extra.raw; - expression.value = expression.extra.expressionValue; - const stmt = directive; - stmt.type = "ExpressionStatement"; - stmt.expression = expression; - stmt.directive = expression.extra.rawValue; - delete expression.extra; - return stmt; - } - initFunction(node, isAsync) { - super.initFunction(node, isAsync); - node.expression = false; - } - checkDeclaration(node) { - if (node != null && this.isObjectProperty(node)) { - this.checkDeclaration(node.value); - } else { - super.checkDeclaration(node); - } - } - getObjectOrClassMethodParams(method) { - return method.value.params; - } - isValidDirective(stmt) { - var _stmt$expression$extr; - return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized); - } - parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { - super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse); - const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); - node.body = directiveStatements.concat(node.body); - delete node.directives; - } - pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { - this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true); - if (method.typeParameters) { - method.value.typeParameters = method.typeParameters; - delete method.typeParameters; - } - classBody.body.push(method); - } - parsePrivateName() { - const node = super.parsePrivateName(); - { - if (!this.getPluginOption("estree", "classFeatures")) { - return node; - } - } - return this.convertPrivateNameToPrivateIdentifier(node); - } - convertPrivateNameToPrivateIdentifier(node) { - const name = super.getPrivateNameSV(node); - node = node; - delete node.id; - node.name = name; - node.type = "PrivateIdentifier"; - return node; - } - isPrivateName(node) { - { - if (!this.getPluginOption("estree", "classFeatures")) { - return super.isPrivateName(node); - } - } - return node.type === "PrivateIdentifier"; - } - getPrivateNameSV(node) { - { - if (!this.getPluginOption("estree", "classFeatures")) { - return super.getPrivateNameSV(node); - } - } - return node.name; - } - parseLiteral(value, type) { - const node = super.parseLiteral(value, type); - node.raw = node.extra.raw; - delete node.extra; - return node; - } - parseFunctionBody(node, allowExpression, isMethod = false) { - super.parseFunctionBody(node, allowExpression, isMethod); - node.expression = node.body.type !== "BlockStatement"; - } - parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { - let funcNode = this.startNode(); - funcNode.kind = node.kind; - funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); - funcNode.type = "FunctionExpression"; - delete funcNode.kind; - node.value = funcNode; - if (type === "ClassPrivateMethod") { - node.computed = false; - } - return this.finishNode(node, "MethodDefinition"); - } - parseClassProperty(...args) { - const propertyNode = super.parseClassProperty(...args); - { - if (!this.getPluginOption("estree", "classFeatures")) { - return propertyNode; - } - } - propertyNode.type = "PropertyDefinition"; - return propertyNode; - } - parseClassPrivateProperty(...args) { - const propertyNode = super.parseClassPrivateProperty(...args); - { - if (!this.getPluginOption("estree", "classFeatures")) { - return propertyNode; - } - } - propertyNode.type = "PropertyDefinition"; - propertyNode.computed = false; - return propertyNode; - } - parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { - const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor); - if (node) { - node.type = "Property"; - if (node.kind === "method") { - node.kind = "init"; - } - node.shorthand = false; - } - return node; - } - parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { - const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); - if (node) { - node.kind = "init"; - node.type = "Property"; - } - return node; - } - isValidLVal(type, isUnparenthesizedInAssign, binding) { - return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding); - } - isAssignable(node, isBinding) { - if (node != null && this.isObjectProperty(node)) { - return this.isAssignable(node.value, isBinding); - } - return super.isAssignable(node, isBinding); - } - toAssignable(node, isLHS = false) { - if (node != null && this.isObjectProperty(node)) { - const { - key, - value - } = node; - if (this.isPrivateName(key)) { - this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); - } - this.toAssignable(value, isLHS); - } else { - super.toAssignable(node, isLHS); - } - } - toAssignableObjectExpressionProp(prop, isLast, isLHS) { - if (prop.kind === "get" || prop.kind === "set") { - this.raise(Errors.PatternHasAccessor, prop.key); - } else if (prop.method) { - this.raise(Errors.PatternHasMethod, prop.key); - } else { - super.toAssignableObjectExpressionProp(prop, isLast, isLHS); - } - } - finishCallExpression(unfinished, optional) { - const node = super.finishCallExpression(unfinished, optional); - if (node.callee.type === "Import") { - node.type = "ImportExpression"; - node.source = node.arguments[0]; - if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { - var _node$arguments$, _node$arguments$2; - node.options = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null; - node.attributes = (_node$arguments$2 = node.arguments[1]) != null ? _node$arguments$2 : null; - } - delete node.arguments; - delete node.callee; - } - return node; - } - toReferencedArguments(node) { - if (node.type === "ImportExpression") { - return; - } - super.toReferencedArguments(node); - } - parseExport(unfinished, decorators) { - const exportStartLoc = this.state.lastTokStartLoc; - const node = super.parseExport(unfinished, decorators); - switch (node.type) { - case "ExportAllDeclaration": - node.exported = null; - break; - case "ExportNamedDeclaration": - if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { - node.type = "ExportAllDeclaration"; - node.exported = node.specifiers[0].exported; - delete node.specifiers; - } - case "ExportDefaultDeclaration": - { - var _declaration$decorato; - const { - declaration - } = node; - if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) { - this.resetStartLocation(node, exportStartLoc); - } - } - break; - } - return node; - } - parseSubscript(base, startLoc, noCalls, state) { - const node = super.parseSubscript(base, startLoc, noCalls, state); - if (state.optionalChainMember) { - if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") { - node.type = node.type.substring(8); - } - if (state.stop) { - const chain = this.startNodeAtNode(node); - chain.expression = node; - return this.finishNode(chain, "ChainExpression"); - } - } else if (node.type === "MemberExpression" || node.type === "CallExpression") { - node.optional = false; - } - return node; - } - isOptionalMemberExpression(node) { - if (node.type === "ChainExpression") { - return node.expression.type === "MemberExpression"; - } - return super.isOptionalMemberExpression(node); - } - hasPropertyAsPrivateName(node) { - if (node.type === "ChainExpression") { - node = node.expression; - } - return super.hasPropertyAsPrivateName(node); - } - isObjectProperty(node) { - return node.type === "Property" && node.kind === "init" && !node.method; - } - isObjectMethod(node) { - return node.method || node.kind === "get" || node.kind === "set"; - } - finishNodeAt(node, type, endLoc) { - return toESTreeLocation(super.finishNodeAt(node, type, endLoc)); - } - resetStartLocation(node, startLoc) { - super.resetStartLocation(node, startLoc); - toESTreeLocation(node); - } - resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { - super.resetEndLocation(node, endLoc); - toESTreeLocation(node); - } - }; - class TokContext { - constructor(token, preserveSpace) { - this.token = void 0; - this.preserveSpace = void 0; - this.token = token; - this.preserveSpace = !!preserveSpace; - } - } - const types$1 = { - brace: new TokContext("{"), - j_oTag: new TokContext("<tag"), - j_cTag: new TokContext("</tag"), - j_expr: new TokContext("<tag>...</tag>", true) - }; - { - types$1.template = new TokContext("`", true); - } - const beforeExpr = true; - const startsExpr = true; - const isLoop = true; - const isAssign = true; - const prefix = true; - const postfix = true; - class ExportedTokenType { - constructor(label, conf = {}) { - this.label = void 0; - this.keyword = void 0; - this.beforeExpr = void 0; - this.startsExpr = void 0; - this.rightAssociative = void 0; - this.isLoop = void 0; - this.isAssign = void 0; - this.prefix = void 0; - this.postfix = void 0; - this.binop = void 0; - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.rightAssociative = !!conf.rightAssociative; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop != null ? conf.binop : null; - { - this.updateContext = null; - } - } - } - const keywords$1 = new Map(); - function createKeyword(name, options = {}) { - options.keyword = name; - const token = createToken(name, options); - keywords$1.set(name, token); - return token; - } - function createBinop(name, binop) { - return createToken(name, { - beforeExpr, - binop - }); - } - let tokenTypeCounter = -1; - const tokenTypes$1 = []; - const tokenLabels = []; - const tokenBinops = []; - const tokenBeforeExprs = []; - const tokenStartsExprs = []; - const tokenPrefixes = []; - function createToken(name, options = {}) { - var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix; - ++tokenTypeCounter; - tokenLabels.push(name); - tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1); - tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false); - tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false); - tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false); - tokenTypes$1.push(new ExportedTokenType(name, options)); - return tokenTypeCounter; - } - function createKeywordLike(name, options = {}) { - var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2; - ++tokenTypeCounter; - keywords$1.set(name, tokenTypeCounter); - tokenLabels.push(name); - tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1); - tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false); - tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false); - tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false); - tokenTypes$1.push(new ExportedTokenType("name", options)); - return tokenTypeCounter; - } - const tt = { - bracketL: createToken("[", { - beforeExpr, - startsExpr - }), - bracketHashL: createToken("#[", { - beforeExpr, - startsExpr - }), - bracketBarL: createToken("[|", { - beforeExpr, - startsExpr - }), - bracketR: createToken("]"), - bracketBarR: createToken("|]"), - braceL: createToken("{", { - beforeExpr, - startsExpr - }), - braceBarL: createToken("{|", { - beforeExpr, - startsExpr - }), - braceHashL: createToken("#{", { - beforeExpr, - startsExpr - }), - braceR: createToken("}"), - braceBarR: createToken("|}"), - parenL: createToken("(", { - beforeExpr, - startsExpr - }), - parenR: createToken(")"), - comma: createToken(",", { - beforeExpr - }), - semi: createToken(";", { - beforeExpr - }), - colon: createToken(":", { - beforeExpr - }), - doubleColon: createToken("::", { - beforeExpr - }), - dot: createToken("."), - question: createToken("?", { - beforeExpr - }), - questionDot: createToken("?."), - arrow: createToken("=>", { - beforeExpr - }), - template: createToken("template"), - ellipsis: createToken("...", { - beforeExpr - }), - backQuote: createToken("`", { - startsExpr - }), - dollarBraceL: createToken("${", { - beforeExpr, - startsExpr - }), - templateTail: createToken("...`", { - startsExpr - }), - templateNonTail: createToken("...${", { - beforeExpr, - startsExpr - }), - at: createToken("@"), - hash: createToken("#", { - startsExpr - }), - interpreterDirective: createToken("#!..."), - eq: createToken("=", { - beforeExpr, - isAssign - }), - assign: createToken("_=", { - beforeExpr, - isAssign - }), - slashAssign: createToken("_=", { - beforeExpr, - isAssign - }), - xorAssign: createToken("_=", { - beforeExpr, - isAssign - }), - moduloAssign: createToken("_=", { - beforeExpr, - isAssign - }), - incDec: createToken("++/--", { - prefix, - postfix, - startsExpr - }), - bang: createToken("!", { - beforeExpr, - prefix, - startsExpr - }), - tilde: createToken("~", { - beforeExpr, - prefix, - startsExpr - }), - doubleCaret: createToken("^^", { - startsExpr - }), - doubleAt: createToken("@@", { - startsExpr - }), - pipeline: createBinop("|>", 0), - nullishCoalescing: createBinop("??", 1), - logicalOR: createBinop("||", 1), - logicalAND: createBinop("&&", 2), - bitwiseOR: createBinop("|", 3), - bitwiseXOR: createBinop("^", 4), - bitwiseAND: createBinop("&", 5), - equality: createBinop("==/!=/===/!==", 6), - lt: createBinop("</>/<=/>=", 7), - gt: createBinop("</>/<=/>=", 7), - relational: createBinop("</>/<=/>=", 7), - bitShift: createBinop("<</>>/>>>", 8), - bitShiftL: createBinop("<</>>/>>>", 8), - bitShiftR: createBinop("<</>>/>>>", 8), - plusMin: createToken("+/-", { - beforeExpr, - binop: 9, - prefix, - startsExpr - }), - modulo: createToken("%", { - binop: 10, - startsExpr - }), - star: createToken("*", { - binop: 10 - }), - slash: createBinop("/", 10), - exponent: createToken("**", { - beforeExpr, - binop: 11, - rightAssociative: true - }), - _in: createKeyword("in", { - beforeExpr, - binop: 7 - }), - _instanceof: createKeyword("instanceof", { - beforeExpr, - binop: 7 - }), - _break: createKeyword("break"), - _case: createKeyword("case", { - beforeExpr - }), - _catch: createKeyword("catch"), - _continue: createKeyword("continue"), - _debugger: createKeyword("debugger"), - _default: createKeyword("default", { - beforeExpr - }), - _else: createKeyword("else", { - beforeExpr - }), - _finally: createKeyword("finally"), - _function: createKeyword("function", { - startsExpr - }), - _if: createKeyword("if"), - _return: createKeyword("return", { - beforeExpr - }), - _switch: createKeyword("switch"), - _throw: createKeyword("throw", { - beforeExpr, - prefix, - startsExpr - }), - _try: createKeyword("try"), - _var: createKeyword("var"), - _const: createKeyword("const"), - _with: createKeyword("with"), - _new: createKeyword("new", { - beforeExpr, - startsExpr - }), - _this: createKeyword("this", { - startsExpr - }), - _super: createKeyword("super", { - startsExpr - }), - _class: createKeyword("class", { - startsExpr - }), - _extends: createKeyword("extends", { - beforeExpr - }), - _export: createKeyword("export"), - _import: createKeyword("import", { - startsExpr - }), - _null: createKeyword("null", { - startsExpr - }), - _true: createKeyword("true", { - startsExpr - }), - _false: createKeyword("false", { - startsExpr - }), - _typeof: createKeyword("typeof", { - beforeExpr, - prefix, - startsExpr - }), - _void: createKeyword("void", { - beforeExpr, - prefix, - startsExpr - }), - _delete: createKeyword("delete", { - beforeExpr, - prefix, - startsExpr - }), - _do: createKeyword("do", { - isLoop, - beforeExpr - }), - _for: createKeyword("for", { - isLoop - }), - _while: createKeyword("while", { - isLoop - }), - _as: createKeywordLike("as", { - startsExpr - }), - _assert: createKeywordLike("assert", { - startsExpr - }), - _async: createKeywordLike("async", { - startsExpr - }), - _await: createKeywordLike("await", { - startsExpr - }), - _defer: createKeywordLike("defer", { - startsExpr - }), - _from: createKeywordLike("from", { - startsExpr - }), - _get: createKeywordLike("get", { - startsExpr - }), - _let: createKeywordLike("let", { - startsExpr - }), - _meta: createKeywordLike("meta", { - startsExpr - }), - _of: createKeywordLike("of", { - startsExpr - }), - _sent: createKeywordLike("sent", { - startsExpr - }), - _set: createKeywordLike("set", { - startsExpr - }), - _source: createKeywordLike("source", { - startsExpr - }), - _static: createKeywordLike("static", { - startsExpr - }), - _using: createKeywordLike("using", { - startsExpr - }), - _yield: createKeywordLike("yield", { - startsExpr - }), - _asserts: createKeywordLike("asserts", { - startsExpr - }), - _checks: createKeywordLike("checks", { - startsExpr - }), - _exports: createKeywordLike("exports", { - startsExpr - }), - _global: createKeywordLike("global", { - startsExpr - }), - _implements: createKeywordLike("implements", { - startsExpr - }), - _intrinsic: createKeywordLike("intrinsic", { - startsExpr - }), - _infer: createKeywordLike("infer", { - startsExpr - }), - _is: createKeywordLike("is", { - startsExpr - }), - _mixins: createKeywordLike("mixins", { - startsExpr - }), - _proto: createKeywordLike("proto", { - startsExpr - }), - _require: createKeywordLike("require", { - startsExpr - }), - _satisfies: createKeywordLike("satisfies", { - startsExpr - }), - _keyof: createKeywordLike("keyof", { - startsExpr - }), - _readonly: createKeywordLike("readonly", { - startsExpr - }), - _unique: createKeywordLike("unique", { - startsExpr - }), - _abstract: createKeywordLike("abstract", { - startsExpr - }), - _declare: createKeywordLike("declare", { - startsExpr - }), - _enum: createKeywordLike("enum", { - startsExpr - }), - _module: createKeywordLike("module", { - startsExpr - }), - _namespace: createKeywordLike("namespace", { - startsExpr - }), - _interface: createKeywordLike("interface", { - startsExpr - }), - _type: createKeywordLike("type", { - startsExpr - }), - _opaque: createKeywordLike("opaque", { - startsExpr - }), - name: createToken("name", { - startsExpr - }), - string: createToken("string", { - startsExpr - }), - num: createToken("num", { - startsExpr - }), - bigint: createToken("bigint", { - startsExpr - }), - decimal: createToken("decimal", { - startsExpr - }), - regexp: createToken("regexp", { - startsExpr - }), - privateName: createToken("#name", { - startsExpr - }), - eof: createToken("eof"), - jsxName: createToken("jsxName"), - jsxText: createToken("jsxText", { - beforeExpr: true - }), - jsxTagStart: createToken("jsxTagStart", { - startsExpr: true - }), - jsxTagEnd: createToken("jsxTagEnd"), - placeholder: createToken("%%", { - startsExpr: true - }) - }; - function tokenIsIdentifier(token) { - return token >= 93 && token <= 132; - } - function tokenKeywordOrIdentifierIsKeyword(token) { - return token <= 92; - } - function tokenIsKeywordOrIdentifier(token) { - return token >= 58 && token <= 132; - } - function tokenIsLiteralPropertyName(token) { - return token >= 58 && token <= 136; - } - function tokenComesBeforeExpression(token) { - return tokenBeforeExprs[token]; - } - function tokenCanStartExpression(token) { - return tokenStartsExprs[token]; - } - function tokenIsAssignment(token) { - return token >= 29 && token <= 33; - } - function tokenIsFlowInterfaceOrTypeOrOpaque(token) { - return token >= 129 && token <= 131; - } - function tokenIsLoop(token) { - return token >= 90 && token <= 92; - } - function tokenIsKeyword(token) { - return token >= 58 && token <= 92; - } - function tokenIsOperator(token) { - return token >= 39 && token <= 59; - } - function tokenIsPostfix(token) { - return token === 34; - } - function tokenIsPrefix(token) { - return tokenPrefixes[token]; - } - function tokenIsTSTypeOperator(token) { - return token >= 121 && token <= 123; - } - function tokenIsTSDeclarationStart(token) { - return token >= 124 && token <= 130; - } - function tokenLabelName(token) { - return tokenLabels[token]; - } - function tokenOperatorPrecedence(token) { - return tokenBinops[token]; - } - function tokenIsRightAssociative(token) { - return token === 57; - } - function tokenIsTemplate(token) { - return token >= 24 && token <= 25; - } - function getExportedToken(token) { - return tokenTypes$1[token]; - } - { - tokenTypes$1[8].updateContext = context => { - context.pop(); - }; - tokenTypes$1[5].updateContext = tokenTypes$1[7].updateContext = tokenTypes$1[23].updateContext = context => { - context.push(types$1.brace); - }; - tokenTypes$1[22].updateContext = context => { - if (context[context.length - 1] === types$1.template) { - context.pop(); - } else { - context.push(types$1.template); - } - }; - tokenTypes$1[142].updateContext = context => { - context.push(types$1.j_expr, types$1.j_oTag); - }; - } - let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; - let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; - const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; - const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; - function isInAstralSet(code, set) { - let pos = 0x10000; - for (let i = 0, length = set.length; i < length; i += 2) { - pos += set[i]; - if (pos > code) return false; - pos += set[i + 1]; - if (pos >= code) return true; - } - return false; - } - function isIdentifierStart(code) { - if (code < 65) return code === 36; - if (code <= 90) return true; - if (code < 97) return code === 95; - if (code <= 122) return true; - if (code <= 0xffff) { - return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - } - return isInAstralSet(code, astralIdentifierStartCodes); - } - function isIdentifierChar(code) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code <= 90) return true; - if (code < 97) return code === 95; - if (code <= 122) return true; - if (code <= 0xffff) { - return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); - } - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); - } - const reservedWords = { - keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], - strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], - strictBind: ["eval", "arguments"] - }; - const keywords = new Set(reservedWords.keyword); - const reservedWordsStrictSet = new Set(reservedWords.strict); - const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); - function isReservedWord(word, inModule) { - return inModule && word === "await" || word === "enum"; - } - function isStrictReservedWord(word, inModule) { - return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); - } - function isStrictBindOnlyReservedWord(word) { - return reservedWordsStrictBindSet.has(word); - } - function isStrictBindReservedWord(word, inModule) { - return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); - } - function isKeyword(word) { - return keywords.has(word); - } - function isIteratorStart(current, next, next2) { - return current === 64 && next === 64 && isIdentifierStart(next2); - } - const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); - function canBeReservedWord(word) { - return reservedWordLikeSet.has(word); - } - class Scope { - constructor(flags) { - this.flags = 0; - this.names = new Map(); - this.firstLexicalName = ""; - this.flags = flags; - } - } - class ScopeHandler { - constructor(parser, inModule) { - this.parser = void 0; - this.scopeStack = []; - this.inModule = void 0; - this.undefinedExports = new Map(); - this.parser = parser; - this.inModule = inModule; - } - get inTopLevel() { - return (this.currentScope().flags & 1) > 0; - } - get inFunction() { - return (this.currentVarScopeFlags() & 2) > 0; - } - get allowSuper() { - return (this.currentThisScopeFlags() & 16) > 0; - } - get allowDirectSuper() { - return (this.currentThisScopeFlags() & 32) > 0; - } - get inClass() { - return (this.currentThisScopeFlags() & 64) > 0; - } - get inClassAndNotInNonArrowFunction() { - const flags = this.currentThisScopeFlags(); - return (flags & 64) > 0 && (flags & 2) === 0; - } - get inStaticBlock() { - for (let i = this.scopeStack.length - 1; ; i--) { - const { - flags - } = this.scopeStack[i]; - if (flags & 128) { - return true; - } - if (flags & (387 | 64)) { - return false; - } - } - } - get inNonArrowFunction() { - return (this.currentThisScopeFlags() & 2) > 0; - } - get treatFunctionsAsVar() { - return this.treatFunctionsAsVarInScope(this.currentScope()); - } - createScope(flags) { - return new Scope(flags); - } - enter(flags) { - this.scopeStack.push(this.createScope(flags)); - } - exit() { - const scope = this.scopeStack.pop(); - return scope.flags; - } - treatFunctionsAsVarInScope(scope) { - return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1); - } - declareName(name, bindingType, loc) { - let scope = this.currentScope(); - if (bindingType & 8 || bindingType & 16) { - this.checkRedeclarationInScope(scope, name, bindingType, loc); - let type = scope.names.get(name) || 0; - if (bindingType & 16) { - type = type | 4; - } else { - if (!scope.firstLexicalName) { - scope.firstLexicalName = name; - } - type = type | 2; - } - scope.names.set(name, type); - if (bindingType & 8) { - this.maybeExportDefined(scope, name); - } - } else if (bindingType & 4) { - for (let i = this.scopeStack.length - 1; i >= 0; --i) { - scope = this.scopeStack[i]; - this.checkRedeclarationInScope(scope, name, bindingType, loc); - scope.names.set(name, (scope.names.get(name) || 0) | 1); - this.maybeExportDefined(scope, name); - if (scope.flags & 387) break; - } - } - if (this.parser.inModule && scope.flags & 1) { - this.undefinedExports.delete(name); - } - } - maybeExportDefined(scope, name) { - if (this.parser.inModule && scope.flags & 1) { - this.undefinedExports.delete(name); - } - } - checkRedeclarationInScope(scope, name, bindingType, loc) { - if (this.isRedeclaredInScope(scope, name, bindingType)) { - this.parser.raise(Errors.VarRedeclaration, loc, { - identifierName: name - }); - } - } - isRedeclaredInScope(scope, name, bindingType) { - if (!(bindingType & 1)) return false; - if (bindingType & 8) { - return scope.names.has(name); - } - const type = scope.names.get(name); - if (bindingType & 16) { - return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0; - } - return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0; - } - checkLocalExport(id) { - const { - name - } = id; - const topLevelScope = this.scopeStack[0]; - if (!topLevelScope.names.has(name)) { - this.undefinedExports.set(name, id.loc.start); - } - } - currentScope() { - return this.scopeStack[this.scopeStack.length - 1]; - } - currentVarScopeFlags() { - for (let i = this.scopeStack.length - 1; ; i--) { - const { - flags - } = this.scopeStack[i]; - if (flags & 387) { - return flags; - } - } - } - currentThisScopeFlags() { - for (let i = this.scopeStack.length - 1; ; i--) { - const { - flags - } = this.scopeStack[i]; - if (flags & (387 | 64) && !(flags & 4)) { - return flags; - } - } - } - } - class FlowScope extends Scope { - constructor(...args) { - super(...args); - this.declareFunctions = new Set(); - } - } - class FlowScopeHandler extends ScopeHandler { - createScope(flags) { - return new FlowScope(flags); - } - declareName(name, bindingType, loc) { - const scope = this.currentScope(); - if (bindingType & 2048) { - this.checkRedeclarationInScope(scope, name, bindingType, loc); - this.maybeExportDefined(scope, name); - scope.declareFunctions.add(name); - return; - } - super.declareName(name, bindingType, loc); - } - isRedeclaredInScope(scope, name, bindingType) { - if (super.isRedeclaredInScope(scope, name, bindingType)) return true; - if (bindingType & 2048 && !scope.declareFunctions.has(name)) { - const type = scope.names.get(name); - return (type & 4) > 0 || (type & 2) > 0; - } - return false; - } - checkLocalExport(id) { - if (!this.scopeStack[0].declareFunctions.has(id.name)) { - super.checkLocalExport(id); - } - } - } - class BaseParser { - constructor() { - this.sawUnambiguousESM = false; - this.ambiguousScriptDifferentAst = false; - } - hasPlugin(pluginConfig) { - if (typeof pluginConfig === "string") { - return this.plugins.has(pluginConfig); - } else { - const [pluginName, pluginOptions] = pluginConfig; - if (!this.hasPlugin(pluginName)) { - return false; - } - const actualOptions = this.plugins.get(pluginName); - for (const key of Object.keys(pluginOptions)) { - if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) { - return false; - } - } - return true; - } - } - getPluginOption(plugin, name) { - var _this$plugins$get; - return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name]; - } - } - function setTrailingComments(node, comments) { - if (node.trailingComments === undefined) { - node.trailingComments = comments; - } else { - node.trailingComments.unshift(...comments); - } - } - function setLeadingComments(node, comments) { - if (node.leadingComments === undefined) { - node.leadingComments = comments; - } else { - node.leadingComments.unshift(...comments); - } - } - function setInnerComments(node, comments) { - if (node.innerComments === undefined) { - node.innerComments = comments; - } else { - node.innerComments.unshift(...comments); - } - } - function adjustInnerComments(node, elements, commentWS) { - let lastElement = null; - let i = elements.length; - while (lastElement === null && i > 0) { - lastElement = elements[--i]; - } - if (lastElement === null || lastElement.start > commentWS.start) { - setInnerComments(node, commentWS.comments); - } else { - setTrailingComments(lastElement, commentWS.comments); - } - } - class CommentsParser extends BaseParser { - addComment(comment) { - if (this.filename) comment.loc.filename = this.filename; - const { - commentsLen - } = this.state; - if (this.comments.length != commentsLen) this.comments.length = commentsLen; - this.comments.push(comment); - this.state.commentsLen++; - } - processComment(node) { - const { - commentStack - } = this.state; - const commentStackLength = commentStack.length; - if (commentStackLength === 0) return; - let i = commentStackLength - 1; - const lastCommentWS = commentStack[i]; - if (lastCommentWS.start === node.end) { - lastCommentWS.leadingNode = node; - i--; - } - const { - start: nodeStart - } = node; - for (; i >= 0; i--) { - const commentWS = commentStack[i]; - const commentEnd = commentWS.end; - if (commentEnd > nodeStart) { - commentWS.containingNode = node; - this.finalizeComment(commentWS); - commentStack.splice(i, 1); - } else { - if (commentEnd === nodeStart) { - commentWS.trailingNode = node; - } - break; - } - } - } - finalizeComment(commentWS) { - const { - comments - } = commentWS; - if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) { - if (commentWS.leadingNode !== null) { - setTrailingComments(commentWS.leadingNode, comments); - } - if (commentWS.trailingNode !== null) { - setLeadingComments(commentWS.trailingNode, comments); - } - } else { - const { - containingNode: node, - start: commentStart - } = commentWS; - if (this.input.charCodeAt(commentStart - 1) === 44) { - switch (node.type) { - case "ObjectExpression": - case "ObjectPattern": - case "RecordExpression": - adjustInnerComments(node, node.properties, commentWS); - break; - case "CallExpression": - case "OptionalCallExpression": - adjustInnerComments(node, node.arguments, commentWS); - break; - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - case "ObjectMethod": - case "ClassMethod": - case "ClassPrivateMethod": - adjustInnerComments(node, node.params, commentWS); - break; - case "ArrayExpression": - case "ArrayPattern": - case "TupleExpression": - adjustInnerComments(node, node.elements, commentWS); - break; - case "ExportNamedDeclaration": - case "ImportDeclaration": - adjustInnerComments(node, node.specifiers, commentWS); - break; - default: - { - setInnerComments(node, comments); - } - } - } else { - setInnerComments(node, comments); - } - } - } - finalizeRemainingComments() { - const { - commentStack - } = this.state; - for (let i = commentStack.length - 1; i >= 0; i--) { - this.finalizeComment(commentStack[i]); - } - this.state.commentStack = []; - } - resetPreviousNodeTrailingComments(node) { - const { - commentStack - } = this.state; - const { - length - } = commentStack; - if (length === 0) return; - const commentWS = commentStack[length - 1]; - if (commentWS.leadingNode === node) { - commentWS.leadingNode = null; - } - } - resetPreviousIdentifierLeadingComments(node) { - const { - commentStack - } = this.state; - const { - length - } = commentStack; - if (length === 0) return; - if (commentStack[length - 1].trailingNode === node) { - commentStack[length - 1].trailingNode = null; - } else if (length >= 2 && commentStack[length - 2].trailingNode === node) { - commentStack[length - 2].trailingNode = null; - } - } - takeSurroundingComments(node, start, end) { - const { - commentStack - } = this.state; - const commentStackLength = commentStack.length; - if (commentStackLength === 0) return; - let i = commentStackLength - 1; - for (; i >= 0; i--) { - const commentWS = commentStack[i]; - const commentEnd = commentWS.end; - const commentStart = commentWS.start; - if (commentStart === end) { - commentWS.leadingNode = node; - } else if (commentEnd === start) { - commentWS.trailingNode = node; - } else if (commentEnd < start) { - break; - } - } - } - } - const lineBreak = /\r\n?|[\n\u2028\u2029]/; - const lineBreakG = new RegExp(lineBreak.source, "g"); - function isNewLine(code) { - switch (code) { - case 10: - case 13: - case 8232: - case 8233: - return true; - default: - return false; - } - } - const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g; - const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y"); - function isWhitespace(code) { - switch (code) { - case 0x0009: - case 0x000b: - case 0x000c: - case 32: - case 160: - case 5760: - case 0x2000: - case 0x2001: - case 0x2002: - case 0x2003: - case 0x2004: - case 0x2005: - case 0x2006: - case 0x2007: - case 0x2008: - case 0x2009: - case 0x200a: - case 0x202f: - case 0x205f: - case 0x3000: - case 0xfeff: - return true; - default: - return false; - } - } - class State { - constructor() { - this.flags = 1024; - this.curLine = void 0; - this.lineStart = void 0; - this.startLoc = void 0; - this.endLoc = void 0; - this.errors = []; - this.potentialArrowAt = -1; - this.noArrowAt = []; - this.noArrowParamsConversionAt = []; - this.topicContext = { - maxNumOfResolvableTopics: 0, - maxTopicIndex: null - }; - this.labels = []; - this.commentsLen = 0; - this.commentStack = []; - this.pos = 0; - this.type = 139; - this.value = null; - this.start = 0; - this.end = 0; - this.lastTokEndLoc = null; - this.lastTokStartLoc = null; - this.context = [types$1.brace]; - this.firstInvalidTemplateEscapePos = null; - this.strictErrors = new Map(); - this.tokensLength = 0; - } - get strict() { - return (this.flags & 1) > 0; - } - set strict(value) { - if (value) { - this.flags |= 1; - } else { - this.flags &= ~1; - } - } - init({ - strictMode, - sourceType, - startLine, - startColumn - }) { - this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; - this.curLine = startLine; - this.lineStart = -startColumn; - this.startLoc = this.endLoc = new Position(startLine, startColumn, 0); - } - get maybeInArrowParameters() { - return (this.flags & 2) > 0; - } - set maybeInArrowParameters(value) { - if (value) { - this.flags |= 2; - } else { - this.flags &= ~2; - } - } - get inType() { - return (this.flags & 4) > 0; - } - set inType(value) { - if (value) { - this.flags |= 4; - } else { - this.flags &= ~4; - } - } - get noAnonFunctionType() { - return (this.flags & 8) > 0; - } - set noAnonFunctionType(value) { - if (value) { - this.flags |= 8; - } else { - this.flags &= ~8; - } - } - get hasFlowComment() { - return (this.flags & 16) > 0; - } - set hasFlowComment(value) { - if (value) { - this.flags |= 16; - } else { - this.flags &= ~16; - } - } - get isAmbientContext() { - return (this.flags & 32) > 0; - } - set isAmbientContext(value) { - if (value) { - this.flags |= 32; - } else { - this.flags &= ~32; - } - } - get inAbstractClass() { - return (this.flags & 64) > 0; - } - set inAbstractClass(value) { - if (value) { - this.flags |= 64; - } else { - this.flags &= ~64; - } - } - get inDisallowConditionalTypesContext() { - return (this.flags & 128) > 0; - } - set inDisallowConditionalTypesContext(value) { - if (value) { - this.flags |= 128; - } else { - this.flags &= ~128; - } - } - get soloAwait() { - return (this.flags & 256) > 0; - } - set soloAwait(value) { - if (value) { - this.flags |= 256; - } else { - this.flags &= ~256; - } - } - get inFSharpPipelineDirectBody() { - return (this.flags & 512) > 0; - } - set inFSharpPipelineDirectBody(value) { - if (value) { - this.flags |= 512; - } else { - this.flags &= ~512; - } - } - get canStartJSXElement() { - return (this.flags & 1024) > 0; - } - set canStartJSXElement(value) { - if (value) { - this.flags |= 1024; - } else { - this.flags &= ~1024; - } - } - get containsEsc() { - return (this.flags & 2048) > 0; - } - set containsEsc(value) { - if (value) { - this.flags |= 2048; - } else { - this.flags &= ~2048; - } - } - curPosition() { - return new Position(this.curLine, this.pos - this.lineStart, this.pos); - } - clone() { - const state = new State(); - state.flags = this.flags; - state.curLine = this.curLine; - state.lineStart = this.lineStart; - state.startLoc = this.startLoc; - state.endLoc = this.endLoc; - state.errors = this.errors.slice(); - state.potentialArrowAt = this.potentialArrowAt; - state.noArrowAt = this.noArrowAt.slice(); - state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice(); - state.topicContext = this.topicContext; - state.labels = this.labels.slice(); - state.commentsLen = this.commentsLen; - state.commentStack = this.commentStack.slice(); - state.pos = this.pos; - state.type = this.type; - state.value = this.value; - state.start = this.start; - state.end = this.end; - state.lastTokEndLoc = this.lastTokEndLoc; - state.lastTokStartLoc = this.lastTokStartLoc; - state.context = this.context.slice(); - state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos; - state.strictErrors = this.strictErrors; - state.tokensLength = this.tokensLength; - return state; - } - } - var _isDigit = function isDigit(code) { - return code >= 48 && code <= 57; - }; - const forbiddenNumericSeparatorSiblings = { - decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), - hex: new Set([46, 88, 95, 120]) - }; - const isAllowedNumericSeparatorSibling = { - bin: ch => ch === 48 || ch === 49, - oct: ch => ch >= 48 && ch <= 55, - dec: ch => ch >= 48 && ch <= 57, - hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 - }; - function readStringContents(type, input, pos, lineStart, curLine, errors) { - const initialPos = pos; - const initialLineStart = lineStart; - const initialCurLine = curLine; - let out = ""; - let firstInvalidLoc = null; - let chunkStart = pos; - const { - length - } = input; - for (; ;) { - if (pos >= length) { - errors.unterminated(initialPos, initialLineStart, initialCurLine); - out += input.slice(chunkStart, pos); - break; - } - const ch = input.charCodeAt(pos); - if (isStringEnd(type, ch, input, pos)) { - out += input.slice(chunkStart, pos); - break; - } - if (ch === 92) { - out += input.slice(chunkStart, pos); - const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); - if (res.ch === null && !firstInvalidLoc) { - firstInvalidLoc = { - pos, - lineStart, - curLine - }; - } else { - out += res.ch; - } - ({ - pos, - lineStart, - curLine - } = res); - chunkStart = pos; - } else if (ch === 8232 || ch === 8233) { - ++pos; - ++curLine; - lineStart = pos; - } else if (ch === 10 || ch === 13) { - if (type === "template") { - out += input.slice(chunkStart, pos) + "\n"; - ++pos; - if (ch === 13 && input.charCodeAt(pos) === 10) { - ++pos; - } - ++curLine; - chunkStart = lineStart = pos; - } else { - errors.unterminated(initialPos, initialLineStart, initialCurLine); - } - } else { - ++pos; - } - } - return { - pos, - str: out, - firstInvalidLoc, - lineStart, - curLine, - containsInvalid: !!firstInvalidLoc - }; - } - function isStringEnd(type, ch, input, pos) { - if (type === "template") { - return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; - } - return ch === (type === "double" ? 34 : 39); - } - function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { - const throwOnInvalid = !inTemplate; - pos++; - const res = ch => ({ - pos, - ch, - lineStart, - curLine - }); - const ch = input.charCodeAt(pos++); - switch (ch) { - case 110: - return res("\n"); - case 114: - return res("\r"); - case 120: - { - let code; - ({ - code, - pos - } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); - return res(code === null ? null : String.fromCharCode(code)); - } - case 117: - { - let code; - ({ - code, - pos - } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); - return res(code === null ? null : String.fromCodePoint(code)); - } - case 116: - return res("\t"); - case 98: - return res("\b"); - case 118: - return res("\u000b"); - case 102: - return res("\f"); - case 13: - if (input.charCodeAt(pos) === 10) { - ++pos; - } - case 10: - lineStart = pos; - ++curLine; - case 8232: - case 8233: - return res(""); - case 56: - case 57: - if (inTemplate) { - return res(null); - } else { - errors.strictNumericEscape(pos - 1, lineStart, curLine); - } - default: - if (ch >= 48 && ch <= 55) { - const startPos = pos - 1; - const match = input.slice(startPos, pos + 2).match(/^[0-7]+/); - let octalStr = match[0]; - let octal = parseInt(octalStr, 8); - if (octal > 255) { - octalStr = octalStr.slice(0, -1); - octal = parseInt(octalStr, 8); - } - pos += octalStr.length - 1; - const next = input.charCodeAt(pos); - if (octalStr !== "0" || next === 56 || next === 57) { - if (inTemplate) { - return res(null); - } else { - errors.strictNumericEscape(startPos, lineStart, curLine); - } - } - return res(String.fromCharCode(octal)); - } - return res(String.fromCharCode(ch)); - } - } - function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { - const initialPos = pos; - let n; - ({ - n, - pos - } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); - if (n === null) { - if (throwOnInvalid) { - errors.invalidEscapeSequence(initialPos, lineStart, curLine); - } else { - pos = initialPos - 1; - } - } - return { - code: n, - pos - }; - } - function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { - const start = pos; - const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; - const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; - let invalid = false; - let total = 0; - for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { - const code = input.charCodeAt(pos); - let val; - if (code === 95 && allowNumSeparator !== "bail") { - const prev = input.charCodeAt(pos - 1); - const next = input.charCodeAt(pos + 1); - if (!allowNumSeparator) { - if (bailOnError) return { - n: null, - pos - }; - errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); - } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { - if (bailOnError) return { - n: null, - pos - }; - errors.unexpectedNumericSeparator(pos, lineStart, curLine); - } - ++pos; - continue; - } - if (code >= 97) { - val = code - 97 + 10; - } else if (code >= 65) { - val = code - 65 + 10; - } else if (_isDigit(code)) { - val = code - 48; - } else { - val = Infinity; - } - if (val >= radix) { - if (val <= 9 && bailOnError) { - return { - n: null, - pos - }; - } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { - val = 0; - } else if (forceLen) { - val = 0; - invalid = true; - } else { - break; - } - } - ++pos; - total = total * radix + val; - } - if (pos === start || len != null && pos - start !== len || invalid) { - return { - n: null, - pos - }; - } - return { - n: total, - pos - }; - } - function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { - const ch = input.charCodeAt(pos); - let code; - if (ch === 123) { - ++pos; - ({ - code, - pos - } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); - ++pos; - if (code !== null && code > 0x10ffff) { - if (throwOnInvalid) { - errors.invalidCodePoint(pos, lineStart, curLine); - } else { - return { - code: null, - pos - }; - } - } - } else { - ({ - code, - pos - } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); - } - return { - code, - pos - }; - } - function buildPosition(pos, lineStart, curLine) { - return new Position(curLine, pos - lineStart, pos); - } - const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]); - class Token { - constructor(state) { - this.type = state.type; - this.value = state.value; - this.start = state.start; - this.end = state.end; - this.loc = new SourceLocation(state.startLoc, state.endLoc); - } - } - class Tokenizer extends CommentsParser { - constructor(options, input) { - super(); - this.isLookahead = void 0; - this.tokens = []; - this.errorHandlers_readInt = { - invalidDigit: (pos, lineStart, curLine, radix) => { - if (!this.options.errorRecovery) return false; - this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), { - radix - }); - return true; - }, - numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence), - unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator) - }; - this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, { - invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence), - invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint) - }); - this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, { - strictNumericEscape: (pos, lineStart, curLine) => { - this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine)); - }, - unterminated: (pos, lineStart, curLine) => { - throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine)); - } - }); - this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, { - strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape), - unterminated: (pos, lineStart, curLine) => { - throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine)); - } - }); - this.state = new State(); - this.state.init(options); - this.input = input; - this.length = input.length; - this.comments = []; - this.isLookahead = false; - } - pushToken(token) { - this.tokens.length = this.state.tokensLength; - this.tokens.push(token); - ++this.state.tokensLength; - } - next() { - this.checkKeywordEscapes(); - if (this.options.tokens) { - this.pushToken(new Token(this.state)); - } - this.state.lastTokEndLoc = this.state.endLoc; - this.state.lastTokStartLoc = this.state.startLoc; - this.nextToken(); - } - eat(type) { - if (this.match(type)) { - this.next(); - return true; - } else { - return false; - } - } - match(type) { - return this.state.type === type; - } - createLookaheadState(state) { - return { - pos: state.pos, - value: null, - type: state.type, - start: state.start, - end: state.end, - context: [this.curContext()], - inType: state.inType, - startLoc: state.startLoc, - lastTokEndLoc: state.lastTokEndLoc, - curLine: state.curLine, - lineStart: state.lineStart, - curPosition: state.curPosition - }; - } - lookahead() { - const old = this.state; - this.state = this.createLookaheadState(old); - this.isLookahead = true; - this.nextToken(); - this.isLookahead = false; - const curr = this.state; - this.state = old; - return curr; - } - nextTokenStart() { - return this.nextTokenStartSince(this.state.pos); - } - nextTokenStartSince(pos) { - skipWhiteSpace.lastIndex = pos; - return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos; - } - lookaheadCharCode() { - return this.input.charCodeAt(this.nextTokenStart()); - } - nextTokenInLineStart() { - return this.nextTokenInLineStartSince(this.state.pos); - } - nextTokenInLineStartSince(pos) { - skipWhiteSpaceInLine.lastIndex = pos; - return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos; - } - lookaheadInLineCharCode() { - return this.input.charCodeAt(this.nextTokenInLineStart()); - } - codePointAtPos(pos) { - let cp = this.input.charCodeAt(pos); - if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) { - const trail = this.input.charCodeAt(pos); - if ((trail & 0xfc00) === 0xdc00) { - cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); - } - } - return cp; - } - setStrict(strict) { - this.state.strict = strict; - if (strict) { - this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at)); - this.state.strictErrors.clear(); - } - } - curContext() { - return this.state.context[this.state.context.length - 1]; - } - nextToken() { - this.skipSpace(); - this.state.start = this.state.pos; - if (!this.isLookahead) this.state.startLoc = this.state.curPosition(); - if (this.state.pos >= this.length) { - this.finishToken(139); - return; - } - this.getTokenFromCode(this.codePointAtPos(this.state.pos)); - } - skipBlockComment(commentEnd) { - let startLoc; - if (!this.isLookahead) startLoc = this.state.curPosition(); - const start = this.state.pos; - const end = this.input.indexOf(commentEnd, start + 2); - if (end === -1) { - throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); - } - this.state.pos = end + commentEnd.length; - lineBreakG.lastIndex = start + 2; - while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) { - ++this.state.curLine; - this.state.lineStart = lineBreakG.lastIndex; - } - if (this.isLookahead) return; - const comment = { - type: "CommentBlock", - value: this.input.slice(start + 2, end), - start, - end: end + commentEnd.length, - loc: new SourceLocation(startLoc, this.state.curPosition()) - }; - if (this.options.tokens) this.pushToken(comment); - return comment; - } - skipLineComment(startSkip) { - const start = this.state.pos; - let startLoc; - if (!this.isLookahead) startLoc = this.state.curPosition(); - let ch = this.input.charCodeAt(this.state.pos += startSkip); - if (this.state.pos < this.length) { - while (!isNewLine(ch) && ++this.state.pos < this.length) { - ch = this.input.charCodeAt(this.state.pos); - } - } - if (this.isLookahead) return; - const end = this.state.pos; - const value = this.input.slice(start + startSkip, end); - const comment = { - type: "CommentLine", - value, - start, - end, - loc: new SourceLocation(startLoc, this.state.curPosition()) - }; - if (this.options.tokens) this.pushToken(comment); - return comment; - } - skipSpace() { - const spaceStart = this.state.pos; - const comments = []; - loop: while (this.state.pos < this.length) { - const ch = this.input.charCodeAt(this.state.pos); - switch (ch) { - case 32: - case 160: - case 9: - ++this.state.pos; - break; - case 13: - if (this.input.charCodeAt(this.state.pos + 1) === 10) { - ++this.state.pos; - } - case 10: - case 8232: - case 8233: - ++this.state.pos; - ++this.state.curLine; - this.state.lineStart = this.state.pos; - break; - case 47: - switch (this.input.charCodeAt(this.state.pos + 1)) { - case 42: - { - const comment = this.skipBlockComment("*/"); - if (comment !== undefined) { - this.addComment(comment); - if (this.options.attachComment) comments.push(comment); - } - break; - } - case 47: - { - const comment = this.skipLineComment(2); - if (comment !== undefined) { - this.addComment(comment); - if (this.options.attachComment) comments.push(comment); - } - break; - } - default: - break loop; - } - break; - default: - if (isWhitespace(ch)) { - ++this.state.pos; - } else if (ch === 45 && !this.inModule && this.options.annexB) { - const pos = this.state.pos; - if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) { - const comment = this.skipLineComment(3); - if (comment !== undefined) { - this.addComment(comment); - if (this.options.attachComment) comments.push(comment); - } - } else { - break loop; - } - } else if (ch === 60 && !this.inModule && this.options.annexB) { - const pos = this.state.pos; - if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) { - const comment = this.skipLineComment(4); - if (comment !== undefined) { - this.addComment(comment); - if (this.options.attachComment) comments.push(comment); - } - } else { - break loop; - } - } else { - break loop; - } - } - } - if (comments.length > 0) { - const end = this.state.pos; - const commentWhitespace = { - start: spaceStart, - end, - comments, - leadingNode: null, - trailingNode: null, - containingNode: null - }; - this.state.commentStack.push(commentWhitespace); - } - } - finishToken(type, val) { - this.state.end = this.state.pos; - this.state.endLoc = this.state.curPosition(); - const prevType = this.state.type; - this.state.type = type; - this.state.value = val; - if (!this.isLookahead) { - this.updateContext(prevType); - } - } - replaceToken(type) { - this.state.type = type; - this.updateContext(); - } - readToken_numberSign() { - if (this.state.pos === 0 && this.readToken_interpreter()) { - return; - } - const nextPos = this.state.pos + 1; - const next = this.codePointAtPos(nextPos); - if (next >= 48 && next <= 57) { - throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition()); - } - if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { - this.expectPlugin("recordAndTuple"); - if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") { - throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition()); - } - this.state.pos += 2; - if (next === 123) { - this.finishToken(7); - } else { - this.finishToken(1); - } - } else if (isIdentifierStart(next)) { - ++this.state.pos; - this.finishToken(138, this.readWord1(next)); - } else if (next === 92) { - ++this.state.pos; - this.finishToken(138, this.readWord1()); - } else { - this.finishOp(27, 1); - } - } - readToken_dot() { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next >= 48 && next <= 57) { - this.readNumber(true); - return; - } - if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { - this.state.pos += 3; - this.finishToken(21); - } else { - ++this.state.pos; - this.finishToken(16); - } - } - readToken_slash() { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - this.finishOp(31, 2); - } else { - this.finishOp(56, 1); - } - } - readToken_interpreter() { - if (this.state.pos !== 0 || this.length < 2) return false; - let ch = this.input.charCodeAt(this.state.pos + 1); - if (ch !== 33) return false; - const start = this.state.pos; - this.state.pos += 1; - while (!isNewLine(ch) && ++this.state.pos < this.length) { - ch = this.input.charCodeAt(this.state.pos); - } - const value = this.input.slice(start + 2, this.state.pos); - this.finishToken(28, value); - return true; - } - readToken_mult_modulo(code) { - let type = code === 42 ? 55 : 54; - let width = 1; - let next = this.input.charCodeAt(this.state.pos + 1); - if (code === 42 && next === 42) { - width++; - next = this.input.charCodeAt(this.state.pos + 2); - type = 57; - } - if (next === 61 && !this.state.inType) { - width++; - type = code === 37 ? 33 : 30; - } - this.finishOp(type, width); - } - readToken_pipe_amp(code) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === code) { - if (this.input.charCodeAt(this.state.pos + 2) === 61) { - this.finishOp(30, 3); - } else { - this.finishOp(code === 124 ? 41 : 42, 2); - } - return; - } - if (code === 124) { - if (next === 62) { - this.finishOp(39, 2); - return; - } - if (this.hasPlugin("recordAndTuple") && next === 125) { - if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); - } - this.state.pos += 2; - this.finishToken(9); - return; - } - if (this.hasPlugin("recordAndTuple") && next === 93) { - if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); - } - this.state.pos += 2; - this.finishToken(4); - return; - } - } - if (next === 61) { - this.finishOp(30, 2); - return; - } - this.finishOp(code === 124 ? 43 : 45, 1); - } - readToken_caret() { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61 && !this.state.inType) { - this.finishOp(32, 2); - } else if (next === 94 && this.hasPlugin(["pipelineOperator", { - proposal: "hack", - topicToken: "^^" - }])) { - this.finishOp(37, 2); - const lookaheadCh = this.input.codePointAt(this.state.pos); - if (lookaheadCh === 94) { - this.unexpected(); - } - } else { - this.finishOp(44, 1); - } - } - readToken_atSign() { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === 64 && this.hasPlugin(["pipelineOperator", { - proposal: "hack", - topicToken: "@@" - }])) { - this.finishOp(38, 2); - } else { - this.finishOp(26, 1); - } - } - readToken_plus_min(code) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === code) { - this.finishOp(34, 2); - return; - } - if (next === 61) { - this.finishOp(30, 2); - } else { - this.finishOp(53, 1); - } - } - readToken_lt() { - const { - pos - } = this.state; - const next = this.input.charCodeAt(pos + 1); - if (next === 60) { - if (this.input.charCodeAt(pos + 2) === 61) { - this.finishOp(30, 3); - return; - } - this.finishOp(51, 2); - return; - } - if (next === 61) { - this.finishOp(49, 2); - return; - } - this.finishOp(47, 1); - } - readToken_gt() { - const { - pos - } = this.state; - const next = this.input.charCodeAt(pos + 1); - if (next === 62) { - const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(pos + size) === 61) { - this.finishOp(30, size + 1); - return; - } - this.finishOp(52, size); - return; - } - if (next === 61) { - this.finishOp(49, 2); - return; - } - this.finishOp(48, 1); - } - readToken_eq_excl(code) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); - return; - } - if (code === 61 && next === 62) { - this.state.pos += 2; - this.finishToken(19); - return; - } - this.finishOp(code === 61 ? 29 : 35, 1); - } - readToken_question() { - const next = this.input.charCodeAt(this.state.pos + 1); - const next2 = this.input.charCodeAt(this.state.pos + 2); - if (next === 63) { - if (next2 === 61) { - this.finishOp(30, 3); - } else { - this.finishOp(40, 2); - } - } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { - this.state.pos += 2; - this.finishToken(18); - } else { - ++this.state.pos; - this.finishToken(17); - } - } - getTokenFromCode(code) { - switch (code) { - case 46: - this.readToken_dot(); - return; - case 40: - ++this.state.pos; - this.finishToken(10); - return; - case 41: - ++this.state.pos; - this.finishToken(11); - return; - case 59: - ++this.state.pos; - this.finishToken(13); - return; - case 44: - ++this.state.pos; - this.finishToken(12); - return; - case 91: - if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { - if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); - } - this.state.pos += 2; - this.finishToken(2); - } else { - ++this.state.pos; - this.finishToken(0); - } - return; - case 93: - ++this.state.pos; - this.finishToken(3); - return; - case 123: - if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { - if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { - throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); - } - this.state.pos += 2; - this.finishToken(6); - } else { - ++this.state.pos; - this.finishToken(5); - } - return; - case 125: - ++this.state.pos; - this.finishToken(8); - return; - case 58: - if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { - this.finishOp(15, 2); - } else { - ++this.state.pos; - this.finishToken(14); - } - return; - case 63: - this.readToken_question(); - return; - case 96: - this.readTemplateToken(); - return; - case 48: - { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === 120 || next === 88) { - this.readRadixNumber(16); - return; - } - if (next === 111 || next === 79) { - this.readRadixNumber(8); - return; - } - if (next === 98 || next === 66) { - this.readRadixNumber(2); - return; - } - } - case 49: - case 50: - case 51: - case 52: - case 53: - case 54: - case 55: - case 56: - case 57: - this.readNumber(false); - return; - case 34: - case 39: - this.readString(code); - return; - case 47: - this.readToken_slash(); - return; - case 37: - case 42: - this.readToken_mult_modulo(code); - return; - case 124: - case 38: - this.readToken_pipe_amp(code); - return; - case 94: - this.readToken_caret(); - return; - case 43: - case 45: - this.readToken_plus_min(code); - return; - case 60: - this.readToken_lt(); - return; - case 62: - this.readToken_gt(); - return; - case 61: - case 33: - this.readToken_eq_excl(code); - return; - case 126: - this.finishOp(36, 1); - return; - case 64: - this.readToken_atSign(); - return; - case 35: - this.readToken_numberSign(); - return; - case 92: - this.readWord(); - return; - default: - if (isIdentifierStart(code)) { - this.readWord(code); - return; - } - } - throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), { - unexpected: String.fromCodePoint(code) - }); - } - finishOp(type, size) { - const str = this.input.slice(this.state.pos, this.state.pos + size); - this.state.pos += size; - this.finishToken(type, str); - } - readRegexp() { - const startLoc = this.state.startLoc; - const start = this.state.start + 1; - let escaped, inClass; - let { - pos - } = this.state; - for (; ; ++pos) { - if (pos >= this.length) { - throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); - } - const ch = this.input.charCodeAt(pos); - if (isNewLine(ch)) { - throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); - } - if (escaped) { - escaped = false; - } else { - if (ch === 91) { - inClass = true; - } else if (ch === 93 && inClass) { - inClass = false; - } else if (ch === 47 && !inClass) { - break; - } - escaped = ch === 92; - } - } - const content = this.input.slice(start, pos); - ++pos; - let mods = ""; - const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start); - while (pos < this.length) { - const cp = this.codePointAtPos(pos); - const char = String.fromCharCode(cp); - if (VALID_REGEX_FLAGS.has(cp)) { - if (cp === 118) { - if (mods.includes("u")) { - this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); - } - } else if (cp === 117) { - if (mods.includes("v")) { - this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); - } - } - if (mods.includes(char)) { - this.raise(Errors.DuplicateRegExpFlags, nextPos()); - } - } else if (isIdentifierChar(cp) || cp === 92) { - this.raise(Errors.MalformedRegExpFlags, nextPos()); - } else { - break; - } - ++pos; - mods += char; - } - this.state.pos = pos; - this.finishToken(137, { - pattern: content, - flags: mods - }); - } - readInt(radix, len, forceLen = false, allowNumSeparator = true) { - const { - n, - pos - } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false); - this.state.pos = pos; - return n; - } - readRadixNumber(radix) { - const startLoc = this.state.curPosition(); - let isBigInt = false; - this.state.pos += 2; - const val = this.readInt(radix); - if (val == null) { - this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), { - radix - }); - } - const next = this.input.charCodeAt(this.state.pos); - if (next === 110) { - ++this.state.pos; - isBigInt = true; - } else if (next === 109) { - throw this.raise(Errors.InvalidDecimal, startLoc); - } - if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { - throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); - } - if (isBigInt) { - const str = this.input.slice(startLoc.index, this.state.pos).replace(/[_n]/g, ""); - this.finishToken(135, str); - return; - } - this.finishToken(134, val); - } - readNumber(startsWithDot) { - const start = this.state.pos; - const startLoc = this.state.curPosition(); - let isFloat = false; - let isBigInt = false; - let isDecimal = false; - let hasExponent = false; - let isOctal = false; - if (!startsWithDot && this.readInt(10) === null) { - this.raise(Errors.InvalidNumber, this.state.curPosition()); - } - const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; - if (hasLeadingZero) { - const integer = this.input.slice(start, this.state.pos); - this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc); - if (!this.state.strict) { - const underscorePos = integer.indexOf("_"); - if (underscorePos > 0) { - this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos)); - } - } - isOctal = hasLeadingZero && !/[89]/.test(integer); - } - let next = this.input.charCodeAt(this.state.pos); - if (next === 46 && !isOctal) { - ++this.state.pos; - this.readInt(10); - isFloat = true; - next = this.input.charCodeAt(this.state.pos); - } - if ((next === 69 || next === 101) && !isOctal) { - next = this.input.charCodeAt(++this.state.pos); - if (next === 43 || next === 45) { - ++this.state.pos; - } - if (this.readInt(10) === null) { - this.raise(Errors.InvalidOrMissingExponent, startLoc); - } - isFloat = true; - hasExponent = true; - next = this.input.charCodeAt(this.state.pos); - } - if (next === 110) { - if (isFloat || hasLeadingZero) { - this.raise(Errors.InvalidBigIntLiteral, startLoc); - } - ++this.state.pos; - isBigInt = true; - } - if (next === 109) { - this.expectPlugin("decimal", this.state.curPosition()); - if (hasExponent || hasLeadingZero) { - this.raise(Errors.InvalidDecimal, startLoc); - } - ++this.state.pos; - isDecimal = true; - } - if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { - throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); - } - const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); - if (isBigInt) { - this.finishToken(135, str); - return; - } - if (isDecimal) { - this.finishToken(136, str); - return; - } - const val = isOctal ? parseInt(str, 8) : parseFloat(str); - this.finishToken(134, val); - } - readCodePoint(throwOnInvalid) { - const { - code, - pos - } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint); - this.state.pos = pos; - return code; - } - readString(quote) { - const { - str, - pos, - curLine, - lineStart - } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string); - this.state.pos = pos + 1; - this.state.lineStart = lineStart; - this.state.curLine = curLine; - this.finishToken(133, str); - } - readTemplateContinuation() { - if (!this.match(8)) { - this.unexpected(null, 8); - } - this.state.pos--; - this.readTemplateToken(); - } - readTemplateToken() { - const opening = this.input[this.state.pos]; - const { - str, - firstInvalidLoc, - pos, - curLine, - lineStart - } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template); - this.state.pos = pos + 1; - this.state.lineStart = lineStart; - this.state.curLine = curLine; - if (firstInvalidLoc) { - this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, firstInvalidLoc.pos); - } - if (this.input.codePointAt(pos) === 96) { - this.finishToken(24, firstInvalidLoc ? null : opening + str + "`"); - } else { - this.state.pos++; - this.finishToken(25, firstInvalidLoc ? null : opening + str + "${"); - } - } - recordStrictModeErrors(toParseError, at) { - const index = at.index; - if (this.state.strict && !this.state.strictErrors.has(index)) { - this.raise(toParseError, at); - } else { - this.state.strictErrors.set(index, [toParseError, at]); - } - } - readWord1(firstCode) { - this.state.containsEsc = false; - let word = ""; - const start = this.state.pos; - let chunkStart = this.state.pos; - if (firstCode !== undefined) { - this.state.pos += firstCode <= 0xffff ? 1 : 2; - } - while (this.state.pos < this.length) { - const ch = this.codePointAtPos(this.state.pos); - if (isIdentifierChar(ch)) { - this.state.pos += ch <= 0xffff ? 1 : 2; - } else if (ch === 92) { - this.state.containsEsc = true; - word += this.input.slice(chunkStart, this.state.pos); - const escStart = this.state.curPosition(); - const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; - if (this.input.charCodeAt(++this.state.pos) !== 117) { - this.raise(Errors.MissingUnicodeEscape, this.state.curPosition()); - chunkStart = this.state.pos - 1; - continue; - } - ++this.state.pos; - const esc = this.readCodePoint(true); - if (esc !== null) { - if (!identifierCheck(esc)) { - this.raise(Errors.EscapedCharNotAnIdentifier, escStart); - } - word += String.fromCodePoint(esc); - } - chunkStart = this.state.pos; - } else { - break; - } - } - return word + this.input.slice(chunkStart, this.state.pos); - } - readWord(firstCode) { - const word = this.readWord1(firstCode); - const type = keywords$1.get(word); - if (type !== undefined) { - this.finishToken(type, tokenLabelName(type)); - } else { - this.finishToken(132, word); - } - } - checkKeywordEscapes() { - const { - type - } = this.state; - if (tokenIsKeyword(type) && this.state.containsEsc) { - this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, { - reservedWord: tokenLabelName(type) - }); - } - } - raise(toParseError, at, details = {}) { - const loc = at instanceof Position ? at : at.loc.start; - const error = toParseError(loc, details); - if (!this.options.errorRecovery) throw error; - if (!this.isLookahead) this.state.errors.push(error); - return error; - } - raiseOverwrite(toParseError, at, details = {}) { - const loc = at instanceof Position ? at : at.loc.start; - const pos = loc.index; - const errors = this.state.errors; - for (let i = errors.length - 1; i >= 0; i--) { - const error = errors[i]; - if (error.loc.index === pos) { - return errors[i] = toParseError(loc, details); - } - if (error.loc.index < pos) break; - } - return this.raise(toParseError, at, details); - } - updateContext(prevType) { } - unexpected(loc, type) { - throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, { - expected: type ? tokenLabelName(type) : null - }); - } - expectPlugin(pluginName, loc) { - if (this.hasPlugin(pluginName)) { - return true; - } - throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, { - missingPlugin: [pluginName] - }); - } - expectOnePlugin(pluginNames) { - if (!pluginNames.some(name => this.hasPlugin(name))) { - throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, { - missingPlugin: pluginNames - }); - } - } - errorBuilder(error) { - return (pos, lineStart, curLine) => { - this.raise(error, buildPosition(pos, lineStart, curLine)); - }; - } - } - class ClassScope { - constructor() { - this.privateNames = new Set(); - this.loneAccessors = new Map(); - this.undefinedPrivateNames = new Map(); - } - } - class ClassScopeHandler { - constructor(parser) { - this.parser = void 0; - this.stack = []; - this.undefinedPrivateNames = new Map(); - this.parser = parser; - } - current() { - return this.stack[this.stack.length - 1]; - } - enter() { - this.stack.push(new ClassScope()); - } - exit() { - const oldClassScope = this.stack.pop(); - const current = this.current(); - for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) { - if (current) { - if (!current.undefinedPrivateNames.has(name)) { - current.undefinedPrivateNames.set(name, loc); - } - } else { - this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { - identifierName: name - }); - } - } - } - declarePrivateName(name, elementType, loc) { - const { - privateNames, - loneAccessors, - undefinedPrivateNames - } = this.current(); - let redefined = privateNames.has(name); - if (elementType & 3) { - const accessor = redefined && loneAccessors.get(name); - if (accessor) { - const oldStatic = accessor & 4; - const newStatic = elementType & 4; - const oldKind = accessor & 3; - const newKind = elementType & 3; - redefined = oldKind === newKind || oldStatic !== newStatic; - if (!redefined) loneAccessors.delete(name); - } else if (!redefined) { - loneAccessors.set(name, elementType); - } - } - if (redefined) { - this.parser.raise(Errors.PrivateNameRedeclaration, loc, { - identifierName: name - }); - } - privateNames.add(name); - undefinedPrivateNames.delete(name); - } - usePrivateName(name, loc) { - let classScope; - for (classScope of this.stack) { - if (classScope.privateNames.has(name)) return; - } - if (classScope) { - classScope.undefinedPrivateNames.set(name, loc); - } else { - this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { - identifierName: name - }); - } - } - } - class ExpressionScope { - constructor(type = 0) { - this.type = type; - } - canBeArrowParameterDeclaration() { - return this.type === 2 || this.type === 1; - } - isCertainlyParameterDeclaration() { - return this.type === 3; - } - } - class ArrowHeadParsingScope extends ExpressionScope { - constructor(type) { - super(type); - this.declarationErrors = new Map(); - } - recordDeclarationError(ParsingErrorClass, at) { - const index = at.index; - this.declarationErrors.set(index, [ParsingErrorClass, at]); - } - clearDeclarationError(index) { - this.declarationErrors.delete(index); - } - iterateErrors(iterator) { - this.declarationErrors.forEach(iterator); - } - } - class ExpressionScopeHandler { - constructor(parser) { - this.parser = void 0; - this.stack = [new ExpressionScope()]; - this.parser = parser; - } - enter(scope) { - this.stack.push(scope); - } - exit() { - this.stack.pop(); - } - recordParameterInitializerError(toParseError, node) { - const origin = node.loc.start; - const { - stack - } = this; - let i = stack.length - 1; - let scope = stack[i]; - while (!scope.isCertainlyParameterDeclaration()) { - if (scope.canBeArrowParameterDeclaration()) { - scope.recordDeclarationError(toParseError, origin); - } else { - return; - } - scope = stack[--i]; - } - this.parser.raise(toParseError, origin); - } - recordArrowParameterBindingError(error, node) { - const { - stack - } = this; - const scope = stack[stack.length - 1]; - const origin = node.loc.start; - if (scope.isCertainlyParameterDeclaration()) { - this.parser.raise(error, origin); - } else if (scope.canBeArrowParameterDeclaration()) { - scope.recordDeclarationError(error, origin); - } else { - return; - } - } - recordAsyncArrowParametersError(at) { - const { - stack - } = this; - let i = stack.length - 1; - let scope = stack[i]; - while (scope.canBeArrowParameterDeclaration()) { - if (scope.type === 2) { - scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at); - } - scope = stack[--i]; - } - } - validateAsPattern() { - const { - stack - } = this; - const currentScope = stack[stack.length - 1]; - if (!currentScope.canBeArrowParameterDeclaration()) return; - currentScope.iterateErrors(([toParseError, loc]) => { - this.parser.raise(toParseError, loc); - let i = stack.length - 2; - let scope = stack[i]; - while (scope.canBeArrowParameterDeclaration()) { - scope.clearDeclarationError(loc.index); - scope = stack[--i]; - } - }); - } - } - function newParameterDeclarationScope() { - return new ExpressionScope(3); - } - function newArrowHeadScope() { - return new ArrowHeadParsingScope(1); - } - function newAsyncArrowScope() { - return new ArrowHeadParsingScope(2); - } - function newExpressionScope() { - return new ExpressionScope(); - } - class ProductionParameterHandler { - constructor() { - this.stacks = []; - } - enter(flags) { - this.stacks.push(flags); - } - exit() { - this.stacks.pop(); - } - currentFlags() { - return this.stacks[this.stacks.length - 1]; - } - get hasAwait() { - return (this.currentFlags() & 2) > 0; - } - get hasYield() { - return (this.currentFlags() & 1) > 0; - } - get hasReturn() { - return (this.currentFlags() & 4) > 0; - } - get hasIn() { - return (this.currentFlags() & 8) > 0; - } - } - function functionFlags(isAsync, isGenerator) { - return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0); - } - class UtilParser extends Tokenizer { - addExtra(node, key, value, enumerable = true) { - if (!node) return; - const extra = node.extra = node.extra || {}; - if (enumerable) { - extra[key] = value; - } else { - Object.defineProperty(extra, key, { - enumerable, - value - }); - } - } - isContextual(token) { - return this.state.type === token && !this.state.containsEsc; - } - isUnparsedContextual(nameStart, name) { - const nameEnd = nameStart + name.length; - if (this.input.slice(nameStart, nameEnd) === name) { - const nextCh = this.input.charCodeAt(nameEnd); - return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800); - } - return false; - } - isLookaheadContextual(name) { - const next = this.nextTokenStart(); - return this.isUnparsedContextual(next, name); - } - eatContextual(token) { - if (this.isContextual(token)) { - this.next(); - return true; - } - return false; - } - expectContextual(token, toParseError) { - if (!this.eatContextual(token)) { - if (toParseError != null) { - throw this.raise(toParseError, this.state.startLoc); - } - this.unexpected(null, token); - } - } - canInsertSemicolon() { - return this.match(139) || this.match(8) || this.hasPrecedingLineBreak(); - } - hasPrecedingLineBreak() { - return lineBreak.test(this.input.slice(this.state.lastTokEndLoc.index, this.state.start)); - } - hasFollowingLineBreak() { - skipWhiteSpaceToLineBreak.lastIndex = this.state.end; - return skipWhiteSpaceToLineBreak.test(this.input); - } - isLineTerminator() { - return this.eat(13) || this.canInsertSemicolon(); - } - semicolon(allowAsi = true) { - if (allowAsi ? this.isLineTerminator() : this.eat(13)) return; - this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc); - } - expect(type, loc) { - this.eat(type) || this.unexpected(loc, type); - } - tryParse(fn, oldState = this.state.clone()) { - const abortSignal = { - node: null - }; - try { - const node = fn((node = null) => { - abortSignal.node = node; - throw abortSignal; - }); - if (this.state.errors.length > oldState.errors.length) { - const failState = this.state; - this.state = oldState; - this.state.tokensLength = failState.tokensLength; - return { - node, - error: failState.errors[oldState.errors.length], - thrown: false, - aborted: false, - failState - }; - } - return { - node, - error: null, - thrown: false, - aborted: false, - failState: null - }; - } catch (error) { - const failState = this.state; - this.state = oldState; - if (error instanceof SyntaxError) { - return { - node: null, - error, - thrown: true, - aborted: false, - failState - }; - } - if (error === abortSignal) { - return { - node: abortSignal.node, - error: null, - thrown: false, - aborted: true, - failState - }; - } - throw error; - } - } - checkExpressionErrors(refExpressionErrors, andThrow) { - if (!refExpressionErrors) return false; - const { - shorthandAssignLoc, - doubleProtoLoc, - privateKeyLoc, - optionalParametersLoc - } = refExpressionErrors; - const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc; - if (!andThrow) { - return hasErrors; - } - if (shorthandAssignLoc != null) { - this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); - } - if (doubleProtoLoc != null) { - this.raise(Errors.DuplicateProto, doubleProtoLoc); - } - if (privateKeyLoc != null) { - this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); - } - if (optionalParametersLoc != null) { - this.unexpected(optionalParametersLoc); - } - } - isLiteralPropertyName() { - return tokenIsLiteralPropertyName(this.state.type); - } - isPrivateName(node) { - return node.type === "PrivateName"; - } - getPrivateNameSV(node) { - return node.id.name; - } - hasPropertyAsPrivateName(node) { - return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property); - } - isObjectProperty(node) { - return node.type === "ObjectProperty"; - } - isObjectMethod(node) { - return node.type === "ObjectMethod"; - } - initializeScopes(inModule = this.options.sourceType === "module") { - const oldLabels = this.state.labels; - this.state.labels = []; - const oldExportedIdentifiers = this.exportedIdentifiers; - this.exportedIdentifiers = new Set(); - const oldInModule = this.inModule; - this.inModule = inModule; - const oldScope = this.scope; - const ScopeHandler = this.getScopeHandler(); - this.scope = new ScopeHandler(this, inModule); - const oldProdParam = this.prodParam; - this.prodParam = new ProductionParameterHandler(); - const oldClassScope = this.classScope; - this.classScope = new ClassScopeHandler(this); - const oldExpressionScope = this.expressionScope; - this.expressionScope = new ExpressionScopeHandler(this); - return () => { - this.state.labels = oldLabels; - this.exportedIdentifiers = oldExportedIdentifiers; - this.inModule = oldInModule; - this.scope = oldScope; - this.prodParam = oldProdParam; - this.classScope = oldClassScope; - this.expressionScope = oldExpressionScope; - }; - } - enterInitialScopes() { - let paramFlags = 0; - if (this.inModule) { - paramFlags |= 2; - } - this.scope.enter(1); - this.prodParam.enter(paramFlags); - } - checkDestructuringPrivate(refExpressionErrors) { - const { - privateKeyLoc - } = refExpressionErrors; - if (privateKeyLoc !== null) { - this.expectPlugin("destructuringPrivate", privateKeyLoc); - } - } - } - class ExpressionErrors { - constructor() { - this.shorthandAssignLoc = null; - this.doubleProtoLoc = null; - this.privateKeyLoc = null; - this.optionalParametersLoc = null; - } - } - let Node$5 = class Node { - constructor(parser, pos, loc) { - this.type = ""; - this.start = pos; - this.end = 0; - this.loc = new SourceLocation(loc); - if (parser != null && parser.options.ranges) this.range = [pos, 0]; - if (parser != null && parser.filename) this.loc.filename = parser.filename; - } - }; - const NodePrototype = Node$5.prototype; - { - NodePrototype.__clone = function () { - const newNode = new Node$5(undefined, this.start, this.loc.start); - const keys = Object.keys(this); - for (let i = 0, length = keys.length; i < length; i++) { - const key = keys[i]; - if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { - newNode[key] = this[key]; - } - } - return newNode; - }; - } - function clonePlaceholder(node) { - return cloneIdentifier(node); - } - function cloneIdentifier(node) { - const { - type, - start, - end, - loc, - range, - extra, - name - } = node; - const cloned = Object.create(NodePrototype); - cloned.type = type; - cloned.start = start; - cloned.end = end; - cloned.loc = loc; - cloned.range = range; - cloned.extra = extra; - cloned.name = name; - if (type === "Placeholder") { - cloned.expectedNode = node.expectedNode; - } - return cloned; - } - function cloneStringLiteral(node) { - const { - type, - start, - end, - loc, - range, - extra - } = node; - if (type === "Placeholder") { - return clonePlaceholder(node); - } - const cloned = Object.create(NodePrototype); - cloned.type = type; - cloned.start = start; - cloned.end = end; - cloned.loc = loc; - cloned.range = range; - if (node.raw !== undefined) { - cloned.raw = node.raw; - } else { - cloned.extra = extra; - } - cloned.value = node.value; - return cloned; - } - class NodeUtils extends UtilParser { - startNode() { - const loc = this.state.startLoc; - return new Node$5(this, loc.index, loc); - } - startNodeAt(loc) { - return new Node$5(this, loc.index, loc); - } - startNodeAtNode(type) { - return this.startNodeAt(type.loc.start); - } - finishNode(node, type) { - return this.finishNodeAt(node, type, this.state.lastTokEndLoc); - } - finishNodeAt(node, type, endLoc) { - node.type = type; - node.end = endLoc.index; - node.loc.end = endLoc; - if (this.options.ranges) node.range[1] = endLoc.index; - if (this.options.attachComment) this.processComment(node); - return node; - } - resetStartLocation(node, startLoc) { - node.start = startLoc.index; - node.loc.start = startLoc; - if (this.options.ranges) node.range[0] = startLoc.index; - } - resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { - node.end = endLoc.index; - node.loc.end = endLoc; - if (this.options.ranges) node.range[1] = endLoc.index; - } - resetStartLocationFromNode(node, locationNode) { - this.resetStartLocation(node, locationNode.loc.start); - } - } - const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); - const FlowErrors = ParseErrorEnum`flow`({ - AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", - AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.", - AssignReservedType: ({ - reservedType - }) => `Cannot overwrite reserved type ${reservedType}.`, - DeclareClassElement: "The `declare` modifier can only appear on class fields.", - DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", - DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.", - EnumBooleanMemberNotInitialized: ({ - memberName, - enumName - }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`, - EnumDuplicateMemberName: ({ - memberName, - enumName - }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`, - EnumInconsistentMemberValues: ({ - enumName - }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`, - EnumInvalidExplicitType: ({ - invalidEnumType, - enumName - }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, - EnumInvalidExplicitTypeUnknownSupplied: ({ - enumName - }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, - EnumInvalidMemberInitializerPrimaryType: ({ - enumName, - memberName, - explicitType - }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`, - EnumInvalidMemberInitializerSymbolType: ({ - enumName, - memberName - }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`, - EnumInvalidMemberInitializerUnknownType: ({ - enumName, - memberName - }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`, - EnumInvalidMemberName: ({ - enumName, - memberName, - suggestion - }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`, - EnumNumberMemberNotInitialized: ({ - enumName, - memberName - }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`, - EnumStringMemberInconsistentlyInitialized: ({ - enumName - }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`, - GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.", - ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.", - ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.", - InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.", - InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.", - InexactVariance: "Explicit inexact syntax cannot have variance.", - InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.", - MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", - NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.", - NestedFlowComment: "Cannot have a flow comment inside another flow comment.", - PatternIsOptional: Object.assign({ - message: "A binding pattern parameter cannot be optional in an implementation signature." - }, { - reasonCode: "OptionalBindingPattern" - }), - SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.", - SpreadVariance: "Spread properties cannot have variance.", - ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.", - ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.", - ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.", - ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.", - ThisParamNoDefault: "The `this` parameter may not have a default value.", - TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", - TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.", - UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.", - UnexpectedReservedType: ({ - reservedType - }) => `Unexpected reserved type ${reservedType}.`, - UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.", - UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", - UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.", - UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".', - UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.", - UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.", - UnsupportedDeclareExportKind: ({ - unsupportedExportKind, - suggestion - }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`, - UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.", - UnterminatedFlowComment: "Unterminated flow-comment." - }); - function isEsModuleType(bodyElement) { - return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); - } - function hasTypeImportKind(node) { - return node.importKind === "type" || node.importKind === "typeof"; - } - const exportSuggestions = { - const: "declare export var", - let: "declare export var", - type: "export type", - interface: "export interface" - }; - function partition(list, test) { - const list1 = []; - const list2 = []; - for (let i = 0; i < list.length; i++) { - (test(list[i], i, list) ? list1 : list2).push(list[i]); - } - return [list1, list2]; - } - const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; - var flow = superClass => class FlowParserMixin extends superClass { - constructor(...args) { - super(...args); - this.flowPragma = undefined; - } - getScopeHandler() { - return FlowScopeHandler; - } - shouldParseTypes() { - return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; - } - shouldParseEnums() { - return !!this.getPluginOption("flow", "enums"); - } - finishToken(type, val) { - if (type !== 133 && type !== 13 && type !== 28) { - if (this.flowPragma === undefined) { - this.flowPragma = null; - } - } - super.finishToken(type, val); - } - addComment(comment) { - if (this.flowPragma === undefined) { - const matches = FLOW_PRAGMA_REGEX.exec(comment.value); - if (!matches); else if (matches[1] === "flow") { - this.flowPragma = "flow"; - } else if (matches[1] === "noflow") { - this.flowPragma = "noflow"; - } else { - throw new Error("Unexpected flow pragma"); - } - } - super.addComment(comment); - } - flowParseTypeInitialiser(tok) { - const oldInType = this.state.inType; - this.state.inType = true; - this.expect(tok || 14); - const type = this.flowParseType(); - this.state.inType = oldInType; - return type; - } - flowParsePredicate() { - const node = this.startNode(); - const moduloLoc = this.state.startLoc; - this.next(); - this.expectContextual(110); - if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) { - this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc); - } - if (this.eat(10)) { - node.value = super.parseExpression(); - this.expect(11); - return this.finishNode(node, "DeclaredPredicate"); - } else { - return this.finishNode(node, "InferredPredicate"); - } - } - flowParseTypeAndPredicateInitialiser() { - const oldInType = this.state.inType; - this.state.inType = true; - this.expect(14); - let type = null; - let predicate = null; - if (this.match(54)) { - this.state.inType = oldInType; - predicate = this.flowParsePredicate(); - } else { - type = this.flowParseType(); - this.state.inType = oldInType; - if (this.match(54)) { - predicate = this.flowParsePredicate(); - } - } - return [type, predicate]; - } - flowParseDeclareClass(node) { - this.next(); - this.flowParseInterfaceish(node, true); - return this.finishNode(node, "DeclareClass"); - } - flowParseDeclareFunction(node) { - this.next(); - const id = node.id = this.parseIdentifier(); - const typeNode = this.startNode(); - const typeContainer = this.startNode(); - if (this.match(47)) { - typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); - } else { - typeNode.typeParameters = null; - } - this.expect(10); - const tmp = this.flowParseFunctionTypeParams(); - typeNode.params = tmp.params; - typeNode.rest = tmp.rest; - typeNode.this = tmp._this; - this.expect(11); - [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); - typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); - id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); - this.resetEndLocation(id); - this.semicolon(); - this.scope.declareName(node.id.name, 2048, node.id.loc.start); - return this.finishNode(node, "DeclareFunction"); - } - flowParseDeclare(node, insideModule) { - if (this.match(80)) { - return this.flowParseDeclareClass(node); - } else if (this.match(68)) { - return this.flowParseDeclareFunction(node); - } else if (this.match(74)) { - return this.flowParseDeclareVariable(node); - } else if (this.eatContextual(127)) { - if (this.match(16)) { - return this.flowParseDeclareModuleExports(node); - } else { - if (insideModule) { - this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc); - } - return this.flowParseDeclareModule(node); - } - } else if (this.isContextual(130)) { - return this.flowParseDeclareTypeAlias(node); - } else if (this.isContextual(131)) { - return this.flowParseDeclareOpaqueType(node); - } else if (this.isContextual(129)) { - return this.flowParseDeclareInterface(node); - } else if (this.match(82)) { - return this.flowParseDeclareExportDeclaration(node, insideModule); - } else { - this.unexpected(); - } - } - flowParseDeclareVariable(node) { - this.next(); - node.id = this.flowParseTypeAnnotatableIdentifier(true); - this.scope.declareName(node.id.name, 5, node.id.loc.start); - this.semicolon(); - return this.finishNode(node, "DeclareVariable"); - } - flowParseDeclareModule(node) { - this.scope.enter(0); - if (this.match(133)) { - node.id = super.parseExprAtom(); - } else { - node.id = this.parseIdentifier(); - } - const bodyNode = node.body = this.startNode(); - const body = bodyNode.body = []; - this.expect(5); - while (!this.match(8)) { - let bodyNode = this.startNode(); - if (this.match(83)) { - this.next(); - if (!this.isContextual(130) && !this.match(87)) { - this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc); - } - super.parseImport(bodyNode); - } else { - this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule); - bodyNode = this.flowParseDeclare(bodyNode, true); - } - body.push(bodyNode); - } - this.scope.exit(); - this.expect(8); - this.finishNode(bodyNode, "BlockStatement"); - let kind = null; - let hasModuleExport = false; - body.forEach(bodyElement => { - if (isEsModuleType(bodyElement)) { - if (kind === "CommonJS") { - this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); - } - kind = "ES"; - } else if (bodyElement.type === "DeclareModuleExports") { - if (hasModuleExport) { - this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement); - } - if (kind === "ES") { - this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); - } - kind = "CommonJS"; - hasModuleExport = true; - } - }); - node.kind = kind || "CommonJS"; - return this.finishNode(node, "DeclareModule"); - } - flowParseDeclareExportDeclaration(node, insideModule) { - this.expect(82); - if (this.eat(65)) { - if (this.match(68) || this.match(80)) { - node.declaration = this.flowParseDeclare(this.startNode()); - } else { - node.declaration = this.flowParseType(); - this.semicolon(); - } - node.default = true; - return this.finishNode(node, "DeclareExportDeclaration"); - } else { - if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) { - const label = this.state.value; - throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, { - unsupportedExportKind: label, - suggestion: exportSuggestions[label] - }); - } - if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) { - node.declaration = this.flowParseDeclare(this.startNode()); - node.default = false; - return this.finishNode(node, "DeclareExportDeclaration"); - } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) { - node = this.parseExport(node, null); - if (node.type === "ExportNamedDeclaration") { - node.type = "ExportDeclaration"; - node.default = false; - delete node.exportKind; - } - node.type = "Declare" + node.type; - return node; - } - } - this.unexpected(); - } - flowParseDeclareModuleExports(node) { - this.next(); - this.expectContextual(111); - node.typeAnnotation = this.flowParseTypeAnnotation(); - this.semicolon(); - return this.finishNode(node, "DeclareModuleExports"); - } - flowParseDeclareTypeAlias(node) { - this.next(); - const finished = this.flowParseTypeAlias(node); - finished.type = "DeclareTypeAlias"; - return finished; - } - flowParseDeclareOpaqueType(node) { - this.next(); - const finished = this.flowParseOpaqueType(node, true); - finished.type = "DeclareOpaqueType"; - return finished; - } - flowParseDeclareInterface(node) { - this.next(); - this.flowParseInterfaceish(node, false); - return this.finishNode(node, "DeclareInterface"); - } - flowParseInterfaceish(node, isClass) { - node.id = this.flowParseRestrictedIdentifier(!isClass, true); - this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start); - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterDeclaration(); - } else { - node.typeParameters = null; - } - node.extends = []; - if (this.eat(81)) { - do { - node.extends.push(this.flowParseInterfaceExtends()); - } while (!isClass && this.eat(12)); - } - if (isClass) { - node.implements = []; - node.mixins = []; - if (this.eatContextual(117)) { - do { - node.mixins.push(this.flowParseInterfaceExtends()); - } while (this.eat(12)); - } - if (this.eatContextual(113)) { - do { - node.implements.push(this.flowParseInterfaceExtends()); - } while (this.eat(12)); - } - } - node.body = this.flowParseObjectType({ - allowStatic: isClass, - allowExact: false, - allowSpread: false, - allowProto: isClass, - allowInexact: false - }); - } - flowParseInterfaceExtends() { - const node = this.startNode(); - node.id = this.flowParseQualifiedTypeIdentifier(); - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterInstantiation(); - } else { - node.typeParameters = null; - } - return this.finishNode(node, "InterfaceExtends"); - } - flowParseInterface(node) { - this.flowParseInterfaceish(node, false); - return this.finishNode(node, "InterfaceDeclaration"); - } - checkNotUnderscore(word) { - if (word === "_") { - this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc); - } - } - checkReservedType(word, startLoc, declaration) { - if (!reservedTypes.has(word)) return; - this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, { - reservedType: word - }); - } - flowParseRestrictedIdentifier(liberal, declaration) { - this.checkReservedType(this.state.value, this.state.startLoc, declaration); - return this.parseIdentifier(liberal); - } - flowParseTypeAlias(node) { - node.id = this.flowParseRestrictedIdentifier(false, true); - this.scope.declareName(node.id.name, 8201, node.id.loc.start); - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterDeclaration(); - } else { - node.typeParameters = null; - } - node.right = this.flowParseTypeInitialiser(29); - this.semicolon(); - return this.finishNode(node, "TypeAlias"); - } - flowParseOpaqueType(node, declare) { - this.expectContextual(130); - node.id = this.flowParseRestrictedIdentifier(true, true); - this.scope.declareName(node.id.name, 8201, node.id.loc.start); - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterDeclaration(); - } else { - node.typeParameters = null; - } - node.supertype = null; - if (this.match(14)) { - node.supertype = this.flowParseTypeInitialiser(14); - } - node.impltype = null; - if (!declare) { - node.impltype = this.flowParseTypeInitialiser(29); - } - this.semicolon(); - return this.finishNode(node, "OpaqueType"); - } - flowParseTypeParameter(requireDefault = false) { - const nodeStartLoc = this.state.startLoc; - const node = this.startNode(); - const variance = this.flowParseVariance(); - const ident = this.flowParseTypeAnnotatableIdentifier(); - node.name = ident.name; - node.variance = variance; - node.bound = ident.typeAnnotation; - if (this.match(29)) { - this.eat(29); - node.default = this.flowParseType(); - } else { - if (requireDefault) { - this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc); - } - } - return this.finishNode(node, "TypeParameter"); - } - flowParseTypeParameterDeclaration() { - const oldInType = this.state.inType; - const node = this.startNode(); - node.params = []; - this.state.inType = true; - if (this.match(47) || this.match(142)) { - this.next(); - } else { - this.unexpected(); - } - let defaultRequired = false; - do { - const typeParameter = this.flowParseTypeParameter(defaultRequired); - node.params.push(typeParameter); - if (typeParameter.default) { - defaultRequired = true; - } - if (!this.match(48)) { - this.expect(12); - } - } while (!this.match(48)); - this.expect(48); - this.state.inType = oldInType; - return this.finishNode(node, "TypeParameterDeclaration"); - } - flowParseTypeParameterInstantiation() { - const node = this.startNode(); - const oldInType = this.state.inType; - node.params = []; - this.state.inType = true; - this.expect(47); - const oldNoAnonFunctionType = this.state.noAnonFunctionType; - this.state.noAnonFunctionType = false; - while (!this.match(48)) { - node.params.push(this.flowParseType()); - if (!this.match(48)) { - this.expect(12); - } - } - this.state.noAnonFunctionType = oldNoAnonFunctionType; - this.expect(48); - this.state.inType = oldInType; - return this.finishNode(node, "TypeParameterInstantiation"); - } - flowParseTypeParameterInstantiationCallOrNew() { - const node = this.startNode(); - const oldInType = this.state.inType; - node.params = []; - this.state.inType = true; - this.expect(47); - while (!this.match(48)) { - node.params.push(this.flowParseTypeOrImplicitInstantiation()); - if (!this.match(48)) { - this.expect(12); - } - } - this.expect(48); - this.state.inType = oldInType; - return this.finishNode(node, "TypeParameterInstantiation"); - } - flowParseInterfaceType() { - const node = this.startNode(); - this.expectContextual(129); - node.extends = []; - if (this.eat(81)) { - do { - node.extends.push(this.flowParseInterfaceExtends()); - } while (this.eat(12)); - } - node.body = this.flowParseObjectType({ - allowStatic: false, - allowExact: false, - allowSpread: false, - allowProto: false, - allowInexact: false - }); - return this.finishNode(node, "InterfaceTypeAnnotation"); - } - flowParseObjectPropertyKey() { - return this.match(134) || this.match(133) ? super.parseExprAtom() : this.parseIdentifier(true); - } - flowParseObjectTypeIndexer(node, isStatic, variance) { - node.static = isStatic; - if (this.lookahead().type === 14) { - node.id = this.flowParseObjectPropertyKey(); - node.key = this.flowParseTypeInitialiser(); - } else { - node.id = null; - node.key = this.flowParseType(); - } - this.expect(3); - node.value = this.flowParseTypeInitialiser(); - node.variance = variance; - return this.finishNode(node, "ObjectTypeIndexer"); - } - flowParseObjectTypeInternalSlot(node, isStatic) { - node.static = isStatic; - node.id = this.flowParseObjectPropertyKey(); - this.expect(3); - this.expect(3); - if (this.match(47) || this.match(10)) { - node.method = true; - node.optional = false; - node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); - } else { - node.method = false; - if (this.eat(17)) { - node.optional = true; - } - node.value = this.flowParseTypeInitialiser(); - } - return this.finishNode(node, "ObjectTypeInternalSlot"); - } - flowParseObjectTypeMethodish(node) { - node.params = []; - node.rest = null; - node.typeParameters = null; - node.this = null; - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterDeclaration(); - } - this.expect(10); - if (this.match(78)) { - node.this = this.flowParseFunctionTypeParam(true); - node.this.name = null; - if (!this.match(11)) { - this.expect(12); - } - } - while (!this.match(11) && !this.match(21)) { - node.params.push(this.flowParseFunctionTypeParam(false)); - if (!this.match(11)) { - this.expect(12); - } - } - if (this.eat(21)) { - node.rest = this.flowParseFunctionTypeParam(false); - } - this.expect(11); - node.returnType = this.flowParseTypeInitialiser(); - return this.finishNode(node, "FunctionTypeAnnotation"); - } - flowParseObjectTypeCallProperty(node, isStatic) { - const valueNode = this.startNode(); - node.static = isStatic; - node.value = this.flowParseObjectTypeMethodish(valueNode); - return this.finishNode(node, "ObjectTypeCallProperty"); - } - flowParseObjectType({ - allowStatic, - allowExact, - allowSpread, - allowProto, - allowInexact - }) { - const oldInType = this.state.inType; - this.state.inType = true; - const nodeStart = this.startNode(); - nodeStart.callProperties = []; - nodeStart.properties = []; - nodeStart.indexers = []; - nodeStart.internalSlots = []; - let endDelim; - let exact; - let inexact = false; - if (allowExact && this.match(6)) { - this.expect(6); - endDelim = 9; - exact = true; - } else { - this.expect(5); - endDelim = 8; - exact = false; - } - nodeStart.exact = exact; - while (!this.match(endDelim)) { - let isStatic = false; - let protoStartLoc = null; - let inexactStartLoc = null; - const node = this.startNode(); - if (allowProto && this.isContextual(118)) { - const lookahead = this.lookahead(); - if (lookahead.type !== 14 && lookahead.type !== 17) { - this.next(); - protoStartLoc = this.state.startLoc; - allowStatic = false; - } - } - if (allowStatic && this.isContextual(106)) { - const lookahead = this.lookahead(); - if (lookahead.type !== 14 && lookahead.type !== 17) { - this.next(); - isStatic = true; - } - } - const variance = this.flowParseVariance(); - if (this.eat(0)) { - if (protoStartLoc != null) { - this.unexpected(protoStartLoc); - } - if (this.eat(0)) { - if (variance) { - this.unexpected(variance.loc.start); - } - nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); - } else { - nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); - } - } else if (this.match(10) || this.match(47)) { - if (protoStartLoc != null) { - this.unexpected(protoStartLoc); - } - if (variance) { - this.unexpected(variance.loc.start); - } - nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); - } else { - let kind = "init"; - if (this.isContextual(99) || this.isContextual(104)) { - const lookahead = this.lookahead(); - if (tokenIsLiteralPropertyName(lookahead.type)) { - kind = this.state.value; - this.next(); - } - } - const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); - if (propOrInexact === null) { - inexact = true; - inexactStartLoc = this.state.lastTokStartLoc; - } else { - nodeStart.properties.push(propOrInexact); - } - } - this.flowObjectTypeSemicolon(); - if (inexactStartLoc && !this.match(8) && !this.match(9)) { - this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc); - } - } - this.expect(endDelim); - if (allowSpread) { - nodeStart.inexact = inexact; - } - const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); - this.state.inType = oldInType; - return out; - } - flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) { - if (this.eat(21)) { - const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9); - if (isInexactToken) { - if (!allowSpread) { - this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc); - } else if (!allowInexact) { - this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc); - } - if (variance) { - this.raise(FlowErrors.InexactVariance, variance); - } - return null; - } - if (!allowSpread) { - this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc); - } - if (protoStartLoc != null) { - this.unexpected(protoStartLoc); - } - if (variance) { - this.raise(FlowErrors.SpreadVariance, variance); - } - node.argument = this.flowParseType(); - return this.finishNode(node, "ObjectTypeSpreadProperty"); - } else { - node.key = this.flowParseObjectPropertyKey(); - node.static = isStatic; - node.proto = protoStartLoc != null; - node.kind = kind; - let optional = false; - if (this.match(47) || this.match(10)) { - node.method = true; - if (protoStartLoc != null) { - this.unexpected(protoStartLoc); - } - if (variance) { - this.unexpected(variance.loc.start); - } - node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); - if (kind === "get" || kind === "set") { - this.flowCheckGetterSetterParams(node); - } - if (!allowSpread && node.key.name === "constructor" && node.value.this) { - this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this); - } - } else { - if (kind !== "init") this.unexpected(); - node.method = false; - if (this.eat(17)) { - optional = true; - } - node.value = this.flowParseTypeInitialiser(); - node.variance = variance; - } - node.optional = optional; - return this.finishNode(node, "ObjectTypeProperty"); - } - } - flowCheckGetterSetterParams(property) { - const paramCount = property.kind === "get" ? 0 : 1; - const length = property.value.params.length + (property.value.rest ? 1 : 0); - if (property.value.this) { - this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this); - } - if (length !== paramCount) { - this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property); - } - if (property.kind === "set" && property.value.rest) { - this.raise(Errors.BadSetterRestParameter, property); - } - } - flowObjectTypeSemicolon() { - if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) { - this.unexpected(); - } - } - flowParseQualifiedTypeIdentifier(startLoc, id) { - var _startLoc; - (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; - let node = id || this.flowParseRestrictedIdentifier(true); - while (this.eat(16)) { - const node2 = this.startNodeAt(startLoc); - node2.qualification = node; - node2.id = this.flowParseRestrictedIdentifier(true); - node = this.finishNode(node2, "QualifiedTypeIdentifier"); - } - return node; - } - flowParseGenericType(startLoc, id) { - const node = this.startNodeAt(startLoc); - node.typeParameters = null; - node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id); - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterInstantiation(); - } - return this.finishNode(node, "GenericTypeAnnotation"); - } - flowParseTypeofType() { - const node = this.startNode(); - this.expect(87); - node.argument = this.flowParsePrimaryType(); - return this.finishNode(node, "TypeofTypeAnnotation"); - } - flowParseTupleType() { - const node = this.startNode(); - node.types = []; - this.expect(0); - while (this.state.pos < this.length && !this.match(3)) { - node.types.push(this.flowParseType()); - if (this.match(3)) break; - this.expect(12); - } - this.expect(3); - return this.finishNode(node, "TupleTypeAnnotation"); - } - flowParseFunctionTypeParam(first) { - let name = null; - let optional = false; - let typeAnnotation = null; - const node = this.startNode(); - const lh = this.lookahead(); - const isThis = this.state.type === 78; - if (lh.type === 14 || lh.type === 17) { - if (isThis && !first) { - this.raise(FlowErrors.ThisParamMustBeFirst, node); - } - name = this.parseIdentifier(isThis); - if (this.eat(17)) { - optional = true; - if (isThis) { - this.raise(FlowErrors.ThisParamMayNotBeOptional, node); - } - } - typeAnnotation = this.flowParseTypeInitialiser(); - } else { - typeAnnotation = this.flowParseType(); - } - node.name = name; - node.optional = optional; - node.typeAnnotation = typeAnnotation; - return this.finishNode(node, "FunctionTypeParam"); - } - reinterpretTypeAsFunctionTypeParam(type) { - const node = this.startNodeAt(type.loc.start); - node.name = null; - node.optional = false; - node.typeAnnotation = type; - return this.finishNode(node, "FunctionTypeParam"); - } - flowParseFunctionTypeParams(params = []) { - let rest = null; - let _this = null; - if (this.match(78)) { - _this = this.flowParseFunctionTypeParam(true); - _this.name = null; - if (!this.match(11)) { - this.expect(12); - } - } - while (!this.match(11) && !this.match(21)) { - params.push(this.flowParseFunctionTypeParam(false)); - if (!this.match(11)) { - this.expect(12); - } - } - if (this.eat(21)) { - rest = this.flowParseFunctionTypeParam(false); - } - return { - params, - rest, - _this - }; - } - flowIdentToTypeAnnotation(startLoc, node, id) { - switch (id.name) { - case "any": - return this.finishNode(node, "AnyTypeAnnotation"); - case "bool": - case "boolean": - return this.finishNode(node, "BooleanTypeAnnotation"); - case "mixed": - return this.finishNode(node, "MixedTypeAnnotation"); - case "empty": - return this.finishNode(node, "EmptyTypeAnnotation"); - case "number": - return this.finishNode(node, "NumberTypeAnnotation"); - case "string": - return this.finishNode(node, "StringTypeAnnotation"); - case "symbol": - return this.finishNode(node, "SymbolTypeAnnotation"); - default: - this.checkNotUnderscore(id.name); - return this.flowParseGenericType(startLoc, id); - } - } - flowParsePrimaryType() { - const startLoc = this.state.startLoc; - const node = this.startNode(); - let tmp; - let type; - let isGroupedType = false; - const oldNoAnonFunctionType = this.state.noAnonFunctionType; - switch (this.state.type) { - case 5: - return this.flowParseObjectType({ - allowStatic: false, - allowExact: false, - allowSpread: true, - allowProto: false, - allowInexact: true - }); - case 6: - return this.flowParseObjectType({ - allowStatic: false, - allowExact: true, - allowSpread: true, - allowProto: false, - allowInexact: false - }); - case 0: - this.state.noAnonFunctionType = false; - type = this.flowParseTupleType(); - this.state.noAnonFunctionType = oldNoAnonFunctionType; - return type; - case 47: - node.typeParameters = this.flowParseTypeParameterDeclaration(); - this.expect(10); - tmp = this.flowParseFunctionTypeParams(); - node.params = tmp.params; - node.rest = tmp.rest; - node.this = tmp._this; - this.expect(11); - this.expect(19); - node.returnType = this.flowParseType(); - return this.finishNode(node, "FunctionTypeAnnotation"); - case 10: - this.next(); - if (!this.match(11) && !this.match(21)) { - if (tokenIsIdentifier(this.state.type) || this.match(78)) { - const token = this.lookahead().type; - isGroupedType = token !== 17 && token !== 14; - } else { - isGroupedType = true; - } - } - if (isGroupedType) { - this.state.noAnonFunctionType = false; - type = this.flowParseType(); - this.state.noAnonFunctionType = oldNoAnonFunctionType; - if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) { - this.expect(11); - return type; - } else { - this.eat(12); - } - } - if (type) { - tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); - } else { - tmp = this.flowParseFunctionTypeParams(); - } - node.params = tmp.params; - node.rest = tmp.rest; - node.this = tmp._this; - this.expect(11); - this.expect(19); - node.returnType = this.flowParseType(); - node.typeParameters = null; - return this.finishNode(node, "FunctionTypeAnnotation"); - case 133: - return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); - case 85: - case 86: - node.value = this.match(85); - this.next(); - return this.finishNode(node, "BooleanLiteralTypeAnnotation"); - case 53: - if (this.state.value === "-") { - this.next(); - if (this.match(134)) { - return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node); - } - if (this.match(135)) { - return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); - } - throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc); - } - this.unexpected(); - return; - case 134: - return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); - case 135: - return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); - case 88: - this.next(); - return this.finishNode(node, "VoidTypeAnnotation"); - case 84: - this.next(); - return this.finishNode(node, "NullLiteralTypeAnnotation"); - case 78: - this.next(); - return this.finishNode(node, "ThisTypeAnnotation"); - case 55: - this.next(); - return this.finishNode(node, "ExistsTypeAnnotation"); - case 87: - return this.flowParseTypeofType(); - default: - if (tokenIsKeyword(this.state.type)) { - const label = tokenLabelName(this.state.type); - this.next(); - return super.createIdentifier(node, label); - } else if (tokenIsIdentifier(this.state.type)) { - if (this.isContextual(129)) { - return this.flowParseInterfaceType(); - } - return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier()); - } - } - this.unexpected(); - } - flowParsePostfixType() { - const startLoc = this.state.startLoc; - let type = this.flowParsePrimaryType(); - let seenOptionalIndexedAccess = false; - while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) { - const node = this.startNodeAt(startLoc); - const optional = this.eat(18); - seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional; - this.expect(0); - if (!optional && this.match(3)) { - node.elementType = type; - this.next(); - type = this.finishNode(node, "ArrayTypeAnnotation"); - } else { - node.objectType = type; - node.indexType = this.flowParseType(); - this.expect(3); - if (seenOptionalIndexedAccess) { - node.optional = optional; - type = this.finishNode(node, "OptionalIndexedAccessType"); - } else { - type = this.finishNode(node, "IndexedAccessType"); - } - } - } - return type; - } - flowParsePrefixType() { - const node = this.startNode(); - if (this.eat(17)) { - node.typeAnnotation = this.flowParsePrefixType(); - return this.finishNode(node, "NullableTypeAnnotation"); - } else { - return this.flowParsePostfixType(); - } - } - flowParseAnonFunctionWithoutParens() { - const param = this.flowParsePrefixType(); - if (!this.state.noAnonFunctionType && this.eat(19)) { - const node = this.startNodeAt(param.loc.start); - node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; - node.rest = null; - node.this = null; - node.returnType = this.flowParseType(); - node.typeParameters = null; - return this.finishNode(node, "FunctionTypeAnnotation"); - } - return param; - } - flowParseIntersectionType() { - const node = this.startNode(); - this.eat(45); - const type = this.flowParseAnonFunctionWithoutParens(); - node.types = [type]; - while (this.eat(45)) { - node.types.push(this.flowParseAnonFunctionWithoutParens()); - } - return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); - } - flowParseUnionType() { - const node = this.startNode(); - this.eat(43); - const type = this.flowParseIntersectionType(); - node.types = [type]; - while (this.eat(43)) { - node.types.push(this.flowParseIntersectionType()); - } - return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); - } - flowParseType() { - const oldInType = this.state.inType; - this.state.inType = true; - const type = this.flowParseUnionType(); - this.state.inType = oldInType; - return type; - } - flowParseTypeOrImplicitInstantiation() { - if (this.state.type === 132 && this.state.value === "_") { - const startLoc = this.state.startLoc; - const node = this.parseIdentifier(); - return this.flowParseGenericType(startLoc, node); - } else { - return this.flowParseType(); - } - } - flowParseTypeAnnotation() { - const node = this.startNode(); - node.typeAnnotation = this.flowParseTypeInitialiser(); - return this.finishNode(node, "TypeAnnotation"); - } - flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { - const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); - if (this.match(14)) { - ident.typeAnnotation = this.flowParseTypeAnnotation(); - this.resetEndLocation(ident); - } - return ident; - } - typeCastToParameter(node) { - node.expression.typeAnnotation = node.typeAnnotation; - this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); - return node.expression; - } - flowParseVariance() { - let variance = null; - if (this.match(53)) { - variance = this.startNode(); - if (this.state.value === "+") { - variance.kind = "plus"; - } else { - variance.kind = "minus"; - } - this.next(); - return this.finishNode(variance, "Variance"); - } - return variance; - } - parseFunctionBody(node, allowExpressionBody, isMethod = false) { - if (allowExpressionBody) { - this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod)); - return; - } - super.parseFunctionBody(node, false, isMethod); - } - parseFunctionBodyAndFinish(node, type, isMethod = false) { - if (this.match(14)) { - const typeNode = this.startNode(); - [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); - node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; - } - return super.parseFunctionBodyAndFinish(node, type, isMethod); - } - parseStatementLike(flags) { - if (this.state.strict && this.isContextual(129)) { - const lookahead = this.lookahead(); - if (tokenIsKeywordOrIdentifier(lookahead.type)) { - const node = this.startNode(); - this.next(); - return this.flowParseInterface(node); - } - } else if (this.shouldParseEnums() && this.isContextual(126)) { - const node = this.startNode(); - this.next(); - return this.flowParseEnumDeclaration(node); - } - const stmt = super.parseStatementLike(flags); - if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { - this.flowPragma = null; - } - return stmt; - } - parseExpressionStatement(node, expr, decorators) { - if (expr.type === "Identifier") { - if (expr.name === "declare") { - if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) { - return this.flowParseDeclare(node); - } - } else if (tokenIsIdentifier(this.state.type)) { - if (expr.name === "interface") { - return this.flowParseInterface(node); - } else if (expr.name === "type") { - return this.flowParseTypeAlias(node); - } else if (expr.name === "opaque") { - return this.flowParseOpaqueType(node, false); - } - } - } - return super.parseExpressionStatement(node, expr, decorators); - } - shouldParseExportDeclaration() { - const { - type - } = this.state; - if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) { - return !this.state.containsEsc; - } - return super.shouldParseExportDeclaration(); - } - isExportDefaultSpecifier() { - const { - type - } = this.state; - if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) { - return this.state.containsEsc; - } - return super.isExportDefaultSpecifier(); - } - parseExportDefaultExpression() { - if (this.shouldParseEnums() && this.isContextual(126)) { - const node = this.startNode(); - this.next(); - return this.flowParseEnumDeclaration(node); - } - return super.parseExportDefaultExpression(); - } - parseConditional(expr, startLoc, refExpressionErrors) { - if (!this.match(17)) return expr; - if (this.state.maybeInArrowParameters) { - const nextCh = this.lookaheadCharCode(); - if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { - this.setOptionalParametersError(refExpressionErrors); - return expr; - } - } - this.expect(17); - const state = this.state.clone(); - const originalNoArrowAt = this.state.noArrowAt; - const node = this.startNodeAt(startLoc); - let { - consequent, - failed - } = this.tryParseConditionalConsequent(); - let [valid, invalid] = this.getArrowLikeExpressions(consequent); - if (failed || invalid.length > 0) { - const noArrowAt = [...originalNoArrowAt]; - if (invalid.length > 0) { - this.state = state; - this.state.noArrowAt = noArrowAt; - for (let i = 0; i < invalid.length; i++) { - noArrowAt.push(invalid[i].start); - } - ({ - consequent, - failed - } = this.tryParseConditionalConsequent()); - [valid, invalid] = this.getArrowLikeExpressions(consequent); - } - if (failed && valid.length > 1) { - this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc); - } - if (failed && valid.length === 1) { - this.state = state; - noArrowAt.push(valid[0].start); - this.state.noArrowAt = noArrowAt; - ({ - consequent, - failed - } = this.tryParseConditionalConsequent()); - } - } - this.getArrowLikeExpressions(consequent, true); - this.state.noArrowAt = originalNoArrowAt; - this.expect(14); - node.test = expr; - node.consequent = consequent; - node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined)); - return this.finishNode(node, "ConditionalExpression"); - } - tryParseConditionalConsequent() { - this.state.noArrowParamsConversionAt.push(this.state.start); - const consequent = this.parseMaybeAssignAllowIn(); - const failed = !this.match(14); - this.state.noArrowParamsConversionAt.pop(); - return { - consequent, - failed - }; - } - getArrowLikeExpressions(node, disallowInvalid) { - const stack = [node]; - const arrows = []; - while (stack.length !== 0) { - const node = stack.pop(); - if (node.type === "ArrowFunctionExpression") { - if (node.typeParameters || !node.returnType) { - this.finishArrowValidation(node); - } else { - arrows.push(node); - } - stack.push(node.body); - } else if (node.type === "ConditionalExpression") { - stack.push(node.consequent); - stack.push(node.alternate); - } - } - if (disallowInvalid) { - arrows.forEach(node => this.finishArrowValidation(node)); - return [arrows, []]; - } - return partition(arrows, node => node.params.every(param => this.isAssignable(param, true))); - } - finishArrowValidation(node) { - var _node$extra; - this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false); - this.scope.enter(2 | 4); - super.checkParams(node, false, true); - this.scope.exit(); - } - forwardNoArrowParamsConversionAt(node, parse) { - let result; - if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { - this.state.noArrowParamsConversionAt.push(this.state.start); - result = parse(); - this.state.noArrowParamsConversionAt.pop(); - } else { - result = parse(); - } - return result; - } - parseParenItem(node, startLoc) { - node = super.parseParenItem(node, startLoc); - if (this.eat(17)) { - node.optional = true; - this.resetEndLocation(node); - } - if (this.match(14)) { - const typeCastNode = this.startNodeAt(startLoc); - typeCastNode.expression = node; - typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); - return this.finishNode(typeCastNode, "TypeCastExpression"); - } - return node; - } - assertModuleNodeAllowed(node) { - if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { - return; - } - super.assertModuleNodeAllowed(node); - } - parseExportDeclaration(node) { - if (this.isContextual(130)) { - node.exportKind = "type"; - const declarationNode = this.startNode(); - this.next(); - if (this.match(5)) { - node.specifiers = this.parseExportSpecifiers(true); - super.parseExportFrom(node); - return null; - } else { - return this.flowParseTypeAlias(declarationNode); - } - } else if (this.isContextual(131)) { - node.exportKind = "type"; - const declarationNode = this.startNode(); - this.next(); - return this.flowParseOpaqueType(declarationNode, false); - } else if (this.isContextual(129)) { - node.exportKind = "type"; - const declarationNode = this.startNode(); - this.next(); - return this.flowParseInterface(declarationNode); - } else if (this.shouldParseEnums() && this.isContextual(126)) { - node.exportKind = "value"; - const declarationNode = this.startNode(); - this.next(); - return this.flowParseEnumDeclaration(declarationNode); - } else { - return super.parseExportDeclaration(node); - } - } - eatExportStar(node) { - if (super.eatExportStar(node)) return true; - if (this.isContextual(130) && this.lookahead().type === 55) { - node.exportKind = "type"; - this.next(); - this.next(); - return true; - } - return false; - } - maybeParseExportNamespaceSpecifier(node) { - const { - startLoc - } = this.state; - const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); - if (hasNamespace && node.exportKind === "type") { - this.unexpected(startLoc); - } - return hasNamespace; - } - parseClassId(node, isStatement, optionalId) { - super.parseClassId(node, isStatement, optionalId); - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterDeclaration(); - } - } - parseClassMember(classBody, member, state) { - const { - startLoc - } = this.state; - if (this.isContextual(125)) { - if (super.parseClassMemberFromModifier(classBody, member)) { - return; - } - member.declare = true; - } - super.parseClassMember(classBody, member, state); - if (member.declare) { - if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { - this.raise(FlowErrors.DeclareClassElement, startLoc); - } else if (member.value) { - this.raise(FlowErrors.DeclareClassFieldInitializer, member.value); - } - } - } - isIterator(word) { - return word === "iterator" || word === "asyncIterator"; - } - readIterator() { - const word = super.readWord1(); - const fullWord = "@@" + word; - if (!this.isIterator(word) || !this.state.inType) { - this.raise(Errors.InvalidIdentifier, this.state.curPosition(), { - identifierName: fullWord - }); - } - this.finishToken(132, fullWord); - } - getTokenFromCode(code) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (code === 123 && next === 124) { - this.finishOp(6, 2); - } else if (this.state.inType && (code === 62 || code === 60)) { - this.finishOp(code === 62 ? 48 : 47, 1); - } else if (this.state.inType && code === 63) { - if (next === 46) { - this.finishOp(18, 2); - } else { - this.finishOp(17, 1); - } - } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) { - this.state.pos += 2; - this.readIterator(); - } else { - super.getTokenFromCode(code); - } - } - isAssignable(node, isBinding) { - if (node.type === "TypeCastExpression") { - return this.isAssignable(node.expression, isBinding); - } else { - return super.isAssignable(node, isBinding); - } - } - toAssignable(node, isLHS = false) { - if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") { - node.left = this.typeCastToParameter(node.left); - } - super.toAssignable(node, isLHS); - } - toAssignableList(exprList, trailingCommaLoc, isLHS) { - for (let i = 0; i < exprList.length; i++) { - const expr = exprList[i]; - if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { - exprList[i] = this.typeCastToParameter(expr); - } - } - super.toAssignableList(exprList, trailingCommaLoc, isLHS); - } - toReferencedList(exprList, isParenthesizedExpr) { - for (let i = 0; i < exprList.length; i++) { - var _expr$extra; - const expr = exprList[i]; - if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { - this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation); - } - } - return exprList; - } - parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { - const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); - if (canBePattern && !this.state.maybeInArrowParameters) { - this.toReferencedList(node.elements); - } - return node; - } - isValidLVal(type, isParenthesized, binding) { - return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding); - } - parseClassProperty(node) { - if (this.match(14)) { - node.typeAnnotation = this.flowParseTypeAnnotation(); - } - return super.parseClassProperty(node); - } - parseClassPrivateProperty(node) { - if (this.match(14)) { - node.typeAnnotation = this.flowParseTypeAnnotation(); - } - return super.parseClassPrivateProperty(node); - } - isClassMethod() { - return this.match(47) || super.isClassMethod(); - } - isClassProperty() { - return this.match(14) || super.isClassProperty(); - } - isNonstaticConstructor(method) { - return !this.match(14) && super.isNonstaticConstructor(method); - } - pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { - if (method.variance) { - this.unexpected(method.variance.loc.start); - } - delete method.variance; - if (this.match(47)) { - method.typeParameters = this.flowParseTypeParameterDeclaration(); - } - super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); - if (method.params && isConstructor) { - const params = method.params; - if (params.length > 0 && this.isThisParam(params[0])) { - this.raise(FlowErrors.ThisParamBannedInConstructor, method); - } - } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { - const params = method.value.params; - if (params.length > 0 && this.isThisParam(params[0])) { - this.raise(FlowErrors.ThisParamBannedInConstructor, method); - } - } - } - pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { - if (method.variance) { - this.unexpected(method.variance.loc.start); - } - delete method.variance; - if (this.match(47)) { - method.typeParameters = this.flowParseTypeParameterDeclaration(); - } - super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); - } - parseClassSuper(node) { - super.parseClassSuper(node); - if (node.superClass && this.match(47)) { - node.superTypeParameters = this.flowParseTypeParameterInstantiation(); - } - if (this.isContextual(113)) { - this.next(); - const implemented = node.implements = []; - do { - const node = this.startNode(); - node.id = this.flowParseRestrictedIdentifier(true); - if (this.match(47)) { - node.typeParameters = this.flowParseTypeParameterInstantiation(); - } else { - node.typeParameters = null; - } - implemented.push(this.finishNode(node, "ClassImplements")); - } while (this.eat(12)); - } - } - checkGetterSetterParams(method) { - super.checkGetterSetterParams(method); - const params = this.getObjectOrClassMethodParams(method); - if (params.length > 0) { - const param = params[0]; - if (this.isThisParam(param) && method.kind === "get") { - this.raise(FlowErrors.GetterMayNotHaveThisParam, param); - } else if (this.isThisParam(param)) { - this.raise(FlowErrors.SetterMayNotHaveThisParam, param); - } - } - } - parsePropertyNamePrefixOperator(node) { - node.variance = this.flowParseVariance(); - } - parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { - if (prop.variance) { - this.unexpected(prop.variance.loc.start); - } - delete prop.variance; - let typeParameters; - if (this.match(47) && !isAccessor) { - typeParameters = this.flowParseTypeParameterDeclaration(); - if (!this.match(10)) this.unexpected(); - } - const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); - if (typeParameters) { - (result.value || result).typeParameters = typeParameters; - } - return result; - } - parseAssignableListItemTypes(param) { - if (this.eat(17)) { - if (param.type !== "Identifier") { - this.raise(FlowErrors.PatternIsOptional, param); - } - if (this.isThisParam(param)) { - this.raise(FlowErrors.ThisParamMayNotBeOptional, param); - } - param.optional = true; - } - if (this.match(14)) { - param.typeAnnotation = this.flowParseTypeAnnotation(); - } else if (this.isThisParam(param)) { - this.raise(FlowErrors.ThisParamAnnotationRequired, param); - } - if (this.match(29) && this.isThisParam(param)) { - this.raise(FlowErrors.ThisParamNoDefault, param); - } - this.resetEndLocation(param); - return param; - } - parseMaybeDefault(startLoc, left) { - const node = super.parseMaybeDefault(startLoc, left); - if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { - this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation); - } - return node; - } - checkImportReflection(node) { - super.checkImportReflection(node); - if (node.module && node.importKind !== "value") { - this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); - } - } - parseImportSpecifierLocal(node, specifier, type) { - specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier(); - node.specifiers.push(this.finishImportSpecifier(specifier, type)); - } - isPotentialImportPhase(isExport) { - if (super.isPotentialImportPhase(isExport)) return true; - if (this.isContextual(130)) { - if (!isExport) return true; - const ch = this.lookaheadCharCode(); - return ch === 123 || ch === 42; - } - return !isExport && this.isContextual(87); - } - applyImportPhase(node, isExport, phase, loc) { - super.applyImportPhase(node, isExport, phase, loc); - if (isExport) { - if (!phase && this.match(65)) { - return; - } - node.exportKind = phase === "type" ? phase : "value"; - } else { - if (phase === "type" && this.match(55)) this.unexpected(); - node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; - } - } - parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { - const firstIdent = specifier.imported; - let specifierTypeKind = null; - if (firstIdent.type === "Identifier") { - if (firstIdent.name === "type") { - specifierTypeKind = "type"; - } else if (firstIdent.name === "typeof") { - specifierTypeKind = "typeof"; - } - } - let isBinding = false; - if (this.isContextual(93) && !this.isLookaheadContextual("as")) { - const as_ident = this.parseIdentifier(true); - if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) { - specifier.imported = as_ident; - specifier.importKind = specifierTypeKind; - specifier.local = cloneIdentifier(as_ident); - } else { - specifier.imported = firstIdent; - specifier.importKind = null; - specifier.local = this.parseIdentifier(); - } - } else { - if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) { - specifier.imported = this.parseIdentifier(true); - specifier.importKind = specifierTypeKind; - } else { - if (importedIsString) { - throw this.raise(Errors.ImportBindingIsString, specifier, { - importName: firstIdent.value - }); - } - specifier.imported = firstIdent; - specifier.importKind = null; - } - if (this.eatContextual(93)) { - specifier.local = this.parseIdentifier(); - } else { - isBinding = true; - specifier.local = cloneIdentifier(specifier.imported); - } - } - const specifierIsTypeImport = hasTypeImportKind(specifier); - if (isInTypeOnlyImport && specifierIsTypeImport) { - this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier); - } - if (isInTypeOnlyImport || specifierIsTypeImport) { - this.checkReservedType(specifier.local.name, specifier.local.loc.start, true); - } - if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) { - this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true); - } - return this.finishImportSpecifier(specifier, "ImportSpecifier"); - } - parseBindingAtom() { - switch (this.state.type) { - case 78: - return this.parseIdentifier(true); - default: - return super.parseBindingAtom(); - } - } - parseFunctionParams(node, isConstructor) { - const kind = node.kind; - if (kind !== "get" && kind !== "set" && this.match(47)) { - node.typeParameters = this.flowParseTypeParameterDeclaration(); - } - super.parseFunctionParams(node, isConstructor); - } - parseVarId(decl, kind) { - super.parseVarId(decl, kind); - if (this.match(14)) { - decl.id.typeAnnotation = this.flowParseTypeAnnotation(); - this.resetEndLocation(decl.id); - } - } - parseAsyncArrowFromCallExpression(node, call) { - if (this.match(14)) { - const oldNoAnonFunctionType = this.state.noAnonFunctionType; - this.state.noAnonFunctionType = true; - node.returnType = this.flowParseTypeAnnotation(); - this.state.noAnonFunctionType = oldNoAnonFunctionType; - } - return super.parseAsyncArrowFromCallExpression(node, call); - } - shouldParseAsyncArrow() { - return this.match(14) || super.shouldParseAsyncArrow(); - } - parseMaybeAssign(refExpressionErrors, afterLeftParse) { - var _jsx; - let state = null; - let jsx; - if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { - state = this.state.clone(); - jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); - if (!jsx.error) return jsx.node; - const { - context - } = this.state; - const currentContext = context[context.length - 1]; - if (currentContext === types$1.j_oTag || currentContext === types$1.j_expr) { - context.pop(); - } - } - if ((_jsx = jsx) != null && _jsx.error || this.match(47)) { - var _jsx2, _jsx3; - state = state || this.state.clone(); - let typeParameters; - const arrow = this.tryParse(abort => { - var _arrowExpression$extr; - typeParameters = this.flowParseTypeParameterDeclaration(); - const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => { - const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); - this.resetStartLocationFromNode(result, typeParameters); - return result; - }); - if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort(); - const expr = this.maybeUnwrapTypeCastExpression(arrowExpression); - if (expr.type !== "ArrowFunctionExpression") abort(); - expr.typeParameters = typeParameters; - this.resetStartLocationFromNode(expr, typeParameters); - return arrowExpression; - }, state); - let arrowExpression = null; - if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { - if (!arrow.error && !arrow.aborted) { - if (arrow.node.async) { - this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters); - } - return arrow.node; - } - arrowExpression = arrow.node; - } - if ((_jsx2 = jsx) != null && _jsx2.node) { - this.state = jsx.failState; - return jsx.node; - } - if (arrowExpression) { - this.state = arrow.failState; - return arrowExpression; - } - if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; - if (arrow.thrown) throw arrow.error; - throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters); - } - return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); - } - parseArrow(node) { - if (this.match(14)) { - const result = this.tryParse(() => { - const oldNoAnonFunctionType = this.state.noAnonFunctionType; - this.state.noAnonFunctionType = true; - const typeNode = this.startNode(); - [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); - this.state.noAnonFunctionType = oldNoAnonFunctionType; - if (this.canInsertSemicolon()) this.unexpected(); - if (!this.match(19)) this.unexpected(); - return typeNode; - }); - if (result.thrown) return null; - if (result.error) this.state = result.failState; - node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; - } - return super.parseArrow(node); - } - shouldParseArrow(params) { - return this.match(14) || super.shouldParseArrow(params); - } - setArrowFunctionParameters(node, params) { - if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { - node.params = params; - } else { - super.setArrowFunctionParameters(node, params); - } - } - checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { - if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { - return; - } - for (let i = 0; i < node.params.length; i++) { - if (this.isThisParam(node.params[i]) && i > 0) { - this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]); - } - } - super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged); - } - parseParenAndDistinguishExpression(canBeArrow) { - return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1); - } - parseSubscripts(base, startLoc, noCalls) { - if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startLoc.index) !== -1) { - this.next(); - const node = this.startNodeAt(startLoc); - node.callee = base; - node.arguments = super.parseCallExpressionArguments(11, false); - base = this.finishNode(node, "CallExpression"); - } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) { - const state = this.state.clone(); - const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state); - if (!arrow.error && !arrow.aborted) return arrow.node; - const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state); - if (result.node && !result.error) return result.node; - if (arrow.node) { - this.state = arrow.failState; - return arrow.node; - } - if (result.node) { - this.state = result.failState; - return result.node; - } - throw arrow.error || result.error; - } - return super.parseSubscripts(base, startLoc, noCalls); - } - parseSubscript(base, startLoc, noCalls, subscriptState) { - if (this.match(18) && this.isLookaheadToken_lt()) { - subscriptState.optionalChainMember = true; - if (noCalls) { - subscriptState.stop = true; - return base; - } - this.next(); - const node = this.startNodeAt(startLoc); - node.callee = base; - node.typeArguments = this.flowParseTypeParameterInstantiation(); - this.expect(10); - node.arguments = this.parseCallExpressionArguments(11, false); - node.optional = true; - return this.finishCallExpression(node, true); - } else if (!noCalls && this.shouldParseTypes() && this.match(47)) { - const node = this.startNodeAt(startLoc); - node.callee = base; - const result = this.tryParse(() => { - node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); - this.expect(10); - node.arguments = super.parseCallExpressionArguments(11, false); - if (subscriptState.optionalChainMember) { - node.optional = false; - } - return this.finishCallExpression(node, subscriptState.optionalChainMember); - }); - if (result.node) { - if (result.error) this.state = result.failState; - return result.node; - } - } - return super.parseSubscript(base, startLoc, noCalls, subscriptState); - } - parseNewCallee(node) { - super.parseNewCallee(node); - let targs = null; - if (this.shouldParseTypes() && this.match(47)) { - targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; - } - node.typeArguments = targs; - } - parseAsyncArrowWithTypeParameters(startLoc) { - const node = this.startNodeAt(startLoc); - this.parseFunctionParams(node, false); - if (!this.parseArrow(node)) return; - return super.parseArrowExpression(node, undefined, true); - } - readToken_mult_modulo(code) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (code === 42 && next === 47 && this.state.hasFlowComment) { - this.state.hasFlowComment = false; - this.state.pos += 2; - this.nextToken(); - return; - } - super.readToken_mult_modulo(code); - } - readToken_pipe_amp(code) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (code === 124 && next === 125) { - this.finishOp(9, 2); - return; - } - super.readToken_pipe_amp(code); - } - parseTopLevel(file, program) { - const fileNode = super.parseTopLevel(file, program); - if (this.state.hasFlowComment) { - this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition()); - } - return fileNode; - } - skipBlockComment() { - if (this.hasPlugin("flowComments") && this.skipFlowComment()) { - if (this.state.hasFlowComment) { - throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc); - } - this.hasFlowCommentCompletion(); - const commentSkip = this.skipFlowComment(); - if (commentSkip) { - this.state.pos += commentSkip; - this.state.hasFlowComment = true; - } - return; - } - return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/"); - } - skipFlowComment() { - const { - pos - } = this.state; - let shiftToFirstNonWhiteSpace = 2; - while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { - shiftToFirstNonWhiteSpace++; - } - const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); - const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); - if (ch2 === 58 && ch3 === 58) { - return shiftToFirstNonWhiteSpace + 2; - } - if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { - return shiftToFirstNonWhiteSpace + 12; - } - if (ch2 === 58 && ch3 !== 58) { - return shiftToFirstNonWhiteSpace; - } - return false; - } - hasFlowCommentCompletion() { - const end = this.input.indexOf("*/", this.state.pos); - if (end === -1) { - throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); - } - } - flowEnumErrorBooleanMemberNotInitialized(loc, { - enumName, - memberName - }) { - this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, { - memberName, - enumName - }); - } - flowEnumErrorInvalidMemberInitializer(loc, enumContext) { - return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext); - } - flowEnumErrorNumberMemberNotInitialized(loc, details) { - this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details); - } - flowEnumErrorStringMemberInconsistentlyInitialized(node, details) { - this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details); - } - flowEnumMemberInit() { - const startLoc = this.state.startLoc; - const endOfInit = () => this.match(12) || this.match(8); - switch (this.state.type) { - case 134: - { - const literal = this.parseNumericLiteral(this.state.value); - if (endOfInit()) { - return { - type: "number", - loc: literal.loc.start, - value: literal - }; - } - return { - type: "invalid", - loc: startLoc - }; - } - case 133: - { - const literal = this.parseStringLiteral(this.state.value); - if (endOfInit()) { - return { - type: "string", - loc: literal.loc.start, - value: literal - }; - } - return { - type: "invalid", - loc: startLoc - }; - } - case 85: - case 86: - { - const literal = this.parseBooleanLiteral(this.match(85)); - if (endOfInit()) { - return { - type: "boolean", - loc: literal.loc.start, - value: literal - }; - } - return { - type: "invalid", - loc: startLoc - }; - } - default: - return { - type: "invalid", - loc: startLoc - }; - } - } - flowEnumMemberRaw() { - const loc = this.state.startLoc; - const id = this.parseIdentifier(true); - const init = this.eat(29) ? this.flowEnumMemberInit() : { - type: "none", - loc - }; - return { - id, - init - }; - } - flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) { - const { - explicitType - } = context; - if (explicitType === null) { - return; - } - if (explicitType !== expectedType) { - this.flowEnumErrorInvalidMemberInitializer(loc, context); - } - } - flowEnumMembers({ - enumName, - explicitType - }) { - const seenNames = new Set(); - const members = { - booleanMembers: [], - numberMembers: [], - stringMembers: [], - defaultedMembers: [] - }; - let hasUnknownMembers = false; - while (!this.match(8)) { - if (this.eat(21)) { - hasUnknownMembers = true; - break; - } - const memberNode = this.startNode(); - const { - id, - init - } = this.flowEnumMemberRaw(); - const memberName = id.name; - if (memberName === "") { - continue; - } - if (/^[a-z]/.test(memberName)) { - this.raise(FlowErrors.EnumInvalidMemberName, id, { - memberName, - suggestion: memberName[0].toUpperCase() + memberName.slice(1), - enumName - }); - } - if (seenNames.has(memberName)) { - this.raise(FlowErrors.EnumDuplicateMemberName, id, { - memberName, - enumName - }); - } - seenNames.add(memberName); - const context = { - enumName, - explicitType, - memberName - }; - memberNode.id = id; - switch (init.type) { - case "boolean": - { - this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean"); - memberNode.init = init.value; - members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); - break; - } - case "number": - { - this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number"); - memberNode.init = init.value; - members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); - break; - } - case "string": - { - this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string"); - memberNode.init = init.value; - members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); - break; - } - case "invalid": - { - throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context); - } - case "none": - { - switch (explicitType) { - case "boolean": - this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context); - break; - case "number": - this.flowEnumErrorNumberMemberNotInitialized(init.loc, context); - break; - default: - members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); - } - } - } - if (!this.match(8)) { - this.expect(12); - } - } - return { - members, - hasUnknownMembers - }; - } - flowEnumStringMembers(initializedMembers, defaultedMembers, { - enumName - }) { - if (initializedMembers.length === 0) { - return defaultedMembers; - } else if (defaultedMembers.length === 0) { - return initializedMembers; - } else if (defaultedMembers.length > initializedMembers.length) { - for (const member of initializedMembers) { - this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { - enumName - }); - } - return defaultedMembers; - } else { - for (const member of defaultedMembers) { - this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { - enumName - }); - } - return initializedMembers; - } - } - flowEnumParseExplicitType({ - enumName - }) { - if (!this.eatContextual(102)) return null; - if (!tokenIsIdentifier(this.state.type)) { - throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, { - enumName - }); - } - const { - value - } = this.state; - this.next(); - if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { - this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, { - enumName, - invalidEnumType: value - }); - } - return value; - } - flowEnumBody(node, id) { - const enumName = id.name; - const nameLoc = id.loc.start; - const explicitType = this.flowEnumParseExplicitType({ - enumName - }); - this.expect(5); - const { - members, - hasUnknownMembers - } = this.flowEnumMembers({ - enumName, - explicitType - }); - node.hasUnknownMembers = hasUnknownMembers; - switch (explicitType) { - case "boolean": - node.explicitType = true; - node.members = members.booleanMembers; - this.expect(8); - return this.finishNode(node, "EnumBooleanBody"); - case "number": - node.explicitType = true; - node.members = members.numberMembers; - this.expect(8); - return this.finishNode(node, "EnumNumberBody"); - case "string": - node.explicitType = true; - node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { - enumName - }); - this.expect(8); - return this.finishNode(node, "EnumStringBody"); - case "symbol": - node.members = members.defaultedMembers; - this.expect(8); - return this.finishNode(node, "EnumSymbolBody"); - default: - { - const empty = () => { - node.members = []; - this.expect(8); - return this.finishNode(node, "EnumStringBody"); - }; - node.explicitType = false; - const boolsLen = members.booleanMembers.length; - const numsLen = members.numberMembers.length; - const strsLen = members.stringMembers.length; - const defaultedLen = members.defaultedMembers.length; - if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { - return empty(); - } else if (!boolsLen && !numsLen) { - node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { - enumName - }); - this.expect(8); - return this.finishNode(node, "EnumStringBody"); - } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { - for (const member of members.defaultedMembers) { - this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, { - enumName, - memberName: member.id.name - }); - } - node.members = members.booleanMembers; - this.expect(8); - return this.finishNode(node, "EnumBooleanBody"); - } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { - for (const member of members.defaultedMembers) { - this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, { - enumName, - memberName: member.id.name - }); - } - node.members = members.numberMembers; - this.expect(8); - return this.finishNode(node, "EnumNumberBody"); - } else { - this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, { - enumName - }); - return empty(); - } - } - } - } - flowParseEnumDeclaration(node) { - const id = this.parseIdentifier(); - node.id = id; - node.body = this.flowEnumBody(this.startNode(), id); - return this.finishNode(node, "EnumDeclaration"); - } - isLookaheadToken_lt() { - const next = this.nextTokenStart(); - if (this.input.charCodeAt(next) === 60) { - const afterNext = this.input.charCodeAt(next + 1); - return afterNext !== 60 && afterNext !== 61; - } - return false; - } - maybeUnwrapTypeCastExpression(node) { - return node.type === "TypeCastExpression" ? node.expression : node; - } - }; - const entities = { - __proto__: null, - quot: "\u0022", - amp: "&", - apos: "\u0027", - lt: "<", - gt: ">", - nbsp: "\u00A0", - iexcl: "\u00A1", - cent: "\u00A2", - pound: "\u00A3", - curren: "\u00A4", - yen: "\u00A5", - brvbar: "\u00A6", - sect: "\u00A7", - uml: "\u00A8", - copy: "\u00A9", - ordf: "\u00AA", - laquo: "\u00AB", - not: "\u00AC", - shy: "\u00AD", - reg: "\u00AE", - macr: "\u00AF", - deg: "\u00B0", - plusmn: "\u00B1", - sup2: "\u00B2", - sup3: "\u00B3", - acute: "\u00B4", - micro: "\u00B5", - para: "\u00B6", - middot: "\u00B7", - cedil: "\u00B8", - sup1: "\u00B9", - ordm: "\u00BA", - raquo: "\u00BB", - frac14: "\u00BC", - frac12: "\u00BD", - frac34: "\u00BE", - iquest: "\u00BF", - Agrave: "\u00C0", - Aacute: "\u00C1", - Acirc: "\u00C2", - Atilde: "\u00C3", - Auml: "\u00C4", - Aring: "\u00C5", - AElig: "\u00C6", - Ccedil: "\u00C7", - Egrave: "\u00C8", - Eacute: "\u00C9", - Ecirc: "\u00CA", - Euml: "\u00CB", - Igrave: "\u00CC", - Iacute: "\u00CD", - Icirc: "\u00CE", - Iuml: "\u00CF", - ETH: "\u00D0", - Ntilde: "\u00D1", - Ograve: "\u00D2", - Oacute: "\u00D3", - Ocirc: "\u00D4", - Otilde: "\u00D5", - Ouml: "\u00D6", - times: "\u00D7", - Oslash: "\u00D8", - Ugrave: "\u00D9", - Uacute: "\u00DA", - Ucirc: "\u00DB", - Uuml: "\u00DC", - Yacute: "\u00DD", - THORN: "\u00DE", - szlig: "\u00DF", - agrave: "\u00E0", - aacute: "\u00E1", - acirc: "\u00E2", - atilde: "\u00E3", - auml: "\u00E4", - aring: "\u00E5", - aelig: "\u00E6", - ccedil: "\u00E7", - egrave: "\u00E8", - eacute: "\u00E9", - ecirc: "\u00EA", - euml: "\u00EB", - igrave: "\u00EC", - iacute: "\u00ED", - icirc: "\u00EE", - iuml: "\u00EF", - eth: "\u00F0", - ntilde: "\u00F1", - ograve: "\u00F2", - oacute: "\u00F3", - ocirc: "\u00F4", - otilde: "\u00F5", - ouml: "\u00F6", - divide: "\u00F7", - oslash: "\u00F8", - ugrave: "\u00F9", - uacute: "\u00FA", - ucirc: "\u00FB", - uuml: "\u00FC", - yacute: "\u00FD", - thorn: "\u00FE", - yuml: "\u00FF", - OElig: "\u0152", - oelig: "\u0153", - Scaron: "\u0160", - scaron: "\u0161", - Yuml: "\u0178", - fnof: "\u0192", - circ: "\u02C6", - tilde: "\u02DC", - Alpha: "\u0391", - Beta: "\u0392", - Gamma: "\u0393", - Delta: "\u0394", - Epsilon: "\u0395", - Zeta: "\u0396", - Eta: "\u0397", - Theta: "\u0398", - Iota: "\u0399", - Kappa: "\u039A", - Lambda: "\u039B", - Mu: "\u039C", - Nu: "\u039D", - Xi: "\u039E", - Omicron: "\u039F", - Pi: "\u03A0", - Rho: "\u03A1", - Sigma: "\u03A3", - Tau: "\u03A4", - Upsilon: "\u03A5", - Phi: "\u03A6", - Chi: "\u03A7", - Psi: "\u03A8", - Omega: "\u03A9", - alpha: "\u03B1", - beta: "\u03B2", - gamma: "\u03B3", - delta: "\u03B4", - epsilon: "\u03B5", - zeta: "\u03B6", - eta: "\u03B7", - theta: "\u03B8", - iota: "\u03B9", - kappa: "\u03BA", - lambda: "\u03BB", - mu: "\u03BC", - nu: "\u03BD", - xi: "\u03BE", - omicron: "\u03BF", - pi: "\u03C0", - rho: "\u03C1", - sigmaf: "\u03C2", - sigma: "\u03C3", - tau: "\u03C4", - upsilon: "\u03C5", - phi: "\u03C6", - chi: "\u03C7", - psi: "\u03C8", - omega: "\u03C9", - thetasym: "\u03D1", - upsih: "\u03D2", - piv: "\u03D6", - ensp: "\u2002", - emsp: "\u2003", - thinsp: "\u2009", - zwnj: "\u200C", - zwj: "\u200D", - lrm: "\u200E", - rlm: "\u200F", - ndash: "\u2013", - mdash: "\u2014", - lsquo: "\u2018", - rsquo: "\u2019", - sbquo: "\u201A", - ldquo: "\u201C", - rdquo: "\u201D", - bdquo: "\u201E", - dagger: "\u2020", - Dagger: "\u2021", - bull: "\u2022", - hellip: "\u2026", - permil: "\u2030", - prime: "\u2032", - Prime: "\u2033", - lsaquo: "\u2039", - rsaquo: "\u203A", - oline: "\u203E", - frasl: "\u2044", - euro: "\u20AC", - image: "\u2111", - weierp: "\u2118", - real: "\u211C", - trade: "\u2122", - alefsym: "\u2135", - larr: "\u2190", - uarr: "\u2191", - rarr: "\u2192", - darr: "\u2193", - harr: "\u2194", - crarr: "\u21B5", - lArr: "\u21D0", - uArr: "\u21D1", - rArr: "\u21D2", - dArr: "\u21D3", - hArr: "\u21D4", - forall: "\u2200", - part: "\u2202", - exist: "\u2203", - empty: "\u2205", - nabla: "\u2207", - isin: "\u2208", - notin: "\u2209", - ni: "\u220B", - prod: "\u220F", - sum: "\u2211", - minus: "\u2212", - lowast: "\u2217", - radic: "\u221A", - prop: "\u221D", - infin: "\u221E", - ang: "\u2220", - and: "\u2227", - or: "\u2228", - cap: "\u2229", - cup: "\u222A", - int: "\u222B", - there4: "\u2234", - sim: "\u223C", - cong: "\u2245", - asymp: "\u2248", - ne: "\u2260", - equiv: "\u2261", - le: "\u2264", - ge: "\u2265", - sub: "\u2282", - sup: "\u2283", - nsub: "\u2284", - sube: "\u2286", - supe: "\u2287", - oplus: "\u2295", - otimes: "\u2297", - perp: "\u22A5", - sdot: "\u22C5", - lceil: "\u2308", - rceil: "\u2309", - lfloor: "\u230A", - rfloor: "\u230B", - lang: "\u2329", - rang: "\u232A", - loz: "\u25CA", - spades: "\u2660", - clubs: "\u2663", - hearts: "\u2665", - diams: "\u2666" - }; - const JsxErrors = ParseErrorEnum`jsx`({ - AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.", - MissingClosingTagElement: ({ - openingTagName - }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`, - MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.", - UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?", - UnexpectedToken: ({ - unexpected, - HTMLEntity - }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`, - UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.", - UnterminatedJsxContent: "Unterminated JSX contents.", - UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?" - }); - function isFragment(object) { - return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; - } - function getQualifiedJSXName(object) { - if (object.type === "JSXIdentifier") { - return object.name; - } - if (object.type === "JSXNamespacedName") { - return object.namespace.name + ":" + object.name.name; - } - if (object.type === "JSXMemberExpression") { - return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); - } - throw new Error("Node had unexpected type: " + object.type); - } - var jsx = superClass => class JSXParserMixin extends superClass { - jsxReadToken() { - let out = ""; - let chunkStart = this.state.pos; - for (; ;) { - if (this.state.pos >= this.length) { - throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc); - } - const ch = this.input.charCodeAt(this.state.pos); - switch (ch) { - case 60: - case 123: - if (this.state.pos === this.state.start) { - if (ch === 60 && this.state.canStartJSXElement) { - ++this.state.pos; - this.finishToken(142); - } else { - super.getTokenFromCode(ch); - } - return; - } - out += this.input.slice(chunkStart, this.state.pos); - this.finishToken(141, out); - return; - case 38: - out += this.input.slice(chunkStart, this.state.pos); - out += this.jsxReadEntity(); - chunkStart = this.state.pos; - break; - case 62: - case 125: - default: - if (isNewLine(ch)) { - out += this.input.slice(chunkStart, this.state.pos); - out += this.jsxReadNewLine(true); - chunkStart = this.state.pos; - } else { - ++this.state.pos; - } - } - } - } - jsxReadNewLine(normalizeCRLF) { - const ch = this.input.charCodeAt(this.state.pos); - let out; - ++this.state.pos; - if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { - ++this.state.pos; - out = normalizeCRLF ? "\n" : "\r\n"; - } else { - out = String.fromCharCode(ch); - } - ++this.state.curLine; - this.state.lineStart = this.state.pos; - return out; - } - jsxReadString(quote) { - let out = ""; - let chunkStart = ++this.state.pos; - for (; ;) { - if (this.state.pos >= this.length) { - throw this.raise(Errors.UnterminatedString, this.state.startLoc); - } - const ch = this.input.charCodeAt(this.state.pos); - if (ch === quote) break; - if (ch === 38) { - out += this.input.slice(chunkStart, this.state.pos); - out += this.jsxReadEntity(); - chunkStart = this.state.pos; - } else if (isNewLine(ch)) { - out += this.input.slice(chunkStart, this.state.pos); - out += this.jsxReadNewLine(false); - chunkStart = this.state.pos; - } else { - ++this.state.pos; - } - } - out += this.input.slice(chunkStart, this.state.pos++); - this.finishToken(133, out); - } - jsxReadEntity() { - const startPos = ++this.state.pos; - if (this.codePointAtPos(this.state.pos) === 35) { - ++this.state.pos; - let radix = 10; - if (this.codePointAtPos(this.state.pos) === 120) { - radix = 16; - ++this.state.pos; - } - const codePoint = this.readInt(radix, undefined, false, "bail"); - if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) { - ++this.state.pos; - return String.fromCodePoint(codePoint); - } - } else { - let count = 0; - let semi = false; - while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) == 59)) { - ++this.state.pos; - } - if (semi) { - const desc = this.input.slice(startPos, this.state.pos); - const entity = entities[desc]; - ++this.state.pos; - if (entity) { - return entity; - } - } - } - this.state.pos = startPos; - return "&"; - } - jsxReadWord() { - let ch; - const start = this.state.pos; - do { - ch = this.input.charCodeAt(++this.state.pos); - } while (isIdentifierChar(ch) || ch === 45); - this.finishToken(140, this.input.slice(start, this.state.pos)); - } - jsxParseIdentifier() { - const node = this.startNode(); - if (this.match(140)) { - node.name = this.state.value; - } else if (tokenIsKeyword(this.state.type)) { - node.name = tokenLabelName(this.state.type); - } else { - this.unexpected(); - } - this.next(); - return this.finishNode(node, "JSXIdentifier"); - } - jsxParseNamespacedName() { - const startLoc = this.state.startLoc; - const name = this.jsxParseIdentifier(); - if (!this.eat(14)) return name; - const node = this.startNodeAt(startLoc); - node.namespace = name; - node.name = this.jsxParseIdentifier(); - return this.finishNode(node, "JSXNamespacedName"); - } - jsxParseElementName() { - const startLoc = this.state.startLoc; - let node = this.jsxParseNamespacedName(); - if (node.type === "JSXNamespacedName") { - return node; - } - while (this.eat(16)) { - const newNode = this.startNodeAt(startLoc); - newNode.object = node; - newNode.property = this.jsxParseIdentifier(); - node = this.finishNode(newNode, "JSXMemberExpression"); - } - return node; - } - jsxParseAttributeValue() { - let node; - switch (this.state.type) { - case 5: - node = this.startNode(); - this.setContext(types$1.brace); - this.next(); - node = this.jsxParseExpressionContainer(node, types$1.j_oTag); - if (node.expression.type === "JSXEmptyExpression") { - this.raise(JsxErrors.AttributeIsEmpty, node); - } - return node; - case 142: - case 133: - return this.parseExprAtom(); - default: - throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc); - } - } - jsxParseEmptyExpression() { - const node = this.startNodeAt(this.state.lastTokEndLoc); - return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc); - } - jsxParseSpreadChild(node) { - this.next(); - node.expression = this.parseExpression(); - this.setContext(types$1.j_expr); - this.state.canStartJSXElement = true; - this.expect(8); - return this.finishNode(node, "JSXSpreadChild"); - } - jsxParseExpressionContainer(node, previousContext) { - if (this.match(8)) { - node.expression = this.jsxParseEmptyExpression(); - } else { - const expression = this.parseExpression(); - node.expression = expression; - } - this.setContext(previousContext); - this.state.canStartJSXElement = true; - this.expect(8); - return this.finishNode(node, "JSXExpressionContainer"); - } - jsxParseAttribute() { - const node = this.startNode(); - if (this.match(5)) { - this.setContext(types$1.brace); - this.next(); - this.expect(21); - node.argument = this.parseMaybeAssignAllowIn(); - this.setContext(types$1.j_oTag); - this.state.canStartJSXElement = true; - this.expect(8); - return this.finishNode(node, "JSXSpreadAttribute"); - } - node.name = this.jsxParseNamespacedName(); - node.value = this.eat(29) ? this.jsxParseAttributeValue() : null; - return this.finishNode(node, "JSXAttribute"); - } - jsxParseOpeningElementAt(startLoc) { - const node = this.startNodeAt(startLoc); - if (this.eat(143)) { - return this.finishNode(node, "JSXOpeningFragment"); - } - node.name = this.jsxParseElementName(); - return this.jsxParseOpeningElementAfterName(node); - } - jsxParseOpeningElementAfterName(node) { - const attributes = []; - while (!this.match(56) && !this.match(143)) { - attributes.push(this.jsxParseAttribute()); - } - node.attributes = attributes; - node.selfClosing = this.eat(56); - this.expect(143); - return this.finishNode(node, "JSXOpeningElement"); - } - jsxParseClosingElementAt(startLoc) { - const node = this.startNodeAt(startLoc); - if (this.eat(143)) { - return this.finishNode(node, "JSXClosingFragment"); - } - node.name = this.jsxParseElementName(); - this.expect(143); - return this.finishNode(node, "JSXClosingElement"); - } - jsxParseElementAt(startLoc) { - const node = this.startNodeAt(startLoc); - const children = []; - const openingElement = this.jsxParseOpeningElementAt(startLoc); - let closingElement = null; - if (!openingElement.selfClosing) { - contents: for (; ;) { - switch (this.state.type) { - case 142: - startLoc = this.state.startLoc; - this.next(); - if (this.eat(56)) { - closingElement = this.jsxParseClosingElementAt(startLoc); - break contents; - } - children.push(this.jsxParseElementAt(startLoc)); - break; - case 141: - children.push(this.parseExprAtom()); - break; - case 5: - { - const node = this.startNode(); - this.setContext(types$1.brace); - this.next(); - if (this.match(21)) { - children.push(this.jsxParseSpreadChild(node)); - } else { - children.push(this.jsxParseExpressionContainer(node, types$1.j_expr)); - } - break; - } - default: - this.unexpected(); - } - } - if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) { - this.raise(JsxErrors.MissingClosingTagFragment, closingElement); - } else if (!isFragment(openingElement) && isFragment(closingElement)) { - this.raise(JsxErrors.MissingClosingTagElement, closingElement, { - openingTagName: getQualifiedJSXName(openingElement.name) - }); - } else if (!isFragment(openingElement) && !isFragment(closingElement)) { - if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { - this.raise(JsxErrors.MissingClosingTagElement, closingElement, { - openingTagName: getQualifiedJSXName(openingElement.name) - }); - } - } - } - if (isFragment(openingElement)) { - node.openingFragment = openingElement; - node.closingFragment = closingElement; - } else { - node.openingElement = openingElement; - node.closingElement = closingElement; - } - node.children = children; - if (this.match(47)) { - throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc); - } - return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); - } - jsxParseElement() { - const startLoc = this.state.startLoc; - this.next(); - return this.jsxParseElementAt(startLoc); - } - setContext(newContext) { - const { - context - } = this.state; - context[context.length - 1] = newContext; - } - parseExprAtom(refExpressionErrors) { - if (this.match(141)) { - return this.parseLiteral(this.state.value, "JSXText"); - } else if (this.match(142)) { - return this.jsxParseElement(); - } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) { - this.replaceToken(142); - return this.jsxParseElement(); - } else { - return super.parseExprAtom(refExpressionErrors); - } - } - skipSpace() { - const curContext = this.curContext(); - if (!curContext.preserveSpace) super.skipSpace(); - } - getTokenFromCode(code) { - const context = this.curContext(); - if (context === types$1.j_expr) { - this.jsxReadToken(); - return; - } - if (context === types$1.j_oTag || context === types$1.j_cTag) { - if (isIdentifierStart(code)) { - this.jsxReadWord(); - return; - } - if (code === 62) { - ++this.state.pos; - this.finishToken(143); - return; - } - if ((code === 34 || code === 39) && context === types$1.j_oTag) { - this.jsxReadString(code); - return; - } - } - if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) { - ++this.state.pos; - this.finishToken(142); - return; - } - super.getTokenFromCode(code); - } - updateContext(prevType) { - const { - context, - type - } = this.state; - if (type === 56 && prevType === 142) { - context.splice(-2, 2, types$1.j_cTag); - this.state.canStartJSXElement = false; - } else if (type === 142) { - context.push(types$1.j_oTag); - } else if (type === 143) { - const out = context[context.length - 1]; - if (out === types$1.j_oTag && prevType === 56 || out === types$1.j_cTag) { - context.pop(); - this.state.canStartJSXElement = context[context.length - 1] === types$1.j_expr; - } else { - this.setContext(types$1.j_expr); - this.state.canStartJSXElement = true; - } - } else { - this.state.canStartJSXElement = tokenComesBeforeExpression(type); - } - } - }; - class TypeScriptScope extends Scope { - constructor(...args) { - super(...args); - this.tsNames = new Map(); - } - } - class TypeScriptScopeHandler extends ScopeHandler { - constructor(...args) { - super(...args); - this.importsStack = []; - } - createScope(flags) { - this.importsStack.push(new Set()); - return new TypeScriptScope(flags); - } - enter(flags) { - if (flags == 256) { - this.importsStack.push(new Set()); - } - super.enter(flags); - } - exit() { - const flags = super.exit(); - if (flags == 256) { - this.importsStack.pop(); - } - return flags; - } - hasImport(name, allowShadow) { - const len = this.importsStack.length; - if (this.importsStack[len - 1].has(name)) { - return true; - } - if (!allowShadow && len > 1) { - for (let i = 0; i < len - 1; i++) { - if (this.importsStack[i].has(name)) return true; - } - } - return false; - } - declareName(name, bindingType, loc) { - if (bindingType & 4096) { - if (this.hasImport(name, true)) { - this.parser.raise(Errors.VarRedeclaration, loc, { - identifierName: name - }); - } - this.importsStack[this.importsStack.length - 1].add(name); - return; - } - const scope = this.currentScope(); - let type = scope.tsNames.get(name) || 0; - if (bindingType & 1024) { - this.maybeExportDefined(scope, name); - scope.tsNames.set(name, type | 16); - return; - } - super.declareName(name, bindingType, loc); - if (bindingType & 2) { - if (!(bindingType & 1)) { - this.checkRedeclarationInScope(scope, name, bindingType, loc); - this.maybeExportDefined(scope, name); - } - type = type | 1; - } - if (bindingType & 256) { - type = type | 2; - } - if (bindingType & 512) { - type = type | 4; - } - if (bindingType & 128) { - type = type | 8; - } - if (type) scope.tsNames.set(name, type); - } - isRedeclaredInScope(scope, name, bindingType) { - const type = scope.tsNames.get(name); - if ((type & 2) > 0) { - if (bindingType & 256) { - const isConst = !!(bindingType & 512); - const wasConst = (type & 4) > 0; - return isConst !== wasConst; - } - return true; - } - if (bindingType & 128 && (type & 8) > 0) { - if (scope.names.get(name) & 2) { - return !!(bindingType & 1); - } else { - return false; - } - } - if (bindingType & 2 && (type & 1) > 0) { - return true; - } - return super.isRedeclaredInScope(scope, name, bindingType); - } - checkLocalExport(id) { - const { - name - } = id; - if (this.hasImport(name)) return; - const len = this.scopeStack.length; - for (let i = len - 1; i >= 0; i--) { - const scope = this.scopeStack[i]; - const type = scope.tsNames.get(name); - if ((type & 1) > 0 || (type & 16) > 0) { - return; - } - } - super.checkLocalExport(id); - } - } - const getOwn$1 = (object, key) => Object.hasOwnProperty.call(object, key) && object[key]; - const unwrapParenthesizedExpression = node => { - return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; - }; - class LValParser extends NodeUtils { - toAssignable(node, isLHS = false) { - var _node$extra, _node$extra3; - let parenthesized = undefined; - if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) { - parenthesized = unwrapParenthesizedExpression(node); - if (isLHS) { - if (parenthesized.type === "Identifier") { - this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node); - } else if (parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) { - this.raise(Errors.InvalidParenthesizedAssignment, node); - } - } else { - this.raise(Errors.InvalidParenthesizedAssignment, node); - } - } - switch (node.type) { - case "Identifier": - case "ObjectPattern": - case "ArrayPattern": - case "AssignmentPattern": - case "RestElement": - break; - case "ObjectExpression": - node.type = "ObjectPattern"; - for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) { - var _node$extra2; - const prop = node.properties[i]; - const isLast = i === last; - this.toAssignableObjectExpressionProp(prop, isLast, isLHS); - if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) { - this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc); - } - } - break; - case "ObjectProperty": - { - const { - key, - value - } = node; - if (this.isPrivateName(key)) { - this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); - } - this.toAssignable(value, isLHS); - break; - } - case "SpreadElement": - { - throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller."); - } - case "ArrayExpression": - node.type = "ArrayPattern"; - this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS); - break; - case "AssignmentExpression": - if (node.operator !== "=") { - this.raise(Errors.MissingEqInAssignment, node.left.loc.end); - } - node.type = "AssignmentPattern"; - delete node.operator; - this.toAssignable(node.left, isLHS); - break; - case "ParenthesizedExpression": - this.toAssignable(parenthesized, isLHS); - break; - } - } - toAssignableObjectExpressionProp(prop, isLast, isLHS) { - if (prop.type === "ObjectMethod") { - this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key); - } else if (prop.type === "SpreadElement") { - prop.type = "RestElement"; - const arg = prop.argument; - this.checkToRestConversion(arg, false); - this.toAssignable(arg, isLHS); - if (!isLast) { - this.raise(Errors.RestTrailingComma, prop); - } - } else { - this.toAssignable(prop, isLHS); - } - } - toAssignableList(exprList, trailingCommaLoc, isLHS) { - const end = exprList.length - 1; - for (let i = 0; i <= end; i++) { - const elt = exprList[i]; - if (!elt) continue; - if (elt.type === "SpreadElement") { - elt.type = "RestElement"; - const arg = elt.argument; - this.checkToRestConversion(arg, true); - this.toAssignable(arg, isLHS); - } else { - this.toAssignable(elt, isLHS); - } - if (elt.type === "RestElement") { - if (i < end) { - this.raise(Errors.RestTrailingComma, elt); - } else if (trailingCommaLoc) { - this.raise(Errors.RestTrailingComma, trailingCommaLoc); - } - } - } - } - isAssignable(node, isBinding) { - switch (node.type) { - case "Identifier": - case "ObjectPattern": - case "ArrayPattern": - case "AssignmentPattern": - case "RestElement": - return true; - case "ObjectExpression": - { - const last = node.properties.length - 1; - return node.properties.every((prop, i) => { - return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop); - }); - } - case "ObjectProperty": - return this.isAssignable(node.value); - case "SpreadElement": - return this.isAssignable(node.argument); - case "ArrayExpression": - return node.elements.every(element => element === null || this.isAssignable(element)); - case "AssignmentExpression": - return node.operator === "="; - case "ParenthesizedExpression": - return this.isAssignable(node.expression); - case "MemberExpression": - case "OptionalMemberExpression": - return !isBinding; - default: - return false; - } - } - toReferencedList(exprList, isParenthesizedExpr) { - return exprList; - } - toReferencedListDeep(exprList, isParenthesizedExpr) { - this.toReferencedList(exprList, isParenthesizedExpr); - for (const expr of exprList) { - if ((expr == null ? void 0 : expr.type) === "ArrayExpression") { - this.toReferencedListDeep(expr.elements); - } - } - } - parseSpread(refExpressionErrors) { - const node = this.startNode(); - this.next(); - node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined); - return this.finishNode(node, "SpreadElement"); - } - parseRestBinding() { - const node = this.startNode(); - this.next(); - node.argument = this.parseBindingAtom(); - return this.finishNode(node, "RestElement"); - } - parseBindingAtom() { - switch (this.state.type) { - case 0: - { - const node = this.startNode(); - this.next(); - node.elements = this.parseBindingList(3, 93, 1); - return this.finishNode(node, "ArrayPattern"); - } - case 5: - return this.parseObjectLike(8, true); - } - return this.parseIdentifier(); - } - parseBindingList(close, closeCharCode, flags) { - const allowEmpty = flags & 1; - const elts = []; - let first = true; - while (!this.eat(close)) { - if (first) { - first = false; - } else { - this.expect(12); - } - if (allowEmpty && this.match(12)) { - elts.push(null); - } else if (this.eat(close)) { - break; - } else if (this.match(21)) { - elts.push(this.parseAssignableListItemTypes(this.parseRestBinding(), flags)); - if (!this.checkCommaAfterRest(closeCharCode)) { - this.expect(close); - break; - } - } else { - const decorators = []; - if (this.match(26) && this.hasPlugin("decorators")) { - this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc); - } - while (this.match(26)) { - decorators.push(this.parseDecorator()); - } - elts.push(this.parseAssignableListItem(flags, decorators)); - } - } - return elts; - } - parseBindingRestProperty(prop) { - this.next(); - prop.argument = this.parseIdentifier(); - this.checkCommaAfterRest(125); - return this.finishNode(prop, "RestElement"); - } - parseBindingProperty() { - const prop = this.startNode(); - const { - type, - startLoc - } = this.state; - if (type === 21) { - return this.parseBindingRestProperty(prop); - } else if (type === 138) { - this.expectPlugin("destructuringPrivate", startLoc); - this.classScope.usePrivateName(this.state.value, startLoc); - prop.key = this.parsePrivateName(); - } else { - this.parsePropertyName(prop); - } - prop.method = false; - return this.parseObjPropValue(prop, startLoc, false, false, true, false); - } - parseAssignableListItem(flags, decorators) { - const left = this.parseMaybeDefault(); - this.parseAssignableListItemTypes(left, flags); - const elt = this.parseMaybeDefault(left.loc.start, left); - if (decorators.length) { - left.decorators = decorators; - } - return elt; - } - parseAssignableListItemTypes(param, flags) { - return param; - } - parseMaybeDefault(startLoc, left) { - var _startLoc, _left; - (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; - left = (_left = left) != null ? _left : this.parseBindingAtom(); - if (!this.eat(29)) return left; - const node = this.startNodeAt(startLoc); - node.left = left; - node.right = this.parseMaybeAssignAllowIn(); - return this.finishNode(node, "AssignmentPattern"); - } - isValidLVal(type, isUnparenthesizedInAssign, binding) { - return getOwn$1({ - AssignmentPattern: "left", - RestElement: "argument", - ObjectProperty: "value", - ParenthesizedExpression: "expression", - ArrayPattern: "elements", - ObjectPattern: "properties" - }, type); - } - isOptionalMemberExpression(expression) { - return expression.type === "OptionalMemberExpression"; - } - checkLVal(expression, { - in: ancestor, - binding = 64, - checkClashes = false, - strictModeChanged = false, - hasParenthesizedAncestor = false - }) { - var _expression$extra; - const type = expression.type; - if (this.isObjectMethod(expression)) return; - const isOptionalMemberExpression = this.isOptionalMemberExpression(expression); - if (isOptionalMemberExpression || type === "MemberExpression") { - if (isOptionalMemberExpression) { - this.expectPlugin("optionalChainingAssign", expression.loc.start); - if (ancestor.type !== "AssignmentExpression") { - this.raise(Errors.InvalidLhsOptionalChaining, expression, { - ancestor - }); - } - } - if (binding !== 64) { - this.raise(Errors.InvalidPropertyBindingPattern, expression); - } - return; - } - if (type === "Identifier") { - this.checkIdentifier(expression, binding, strictModeChanged); - const { - name - } = expression; - if (checkClashes) { - if (checkClashes.has(name)) { - this.raise(Errors.ParamDupe, expression); - } else { - checkClashes.add(name); - } - } - return; - } - const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding); - if (validity === true) return; - if (validity === false) { - const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding; - this.raise(ParseErrorClass, expression, { - ancestor - }); - return; - } - const [key, isParenthesizedExpression] = Array.isArray(validity) ? validity : [validity, type === "ParenthesizedExpression"]; - const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? { - type - } : ancestor; - for (const child of [].concat(expression[key])) { - if (child) { - this.checkLVal(child, { - in: nextAncestor, - binding, - checkClashes, - strictModeChanged, - hasParenthesizedAncestor: isParenthesizedExpression - }); - } - } - } - checkIdentifier(at, bindingType, strictModeChanged = false) { - if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) { - if (bindingType === 64) { - this.raise(Errors.StrictEvalArguments, at, { - referenceName: at.name - }); - } else { - this.raise(Errors.StrictEvalArgumentsBinding, at, { - bindingName: at.name - }); - } - } - if (bindingType & 8192 && at.name === "let") { - this.raise(Errors.LetInLexicalBinding, at); - } - if (!(bindingType & 64)) { - this.declareNameFromIdentifier(at, bindingType); - } - } - declareNameFromIdentifier(identifier, binding) { - this.scope.declareName(identifier.name, binding, identifier.loc.start); - } - checkToRestConversion(node, allowPattern) { - switch (node.type) { - case "ParenthesizedExpression": - this.checkToRestConversion(node.expression, allowPattern); - break; - case "Identifier": - case "MemberExpression": - break; - case "ArrayExpression": - case "ObjectExpression": - if (allowPattern) break; - default: - this.raise(Errors.InvalidRestAssignmentPattern, node); - } - } - checkCommaAfterRest(close) { - if (!this.match(12)) { - return false; - } - this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc); - return true; - } - } - const getOwn = (object, key) => Object.hasOwnProperty.call(object, key) && object[key]; - function nonNull(x) { - if (x == null) { - throw new Error(`Unexpected ${x} value.`); - } - return x; - } - function assert$1(x) { - if (!x) { - throw new Error("Assert fail"); - } - } - const TSErrors = ParseErrorEnum`typescript`({ - AbstractMethodHasImplementation: ({ - methodName - }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`, - AbstractPropertyHasInitializer: ({ - propertyName - }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`, - AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", - AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.", - AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.", - ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", - ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", - ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.", - ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", - DeclareAccessor: ({ - kind - }) => `'declare' is not allowed in ${kind}ters.`, - DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", - DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", - DuplicateAccessibilityModifier: ({ - modifier - }) => `Accessibility modifier already seen.`, - DuplicateModifier: ({ - modifier - }) => `Duplicate modifier: '${modifier}'.`, - EmptyHeritageClauseType: ({ - token - }) => `'${token}' list cannot be empty.`, - EmptyTypeArguments: "Type argument list cannot be empty.", - EmptyTypeParameters: "Type parameter list cannot be empty.", - ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", - ImportAliasHasImportType: "An import alias can not use 'import type'.", - ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier", - IncompatibleModifiers: ({ - modifiers - }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`, - IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", - IndexSignatureHasAccessibility: ({ - modifier - }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`, - IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", - IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", - IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", - InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.", - InvalidModifierOnTypeMember: ({ - modifier - }) => `'${modifier}' modifier cannot appear on a type member.`, - InvalidModifierOnTypeParameter: ({ - modifier - }) => `'${modifier}' modifier cannot appear on a type parameter.`, - InvalidModifierOnTypeParameterPositions: ({ - modifier - }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`, - InvalidModifiersOrder: ({ - orderedModifiers - }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`, - InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.", - InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", - MissingInterfaceName: "'interface' declarations must be followed by an identifier.", - NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", - NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.", - OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", - OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", - PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", - PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", - PrivateElementHasAccessibility: ({ - modifier - }) => `Private elements cannot have an accessibility modifier ('${modifier}').`, - ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", - ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.", - ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", - SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", - SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", - SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", - SingleTypeParameterWithoutTrailingComma: ({ - typeParameterName - }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`, - StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", - TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).", - TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", - TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", - TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.", - TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.", - UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", - UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", - UnexpectedTypeAnnotation: "Did not expect a type annotation here.", - UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", - UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", - UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", - UnsupportedSignatureParameterKind: ({ - type - }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.` - }); - function keywordTypeFromName(value) { - switch (value) { - case "any": - return "TSAnyKeyword"; - case "boolean": - return "TSBooleanKeyword"; - case "bigint": - return "TSBigIntKeyword"; - case "never": - return "TSNeverKeyword"; - case "number": - return "TSNumberKeyword"; - case "object": - return "TSObjectKeyword"; - case "string": - return "TSStringKeyword"; - case "symbol": - return "TSSymbolKeyword"; - case "undefined": - return "TSUndefinedKeyword"; - case "unknown": - return "TSUnknownKeyword"; - default: - return undefined; - } - } - function tsIsAccessModifier(modifier) { - return modifier === "private" || modifier === "public" || modifier === "protected"; - } - function tsIsVarianceAnnotations(modifier) { - return modifier === "in" || modifier === "out"; - } - var typescript = superClass => class TypeScriptParserMixin extends superClass { - constructor(...args) { - super(...args); - this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, { - allowedModifiers: ["in", "out"], - disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"], - errorTemplate: TSErrors.InvalidModifierOnTypeParameter - }); - this.tsParseConstModifier = this.tsParseModifiers.bind(this, { - allowedModifiers: ["const"], - disallowedModifiers: ["in", "out"], - errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions - }); - this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, { - allowedModifiers: ["in", "out", "const"], - disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"], - errorTemplate: TSErrors.InvalidModifierOnTypeParameter - }); - } - getScopeHandler() { - return TypeScriptScopeHandler; - } - tsIsIdentifier() { - return tokenIsIdentifier(this.state.type); - } - tsTokenCanFollowModifier() { - return (this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(138) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak(); - } - tsNextTokenCanFollowModifier() { - this.next(); - return this.tsTokenCanFollowModifier(); - } - tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) { - if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) { - return undefined; - } - const modifier = this.state.value; - if (allowedModifiers.indexOf(modifier) !== -1) { - if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { - return undefined; - } - if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { - return modifier; - } - } - return undefined; - } - tsParseModifiers({ - allowedModifiers, - disallowedModifiers, - stopOnStartOfClassStaticBlock, - errorTemplate = TSErrors.InvalidModifierOnTypeMember - }, modified) { - const enforceOrder = (loc, modifier, before, after) => { - if (modifier === before && modified[after]) { - this.raise(TSErrors.InvalidModifiersOrder, loc, { - orderedModifiers: [before, after] - }); - } - }; - const incompatible = (loc, modifier, mod1, mod2) => { - if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { - this.raise(TSErrors.IncompatibleModifiers, loc, { - modifiers: [mod1, mod2] - }); - } - }; - for (; ;) { - const { - startLoc - } = this.state; - const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock); - if (!modifier) break; - if (tsIsAccessModifier(modifier)) { - if (modified.accessibility) { - this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, { - modifier - }); - } else { - enforceOrder(startLoc, modifier, modifier, "override"); - enforceOrder(startLoc, modifier, modifier, "static"); - enforceOrder(startLoc, modifier, modifier, "readonly"); - modified.accessibility = modifier; - } - } else if (tsIsVarianceAnnotations(modifier)) { - if (modified[modifier]) { - this.raise(TSErrors.DuplicateModifier, startLoc, { - modifier - }); - } - modified[modifier] = true; - enforceOrder(startLoc, modifier, "in", "out"); - } else { - if (Object.hasOwnProperty.call(modified, modifier)) { - this.raise(TSErrors.DuplicateModifier, startLoc, { - modifier - }); - } else { - enforceOrder(startLoc, modifier, "static", "readonly"); - enforceOrder(startLoc, modifier, "static", "override"); - enforceOrder(startLoc, modifier, "override", "readonly"); - enforceOrder(startLoc, modifier, "abstract", "override"); - incompatible(startLoc, modifier, "declare", "override"); - incompatible(startLoc, modifier, "static", "abstract"); - } - modified[modifier] = true; - } - if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { - this.raise(errorTemplate, startLoc, { - modifier - }); - } - } - } - tsIsListTerminator(kind) { - switch (kind) { - case "EnumMembers": - case "TypeMembers": - return this.match(8); - case "HeritageClauseElement": - return this.match(5); - case "TupleElementTypes": - return this.match(3); - case "TypeParametersOrArguments": - return this.match(48); - } - } - tsParseList(kind, parseElement) { - const result = []; - while (!this.tsIsListTerminator(kind)) { - result.push(parseElement()); - } - return result; - } - tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) { - return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos)); - } - tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) { - const result = []; - let trailingCommaPos = -1; - for (; ;) { - if (this.tsIsListTerminator(kind)) { - break; - } - trailingCommaPos = -1; - const element = parseElement(); - if (element == null) { - return undefined; - } - result.push(element); - if (this.eat(12)) { - trailingCommaPos = this.state.lastTokStartLoc.index; - continue; - } - if (this.tsIsListTerminator(kind)) { - break; - } - if (expectSuccess) { - this.expect(12); - } - return undefined; - } - if (refTrailingCommaPos) { - refTrailingCommaPos.value = trailingCommaPos; - } - return result; - } - tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) { - if (!skipFirstToken) { - if (bracket) { - this.expect(0); - } else { - this.expect(47); - } - } - const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos); - if (bracket) { - this.expect(3); - } else { - this.expect(48); - } - return result; - } - tsParseImportType() { - const node = this.startNode(); - this.expect(83); - this.expect(10); - if (!this.match(133)) { - this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc); - } - node.argument = super.parseExprAtom(); - this.expect(11); - if (this.eat(16)) { - node.qualifier = this.tsParseEntityName(); - } - if (this.match(47)) { - node.typeParameters = this.tsParseTypeArguments(); - } - return this.finishNode(node, "TSImportType"); - } - tsParseEntityName(allowReservedWords = true) { - let entity = this.parseIdentifier(allowReservedWords); - while (this.eat(16)) { - const node = this.startNodeAtNode(entity); - node.left = entity; - node.right = this.parseIdentifier(allowReservedWords); - entity = this.finishNode(node, "TSQualifiedName"); - } - return entity; - } - tsParseTypeReference() { - const node = this.startNode(); - node.typeName = this.tsParseEntityName(); - if (!this.hasPrecedingLineBreak() && this.match(47)) { - node.typeParameters = this.tsParseTypeArguments(); - } - return this.finishNode(node, "TSTypeReference"); - } - tsParseThisTypePredicate(lhs) { - this.next(); - const node = this.startNodeAtNode(lhs); - node.parameterName = lhs; - node.typeAnnotation = this.tsParseTypeAnnotation(false); - node.asserts = false; - return this.finishNode(node, "TSTypePredicate"); - } - tsParseThisTypeNode() { - const node = this.startNode(); - this.next(); - return this.finishNode(node, "TSThisType"); - } - tsParseTypeQuery() { - const node = this.startNode(); - this.expect(87); - if (this.match(83)) { - node.exprName = this.tsParseImportType(); - } else { - node.exprName = this.tsParseEntityName(); - } - if (!this.hasPrecedingLineBreak() && this.match(47)) { - node.typeParameters = this.tsParseTypeArguments(); - } - return this.finishNode(node, "TSTypeQuery"); - } - tsParseTypeParameter(parseModifiers) { - const node = this.startNode(); - parseModifiers(node); - node.name = this.tsParseTypeParameterName(); - node.constraint = this.tsEatThenParseType(81); - node.default = this.tsEatThenParseType(29); - return this.finishNode(node, "TSTypeParameter"); - } - tsTryParseTypeParameters(parseModifiers) { - if (this.match(47)) { - return this.tsParseTypeParameters(parseModifiers); - } - } - tsParseTypeParameters(parseModifiers) { - const node = this.startNode(); - if (this.match(47) || this.match(142)) { - this.next(); - } else { - this.unexpected(); - } - const refTrailingCommaPos = { - value: -1 - }; - node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos); - if (node.params.length === 0) { - this.raise(TSErrors.EmptyTypeParameters, node); - } - if (refTrailingCommaPos.value !== -1) { - this.addExtra(node, "trailingComma", refTrailingCommaPos.value); - } - return this.finishNode(node, "TSTypeParameterDeclaration"); - } - tsFillSignature(returnToken, signature) { - const returnTokenRequired = returnToken === 19; - const paramsKey = "parameters"; - const returnTypeKey = "typeAnnotation"; - signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); - this.expect(10); - signature[paramsKey] = this.tsParseBindingListForSignature(); - if (returnTokenRequired) { - signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); - } else if (this.match(returnToken)) { - signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); - } - } - tsParseBindingListForSignature() { - const list = super.parseBindingList(11, 41, 2); - for (const pattern of list) { - const { - type - } = pattern; - if (type === "AssignmentPattern" || type === "TSParameterProperty") { - this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, { - type - }); - } - } - return list; - } - tsParseTypeMemberSemicolon() { - if (!this.eat(12) && !this.isLineTerminator()) { - this.expect(13); - } - } - tsParseSignatureMember(kind, node) { - this.tsFillSignature(14, node); - this.tsParseTypeMemberSemicolon(); - return this.finishNode(node, kind); - } - tsIsUnambiguouslyIndexSignature() { - this.next(); - if (tokenIsIdentifier(this.state.type)) { - this.next(); - return this.match(14); - } - return false; - } - tsTryParseIndexSignature(node) { - if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { - return; - } - this.expect(0); - const id = this.parseIdentifier(); - id.typeAnnotation = this.tsParseTypeAnnotation(); - this.resetEndLocation(id); - this.expect(3); - node.parameters = [id]; - const type = this.tsTryParseTypeAnnotation(); - if (type) node.typeAnnotation = type; - this.tsParseTypeMemberSemicolon(); - return this.finishNode(node, "TSIndexSignature"); - } - tsParsePropertyOrMethodSignature(node, readonly) { - if (this.eat(17)) node.optional = true; - const nodeAny = node; - if (this.match(10) || this.match(47)) { - if (readonly) { - this.raise(TSErrors.ReadonlyForMethodSignature, node); - } - const method = nodeAny; - if (method.kind && this.match(47)) { - this.raise(TSErrors.AccesorCannotHaveTypeParameters, this.state.curPosition()); - } - this.tsFillSignature(14, method); - this.tsParseTypeMemberSemicolon(); - const paramsKey = "parameters"; - const returnTypeKey = "typeAnnotation"; - if (method.kind === "get") { - if (method[paramsKey].length > 0) { - this.raise(Errors.BadGetterArity, this.state.curPosition()); - if (this.isThisParam(method[paramsKey][0])) { - this.raise(TSErrors.AccesorCannotDeclareThisParameter, this.state.curPosition()); - } - } - } else if (method.kind === "set") { - if (method[paramsKey].length !== 1) { - this.raise(Errors.BadSetterArity, this.state.curPosition()); - } else { - const firstParameter = method[paramsKey][0]; - if (this.isThisParam(firstParameter)) { - this.raise(TSErrors.AccesorCannotDeclareThisParameter, this.state.curPosition()); - } - if (firstParameter.type === "Identifier" && firstParameter.optional) { - this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, this.state.curPosition()); - } - if (firstParameter.type === "RestElement") { - this.raise(TSErrors.SetAccesorCannotHaveRestParameter, this.state.curPosition()); - } - } - if (method[returnTypeKey]) { - this.raise(TSErrors.SetAccesorCannotHaveReturnType, method[returnTypeKey]); - } - } else { - method.kind = "method"; - } - return this.finishNode(method, "TSMethodSignature"); - } else { - const property = nodeAny; - if (readonly) property.readonly = true; - const type = this.tsTryParseTypeAnnotation(); - if (type) property.typeAnnotation = type; - this.tsParseTypeMemberSemicolon(); - return this.finishNode(property, "TSPropertySignature"); - } - } - tsParseTypeMember() { - const node = this.startNode(); - if (this.match(10) || this.match(47)) { - return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); - } - if (this.match(77)) { - const id = this.startNode(); - this.next(); - if (this.match(10) || this.match(47)) { - return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); - } else { - node.key = this.createIdentifier(id, "new"); - return this.tsParsePropertyOrMethodSignature(node, false); - } - } - this.tsParseModifiers({ - allowedModifiers: ["readonly"], - disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"] - }, node); - const idx = this.tsTryParseIndexSignature(node); - if (idx) { - return idx; - } - super.parsePropertyName(node); - if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) { - node.kind = node.key.name; - super.parsePropertyName(node); - } - return this.tsParsePropertyOrMethodSignature(node, !!node.readonly); - } - tsParseTypeLiteral() { - const node = this.startNode(); - node.members = this.tsParseObjectTypeMembers(); - return this.finishNode(node, "TSTypeLiteral"); - } - tsParseObjectTypeMembers() { - this.expect(5); - const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); - this.expect(8); - return members; - } - tsIsStartOfMappedType() { - this.next(); - if (this.eat(53)) { - return this.isContextual(122); - } - if (this.isContextual(122)) { - this.next(); - } - if (!this.match(0)) { - return false; - } - this.next(); - if (!this.tsIsIdentifier()) { - return false; - } - this.next(); - return this.match(58); - } - tsParseMappedTypeParameter() { - const node = this.startNode(); - node.name = this.tsParseTypeParameterName(); - node.constraint = this.tsExpectThenParseType(58); - return this.finishNode(node, "TSTypeParameter"); - } - tsParseMappedType() { - const node = this.startNode(); - this.expect(5); - if (this.match(53)) { - node.readonly = this.state.value; - this.next(); - this.expectContextual(122); - } else if (this.eatContextual(122)) { - node.readonly = true; - } - this.expect(0); - node.typeParameter = this.tsParseMappedTypeParameter(); - node.nameType = this.eatContextual(93) ? this.tsParseType() : null; - this.expect(3); - if (this.match(53)) { - node.optional = this.state.value; - this.next(); - this.expect(17); - } else if (this.eat(17)) { - node.optional = true; - } - node.typeAnnotation = this.tsTryParseType(); - this.semicolon(); - this.expect(8); - return this.finishNode(node, "TSMappedType"); - } - tsParseTupleType() { - const node = this.startNode(); - node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); - let seenOptionalElement = false; - node.elementTypes.forEach(elementNode => { - const { - type - } = elementNode; - if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { - this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode); - } - seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"); - }); - return this.finishNode(node, "TSTupleType"); - } - tsParseTupleElementType() { - const { - startLoc - } = this.state; - const rest = this.eat(21); - let labeled; - let label; - let optional; - let type; - const isWord = tokenIsKeywordOrIdentifier(this.state.type); - const chAfterWord = isWord ? this.lookaheadCharCode() : null; - if (chAfterWord === 58) { - labeled = true; - optional = false; - label = this.parseIdentifier(true); - this.expect(14); - type = this.tsParseType(); - } else if (chAfterWord === 63) { - optional = true; - const startLoc = this.state.startLoc; - const wordName = this.state.value; - const typeOrLabel = this.tsParseNonArrayType(); - if (this.lookaheadCharCode() === 58) { - labeled = true; - label = this.createIdentifier(this.startNodeAt(startLoc), wordName); - this.expect(17); - this.expect(14); - type = this.tsParseType(); - } else { - labeled = false; - type = typeOrLabel; - this.expect(17); - } - } else { - type = this.tsParseType(); - optional = this.eat(17); - labeled = this.eat(14); - } - if (labeled) { - let labeledNode; - if (label) { - labeledNode = this.startNodeAtNode(label); - labeledNode.optional = optional; - labeledNode.label = label; - labeledNode.elementType = type; - if (this.eat(17)) { - labeledNode.optional = true; - this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc); - } - } else { - labeledNode = this.startNodeAtNode(type); - labeledNode.optional = optional; - this.raise(TSErrors.InvalidTupleMemberLabel, type); - labeledNode.label = type; - labeledNode.elementType = this.tsParseType(); - } - type = this.finishNode(labeledNode, "TSNamedTupleMember"); - } else if (optional) { - const optionalTypeNode = this.startNodeAtNode(type); - optionalTypeNode.typeAnnotation = type; - type = this.finishNode(optionalTypeNode, "TSOptionalType"); - } - if (rest) { - const restNode = this.startNodeAt(startLoc); - restNode.typeAnnotation = type; - type = this.finishNode(restNode, "TSRestType"); - } - return type; - } - tsParseParenthesizedType() { - const node = this.startNode(); - this.expect(10); - node.typeAnnotation = this.tsParseType(); - this.expect(11); - return this.finishNode(node, "TSParenthesizedType"); - } - tsParseFunctionOrConstructorType(type, abstract) { - const node = this.startNode(); - if (type === "TSConstructorType") { - node.abstract = !!abstract; - if (abstract) this.next(); - this.next(); - } - this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node)); - return this.finishNode(node, type); - } - tsParseLiteralTypeNode() { - const node = this.startNode(); - switch (this.state.type) { - case 134: - case 135: - case 133: - case 85: - case 86: - node.literal = super.parseExprAtom(); - break; - default: - this.unexpected(); - } - return this.finishNode(node, "TSLiteralType"); - } - tsParseTemplateLiteralType() { - const node = this.startNode(); - node.literal = super.parseTemplate(false); - return this.finishNode(node, "TSLiteralType"); - } - parseTemplateSubstitution() { - if (this.state.inType) return this.tsParseType(); - return super.parseTemplateSubstitution(); - } - tsParseThisTypeOrThisTypePredicate() { - const thisKeyword = this.tsParseThisTypeNode(); - if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { - return this.tsParseThisTypePredicate(thisKeyword); - } else { - return thisKeyword; - } - } - tsParseNonArrayType() { - switch (this.state.type) { - case 133: - case 134: - case 135: - case 85: - case 86: - return this.tsParseLiteralTypeNode(); - case 53: - if (this.state.value === "-") { - const node = this.startNode(); - const nextToken = this.lookahead(); - if (nextToken.type !== 134 && nextToken.type !== 135) { - this.unexpected(); - } - node.literal = this.parseMaybeUnary(); - return this.finishNode(node, "TSLiteralType"); - } - break; - case 78: - return this.tsParseThisTypeOrThisTypePredicate(); - case 87: - return this.tsParseTypeQuery(); - case 83: - return this.tsParseImportType(); - case 5: - return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); - case 0: - return this.tsParseTupleType(); - case 10: - return this.tsParseParenthesizedType(); - case 25: - case 24: - return this.tsParseTemplateLiteralType(); - default: - { - const { - type - } = this.state; - if (tokenIsIdentifier(type) || type === 88 || type === 84) { - const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value); - if (nodeType !== undefined && this.lookaheadCharCode() !== 46) { - const node = this.startNode(); - this.next(); - return this.finishNode(node, nodeType); - } - return this.tsParseTypeReference(); - } - } - } - this.unexpected(); - } - tsParseArrayTypeOrHigher() { - let type = this.tsParseNonArrayType(); - while (!this.hasPrecedingLineBreak() && this.eat(0)) { - if (this.match(3)) { - const node = this.startNodeAtNode(type); - node.elementType = type; - this.expect(3); - type = this.finishNode(node, "TSArrayType"); - } else { - const node = this.startNodeAtNode(type); - node.objectType = type; - node.indexType = this.tsParseType(); - this.expect(3); - type = this.finishNode(node, "TSIndexedAccessType"); - } - } - return type; - } - tsParseTypeOperator() { - const node = this.startNode(); - const operator = this.state.value; - this.next(); - node.operator = operator; - node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); - if (operator === "readonly") { - this.tsCheckTypeAnnotationForReadOnly(node); - } - return this.finishNode(node, "TSTypeOperator"); - } - tsCheckTypeAnnotationForReadOnly(node) { - switch (node.typeAnnotation.type) { - case "TSTupleType": - case "TSArrayType": - return; - default: - this.raise(TSErrors.UnexpectedReadonly, node); - } - } - tsParseInferType() { - const node = this.startNode(); - this.expectContextual(115); - const typeParameter = this.startNode(); - typeParameter.name = this.tsParseTypeParameterName(); - typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType()); - node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); - return this.finishNode(node, "TSInferType"); - } - tsParseConstraintForInferType() { - if (this.eat(81)) { - const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType()); - if (this.state.inDisallowConditionalTypesContext || !this.match(17)) { - return constraint; - } - } - } - tsParseTypeOperatorOrHigher() { - const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc; - return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher()); - } - tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { - const node = this.startNode(); - const hasLeadingOperator = this.eat(operator); - const types = []; - do { - types.push(parseConstituentType()); - } while (this.eat(operator)); - if (types.length === 1 && !hasLeadingOperator) { - return types[0]; - } - node.types = types; - return this.finishNode(node, kind); - } - tsParseIntersectionTypeOrHigher() { - return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45); - } - tsParseUnionTypeOrHigher() { - return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43); - } - tsIsStartOfFunctionType() { - if (this.match(47)) { - return true; - } - return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); - } - tsSkipParameterStart() { - if (tokenIsIdentifier(this.state.type) || this.match(78)) { - this.next(); - return true; - } - if (this.match(5)) { - const { - errors - } = this.state; - const previousErrorCount = errors.length; - try { - this.parseObjectLike(8, true); - return errors.length === previousErrorCount; - } catch (_unused) { - return false; - } - } - if (this.match(0)) { - this.next(); - const { - errors - } = this.state; - const previousErrorCount = errors.length; - try { - super.parseBindingList(3, 93, 1); - return errors.length === previousErrorCount; - } catch (_unused2) { - return false; - } - } - return false; - } - tsIsUnambiguouslyStartOfFunctionType() { - this.next(); - if (this.match(11) || this.match(21)) { - return true; - } - if (this.tsSkipParameterStart()) { - if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) { - return true; - } - if (this.match(11)) { - this.next(); - if (this.match(19)) { - return true; - } - } - } - return false; - } - tsParseTypeOrTypePredicateAnnotation(returnToken) { - return this.tsInType(() => { - const t = this.startNode(); - this.expect(returnToken); - const node = this.startNode(); - const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); - if (asserts && this.match(78)) { - let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); - if (thisTypePredicate.type === "TSThisType") { - node.parameterName = thisTypePredicate; - node.asserts = true; - node.typeAnnotation = null; - thisTypePredicate = this.finishNode(node, "TSTypePredicate"); - } else { - this.resetStartLocationFromNode(thisTypePredicate, node); - thisTypePredicate.asserts = true; - } - t.typeAnnotation = thisTypePredicate; - return this.finishNode(t, "TSTypeAnnotation"); - } - const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); - if (!typePredicateVariable) { - if (!asserts) { - return this.tsParseTypeAnnotation(false, t); - } - node.parameterName = this.parseIdentifier(); - node.asserts = asserts; - node.typeAnnotation = null; - t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); - return this.finishNode(t, "TSTypeAnnotation"); - } - const type = this.tsParseTypeAnnotation(false); - node.parameterName = typePredicateVariable; - node.typeAnnotation = type; - node.asserts = asserts; - t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); - return this.finishNode(t, "TSTypeAnnotation"); - }); - } - tsTryParseTypeOrTypePredicateAnnotation() { - if (this.match(14)) { - return this.tsParseTypeOrTypePredicateAnnotation(14); - } - } - tsTryParseTypeAnnotation() { - if (this.match(14)) { - return this.tsParseTypeAnnotation(); - } - } - tsTryParseType() { - return this.tsEatThenParseType(14); - } - tsParseTypePredicatePrefix() { - const id = this.parseIdentifier(); - if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { - this.next(); - return id; - } - } - tsParseTypePredicateAsserts() { - if (this.state.type !== 109) { - return false; - } - const containsEsc = this.state.containsEsc; - this.next(); - if (!tokenIsIdentifier(this.state.type) && !this.match(78)) { - return false; - } - if (containsEsc) { - this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, { - reservedWord: "asserts" - }); - } - return true; - } - tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { - this.tsInType(() => { - if (eatColon) this.expect(14); - t.typeAnnotation = this.tsParseType(); - }); - return this.finishNode(t, "TSTypeAnnotation"); - } - tsParseType() { - assert$1(this.state.inType); - const type = this.tsParseNonConditionalType(); - if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) { - return type; - } - const node = this.startNodeAtNode(type); - node.checkType = type; - node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType()); - this.expect(17); - node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); - this.expect(14); - node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); - return this.finishNode(node, "TSConditionalType"); - } - isAbstractConstructorSignature() { - return this.isContextual(124) && this.lookahead().type === 77; - } - tsParseNonConditionalType() { - if (this.tsIsStartOfFunctionType()) { - return this.tsParseFunctionOrConstructorType("TSFunctionType"); - } - if (this.match(77)) { - return this.tsParseFunctionOrConstructorType("TSConstructorType"); - } else if (this.isAbstractConstructorSignature()) { - return this.tsParseFunctionOrConstructorType("TSConstructorType", true); - } - return this.tsParseUnionTypeOrHigher(); - } - tsParseTypeAssertion() { - if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { - this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc); - } - const node = this.startNode(); - node.typeAnnotation = this.tsInType(() => { - this.next(); - return this.match(75) ? this.tsParseTypeReference() : this.tsParseType(); - }); - this.expect(48); - node.expression = this.parseMaybeUnary(); - return this.finishNode(node, "TSTypeAssertion"); - } - tsParseHeritageClause(token) { - const originalStartLoc = this.state.startLoc; - const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => { - const node = this.startNode(); - node.expression = this.tsParseEntityName(); - if (this.match(47)) { - node.typeParameters = this.tsParseTypeArguments(); - } - return this.finishNode(node, "TSExpressionWithTypeArguments"); - }); - if (!delimitedList.length) { - this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, { - token - }); - } - return delimitedList; - } - tsParseInterfaceDeclaration(node, properties = {}) { - if (this.hasFollowingLineBreak()) return null; - this.expectContextual(129); - if (properties.declare) node.declare = true; - if (tokenIsIdentifier(this.state.type)) { - node.id = this.parseIdentifier(); - this.checkIdentifier(node.id, 130); - } else { - node.id = null; - this.raise(TSErrors.MissingInterfaceName, this.state.startLoc); - } - node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); - if (this.eat(81)) { - node.extends = this.tsParseHeritageClause("extends"); - } - const body = this.startNode(); - body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); - node.body = this.finishNode(body, "TSInterfaceBody"); - return this.finishNode(node, "TSInterfaceDeclaration"); - } - tsParseTypeAliasDeclaration(node) { - node.id = this.parseIdentifier(); - this.checkIdentifier(node.id, 2); - node.typeAnnotation = this.tsInType(() => { - node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers); - this.expect(29); - if (this.isContextual(114) && this.lookahead().type !== 16) { - const node = this.startNode(); - this.next(); - return this.finishNode(node, "TSIntrinsicKeyword"); - } - return this.tsParseType(); - }); - this.semicolon(); - return this.finishNode(node, "TSTypeAliasDeclaration"); - } - tsInNoContext(cb) { - const oldContext = this.state.context; - this.state.context = [oldContext[0]]; - try { - return cb(); - } finally { - this.state.context = oldContext; - } - } - tsInType(cb) { - const oldInType = this.state.inType; - this.state.inType = true; - try { - return cb(); - } finally { - this.state.inType = oldInType; - } - } - tsInDisallowConditionalTypesContext(cb) { - const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; - this.state.inDisallowConditionalTypesContext = true; - try { - return cb(); - } finally { - this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; - } - } - tsInAllowConditionalTypesContext(cb) { - const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; - this.state.inDisallowConditionalTypesContext = false; - try { - return cb(); - } finally { - this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; - } - } - tsEatThenParseType(token) { - if (this.match(token)) { - return this.tsNextThenParseType(); - } - } - tsExpectThenParseType(token) { - return this.tsInType(() => { - this.expect(token); - return this.tsParseType(); - }); - } - tsNextThenParseType() { - return this.tsInType(() => { - this.next(); - return this.tsParseType(); - }); - } - tsParseEnumMember() { - const node = this.startNode(); - node.id = this.match(133) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true); - if (this.eat(29)) { - node.initializer = super.parseMaybeAssignAllowIn(); - } - return this.finishNode(node, "TSEnumMember"); - } - tsParseEnumDeclaration(node, properties = {}) { - if (properties.const) node.const = true; - if (properties.declare) node.declare = true; - this.expectContextual(126); - node.id = this.parseIdentifier(); - this.checkIdentifier(node.id, node.const ? 8971 : 8459); - this.expect(5); - node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); - this.expect(8); - return this.finishNode(node, "TSEnumDeclaration"); - } - tsParseModuleBlock() { - const node = this.startNode(); - this.scope.enter(0); - this.expect(5); - super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8); - this.scope.exit(); - return this.finishNode(node, "TSModuleBlock"); - } - tsParseModuleOrNamespaceDeclaration(node, nested = false) { - node.id = this.parseIdentifier(); - if (!nested) { - this.checkIdentifier(node.id, 1024); - } - if (this.eat(16)) { - const inner = this.startNode(); - this.tsParseModuleOrNamespaceDeclaration(inner, true); - node.body = inner; - } else { - this.scope.enter(256); - this.prodParam.enter(0); - node.body = this.tsParseModuleBlock(); - this.prodParam.exit(); - this.scope.exit(); - } - return this.finishNode(node, "TSModuleDeclaration"); - } - tsParseAmbientExternalModuleDeclaration(node) { - if (this.isContextual(112)) { - node.global = true; - node.id = this.parseIdentifier(); - } else if (this.match(133)) { - node.id = super.parseStringLiteral(this.state.value); - } else { - this.unexpected(); - } - if (this.match(5)) { - this.scope.enter(256); - this.prodParam.enter(0); - node.body = this.tsParseModuleBlock(); - this.prodParam.exit(); - this.scope.exit(); - } else { - this.semicolon(); - } - return this.finishNode(node, "TSModuleDeclaration"); - } - tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) { - node.isExport = isExport || false; - node.id = maybeDefaultIdentifier || this.parseIdentifier(); - this.checkIdentifier(node.id, 4096); - this.expect(29); - const moduleReference = this.tsParseModuleReference(); - if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { - this.raise(TSErrors.ImportAliasHasImportType, moduleReference); - } - node.moduleReference = moduleReference; - this.semicolon(); - return this.finishNode(node, "TSImportEqualsDeclaration"); - } - tsIsExternalModuleReference() { - return this.isContextual(119) && this.lookaheadCharCode() === 40; - } - tsParseModuleReference() { - return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false); - } - tsParseExternalModuleReference() { - const node = this.startNode(); - this.expectContextual(119); - this.expect(10); - if (!this.match(133)) { - this.unexpected(); - } - node.expression = super.parseExprAtom(); - this.expect(11); - this.sawUnambiguousESM = true; - return this.finishNode(node, "TSExternalModuleReference"); - } - tsLookAhead(f) { - const state = this.state.clone(); - const res = f(); - this.state = state; - return res; - } - tsTryParseAndCatch(f) { - const result = this.tryParse(abort => f() || abort()); - if (result.aborted || !result.node) return; - if (result.error) this.state = result.failState; - return result.node; - } - tsTryParse(f) { - const state = this.state.clone(); - const result = f(); - if (result !== undefined && result !== false) { - return result; - } - this.state = state; - } - tsTryParseDeclare(nany) { - if (this.isLineTerminator()) { - return; - } - let startType = this.state.type; - let kind; - if (this.isContextual(100)) { - startType = 74; - kind = "let"; - } - return this.tsInAmbientContext(() => { - switch (startType) { - case 68: - nany.declare = true; - return super.parseFunctionStatement(nany, false, false); - case 80: - nany.declare = true; - return this.parseClass(nany, true, false); - case 126: - return this.tsParseEnumDeclaration(nany, { - declare: true - }); - case 112: - return this.tsParseAmbientExternalModuleDeclaration(nany); - case 75: - case 74: - if (!this.match(75) || !this.isLookaheadContextual("enum")) { - nany.declare = true; - return this.parseVarStatement(nany, kind || this.state.value, true); - } - this.expect(75); - return this.tsParseEnumDeclaration(nany, { - const: true, - declare: true - }); - case 129: - { - const result = this.tsParseInterfaceDeclaration(nany, { - declare: true - }); - if (result) return result; - } - default: - if (tokenIsIdentifier(startType)) { - return this.tsParseDeclaration(nany, this.state.value, true, null); - } - } - }); - } - tsTryParseExportDeclaration() { - return this.tsParseDeclaration(this.startNode(), this.state.value, true, null); - } - tsParseExpressionStatement(node, expr, decorators) { - switch (expr.name) { - case "declare": - { - const declaration = this.tsTryParseDeclare(node); - if (declaration) { - declaration.declare = true; - } - return declaration; - } - case "global": - if (this.match(5)) { - this.scope.enter(256); - this.prodParam.enter(0); - const mod = node; - mod.global = true; - mod.id = expr; - mod.body = this.tsParseModuleBlock(); - this.scope.exit(); - this.prodParam.exit(); - return this.finishNode(mod, "TSModuleDeclaration"); - } - break; - default: - return this.tsParseDeclaration(node, expr.name, false, decorators); - } - } - tsParseDeclaration(node, value, next, decorators) { - switch (value) { - case "abstract": - if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) { - return this.tsParseAbstractDeclaration(node, decorators); - } - break; - case "module": - if (this.tsCheckLineTerminator(next)) { - if (this.match(133)) { - return this.tsParseAmbientExternalModuleDeclaration(node); - } else if (tokenIsIdentifier(this.state.type)) { - return this.tsParseModuleOrNamespaceDeclaration(node); - } - } - break; - case "namespace": - if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { - return this.tsParseModuleOrNamespaceDeclaration(node); - } - break; - case "type": - if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { - return this.tsParseTypeAliasDeclaration(node); - } - break; - } - } - tsCheckLineTerminator(next) { - if (next) { - if (this.hasFollowingLineBreak()) return false; - this.next(); - return true; - } - return !this.isLineTerminator(); - } - tsTryParseGenericAsyncArrowFunction(startLoc) { - if (!this.match(47)) return; - const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; - this.state.maybeInArrowParameters = true; - const res = this.tsTryParseAndCatch(() => { - const node = this.startNodeAt(startLoc); - node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); - super.parseFunctionParams(node); - node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); - this.expect(19); - return node; - }); - this.state.maybeInArrowParameters = oldMaybeInArrowParameters; - if (!res) return; - return super.parseArrowExpression(res, null, true); - } - tsParseTypeArgumentsInExpression() { - if (this.reScan_lt() !== 47) return; - return this.tsParseTypeArguments(); - } - tsParseTypeArguments() { - const node = this.startNode(); - node.params = this.tsInType(() => this.tsInNoContext(() => { - this.expect(47); - return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); - })); - if (node.params.length === 0) { - this.raise(TSErrors.EmptyTypeArguments, node); - } else if (!this.state.inType && this.curContext() === types$1.brace) { - this.reScan_lt_gt(); - } - this.expect(48); - return this.finishNode(node, "TSTypeParameterInstantiation"); - } - tsIsDeclarationStart() { - return tokenIsTSDeclarationStart(this.state.type); - } - isExportDefaultSpecifier() { - if (this.tsIsDeclarationStart()) return false; - return super.isExportDefaultSpecifier(); - } - parseAssignableListItem(flags, decorators) { - const startLoc = this.state.startLoc; - const modified = {}; - this.tsParseModifiers({ - allowedModifiers: ["public", "private", "protected", "override", "readonly"] - }, modified); - const accessibility = modified.accessibility; - const override = modified.override; - const readonly = modified.readonly; - if (!(flags & 4) && (accessibility || readonly || override)) { - this.raise(TSErrors.UnexpectedParameterModifier, startLoc); - } - const left = this.parseMaybeDefault(); - this.parseAssignableListItemTypes(left, flags); - const elt = this.parseMaybeDefault(left.loc.start, left); - if (accessibility || readonly || override) { - const pp = this.startNodeAt(startLoc); - if (decorators.length) { - pp.decorators = decorators; - } - if (accessibility) pp.accessibility = accessibility; - if (readonly) pp.readonly = readonly; - if (override) pp.override = override; - if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { - this.raise(TSErrors.UnsupportedParameterPropertyKind, pp); - } - pp.parameter = elt; - return this.finishNode(pp, "TSParameterProperty"); - } - if (decorators.length) { - left.decorators = decorators; - } - return elt; - } - isSimpleParameter(node) { - return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node); - } - tsDisallowOptionalPattern(node) { - for (const param of node.params) { - if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) { - this.raise(TSErrors.PatternIsOptional, param); - } - } - } - setArrowFunctionParameters(node, params, trailingCommaLoc) { - super.setArrowFunctionParameters(node, params, trailingCommaLoc); - this.tsDisallowOptionalPattern(node); - } - parseFunctionBodyAndFinish(node, type, isMethod = false) { - if (this.match(14)) { - node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14); - } - const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined; - if (bodilessType && !this.match(5) && this.isLineTerminator()) { - return this.finishNode(node, bodilessType); - } - if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { - this.raise(TSErrors.DeclareFunctionHasImplementation, node); - if (node.declare) { - return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); - } - } - this.tsDisallowOptionalPattern(node); - return super.parseFunctionBodyAndFinish(node, type, isMethod); - } - registerFunctionStatementId(node) { - if (!node.body && node.id) { - this.checkIdentifier(node.id, 1024); - } else { - super.registerFunctionStatementId(node); - } - } - tsCheckForInvalidTypeCasts(items) { - items.forEach(node => { - if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { - this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation); - } - }); - } - toReferencedList(exprList, isInParens) { - this.tsCheckForInvalidTypeCasts(exprList); - return exprList; - } - parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { - const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); - if (node.type === "ArrayExpression") { - this.tsCheckForInvalidTypeCasts(node.elements); - } - return node; - } - parseSubscript(base, startLoc, noCalls, state) { - if (!this.hasPrecedingLineBreak() && this.match(35)) { - this.state.canStartJSXElement = false; - this.next(); - const nonNullExpression = this.startNodeAt(startLoc); - nonNullExpression.expression = base; - return this.finishNode(nonNullExpression, "TSNonNullExpression"); - } - let isOptionalCall = false; - if (this.match(18) && this.lookaheadCharCode() === 60) { - if (noCalls) { - state.stop = true; - return base; - } - state.optionalChainMember = isOptionalCall = true; - this.next(); - } - if (this.match(47) || this.match(51)) { - let missingParenErrorLoc; - const result = this.tsTryParseAndCatch(() => { - if (!noCalls && this.atPossibleAsyncArrow(base)) { - const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc); - if (asyncArrowFn) { - return asyncArrowFn; - } - } - const typeArguments = this.tsParseTypeArgumentsInExpression(); - if (!typeArguments) return; - if (isOptionalCall && !this.match(10)) { - missingParenErrorLoc = this.state.curPosition(); - return; - } - if (tokenIsTemplate(this.state.type)) { - const result = super.parseTaggedTemplateExpression(base, startLoc, state); - result.typeParameters = typeArguments; - return result; - } - if (!noCalls && this.eat(10)) { - const node = this.startNodeAt(startLoc); - node.callee = base; - node.arguments = this.parseCallExpressionArguments(11, false); - this.tsCheckForInvalidTypeCasts(node.arguments); - node.typeParameters = typeArguments; - if (state.optionalChainMember) { - node.optional = isOptionalCall; - } - return this.finishCallExpression(node, state.optionalChainMember); - } - const tokenType = this.state.type; - if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) { - return; - } - const node = this.startNodeAt(startLoc); - node.expression = base; - node.typeParameters = typeArguments; - return this.finishNode(node, "TSInstantiationExpression"); - }); - if (missingParenErrorLoc) { - this.unexpected(missingParenErrorLoc, 10); - } - if (result) { - if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) { - this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc); - } - return result; - } - } - return super.parseSubscript(base, startLoc, noCalls, state); - } - parseNewCallee(node) { - var _callee$extra; - super.parseNewCallee(node); - const { - callee - } = node; - if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) { - node.typeParameters = callee.typeParameters; - node.callee = callee.expression; - } - } - parseExprOp(left, leftStartLoc, minPrec) { - let isSatisfies; - if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) { - const node = this.startNodeAt(leftStartLoc); - node.expression = left; - node.typeAnnotation = this.tsInType(() => { - this.next(); - if (this.match(75)) { - if (isSatisfies) { - this.raise(Errors.UnexpectedKeyword, this.state.startLoc, { - keyword: "const" - }); - } - return this.tsParseTypeReference(); - } - return this.tsParseType(); - }); - this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression"); - this.reScan_lt_gt(); - return this.parseExprOp(node, leftStartLoc, minPrec); - } - return super.parseExprOp(left, leftStartLoc, minPrec); - } - checkReservedWord(word, startLoc, checkKeywords, isBinding) { - if (!this.state.isAmbientContext) { - super.checkReservedWord(word, startLoc, checkKeywords, isBinding); - } - } - checkImportReflection(node) { - super.checkImportReflection(node); - if (node.module && node.importKind !== "value") { - this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); - } - } - checkDuplicateExports() { } - isPotentialImportPhase(isExport) { - if (super.isPotentialImportPhase(isExport)) return true; - if (this.isContextual(130)) { - const ch = this.lookaheadCharCode(); - return isExport ? ch === 123 || ch === 42 : ch !== 61; - } - return !isExport && this.isContextual(87); - } - applyImportPhase(node, isExport, phase, loc) { - super.applyImportPhase(node, isExport, phase, loc); - if (isExport) { - node.exportKind = phase === "type" ? "type" : "value"; - } else { - node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; - } - } - parseImport(node) { - if (this.match(133)) { - node.importKind = "value"; - return super.parseImport(node); - } - let importNode; - if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) { - node.importKind = "value"; - return this.tsParseImportEqualsDeclaration(node); - } else if (this.isContextual(130)) { - const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false); - if (this.lookaheadCharCode() === 61) { - return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier); - } else { - importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier); - } - } else { - importNode = super.parseImport(node); - } - if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { - this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode); - } - return importNode; - } - parseExport(node, decorators) { - if (this.match(83)) { - this.next(); - let maybeDefaultIdentifier = null; - if (this.isContextual(130) && this.isPotentialImportPhase(false)) { - maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false); - } else { - node.importKind = "value"; - } - return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, true); - } else if (this.eat(29)) { - const assign = node; - assign.expression = super.parseExpression(); - this.semicolon(); - this.sawUnambiguousESM = true; - return this.finishNode(assign, "TSExportAssignment"); - } else if (this.eatContextual(93)) { - const decl = node; - this.expectContextual(128); - decl.id = this.parseIdentifier(); - this.semicolon(); - return this.finishNode(decl, "TSNamespaceExportDeclaration"); - } else { - return super.parseExport(node, decorators); - } - } - isAbstractClass() { - return this.isContextual(124) && this.lookahead().type === 80; - } - parseExportDefaultExpression() { - if (this.isAbstractClass()) { - const cls = this.startNode(); - this.next(); - cls.abstract = true; - return this.parseClass(cls, true, true); - } - if (this.match(129)) { - const result = this.tsParseInterfaceDeclaration(this.startNode()); - if (result) return result; - } - return super.parseExportDefaultExpression(); - } - parseVarStatement(node, kind, allowMissingInitializer = false) { - const { - isAmbientContext - } = this.state; - const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext); - if (!isAmbientContext) return declaration; - for (const { - id, - init - } of declaration.declarations) { - if (!init) continue; - if (kind !== "const" || !!id.typeAnnotation) { - this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init); - } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) { - this.raise(TSErrors.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference, init); - } - } - return declaration; - } - parseStatementContent(flags, decorators) { - if (this.match(75) && this.isLookaheadContextual("enum")) { - const node = this.startNode(); - this.expect(75); - return this.tsParseEnumDeclaration(node, { - const: true - }); - } - if (this.isContextual(126)) { - return this.tsParseEnumDeclaration(this.startNode()); - } - if (this.isContextual(129)) { - const result = this.tsParseInterfaceDeclaration(this.startNode()); - if (result) return result; - } - return super.parseStatementContent(flags, decorators); - } - parseAccessModifier() { - return this.tsParseModifier(["public", "protected", "private"]); - } - tsHasSomeModifiers(member, modifiers) { - return modifiers.some(modifier => { - if (tsIsAccessModifier(modifier)) { - return member.accessibility === modifier; - } - return !!member[modifier]; - }); - } - tsIsStartOfStaticBlocks() { - return this.isContextual(106) && this.lookaheadCharCode() === 123; - } - parseClassMember(classBody, member, state) { - const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"]; - this.tsParseModifiers({ - allowedModifiers: modifiers, - disallowedModifiers: ["in", "out"], - stopOnStartOfClassStaticBlock: true, - errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions - }, member); - const callParseClassMemberWithIsStatic = () => { - if (this.tsIsStartOfStaticBlocks()) { - this.next(); - this.next(); - if (this.tsHasSomeModifiers(member, modifiers)) { - this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition()); - } - super.parseClassStaticBlock(classBody, member); - } else { - this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static); - } - }; - if (member.declare) { - this.tsInAmbientContext(callParseClassMemberWithIsStatic); - } else { - callParseClassMemberWithIsStatic(); - } - } - parseClassMemberWithIsStatic(classBody, member, state, isStatic) { - const idx = this.tsTryParseIndexSignature(member); - if (idx) { - classBody.body.push(idx); - if (member.abstract) { - this.raise(TSErrors.IndexSignatureHasAbstract, member); - } - if (member.accessibility) { - this.raise(TSErrors.IndexSignatureHasAccessibility, member, { - modifier: member.accessibility - }); - } - if (member.declare) { - this.raise(TSErrors.IndexSignatureHasDeclare, member); - } - if (member.override) { - this.raise(TSErrors.IndexSignatureHasOverride, member); - } - return; - } - if (!this.state.inAbstractClass && member.abstract) { - this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member); - } - if (member.override) { - if (!state.hadSuperClass) { - this.raise(TSErrors.OverrideNotInSubClass, member); - } - } - super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); - } - parsePostMemberNameModifiers(methodOrProp) { - const optional = this.eat(17); - if (optional) methodOrProp.optional = true; - if (methodOrProp.readonly && this.match(10)) { - this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp); - } - if (methodOrProp.declare && this.match(10)) { - this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp); - } - } - parseExpressionStatement(node, expr, decorators) { - const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr, decorators) : undefined; - return decl || super.parseExpressionStatement(node, expr, decorators); - } - shouldParseExportDeclaration() { - if (this.tsIsDeclarationStart()) return true; - return super.shouldParseExportDeclaration(); - } - parseConditional(expr, startLoc, refExpressionErrors) { - if (!this.state.maybeInArrowParameters || !this.match(17)) { - return super.parseConditional(expr, startLoc, refExpressionErrors); - } - const result = this.tryParse(() => super.parseConditional(expr, startLoc)); - if (!result.node) { - if (result.error) { - super.setOptionalParametersError(refExpressionErrors, result.error); - } - return expr; - } - if (result.error) this.state = result.failState; - return result.node; - } - parseParenItem(node, startLoc) { - node = super.parseParenItem(node, startLoc); - if (this.eat(17)) { - node.optional = true; - this.resetEndLocation(node); - } - if (this.match(14)) { - const typeCastNode = this.startNodeAt(startLoc); - typeCastNode.expression = node; - typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); - return this.finishNode(typeCastNode, "TSTypeCastExpression"); - } - return node; - } - parseExportDeclaration(node) { - if (!this.state.isAmbientContext && this.isContextual(125)) { - return this.tsInAmbientContext(() => this.parseExportDeclaration(node)); - } - const startLoc = this.state.startLoc; - const isDeclare = this.eatContextual(125); - if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) { - throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc); - } - const isIdentifier = tokenIsIdentifier(this.state.type); - const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node); - if (!declaration) return null; - if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) { - node.exportKind = "type"; - } - if (isDeclare) { - this.resetStartLocation(declaration, startLoc); - declaration.declare = true; - } - return declaration; - } - parseClassId(node, isStatement, optionalId, bindingType) { - if ((!isStatement || optionalId) && this.isContextual(113)) { - return; - } - super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331); - const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); - if (typeParameters) node.typeParameters = typeParameters; - } - parseClassPropertyAnnotation(node) { - if (!node.optional) { - if (this.eat(35)) { - node.definite = true; - } else if (this.eat(17)) { - node.optional = true; - } - } - const type = this.tsTryParseTypeAnnotation(); - if (type) node.typeAnnotation = type; - } - parseClassProperty(node) { - this.parseClassPropertyAnnotation(node); - if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) { - this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc); - } - if (node.abstract && this.match(29)) { - const { - key - } = node; - this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, { - propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` - }); - } - return super.parseClassProperty(node); - } - parseClassPrivateProperty(node) { - if (node.abstract) { - this.raise(TSErrors.PrivateElementHasAbstract, node); - } - if (node.accessibility) { - this.raise(TSErrors.PrivateElementHasAccessibility, node, { - modifier: node.accessibility - }); - } - this.parseClassPropertyAnnotation(node); - return super.parseClassPrivateProperty(node); - } - parseClassAccessorProperty(node) { - this.parseClassPropertyAnnotation(node); - if (node.optional) { - this.raise(TSErrors.AccessorCannotBeOptional, node); - } - return super.parseClassAccessorProperty(node); - } - pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { - const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); - if (typeParameters && isConstructor) { - this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters); - } - const { - declare = false, - kind - } = method; - if (declare && (kind === "get" || kind === "set")) { - this.raise(TSErrors.DeclareAccessor, method, { - kind - }); - } - if (typeParameters) method.typeParameters = typeParameters; - super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); - } - pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { - const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); - if (typeParameters) method.typeParameters = typeParameters; - super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); - } - declareClassPrivateMethodInScope(node, kind) { - if (node.type === "TSDeclareMethod") return; - if (node.type === "MethodDefinition" && !node.value.body) return; - super.declareClassPrivateMethodInScope(node, kind); - } - parseClassSuper(node) { - super.parseClassSuper(node); - if (node.superClass && (this.match(47) || this.match(51))) { - node.superTypeParameters = this.tsParseTypeArgumentsInExpression(); - } - if (this.eatContextual(113)) { - node.implements = this.tsParseHeritageClause("implements"); - } - } - parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { - const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); - if (typeParameters) prop.typeParameters = typeParameters; - return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); - } - parseFunctionParams(node, isConstructor) { - const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); - if (typeParameters) node.typeParameters = typeParameters; - super.parseFunctionParams(node, isConstructor); - } - parseVarId(decl, kind) { - super.parseVarId(decl, kind); - if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) { - decl.definite = true; - } - const type = this.tsTryParseTypeAnnotation(); - if (type) { - decl.id.typeAnnotation = type; - this.resetEndLocation(decl.id); - } - } - parseAsyncArrowFromCallExpression(node, call) { - if (this.match(14)) { - node.returnType = this.tsParseTypeAnnotation(); - } - return super.parseAsyncArrowFromCallExpression(node, call); - } - parseMaybeAssign(refExpressionErrors, afterLeftParse) { - var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2; - let state; - let jsx; - let typeCast; - if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { - state = this.state.clone(); - jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); - if (!jsx.error) return jsx.node; - const { - context - } = this.state; - const currentContext = context[context.length - 1]; - if (currentContext === types$1.j_oTag || currentContext === types$1.j_expr) { - context.pop(); - } - } - if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) { - return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); - } - if (!state || state === this.state) state = this.state.clone(); - let typeParameters; - const arrow = this.tryParse(abort => { - var _expr$extra, _typeParameters; - typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); - const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); - if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { - abort(); - } - if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { - this.resetStartLocationFromNode(expr, typeParameters); - } - expr.typeParameters = typeParameters; - return expr; - }, state); - if (!arrow.error && !arrow.aborted) { - if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); - return arrow.node; - } - if (!jsx) { - assert$1(!this.hasPlugin("jsx")); - typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); - if (!typeCast.error) return typeCast.node; - } - if ((_jsx2 = jsx) != null && _jsx2.node) { - this.state = jsx.failState; - return jsx.node; - } - if (arrow.node) { - this.state = arrow.failState; - if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); - return arrow.node; - } - if ((_typeCast = typeCast) != null && _typeCast.node) { - this.state = typeCast.failState; - return typeCast.node; - } - throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error); - } - reportReservedArrowTypeParam(node) { - var _node$extra; - if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { - this.raise(TSErrors.ReservedArrowTypeParam, node); - } - } - parseMaybeUnary(refExpressionErrors, sawUnary) { - if (!this.hasPlugin("jsx") && this.match(47)) { - return this.tsParseTypeAssertion(); - } - return super.parseMaybeUnary(refExpressionErrors, sawUnary); - } - parseArrow(node) { - if (this.match(14)) { - const result = this.tryParse(abort => { - const returnType = this.tsParseTypeOrTypePredicateAnnotation(14); - if (this.canInsertSemicolon() || !this.match(19)) abort(); - return returnType; - }); - if (result.aborted) return; - if (!result.thrown) { - if (result.error) this.state = result.failState; - node.returnType = result.node; - } - } - return super.parseArrow(node); - } - parseAssignableListItemTypes(param, flags) { - if (!(flags & 2)) return param; - if (this.eat(17)) { - param.optional = true; - } - const type = this.tsTryParseTypeAnnotation(); - if (type) param.typeAnnotation = type; - this.resetEndLocation(param); - return param; - } - isAssignable(node, isBinding) { - switch (node.type) { - case "TSTypeCastExpression": - return this.isAssignable(node.expression, isBinding); - case "TSParameterProperty": - return true; - default: - return super.isAssignable(node, isBinding); - } - } - toAssignable(node, isLHS = false) { - switch (node.type) { - case "ParenthesizedExpression": - this.toAssignableParenthesizedExpression(node, isLHS); - break; - case "TSAsExpression": - case "TSSatisfiesExpression": - case "TSNonNullExpression": - case "TSTypeAssertion": - if (isLHS) { - this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node); - } else { - this.raise(TSErrors.UnexpectedTypeCastInParameter, node); - } - this.toAssignable(node.expression, isLHS); - break; - case "AssignmentExpression": - if (!isLHS && node.left.type === "TSTypeCastExpression") { - node.left = this.typeCastToParameter(node.left); - } - default: - super.toAssignable(node, isLHS); - } - } - toAssignableParenthesizedExpression(node, isLHS) { - switch (node.expression.type) { - case "TSAsExpression": - case "TSSatisfiesExpression": - case "TSNonNullExpression": - case "TSTypeAssertion": - case "ParenthesizedExpression": - this.toAssignable(node.expression, isLHS); - break; - default: - super.toAssignable(node, isLHS); - } - } - checkToRestConversion(node, allowPattern) { - switch (node.type) { - case "TSAsExpression": - case "TSSatisfiesExpression": - case "TSTypeAssertion": - case "TSNonNullExpression": - this.checkToRestConversion(node.expression, false); - break; - default: - super.checkToRestConversion(node, allowPattern); - } - } - isValidLVal(type, isUnparenthesizedInAssign, binding) { - return getOwn({ - TSTypeCastExpression: true, - TSParameterProperty: "parameter", - TSNonNullExpression: "expression", - TSAsExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true], - TSSatisfiesExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true], - TSTypeAssertion: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true] - }, type) || super.isValidLVal(type, isUnparenthesizedInAssign, binding); - } - parseBindingAtom() { - if (this.state.type === 78) { - return this.parseIdentifier(true); - } - return super.parseBindingAtom(); - } - parseMaybeDecoratorArguments(expr) { - if (this.match(47) || this.match(51)) { - const typeArguments = this.tsParseTypeArgumentsInExpression(); - if (this.match(10)) { - const call = super.parseMaybeDecoratorArguments(expr); - call.typeParameters = typeArguments; - return call; - } - this.unexpected(null, 10); - } - return super.parseMaybeDecoratorArguments(expr); - } - checkCommaAfterRest(close) { - if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) { - this.next(); - return false; - } - return super.checkCommaAfterRest(close); - } - isClassMethod() { - return this.match(47) || super.isClassMethod(); - } - isClassProperty() { - return this.match(35) || this.match(14) || super.isClassProperty(); - } - parseMaybeDefault(startLoc, left) { - const node = super.parseMaybeDefault(startLoc, left); - if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { - this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation); - } - return node; - } - getTokenFromCode(code) { - if (this.state.inType) { - if (code === 62) { - this.finishOp(48, 1); - return; - } - if (code === 60) { - this.finishOp(47, 1); - return; - } - } - super.getTokenFromCode(code); - } - reScan_lt_gt() { - const { - type - } = this.state; - if (type === 47) { - this.state.pos -= 1; - this.readToken_lt(); - } else if (type === 48) { - this.state.pos -= 1; - this.readToken_gt(); - } - } - reScan_lt() { - const { - type - } = this.state; - if (type === 51) { - this.state.pos -= 2; - this.finishOp(47, 1); - return 47; - } - return type; - } - toAssignableList(exprList, trailingCommaLoc, isLHS) { - for (let i = 0; i < exprList.length; i++) { - const expr = exprList[i]; - if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") { - exprList[i] = this.typeCastToParameter(expr); - } - } - super.toAssignableList(exprList, trailingCommaLoc, isLHS); - } - typeCastToParameter(node) { - node.expression.typeAnnotation = node.typeAnnotation; - this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); - return node.expression; - } - shouldParseArrow(params) { - if (this.match(14)) { - return params.every(expr => this.isAssignable(expr, true)); - } - return super.shouldParseArrow(params); - } - shouldParseAsyncArrow() { - return this.match(14) || super.shouldParseAsyncArrow(); - } - canHaveLeadingDecorator() { - return super.canHaveLeadingDecorator() || this.isAbstractClass(); - } - jsxParseOpeningElementAfterName(node) { - if (this.match(47) || this.match(51)) { - const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression()); - if (typeArguments) node.typeParameters = typeArguments; - } - return super.jsxParseOpeningElementAfterName(node); - } - getGetterSetterExpectedParamCount(method) { - const baseCount = super.getGetterSetterExpectedParamCount(method); - const params = this.getObjectOrClassMethodParams(method); - const firstParam = params[0]; - const hasContextParam = firstParam && this.isThisParam(firstParam); - return hasContextParam ? baseCount + 1 : baseCount; - } - parseCatchClauseParam() { - const param = super.parseCatchClauseParam(); - const type = this.tsTryParseTypeAnnotation(); - if (type) { - param.typeAnnotation = type; - this.resetEndLocation(param); - } - return param; - } - tsInAmbientContext(cb) { - const oldIsAmbientContext = this.state.isAmbientContext; - this.state.isAmbientContext = true; - try { - return cb(); - } finally { - this.state.isAmbientContext = oldIsAmbientContext; - } - } - parseClass(node, isStatement, optionalId) { - const oldInAbstractClass = this.state.inAbstractClass; - this.state.inAbstractClass = !!node.abstract; - try { - return super.parseClass(node, isStatement, optionalId); - } finally { - this.state.inAbstractClass = oldInAbstractClass; - } - } - tsParseAbstractDeclaration(node, decorators) { - if (this.match(80)) { - node.abstract = true; - return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false)); - } else if (this.isContextual(129)) { - if (!this.hasFollowingLineBreak()) { - node.abstract = true; - this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, node); - return this.tsParseInterfaceDeclaration(node); - } - } else { - this.unexpected(null, 80); - } - } - parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) { - const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); - if (method.abstract) { - const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body; - if (hasBody) { - const { - key - } = method; - this.raise(TSErrors.AbstractMethodHasImplementation, method, { - methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` - }); - } - } - return method; - } - tsParseTypeParameterName() { - const typeName = this.parseIdentifier(); - return typeName.name; - } - shouldParseAsAmbientContext() { - return !!this.getPluginOption("typescript", "dts"); - } - parse() { - if (this.shouldParseAsAmbientContext()) { - this.state.isAmbientContext = true; - } - return super.parse(); - } - getExpression() { - if (this.shouldParseAsAmbientContext()) { - this.state.isAmbientContext = true; - } - return super.getExpression(); - } - parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { - if (!isString && isMaybeTypeOnly) { - this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport); - return this.finishNode(node, "ExportSpecifier"); - } - node.exportKind = "value"; - return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly); - } - parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { - if (!importedIsString && isMaybeTypeOnly) { - this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport); - return this.finishNode(specifier, "ImportSpecifier"); - } - specifier.importKind = "value"; - return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096); - } - parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) { - const leftOfAsKey = isImport ? "imported" : "local"; - const rightOfAsKey = isImport ? "local" : "exported"; - let leftOfAs = node[leftOfAsKey]; - let rightOfAs; - let hasTypeSpecifier = false; - let canParseAsKeyword = true; - const loc = leftOfAs.loc.start; - if (this.isContextual(93)) { - const firstAs = this.parseIdentifier(); - if (this.isContextual(93)) { - const secondAs = this.parseIdentifier(); - if (tokenIsKeywordOrIdentifier(this.state.type)) { - hasTypeSpecifier = true; - leftOfAs = firstAs; - rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); - canParseAsKeyword = false; - } else { - rightOfAs = secondAs; - canParseAsKeyword = false; - } - } else if (tokenIsKeywordOrIdentifier(this.state.type)) { - canParseAsKeyword = false; - rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); - } else { - hasTypeSpecifier = true; - leftOfAs = firstAs; - } - } else if (tokenIsKeywordOrIdentifier(this.state.type)) { - hasTypeSpecifier = true; - if (isImport) { - leftOfAs = this.parseIdentifier(true); - if (!this.isContextual(93)) { - this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true); - } - } else { - leftOfAs = this.parseModuleExportName(); - } - } - if (hasTypeSpecifier && isInTypeOnlyImportExport) { - this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc); - } - node[leftOfAsKey] = leftOfAs; - node[rightOfAsKey] = rightOfAs; - const kindKey = isImport ? "importKind" : "exportKind"; - node[kindKey] = hasTypeSpecifier ? "type" : "value"; - if (canParseAsKeyword && this.eatContextual(93)) { - node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName(); - } - if (!node[rightOfAsKey]) { - node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]); - } - if (isImport) { - this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096); - } - } - }; - function isPossiblyLiteralEnum(expression) { - if (expression.type !== "MemberExpression") return false; - const { - computed, - property - } = expression; - if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) { - return false; - } - return isUncomputedMemberExpressionChain(expression.object); - } - function isValidAmbientConstInitializer(expression, estree) { - var _expression$extra; - const { - type - } = expression; - if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) { - return false; - } - if (estree) { - if (type === "Literal") { - const { - value - } = expression; - if (typeof value === "string" || typeof value === "boolean") { - return true; - } - } - } else { - if (type === "StringLiteral" || type === "BooleanLiteral") { - return true; - } - } - if (isNumber$1(expression, estree) || isNegativeNumber(expression, estree)) { - return true; - } - if (type === "TemplateLiteral" && expression.expressions.length === 0) { - return true; - } - if (isPossiblyLiteralEnum(expression)) { - return true; - } - return false; - } - function isNumber$1(expression, estree) { - if (estree) { - return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression); - } - return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral"; - } - function isNegativeNumber(expression, estree) { - if (expression.type === "UnaryExpression") { - const { - operator, - argument - } = expression; - if (operator === "-" && isNumber$1(argument, estree)) { - return true; - } - } - return false; - } - function isUncomputedMemberExpressionChain(expression) { - if (expression.type === "Identifier") return true; - if (expression.type !== "MemberExpression" || expression.computed) { - return false; - } - return isUncomputedMemberExpressionChain(expression.object); - } - const PlaceholderErrors = ParseErrorEnum`placeholders`({ - ClassNameIsRequired: "A class name is required.", - UnexpectedSpace: "Unexpected space in placeholder." - }); - var placeholders = superClass => class PlaceholdersParserMixin extends superClass { - parsePlaceholder(expectedNode) { - if (this.match(144)) { - const node = this.startNode(); - this.next(); - this.assertNoSpace(); - node.name = super.parseIdentifier(true); - this.assertNoSpace(); - this.expect(144); - return this.finishPlaceholder(node, expectedNode); - } - } - finishPlaceholder(node, expectedNode) { - const isFinished = !!(node.expectedNode && node.type === "Placeholder"); - node.expectedNode = expectedNode; - return isFinished ? node : this.finishNode(node, "Placeholder"); - } - getTokenFromCode(code) { - if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { - this.finishOp(144, 2); - } else { - super.getTokenFromCode(code); - } - } - parseExprAtom(refExpressionErrors) { - return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors); - } - parseIdentifier(liberal) { - return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal); - } - checkReservedWord(word, startLoc, checkKeywords, isBinding) { - if (word !== undefined) { - super.checkReservedWord(word, startLoc, checkKeywords, isBinding); - } - } - parseBindingAtom() { - return this.parsePlaceholder("Pattern") || super.parseBindingAtom(); - } - isValidLVal(type, isParenthesized, binding) { - return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding); - } - toAssignable(node, isLHS) { - if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { - node.expectedNode = "Pattern"; - } else { - super.toAssignable(node, isLHS); - } - } - chStartsBindingIdentifier(ch, pos) { - if (super.chStartsBindingIdentifier(ch, pos)) { - return true; - } - const nextToken = this.lookahead(); - if (nextToken.type === 144) { - return true; - } - return false; - } - verifyBreakContinue(node, isBreak) { - if (node.label && node.label.type === "Placeholder") return; - super.verifyBreakContinue(node, isBreak); - } - parseExpressionStatement(node, expr) { - var _expr$extra; - if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { - return super.parseExpressionStatement(node, expr); - } - if (this.match(14)) { - const stmt = node; - stmt.label = this.finishPlaceholder(expr, "Identifier"); - this.next(); - stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration(); - return this.finishNode(stmt, "LabeledStatement"); - } - this.semicolon(); - node.name = expr.name; - return this.finishPlaceholder(node, "Statement"); - } - parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) { - return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse); - } - parseFunctionId(requireId) { - return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId); - } - parseClass(node, isStatement, optionalId) { - const type = isStatement ? "ClassDeclaration" : "ClassExpression"; - this.next(); - const oldStrict = this.state.strict; - const placeholder = this.parsePlaceholder("Identifier"); - if (placeholder) { - if (this.match(81) || this.match(144) || this.match(5)) { - node.id = placeholder; - } else if (optionalId || !isStatement) { - node.id = null; - node.body = this.finishPlaceholder(placeholder, "ClassBody"); - return this.finishNode(node, type); - } else { - throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc); - } - } else { - this.parseClassId(node, isStatement, optionalId); - } - super.parseClassSuper(node); - node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict); - return this.finishNode(node, type); - } - parseExport(node, decorators) { - const placeholder = this.parsePlaceholder("Identifier"); - if (!placeholder) return super.parseExport(node, decorators); - if (!this.isContextual(98) && !this.match(12)) { - node.specifiers = []; - node.source = null; - node.declaration = this.finishPlaceholder(placeholder, "Declaration"); - return this.finishNode(node, "ExportNamedDeclaration"); - } - this.expectPlugin("exportDefaultFrom"); - const specifier = this.startNode(); - specifier.exported = placeholder; - node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; - return super.parseExport(node, decorators); - } - isExportDefaultSpecifier() { - if (this.match(65)) { - const next = this.nextTokenStart(); - if (this.isUnparsedContextual(next, "from")) { - if (this.input.startsWith(tokenLabelName(144), this.nextTokenStartSince(next + 4))) { - return true; - } - } - } - return super.isExportDefaultSpecifier(); - } - maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { - var _specifiers; - if ((_specifiers = node.specifiers) != null && _specifiers.length) { - return true; - } - return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); - } - checkExport(node) { - const { - specifiers - } = node; - if (specifiers != null && specifiers.length) { - node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder"); - } - super.checkExport(node); - node.specifiers = specifiers; - } - parseImport(node) { - const placeholder = this.parsePlaceholder("Identifier"); - if (!placeholder) return super.parseImport(node); - node.specifiers = []; - if (!this.isContextual(98) && !this.match(12)) { - node.source = this.finishPlaceholder(placeholder, "StringLiteral"); - this.semicolon(); - return this.finishNode(node, "ImportDeclaration"); - } - const specifier = this.startNodeAtNode(placeholder); - specifier.local = placeholder; - node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier")); - if (this.eat(12)) { - const hasStarImport = this.maybeParseStarImportSpecifier(node); - if (!hasStarImport) this.parseNamedImportSpecifiers(node); - } - this.expectContextual(98); - node.source = this.parseImportSource(); - this.semicolon(); - return this.finishNode(node, "ImportDeclaration"); - } - parseImportSource() { - return this.parsePlaceholder("StringLiteral") || super.parseImportSource(); - } - assertNoSpace() { - if (this.state.start > this.state.lastTokEndLoc.index) { - this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc); - } - } - }; - var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass { - parseV8Intrinsic() { - if (this.match(54)) { - const v8IntrinsicStartLoc = this.state.startLoc; - const node = this.startNode(); - this.next(); - if (tokenIsIdentifier(this.state.type)) { - const name = this.parseIdentifierName(); - const identifier = this.createIdentifier(node, name); - identifier.type = "V8IntrinsicIdentifier"; - if (this.match(10)) { - return identifier; - } - } - this.unexpected(v8IntrinsicStartLoc); - } - } - parseExprAtom(refExpressionErrors) { - return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors); - } - }; - function hasPlugin(plugins, expectedConfig) { - const [expectedName, expectedOptions] = typeof expectedConfig === "string" ? [expectedConfig, {}] : expectedConfig; - const expectedKeys = Object.keys(expectedOptions); - const expectedOptionsIsEmpty = expectedKeys.length === 0; - return plugins.some(p => { - if (typeof p === "string") { - return expectedOptionsIsEmpty && p === expectedName; - } else { - const [pluginName, pluginOptions] = p; - if (pluginName !== expectedName) { - return false; - } - for (const key of expectedKeys) { - if (pluginOptions[key] !== expectedOptions[key]) { - return false; - } - } - return true; - } - }); - } - function getPluginOption(plugins, name, option) { - const plugin = plugins.find(plugin => { - if (Array.isArray(plugin)) { - return plugin[0] === name; - } else { - return plugin === name; - } - }); - if (plugin && Array.isArray(plugin) && plugin.length > 1) { - return plugin[1][option]; - } - return null; - } - const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; - const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"]; - const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; - function validatePlugins(plugins) { - if (hasPlugin(plugins, "decorators")) { - if (hasPlugin(plugins, "decorators-legacy")) { - throw new Error("Cannot use the decorators and decorators-legacy plugin together"); - } - const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport"); - if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") { - throw new Error("'decoratorsBeforeExport' must be a boolean, if specified."); - } - const allowCallParenthesized = getPluginOption(plugins, "decorators", "allowCallParenthesized"); - if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") { - throw new Error("'allowCallParenthesized' must be a boolean."); - } - } - if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) { - throw new Error("Cannot combine flow and typescript plugins."); - } - if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) { - throw new Error("Cannot combine placeholders and v8intrinsic plugins."); - } - if (hasPlugin(plugins, "pipelineOperator")) { - const proposal = getPluginOption(plugins, "pipelineOperator", "proposal"); - if (!PIPELINE_PROPOSALS.includes(proposal)) { - const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", "); - throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`); - } - const tupleSyntaxIsHash = hasPlugin(plugins, ["recordAndTuple", { - syntaxType: "hash" - }]); - if (proposal === "hack") { - if (hasPlugin(plugins, "placeholders")) { - throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); - } - if (hasPlugin(plugins, "v8intrinsic")) { - throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); - } - const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken"); - if (!TOPIC_TOKENS.includes(topicToken)) { - const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", "); - throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`); - } - if (topicToken === "#" && tupleSyntaxIsHash) { - throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); - } - } else if (proposal === "smart" && tupleSyntaxIsHash) { - throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); - } - } - if (hasPlugin(plugins, "moduleAttributes")) { - { - if (hasPlugin(plugins, "importAssertions") || hasPlugin(plugins, "importAttributes")) { - throw new Error("Cannot combine importAssertions, importAttributes and moduleAttributes plugins."); - } - const moduleAttributesVersionPluginOption = getPluginOption(plugins, "moduleAttributes", "version"); - if (moduleAttributesVersionPluginOption !== "may-2020") { - throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'."); - } - } - } - if (hasPlugin(plugins, "importAssertions") && hasPlugin(plugins, "importAttributes")) { - throw new Error("Cannot combine importAssertions and importAttributes plugins."); - } - if (hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") != null && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) { - throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", ")); - } - if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) { - const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); - error.missingPlugins = "doExpressions"; - throw error; - } - if (hasPlugin(plugins, "optionalChainingAssign") && getPluginOption(plugins, "optionalChainingAssign", "version") !== "2023-07") { - throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'."); - } - } - const mixinPlugins = { - estree, - jsx, - flow, - typescript, - v8intrinsic, - placeholders - }; - const mixinPluginNames = Object.keys(mixinPlugins); - const defaultOptions = { - sourceType: "script", - sourceFilename: undefined, - startColumn: 0, - startLine: 1, - allowAwaitOutsideFunction: false, - allowReturnOutsideFunction: false, - allowNewTargetOutsideFunction: false, - allowImportExportEverywhere: false, - allowSuperOutsideMethod: false, - allowUndeclaredExports: false, - plugins: [], - strictMode: null, - ranges: false, - tokens: false, - createImportExpressions: false, - createParenthesizedExpressions: false, - errorRecovery: false, - attachComment: true, - annexB: true - }; - function getOptions(opts) { - if (opts == null) { - return Object.assign({}, defaultOptions); - } - if (opts.annexB != null && opts.annexB !== false) { - throw new Error("The `annexB` option can only be set to `false`."); - } - const options = {}; - for (const key of Object.keys(defaultOptions)) { - var _opts$key; - options[key] = (_opts$key = opts[key]) != null ? _opts$key : defaultOptions[key]; - } - return options; - } - class ExpressionParser extends LValParser { - checkProto(prop, isRecord, protoRef, refExpressionErrors) { - if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { - return; - } - const key = prop.key; - const name = key.type === "Identifier" ? key.name : key.value; - if (name === "__proto__") { - if (isRecord) { - this.raise(Errors.RecordNoProto, key); - return; - } - if (protoRef.used) { - if (refExpressionErrors) { - if (refExpressionErrors.doubleProtoLoc === null) { - refExpressionErrors.doubleProtoLoc = key.loc.start; - } - } else { - this.raise(Errors.DuplicateProto, key); - } - } - protoRef.used = true; - } - } - shouldExitDescending(expr, potentialArrowAt) { - return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt; - } - getExpression() { - this.enterInitialScopes(); - this.nextToken(); - const expr = this.parseExpression(); - if (!this.match(139)) { - this.unexpected(); - } - this.finalizeRemainingComments(); - expr.comments = this.comments; - expr.errors = this.state.errors; - if (this.options.tokens) { - expr.tokens = this.tokens; - } - return expr; - } - parseExpression(disallowIn, refExpressionErrors) { - if (disallowIn) { - return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); - } - return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); - } - parseExpressionBase(refExpressionErrors) { - const startLoc = this.state.startLoc; - const expr = this.parseMaybeAssign(refExpressionErrors); - if (this.match(12)) { - const node = this.startNodeAt(startLoc); - node.expressions = [expr]; - while (this.eat(12)) { - node.expressions.push(this.parseMaybeAssign(refExpressionErrors)); - } - this.toReferencedList(node.expressions); - return this.finishNode(node, "SequenceExpression"); - } - return expr; - } - parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) { - return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); - } - parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) { - return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); - } - setOptionalParametersError(refExpressionErrors, resultError) { - var _resultError$loc; - refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc; - } - parseMaybeAssign(refExpressionErrors, afterLeftParse) { - const startLoc = this.state.startLoc; - if (this.isContextual(108)) { - if (this.prodParam.hasYield) { - let left = this.parseYield(); - if (afterLeftParse) { - left = afterLeftParse.call(this, left, startLoc); - } - return left; - } - } - let ownExpressionErrors; - if (refExpressionErrors) { - ownExpressionErrors = false; - } else { - refExpressionErrors = new ExpressionErrors(); - ownExpressionErrors = true; - } - const { - type - } = this.state; - if (type === 10 || tokenIsIdentifier(type)) { - this.state.potentialArrowAt = this.state.start; - } - let left = this.parseMaybeConditional(refExpressionErrors); - if (afterLeftParse) { - left = afterLeftParse.call(this, left, startLoc); - } - if (tokenIsAssignment(this.state.type)) { - const node = this.startNodeAt(startLoc); - const operator = this.state.value; - node.operator = operator; - if (this.match(29)) { - this.toAssignable(left, true); - node.left = left; - const startIndex = startLoc.index; - if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) { - refExpressionErrors.doubleProtoLoc = null; - } - if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) { - refExpressionErrors.shorthandAssignLoc = null; - } - if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) { - this.checkDestructuringPrivate(refExpressionErrors); - refExpressionErrors.privateKeyLoc = null; - } - } else { - node.left = left; - } - this.next(); - node.right = this.parseMaybeAssign(); - this.checkLVal(left, { - in: this.finishNode(node, "AssignmentExpression") - }); - return node; - } else if (ownExpressionErrors) { - this.checkExpressionErrors(refExpressionErrors, true); - } - return left; - } - parseMaybeConditional(refExpressionErrors) { - const startLoc = this.state.startLoc; - const potentialArrowAt = this.state.potentialArrowAt; - const expr = this.parseExprOps(refExpressionErrors); - if (this.shouldExitDescending(expr, potentialArrowAt)) { - return expr; - } - return this.parseConditional(expr, startLoc, refExpressionErrors); - } - parseConditional(expr, startLoc, refExpressionErrors) { - if (this.eat(17)) { - const node = this.startNodeAt(startLoc); - node.test = expr; - node.consequent = this.parseMaybeAssignAllowIn(); - this.expect(14); - node.alternate = this.parseMaybeAssign(); - return this.finishNode(node, "ConditionalExpression"); - } - return expr; - } - parseMaybeUnaryOrPrivate(refExpressionErrors) { - return this.match(138) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors); - } - parseExprOps(refExpressionErrors) { - const startLoc = this.state.startLoc; - const potentialArrowAt = this.state.potentialArrowAt; - const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors); - if (this.shouldExitDescending(expr, potentialArrowAt)) { - return expr; - } - return this.parseExprOp(expr, startLoc, -1); - } - parseExprOp(left, leftStartLoc, minPrec) { - if (this.isPrivateName(left)) { - const value = this.getPrivateNameSV(left); - if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) { - this.raise(Errors.PrivateInExpectedIn, left, { - identifierName: value - }); - } - this.classScope.usePrivateName(value, left.loc.start); - } - const op = this.state.type; - if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) { - let prec = tokenOperatorPrecedence(op); - if (prec > minPrec) { - if (op === 39) { - this.expectPlugin("pipelineOperator"); - if (this.state.inFSharpPipelineDirectBody) { - return left; - } - this.checkPipelineAtInfixOperator(left, leftStartLoc); - } - const node = this.startNodeAt(leftStartLoc); - node.left = left; - node.operator = this.state.value; - const logical = op === 41 || op === 42; - const coalesce = op === 40; - if (coalesce) { - prec = tokenOperatorPrecedence(42); - } - this.next(); - if (op === 39 && this.hasPlugin(["pipelineOperator", { - proposal: "minimal" - }])) { - if (this.state.type === 96 && this.prodParam.hasAwait) { - throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc); - } - } - node.right = this.parseExprOpRightExpr(op, prec); - const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); - const nextOp = this.state.type; - if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) { - throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc); - } - return this.parseExprOp(finishedNode, leftStartLoc, minPrec); - } - } - return left; - } - parseExprOpRightExpr(op, prec) { - const startLoc = this.state.startLoc; - switch (op) { - case 39: - switch (this.getPluginOption("pipelineOperator", "proposal")) { - case "hack": - return this.withTopicBindingContext(() => { - return this.parseHackPipeBody(); - }); - case "smart": - return this.withTopicBindingContext(() => { - if (this.prodParam.hasYield && this.isContextual(108)) { - throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc); - } - return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc); - }); - case "fsharp": - return this.withSoloAwaitPermittingContext(() => { - return this.parseFSharpPipelineBody(prec); - }); - } - default: - return this.parseExprOpBaseRightExpr(op, prec); - } - } - parseExprOpBaseRightExpr(op, prec) { - const startLoc = this.state.startLoc; - return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec); - } - parseHackPipeBody() { - var _body$extra; - const { - startLoc - } = this.state; - const body = this.parseMaybeAssign(); - const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type); - if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) { - this.raise(Errors.PipeUnparenthesizedBody, startLoc, { - type: body.type - }); - } - if (!this.topicReferenceWasUsedInCurrentContext()) { - this.raise(Errors.PipeTopicUnused, startLoc); - } - return body; - } - checkExponentialAfterUnary(node) { - if (this.match(57)) { - this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument); - } - } - parseMaybeUnary(refExpressionErrors, sawUnary) { - const startLoc = this.state.startLoc; - const isAwait = this.isContextual(96); - if (isAwait && this.isAwaitAllowed()) { - this.next(); - const expr = this.parseAwait(startLoc); - if (!sawUnary) this.checkExponentialAfterUnary(expr); - return expr; - } - const update = this.match(34); - const node = this.startNode(); - if (tokenIsPrefix(this.state.type)) { - node.operator = this.state.value; - node.prefix = true; - if (this.match(72)) { - this.expectPlugin("throwExpressions"); - } - const isDelete = this.match(89); - this.next(); - node.argument = this.parseMaybeUnary(null, true); - this.checkExpressionErrors(refExpressionErrors, true); - if (this.state.strict && isDelete) { - const arg = node.argument; - if (arg.type === "Identifier") { - this.raise(Errors.StrictDelete, node); - } else if (this.hasPropertyAsPrivateName(arg)) { - this.raise(Errors.DeletePrivateField, node); - } - } - if (!update) { - if (!sawUnary) { - this.checkExponentialAfterUnary(node); - } - return this.finishNode(node, "UnaryExpression"); - } - } - const expr = this.parseUpdate(node, update, refExpressionErrors); - if (isAwait) { - const { - type - } = this.state; - const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); - if (startsExpr && !this.isAmbiguousAwait()) { - this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc); - return this.parseAwait(startLoc); - } - } - return expr; - } - parseUpdate(node, update, refExpressionErrors) { - if (update) { - const updateExpressionNode = node; - this.checkLVal(updateExpressionNode.argument, { - in: this.finishNode(updateExpressionNode, "UpdateExpression") - }); - return node; - } - const startLoc = this.state.startLoc; - let expr = this.parseExprSubscripts(refExpressionErrors); - if (this.checkExpressionErrors(refExpressionErrors, false)) return expr; - while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) { - const node = this.startNodeAt(startLoc); - node.operator = this.state.value; - node.prefix = false; - node.argument = expr; - this.next(); - this.checkLVal(expr, { - in: expr = this.finishNode(node, "UpdateExpression") - }); - } - return expr; - } - parseExprSubscripts(refExpressionErrors) { - const startLoc = this.state.startLoc; - const potentialArrowAt = this.state.potentialArrowAt; - const expr = this.parseExprAtom(refExpressionErrors); - if (this.shouldExitDescending(expr, potentialArrowAt)) { - return expr; - } - return this.parseSubscripts(expr, startLoc); - } - parseSubscripts(base, startLoc, noCalls) { - const state = { - optionalChainMember: false, - maybeAsyncArrow: this.atPossibleAsyncArrow(base), - stop: false - }; - do { - base = this.parseSubscript(base, startLoc, noCalls, state); - state.maybeAsyncArrow = false; - } while (!state.stop); - return base; - } - parseSubscript(base, startLoc, noCalls, state) { - const { - type - } = this.state; - if (!noCalls && type === 15) { - return this.parseBind(base, startLoc, noCalls, state); - } else if (tokenIsTemplate(type)) { - return this.parseTaggedTemplateExpression(base, startLoc, state); - } - let optional = false; - if (type === 18) { - if (noCalls) { - this.raise(Errors.OptionalChainingNoNew, this.state.startLoc); - if (this.lookaheadCharCode() === 40) { - state.stop = true; - return base; - } - } - state.optionalChainMember = optional = true; - this.next(); - } - if (!noCalls && this.match(10)) { - return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional); - } else { - const computed = this.eat(0); - if (computed || optional || this.eat(16)) { - return this.parseMember(base, startLoc, state, computed, optional); - } else { - state.stop = true; - return base; - } - } - } - parseMember(base, startLoc, state, computed, optional) { - const node = this.startNodeAt(startLoc); - node.object = base; - node.computed = computed; - if (computed) { - node.property = this.parseExpression(); - this.expect(3); - } else if (this.match(138)) { - if (base.type === "Super") { - this.raise(Errors.SuperPrivateField, startLoc); - } - this.classScope.usePrivateName(this.state.value, this.state.startLoc); - node.property = this.parsePrivateName(); - } else { - node.property = this.parseIdentifier(true); - } - if (state.optionalChainMember) { - node.optional = optional; - return this.finishNode(node, "OptionalMemberExpression"); - } else { - return this.finishNode(node, "MemberExpression"); - } - } - parseBind(base, startLoc, noCalls, state) { - const node = this.startNodeAt(startLoc); - node.object = base; - this.next(); - node.callee = this.parseNoCallExpr(); - state.stop = true; - return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls); - } - parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) { - const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; - let refExpressionErrors = null; - this.state.maybeInArrowParameters = true; - this.next(); - const node = this.startNodeAt(startLoc); - node.callee = base; - const { - maybeAsyncArrow, - optionalChainMember - } = state; - if (maybeAsyncArrow) { - this.expressionScope.enter(newAsyncArrowScope()); - refExpressionErrors = new ExpressionErrors(); - } - if (optionalChainMember) { - node.optional = optional; - } - if (optional) { - node.arguments = this.parseCallExpressionArguments(11); - } else { - node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors); - } - let finishedNode = this.finishCallExpression(node, optionalChainMember); - if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { - state.stop = true; - this.checkDestructuringPrivate(refExpressionErrors); - this.expressionScope.validateAsPattern(); - this.expressionScope.exit(); - finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode); - } else { - if (maybeAsyncArrow) { - this.checkExpressionErrors(refExpressionErrors, true); - this.expressionScope.exit(); - } - this.toReferencedArguments(finishedNode); - } - this.state.maybeInArrowParameters = oldMaybeInArrowParameters; - return finishedNode; - } - toReferencedArguments(node, isParenthesizedExpr) { - this.toReferencedListDeep(node.arguments, isParenthesizedExpr); - } - parseTaggedTemplateExpression(base, startLoc, state) { - const node = this.startNodeAt(startLoc); - node.tag = base; - node.quasi = this.parseTemplate(true); - if (state.optionalChainMember) { - this.raise(Errors.OptionalChainingNoTemplate, startLoc); - } - return this.finishNode(node, "TaggedTemplateExpression"); - } - atPossibleAsyncArrow(base) { - return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; - } - expectImportAttributesPlugin() { - if (!this.hasPlugin("importAssertions")) { - this.expectPlugin("importAttributes"); - } - } - finishCallExpression(node, optional) { - if (node.callee.type === "Import") { - if (node.arguments.length === 2) { - { - if (!this.hasPlugin("moduleAttributes")) { - this.expectImportAttributesPlugin(); - } - } - } - if (node.arguments.length === 0 || node.arguments.length > 2) { - this.raise(Errors.ImportCallArity, node, { - maxArgumentCount: this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? 2 : 1 - }); - } else { - for (const arg of node.arguments) { - if (arg.type === "SpreadElement") { - this.raise(Errors.ImportCallSpreadArgument, arg); - } - } - } - } - return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); - } - parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) { - const elts = []; - let first = true; - const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; - this.state.inFSharpPipelineDirectBody = false; - while (!this.eat(close)) { - if (first) { - first = false; - } else { - this.expect(12); - if (this.match(close)) { - if (dynamicImport && !this.hasPlugin("importAttributes") && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) { - this.raise(Errors.ImportCallArgumentTrailingComma, this.state.lastTokStartLoc); - } - if (nodeForExtra) { - this.addTrailingCommaExtraToNode(nodeForExtra); - } - this.next(); - break; - } - } - elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder)); - } - this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; - return elts; - } - shouldParseAsyncArrow() { - return this.match(19) && !this.canInsertSemicolon(); - } - parseAsyncArrowFromCallExpression(node, call) { - var _call$extra; - this.resetPreviousNodeTrailingComments(call); - this.expect(19); - this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc); - if (call.innerComments) { - setInnerComments(node, call.innerComments); - } - if (call.callee.trailingComments) { - setInnerComments(node, call.callee.trailingComments); - } - return node; - } - parseNoCallExpr() { - const startLoc = this.state.startLoc; - return this.parseSubscripts(this.parseExprAtom(), startLoc, true); - } - parseExprAtom(refExpressionErrors) { - let node; - let decorators = null; - const { - type - } = this.state; - switch (type) { - case 79: - return this.parseSuper(); - case 83: - node = this.startNode(); - this.next(); - if (this.match(16)) { - return this.parseImportMetaProperty(node); - } - if (this.match(10)) { - if (this.options.createImportExpressions) { - return this.parseImportCall(node); - } else { - return this.finishNode(node, "Import"); - } - } else { - this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc); - return this.finishNode(node, "Import"); - } - case 78: - node = this.startNode(); - this.next(); - return this.finishNode(node, "ThisExpression"); - case 90: - { - return this.parseDo(this.startNode(), false); - } - case 56: - case 31: - { - this.readRegexp(); - return this.parseRegExpLiteral(this.state.value); - } - case 134: - return this.parseNumericLiteral(this.state.value); - case 135: - return this.parseBigIntLiteral(this.state.value); - case 136: - return this.parseDecimalLiteral(this.state.value); - case 133: - return this.parseStringLiteral(this.state.value); - case 84: - return this.parseNullLiteral(); - case 85: - return this.parseBooleanLiteral(true); - case 86: - return this.parseBooleanLiteral(false); - case 10: - { - const canBeArrow = this.state.potentialArrowAt === this.state.start; - return this.parseParenAndDistinguishExpression(canBeArrow); - } - case 2: - case 1: - { - return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true); - } - case 0: - { - return this.parseArrayLike(3, true, false, refExpressionErrors); - } - case 6: - case 7: - { - return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true); - } - case 5: - { - return this.parseObjectLike(8, false, false, refExpressionErrors); - } - case 68: - return this.parseFunctionOrFunctionSent(); - case 26: - decorators = this.parseDecorators(); - case 80: - return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false); - case 77: - return this.parseNewOrNewTarget(); - case 25: - case 24: - return this.parseTemplate(false); - case 15: - { - node = this.startNode(); - this.next(); - node.object = null; - const callee = node.callee = this.parseNoCallExpr(); - if (callee.type === "MemberExpression") { - return this.finishNode(node, "BindExpression"); - } else { - throw this.raise(Errors.UnsupportedBind, callee); - } - } - case 138: - { - this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, { - identifierName: this.state.value - }); - return this.parsePrivateName(); - } - case 33: - { - return this.parseTopicReferenceThenEqualsSign(54, "%"); - } - case 32: - { - return this.parseTopicReferenceThenEqualsSign(44, "^"); - } - case 37: - case 38: - { - return this.parseTopicReference("hack"); - } - case 44: - case 54: - case 27: - { - const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); - if (pipeProposal) { - return this.parseTopicReference(pipeProposal); - } - this.unexpected(); - break; - } - case 47: - { - const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); - if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { - this.expectOnePlugin(["jsx", "flow", "typescript"]); - } else { - this.unexpected(); - } - break; - } - default: - if (tokenIsIdentifier(type)) { - if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) { - return this.parseModuleExpression(); - } - const canBeArrow = this.state.potentialArrowAt === this.state.start; - const containsEsc = this.state.containsEsc; - const id = this.parseIdentifier(); - if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { - const { - type - } = this.state; - if (type === 68) { - this.resetPreviousNodeTrailingComments(id); - this.next(); - return this.parseAsyncFunctionExpression(this.startNodeAtNode(id)); - } else if (tokenIsIdentifier(type)) { - if (this.lookaheadCharCode() === 61) { - return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); - } else { - return id; - } - } else if (type === 90) { - this.resetPreviousNodeTrailingComments(id); - return this.parseDo(this.startNodeAtNode(id), true); - } - } - if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) { - this.next(); - return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); - } - return id; - } else { - this.unexpected(); - } - } - } - parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) { - const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); - if (pipeProposal) { - this.state.type = topicTokenType; - this.state.value = topicTokenValue; - this.state.pos--; - this.state.end--; - this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1); - return this.parseTopicReference(pipeProposal); - } else { - this.unexpected(); - } - } - parseTopicReference(pipeProposal) { - const node = this.startNode(); - const startLoc = this.state.startLoc; - const tokenType = this.state.type; - this.next(); - return this.finishTopicReference(node, startLoc, pipeProposal, tokenType); - } - finishTopicReference(node, startLoc, pipeProposal, tokenType) { - if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) { - const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" : "TopicReference"; - if (!this.topicReferenceIsAllowedInCurrentContext()) { - this.raise(pipeProposal === "smart" ? Errors.PrimaryTopicNotAllowed : Errors.PipeTopicUnbound, startLoc); - } - this.registerTopicReference(); - return this.finishNode(node, nodeType); - } else { - throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, { - token: tokenLabelName(tokenType) - }); - } - } - testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) { - switch (pipeProposal) { - case "hack": - { - return this.hasPlugin(["pipelineOperator", { - topicToken: tokenLabelName(tokenType) - }]); - } - case "smart": - return tokenType === 27; - default: - throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc); - } - } - parseAsyncArrowUnaryFunction(node) { - this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); - const params = [this.parseIdentifier()]; - this.prodParam.exit(); - if (this.hasPrecedingLineBreak()) { - this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition()); - } - this.expect(19); - return this.parseArrowExpression(node, params, true); - } - parseDo(node, isAsync) { - this.expectPlugin("doExpressions"); - if (isAsync) { - this.expectPlugin("asyncDoExpressions"); - } - node.async = isAsync; - this.next(); - const oldLabels = this.state.labels; - this.state.labels = []; - if (isAsync) { - this.prodParam.enter(2); - node.body = this.parseBlock(); - this.prodParam.exit(); - } else { - node.body = this.parseBlock(); - } - this.state.labels = oldLabels; - return this.finishNode(node, "DoExpression"); - } - parseSuper() { - const node = this.startNode(); - this.next(); - if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { - this.raise(Errors.SuperNotAllowed, node); - } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { - this.raise(Errors.UnexpectedSuper, node); - } - if (!this.match(10) && !this.match(0) && !this.match(16)) { - this.raise(Errors.UnsupportedSuper, node); - } - return this.finishNode(node, "Super"); - } - parsePrivateName() { - const node = this.startNode(); - const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1)); - const name = this.state.value; - this.next(); - node.id = this.createIdentifier(id, name); - return this.finishNode(node, "PrivateName"); - } - parseFunctionOrFunctionSent() { - const node = this.startNode(); - this.next(); - if (this.prodParam.hasYield && this.match(16)) { - const meta = this.createIdentifier(this.startNodeAtNode(node), "function"); - this.next(); - if (this.match(103)) { - this.expectPlugin("functionSent"); - } else if (!this.hasPlugin("functionSent")) { - this.unexpected(); - } - return this.parseMetaProperty(node, meta, "sent"); - } - return this.parseFunction(node); - } - parseMetaProperty(node, meta, propertyName) { - node.meta = meta; - const containsEsc = this.state.containsEsc; - node.property = this.parseIdentifier(true); - if (node.property.name !== propertyName || containsEsc) { - this.raise(Errors.UnsupportedMetaProperty, node.property, { - target: meta.name, - onlyValidPropertyName: propertyName - }); - } - return this.finishNode(node, "MetaProperty"); - } - parseImportMetaProperty(node) { - const id = this.createIdentifier(this.startNodeAtNode(node), "import"); - this.next(); - if (this.isContextual(101)) { - if (!this.inModule) { - this.raise(Errors.ImportMetaOutsideModule, id); - } - this.sawUnambiguousESM = true; - } else if (this.isContextual(105) || this.isContextual(97)) { - const isSource = this.isContextual(105); - if (!isSource) this.unexpected(); - this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation"); - if (!this.options.createImportExpressions) { - throw this.raise(Errors.DynamicImportPhaseRequiresImportExpressions, this.state.startLoc, { - phase: this.state.value - }); - } - this.next(); - node.phase = isSource ? "source" : "defer"; - return this.parseImportCall(node); - } - return this.parseMetaProperty(node, id, "meta"); - } - parseLiteralAtNode(value, type, node) { - this.addExtra(node, "rawValue", value); - this.addExtra(node, "raw", this.input.slice(node.start, this.state.end)); - node.value = value; - this.next(); - return this.finishNode(node, type); - } - parseLiteral(value, type) { - const node = this.startNode(); - return this.parseLiteralAtNode(value, type, node); - } - parseStringLiteral(value) { - return this.parseLiteral(value, "StringLiteral"); - } - parseNumericLiteral(value) { - return this.parseLiteral(value, "NumericLiteral"); - } - parseBigIntLiteral(value) { - return this.parseLiteral(value, "BigIntLiteral"); - } - parseDecimalLiteral(value) { - return this.parseLiteral(value, "DecimalLiteral"); - } - parseRegExpLiteral(value) { - const node = this.parseLiteral(value.value, "RegExpLiteral"); - node.pattern = value.pattern; - node.flags = value.flags; - return node; - } - parseBooleanLiteral(value) { - const node = this.startNode(); - node.value = value; - this.next(); - return this.finishNode(node, "BooleanLiteral"); - } - parseNullLiteral() { - const node = this.startNode(); - this.next(); - return this.finishNode(node, "NullLiteral"); - } - parseParenAndDistinguishExpression(canBeArrow) { - const startLoc = this.state.startLoc; - let val; - this.next(); - this.expressionScope.enter(newArrowHeadScope()); - const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; - const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; - this.state.maybeInArrowParameters = true; - this.state.inFSharpPipelineDirectBody = false; - const innerStartLoc = this.state.startLoc; - const exprList = []; - const refExpressionErrors = new ExpressionErrors(); - let first = true; - let spreadStartLoc; - let optionalCommaStartLoc; - while (!this.match(11)) { - if (first) { - first = false; - } else { - this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc); - if (this.match(11)) { - optionalCommaStartLoc = this.state.startLoc; - break; - } - } - if (this.match(21)) { - const spreadNodeStartLoc = this.state.startLoc; - spreadStartLoc = this.state.startLoc; - exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc)); - if (!this.checkCommaAfterRest(41)) { - break; - } - } else { - exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem)); - } - } - const innerEndLoc = this.state.lastTokEndLoc; - this.expect(11); - this.state.maybeInArrowParameters = oldMaybeInArrowParameters; - this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; - let arrowNode = this.startNodeAt(startLoc); - if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) { - this.checkDestructuringPrivate(refExpressionErrors); - this.expressionScope.validateAsPattern(); - this.expressionScope.exit(); - this.parseArrowExpression(arrowNode, exprList, false); - return arrowNode; - } - this.expressionScope.exit(); - if (!exprList.length) { - this.unexpected(this.state.lastTokStartLoc); - } - if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc); - if (spreadStartLoc) this.unexpected(spreadStartLoc); - this.checkExpressionErrors(refExpressionErrors, true); - this.toReferencedListDeep(exprList, true); - if (exprList.length > 1) { - val = this.startNodeAt(innerStartLoc); - val.expressions = exprList; - this.finishNode(val, "SequenceExpression"); - this.resetEndLocation(val, innerEndLoc); - } else { - val = exprList[0]; - } - return this.wrapParenthesis(startLoc, val); - } - wrapParenthesis(startLoc, expression) { - if (!this.options.createParenthesizedExpressions) { - this.addExtra(expression, "parenthesized", true); - this.addExtra(expression, "parenStart", startLoc.index); - this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index); - return expression; - } - const parenExpression = this.startNodeAt(startLoc); - parenExpression.expression = expression; - return this.finishNode(parenExpression, "ParenthesizedExpression"); - } - shouldParseArrow(params) { - return !this.canInsertSemicolon(); - } - parseArrow(node) { - if (this.eat(19)) { - return node; - } - } - parseParenItem(node, startLoc) { - return node; - } - parseNewOrNewTarget() { - const node = this.startNode(); - this.next(); - if (this.match(16)) { - const meta = this.createIdentifier(this.startNodeAtNode(node), "new"); - this.next(); - const metaProp = this.parseMetaProperty(node, meta, "target"); - if (!this.scope.inNonArrowFunction && !this.scope.inClass && !this.options.allowNewTargetOutsideFunction) { - this.raise(Errors.UnexpectedNewTarget, metaProp); - } - return metaProp; - } - return this.parseNew(node); - } - parseNew(node) { - this.parseNewCallee(node); - if (this.eat(10)) { - const args = this.parseExprList(11); - this.toReferencedList(args); - node.arguments = args; - } else { - node.arguments = []; - } - return this.finishNode(node, "NewExpression"); - } - parseNewCallee(node) { - const isImport = this.match(83); - const callee = this.parseNoCallExpr(); - node.callee = callee; - if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) { - this.raise(Errors.ImportCallNotNewExpression, callee); - } - } - parseTemplateElement(isTagged) { - const { - start, - startLoc, - end, - value - } = this.state; - const elemStart = start + 1; - const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1)); - if (value === null) { - if (!isTagged) { - this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1)); - } - } - const isTail = this.match(24); - const endOffset = isTail ? -1 : -2; - const elemEnd = end + endOffset; - elem.value = { - raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"), - cooked: value === null ? null : value.slice(1, endOffset) - }; - elem.tail = isTail; - this.next(); - const finishedNode = this.finishNode(elem, "TemplateElement"); - this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); - return finishedNode; - } - parseTemplate(isTagged) { - const node = this.startNode(); - node.expressions = []; - let curElt = this.parseTemplateElement(isTagged); - node.quasis = [curElt]; - while (!curElt.tail) { - node.expressions.push(this.parseTemplateSubstitution()); - this.readTemplateContinuation(); - node.quasis.push(curElt = this.parseTemplateElement(isTagged)); - } - return this.finishNode(node, "TemplateLiteral"); - } - parseTemplateSubstitution() { - return this.parseExpression(); - } - parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { - if (isRecord) { - this.expectPlugin("recordAndTuple"); - } - const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; - this.state.inFSharpPipelineDirectBody = false; - const propHash = Object.create(null); - let first = true; - const node = this.startNode(); - node.properties = []; - this.next(); - while (!this.match(close)) { - if (first) { - first = false; - } else { - this.expect(12); - if (this.match(close)) { - this.addTrailingCommaExtraToNode(node); - break; - } - } - let prop; - if (isPattern) { - prop = this.parseBindingProperty(); - } else { - prop = this.parsePropertyDefinition(refExpressionErrors); - this.checkProto(prop, isRecord, propHash, refExpressionErrors); - } - if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { - this.raise(Errors.InvalidRecordProperty, prop); - } - if (prop.shorthand) { - this.addExtra(prop, "shorthand", true); - } - node.properties.push(prop); - } - this.next(); - this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; - let type = "ObjectExpression"; - if (isPattern) { - type = "ObjectPattern"; - } else if (isRecord) { - type = "RecordExpression"; - } - return this.finishNode(node, type); - } - addTrailingCommaExtraToNode(node) { - this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index); - this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false); - } - maybeAsyncOrAccessorProp(prop) { - return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55)); - } - parsePropertyDefinition(refExpressionErrors) { - let decorators = []; - if (this.match(26)) { - if (this.hasPlugin("decorators")) { - this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc); - } - while (this.match(26)) { - decorators.push(this.parseDecorator()); - } - } - const prop = this.startNode(); - let isAsync = false; - let isAccessor = false; - let startLoc; - if (this.match(21)) { - if (decorators.length) this.unexpected(); - return this.parseSpread(); - } - if (decorators.length) { - prop.decorators = decorators; - decorators = []; - } - prop.method = false; - if (refExpressionErrors) { - startLoc = this.state.startLoc; - } - let isGenerator = this.eat(55); - this.parsePropertyNamePrefixOperator(prop); - const containsEsc = this.state.containsEsc; - const key = this.parsePropertyName(prop, refExpressionErrors); - if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { - const keyName = key.name; - if (keyName === "async" && !this.hasPrecedingLineBreak()) { - isAsync = true; - this.resetPreviousNodeTrailingComments(key); - isGenerator = this.eat(55); - this.parsePropertyName(prop); - } - if (keyName === "get" || keyName === "set") { - isAccessor = true; - this.resetPreviousNodeTrailingComments(key); - prop.kind = keyName; - if (this.match(55)) { - isGenerator = true; - this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), { - kind: keyName - }); - this.next(); - } - this.parsePropertyName(prop); - } - } - return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors); - } - getGetterSetterExpectedParamCount(method) { - return method.kind === "get" ? 0 : 1; - } - getObjectOrClassMethodParams(method) { - return method.params; - } - checkGetterSetterParams(method) { - var _params; - const paramCount = this.getGetterSetterExpectedParamCount(method); - const params = this.getObjectOrClassMethodParams(method); - if (params.length !== paramCount) { - this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method); - } - if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { - this.raise(Errors.BadSetterRestParameter, method); - } - } - parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { - if (isAccessor) { - const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); - this.checkGetterSetterParams(finishedProp); - return finishedProp; - } - if (isAsync || isGenerator || this.match(10)) { - if (isPattern) this.unexpected(); - prop.kind = "method"; - prop.method = true; - return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); - } - } - parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { - prop.shorthand = false; - if (this.eat(14)) { - prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors); - return this.finishNode(prop, "ObjectProperty"); - } - if (!prop.computed && prop.key.type === "Identifier") { - this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false); - if (isPattern) { - prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); - } else if (this.match(29)) { - const shorthandAssignLoc = this.state.startLoc; - if (refExpressionErrors != null) { - if (refExpressionErrors.shorthandAssignLoc === null) { - refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc; - } - } else { - this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); - } - prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); - } else { - prop.value = cloneIdentifier(prop.key); - } - prop.shorthand = true; - return this.finishNode(prop, "ObjectProperty"); - } - } - parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { - const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); - if (!node) this.unexpected(); - return node; - } - parsePropertyName(prop, refExpressionErrors) { - if (this.eat(0)) { - prop.computed = true; - prop.key = this.parseMaybeAssignAllowIn(); - this.expect(3); - } else { - const { - type, - value - } = this.state; - let key; - if (tokenIsKeywordOrIdentifier(type)) { - key = this.parseIdentifier(true); - } else { - switch (type) { - case 134: - key = this.parseNumericLiteral(value); - break; - case 133: - key = this.parseStringLiteral(value); - break; - case 135: - key = this.parseBigIntLiteral(value); - break; - case 136: - key = this.parseDecimalLiteral(value); - break; - case 138: - { - const privateKeyLoc = this.state.startLoc; - if (refExpressionErrors != null) { - if (refExpressionErrors.privateKeyLoc === null) { - refExpressionErrors.privateKeyLoc = privateKeyLoc; - } - } else { - this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); - } - key = this.parsePrivateName(); - break; - } - default: - this.unexpected(); - } - } - prop.key = key; - if (type !== 138) { - prop.computed = false; - } - } - return prop.key; - } - initFunction(node, isAsync) { - node.id = null; - node.generator = false; - node.async = isAsync; - } - parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { - this.initFunction(node, isAsync); - node.generator = isGenerator; - this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0)); - this.prodParam.enter(functionFlags(isAsync, node.generator)); - this.parseFunctionParams(node, isConstructor); - const finishedNode = this.parseFunctionBodyAndFinish(node, type, true); - this.prodParam.exit(); - this.scope.exit(); - return finishedNode; - } - parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { - if (isTuple) { - this.expectPlugin("recordAndTuple"); - } - const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; - this.state.inFSharpPipelineDirectBody = false; - const node = this.startNode(); - this.next(); - node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node); - this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; - return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); - } - parseArrowExpression(node, params, isAsync, trailingCommaLoc) { - this.scope.enter(2 | 4); - let flags = functionFlags(isAsync, false); - if (!this.match(5) && this.prodParam.hasIn) { - flags |= 8; - } - this.prodParam.enter(flags); - this.initFunction(node, isAsync); - const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; - if (params) { - this.state.maybeInArrowParameters = true; - this.setArrowFunctionParameters(node, params, trailingCommaLoc); - } - this.state.maybeInArrowParameters = false; - this.parseFunctionBody(node, true); - this.prodParam.exit(); - this.scope.exit(); - this.state.maybeInArrowParameters = oldMaybeInArrowParameters; - return this.finishNode(node, "ArrowFunctionExpression"); - } - setArrowFunctionParameters(node, params, trailingCommaLoc) { - this.toAssignableList(params, trailingCommaLoc, false); - node.params = params; - } - parseFunctionBodyAndFinish(node, type, isMethod = false) { - this.parseFunctionBody(node, false, isMethod); - return this.finishNode(node, type); - } - parseFunctionBody(node, allowExpression, isMethod = false) { - const isExpression = allowExpression && !this.match(5); - this.expressionScope.enter(newExpressionScope()); - if (isExpression) { - node.body = this.parseMaybeAssign(); - this.checkParams(node, false, allowExpression, false); - } else { - const oldStrict = this.state.strict; - const oldLabels = this.state.labels; - this.state.labels = []; - this.prodParam.enter(this.prodParam.currentFlags() | 4); - node.body = this.parseBlock(true, false, hasStrictModeDirective => { - const nonSimple = !this.isSimpleParamList(node.params); - if (hasStrictModeDirective && nonSimple) { - this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node); - } - const strictModeChanged = !oldStrict && this.state.strict; - this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); - if (this.state.strict && node.id) { - this.checkIdentifier(node.id, 65, strictModeChanged); - } - }); - this.prodParam.exit(); - this.state.labels = oldLabels; - } - this.expressionScope.exit(); - } - isSimpleParameter(node) { - return node.type === "Identifier"; - } - isSimpleParamList(params) { - for (let i = 0, len = params.length; i < len; i++) { - if (!this.isSimpleParameter(params[i])) return false; - } - return true; - } - checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { - const checkClashes = !allowDuplicates && new Set(); - const formalParameters = { - type: "FormalParameters" - }; - for (const param of node.params) { - this.checkLVal(param, { - in: formalParameters, - binding: 5, - checkClashes, - strictModeChanged - }); - } - } - parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { - const elts = []; - let first = true; - while (!this.eat(close)) { - if (first) { - first = false; - } else { - this.expect(12); - if (this.match(close)) { - if (nodeForExtra) { - this.addTrailingCommaExtraToNode(nodeForExtra); - } - this.next(); - break; - } - } - elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors)); - } - return elts; - } - parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) { - let elt; - if (this.match(12)) { - if (!allowEmpty) { - this.raise(Errors.UnexpectedToken, this.state.curPosition(), { - unexpected: "," - }); - } - elt = null; - } else if (this.match(21)) { - const spreadNodeStartLoc = this.state.startLoc; - elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc); - } else if (this.match(17)) { - this.expectPlugin("partialApplication"); - if (!allowPlaceholder) { - this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc); - } - const node = this.startNode(); - this.next(); - elt = this.finishNode(node, "ArgumentPlaceholder"); - } else { - elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem); - } - return elt; - } - parseIdentifier(liberal) { - const node = this.startNode(); - const name = this.parseIdentifierName(liberal); - return this.createIdentifier(node, name); - } - createIdentifier(node, name) { - node.name = name; - node.loc.identifierName = name; - return this.finishNode(node, "Identifier"); - } - parseIdentifierName(liberal) { - let name; - const { - startLoc, - type - } = this.state; - if (tokenIsKeywordOrIdentifier(type)) { - name = this.state.value; - } else { - this.unexpected(); - } - const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type); - if (liberal) { - if (tokenIsKeyword) { - this.replaceToken(132); - } - } else { - this.checkReservedWord(name, startLoc, tokenIsKeyword, false); - } - this.next(); - return name; - } - checkReservedWord(word, startLoc, checkKeywords, isBinding) { - if (word.length > 10) { - return; - } - if (!canBeReservedWord(word)) { - return; - } - if (checkKeywords && isKeyword(word)) { - this.raise(Errors.UnexpectedKeyword, startLoc, { - keyword: word - }); - return; - } - const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; - if (reservedTest(word, this.inModule)) { - this.raise(Errors.UnexpectedReservedWord, startLoc, { - reservedWord: word - }); - return; - } else if (word === "yield") { - if (this.prodParam.hasYield) { - this.raise(Errors.YieldBindingIdentifier, startLoc); - return; - } - } else if (word === "await") { - if (this.prodParam.hasAwait) { - this.raise(Errors.AwaitBindingIdentifier, startLoc); - return; - } - if (this.scope.inStaticBlock) { - this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc); - return; - } - this.expressionScope.recordAsyncArrowParametersError(startLoc); - } else if (word === "arguments") { - if (this.scope.inClassAndNotInNonArrowFunction) { - this.raise(Errors.ArgumentsInClass, startLoc); - return; - } - } - } - isAwaitAllowed() { - if (this.prodParam.hasAwait) return true; - if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) { - return true; - } - return false; - } - parseAwait(startLoc) { - const node = this.startNodeAt(startLoc); - this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node); - if (this.eat(55)) { - this.raise(Errors.ObsoleteAwaitStar, node); - } - if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { - if (this.isAmbiguousAwait()) { - this.ambiguousScriptDifferentAst = true; - } else { - this.sawUnambiguousESM = true; - } - } - if (!this.state.soloAwait) { - node.argument = this.parseMaybeUnary(null, true); - } - return this.finishNode(node, "AwaitExpression"); - } - isAmbiguousAwait() { - if (this.hasPrecedingLineBreak()) return true; - const { - type - } = this.state; - return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 137 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54; - } - parseYield() { - const node = this.startNode(); - this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node); - this.next(); - let delegating = false; - let argument = null; - if (!this.hasPrecedingLineBreak()) { - delegating = this.eat(55); - switch (this.state.type) { - case 13: - case 139: - case 8: - case 11: - case 3: - case 9: - case 14: - case 12: - if (!delegating) break; - default: - argument = this.parseMaybeAssign(); - } - } - node.delegate = delegating; - node.argument = argument; - return this.finishNode(node, "YieldExpression"); - } - parseImportCall(node) { - this.next(); - node.source = this.parseMaybeAssignAllowIn(); - if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { - node.options = null; - } - if (this.eat(12)) { - this.expectImportAttributesPlugin(); - if (!this.match(11)) { - node.options = this.parseMaybeAssignAllowIn(); - this.eat(12); - } - } - this.expect(11); - return this.finishNode(node, "ImportExpression"); - } - checkPipelineAtInfixOperator(left, leftStartLoc) { - if (this.hasPlugin(["pipelineOperator", { - proposal: "smart" - }])) { - if (left.type === "SequenceExpression") { - this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc); - } - } - } - parseSmartPipelineBodyInStyle(childExpr, startLoc) { - if (this.isSimpleReference(childExpr)) { - const bodyNode = this.startNodeAt(startLoc); - bodyNode.callee = childExpr; - return this.finishNode(bodyNode, "PipelineBareFunction"); - } else { - const bodyNode = this.startNodeAt(startLoc); - this.checkSmartPipeTopicBodyEarlyErrors(startLoc); - bodyNode.expression = childExpr; - return this.finishNode(bodyNode, "PipelineTopicExpression"); - } - } - isSimpleReference(expression) { - switch (expression.type) { - case "MemberExpression": - return !expression.computed && this.isSimpleReference(expression.object); - case "Identifier": - return true; - default: - return false; - } - } - checkSmartPipeTopicBodyEarlyErrors(startLoc) { - if (this.match(19)) { - throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc); - } - if (!this.topicReferenceWasUsedInCurrentContext()) { - this.raise(Errors.PipelineTopicUnused, startLoc); - } - } - withTopicBindingContext(callback) { - const outerContextTopicState = this.state.topicContext; - this.state.topicContext = { - maxNumOfResolvableTopics: 1, - maxTopicIndex: null - }; - try { - return callback(); - } finally { - this.state.topicContext = outerContextTopicState; - } - } - withSmartMixTopicForbiddingContext(callback) { - if (this.hasPlugin(["pipelineOperator", { - proposal: "smart" - }])) { - const outerContextTopicState = this.state.topicContext; - this.state.topicContext = { - maxNumOfResolvableTopics: 0, - maxTopicIndex: null - }; - try { - return callback(); - } finally { - this.state.topicContext = outerContextTopicState; - } - } else { - return callback(); - } - } - withSoloAwaitPermittingContext(callback) { - const outerContextSoloAwaitState = this.state.soloAwait; - this.state.soloAwait = true; - try { - return callback(); - } finally { - this.state.soloAwait = outerContextSoloAwaitState; - } - } - allowInAnd(callback) { - const flags = this.prodParam.currentFlags(); - const prodParamToSet = 8 & ~flags; - if (prodParamToSet) { - this.prodParam.enter(flags | 8); - try { - return callback(); - } finally { - this.prodParam.exit(); - } - } - return callback(); - } - disallowInAnd(callback) { - const flags = this.prodParam.currentFlags(); - const prodParamToClear = 8 & flags; - if (prodParamToClear) { - this.prodParam.enter(flags & ~8); - try { - return callback(); - } finally { - this.prodParam.exit(); - } - } - return callback(); - } - registerTopicReference() { - this.state.topicContext.maxTopicIndex = 0; - } - topicReferenceIsAllowedInCurrentContext() { - return this.state.topicContext.maxNumOfResolvableTopics >= 1; - } - topicReferenceWasUsedInCurrentContext() { - return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; - } - parseFSharpPipelineBody(prec) { - const startLoc = this.state.startLoc; - this.state.potentialArrowAt = this.state.start; - const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; - this.state.inFSharpPipelineDirectBody = true; - const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec); - this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; - return ret; - } - parseModuleExpression() { - this.expectPlugin("moduleBlocks"); - const node = this.startNode(); - this.next(); - if (!this.match(5)) { - this.unexpected(null, 5); - } - const program = this.startNodeAt(this.state.endLoc); - this.next(); - const revertScopes = this.initializeScopes(true); - this.enterInitialScopes(); - try { - node.body = this.parseProgram(program, 8, "module"); - } finally { - revertScopes(); - } - return this.finishNode(node, "ModuleExpression"); - } - parsePropertyNamePrefixOperator(prop) { } - } - const loopLabel = { - kind: 1 - }, - switchLabel = { - kind: 2 - }; - const loneSurrogate = /[\uD800-\uDFFF]/u; - const keywordRelationalOperator = /in(?:stanceof)?/y; - function babel7CompatTokens(tokens, input) { - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - const { - type - } = token; - if (typeof type === "number") { - { - if (type === 138) { - const { - loc, - start, - value, - end - } = token; - const hashEndPos = start + 1; - const hashEndLoc = createPositionWithColumnOffset(loc.start, 1); - tokens.splice(i, 1, new Token({ - type: getExportedToken(27), - value: "#", - start: start, - end: hashEndPos, - startLoc: loc.start, - endLoc: hashEndLoc - }), new Token({ - type: getExportedToken(132), - value: value, - start: hashEndPos, - end: end, - startLoc: hashEndLoc, - endLoc: loc.end - })); - i++; - continue; - } - if (tokenIsTemplate(type)) { - const { - loc, - start, - value, - end - } = token; - const backquoteEnd = start + 1; - const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1); - let startToken; - if (input.charCodeAt(start) === 96) { - startToken = new Token({ - type: getExportedToken(22), - value: "`", - start: start, - end: backquoteEnd, - startLoc: loc.start, - endLoc: backquoteEndLoc - }); - } else { - startToken = new Token({ - type: getExportedToken(8), - value: "}", - start: start, - end: backquoteEnd, - startLoc: loc.start, - endLoc: backquoteEndLoc - }); - } - let templateValue, templateElementEnd, templateElementEndLoc, endToken; - if (type === 24) { - templateElementEnd = end - 1; - templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1); - templateValue = value === null ? null : value.slice(1, -1); - endToken = new Token({ - type: getExportedToken(22), - value: "`", - start: templateElementEnd, - end: end, - startLoc: templateElementEndLoc, - endLoc: loc.end - }); - } else { - templateElementEnd = end - 2; - templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2); - templateValue = value === null ? null : value.slice(1, -2); - endToken = new Token({ - type: getExportedToken(23), - value: "${", - start: templateElementEnd, - end: end, - startLoc: templateElementEndLoc, - endLoc: loc.end - }); - } - tokens.splice(i, 1, startToken, new Token({ - type: getExportedToken(20), - value: templateValue, - start: backquoteEnd, - end: templateElementEnd, - startLoc: backquoteEndLoc, - endLoc: templateElementEndLoc - }), endToken); - i += 2; - continue; - } - } - token.type = getExportedToken(type); - } - } - return tokens; - } - class StatementParser extends ExpressionParser { - parseTopLevel(file, program) { - file.program = this.parseProgram(program); - file.comments = this.comments; - if (this.options.tokens) { - file.tokens = babel7CompatTokens(this.tokens, this.input); - } - return this.finishNode(file, "File"); - } - parseProgram(program, end = 139, sourceType = this.options.sourceType) { - program.sourceType = sourceType; - program.interpreter = this.parseInterpreterDirective(); - this.parseBlockBody(program, true, true, end); - if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) { - for (const [localName, at] of Array.from(this.scope.undefinedExports)) { - this.raise(Errors.ModuleExportUndefined, at, { - localName - }); - } - } - let finishedProgram; - if (end === 139) { - finishedProgram = this.finishNode(program, "Program"); - } else { - finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1)); - } - return finishedProgram; - } - stmtToDirective(stmt) { - const directive = stmt; - directive.type = "Directive"; - directive.value = directive.expression; - delete directive.expression; - const directiveLiteral = directive.value; - const expressionValue = directiveLiteral.value; - const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end); - const val = directiveLiteral.value = raw.slice(1, -1); - this.addExtra(directiveLiteral, "raw", raw); - this.addExtra(directiveLiteral, "rawValue", val); - this.addExtra(directiveLiteral, "expressionValue", expressionValue); - directiveLiteral.type = "DirectiveLiteral"; - return directive; - } - parseInterpreterDirective() { - if (!this.match(28)) { - return null; - } - const node = this.startNode(); - node.value = this.state.value; - this.next(); - return this.finishNode(node, "InterpreterDirective"); - } - isLet() { - if (!this.isContextual(100)) { - return false; - } - return this.hasFollowingBindingAtom(); - } - chStartsBindingIdentifier(ch, pos) { - if (isIdentifierStart(ch)) { - keywordRelationalOperator.lastIndex = pos; - if (keywordRelationalOperator.test(this.input)) { - const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex); - if (!isIdentifierChar(endCh) && endCh !== 92) { - return false; - } - } - return true; - } else if (ch === 92) { - return true; - } else { - return false; - } - } - chStartsBindingPattern(ch) { - return ch === 91 || ch === 123; - } - hasFollowingBindingAtom() { - const next = this.nextTokenStart(); - const nextCh = this.codePointAtPos(next); - return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next); - } - hasInLineFollowingBindingIdentifier() { - const next = this.nextTokenInLineStart(); - const nextCh = this.codePointAtPos(next); - return this.chStartsBindingIdentifier(nextCh, next); - } - startsUsingForOf() { - const { - type, - containsEsc - } = this.lookahead(); - if (type === 102 && !containsEsc) { - return false; - } else if (tokenIsIdentifier(type) && !this.hasFollowingLineBreak()) { - this.expectPlugin("explicitResourceManagement"); - return true; - } - } - startsAwaitUsing() { - let next = this.nextTokenInLineStart(); - if (this.isUnparsedContextual(next, "using")) { - next = this.nextTokenInLineStartSince(next + 5); - const nextCh = this.codePointAtPos(next); - if (this.chStartsBindingIdentifier(nextCh, next)) { - this.expectPlugin("explicitResourceManagement"); - return true; - } - } - return false; - } - parseModuleItem() { - return this.parseStatementLike(1 | 2 | 4 | 8); - } - parseStatementListItem() { - return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8)); - } - parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) { - let flags = 0; - if (this.options.annexB && !this.state.strict) { - flags |= 4; - if (allowLabeledFunction) { - flags |= 8; - } - } - return this.parseStatementLike(flags); - } - parseStatement() { - return this.parseStatementLike(0); - } - parseStatementLike(flags) { - let decorators = null; - if (this.match(26)) { - decorators = this.parseDecorators(true); - } - return this.parseStatementContent(flags, decorators); - } - parseStatementContent(flags, decorators) { - const starttype = this.state.type; - const node = this.startNode(); - const allowDeclaration = !!(flags & 2); - const allowFunctionDeclaration = !!(flags & 4); - const topLevel = flags & 1; - switch (starttype) { - case 60: - return this.parseBreakContinueStatement(node, true); - case 63: - return this.parseBreakContinueStatement(node, false); - case 64: - return this.parseDebuggerStatement(node); - case 90: - return this.parseDoWhileStatement(node); - case 91: - return this.parseForStatement(node); - case 68: - if (this.lookaheadCharCode() === 46) break; - if (!allowFunctionDeclaration) { - this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc); - } - return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration); - case 80: - if (!allowDeclaration) this.unexpected(); - return this.parseClass(this.maybeTakeDecorators(decorators, node), true); - case 69: - return this.parseIfStatement(node); - case 70: - return this.parseReturnStatement(node); - case 71: - return this.parseSwitchStatement(node); - case 72: - return this.parseThrowStatement(node); - case 73: - return this.parseTryStatement(node); - case 96: - if (!this.state.containsEsc && this.startsAwaitUsing()) { - if (!this.isAwaitAllowed()) { - this.raise(Errors.AwaitUsingNotInAsyncContext, node); - } else if (!allowDeclaration) { - this.raise(Errors.UnexpectedLexicalDeclaration, node); - } - this.next(); - return this.parseVarStatement(node, "await using"); - } - break; - case 107: - if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifier()) { - break; - } - this.expectPlugin("explicitResourceManagement"); - if (!this.scope.inModule && this.scope.inTopLevel) { - this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc); - } else if (!allowDeclaration) { - this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); - } - return this.parseVarStatement(node, "using"); - case 100: - { - if (this.state.containsEsc) { - break; - } - const next = this.nextTokenStart(); - const nextCh = this.codePointAtPos(next); - if (nextCh !== 91) { - if (!allowDeclaration && this.hasFollowingLineBreak()) break; - if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) { - break; - } - } - } - case 75: - { - if (!allowDeclaration) { - this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); - } - } - case 74: - { - const kind = this.state.value; - return this.parseVarStatement(node, kind); - } - case 92: - return this.parseWhileStatement(node); - case 76: - return this.parseWithStatement(node); - case 5: - return this.parseBlock(); - case 13: - return this.parseEmptyStatement(node); - case 83: - { - const nextTokenCharCode = this.lookaheadCharCode(); - if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { - break; - } - } - case 82: - { - if (!this.options.allowImportExportEverywhere && !topLevel) { - this.raise(Errors.UnexpectedImportExport, this.state.startLoc); - } - this.next(); - let result; - if (starttype === 83) { - result = this.parseImport(node); - if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) { - this.sawUnambiguousESM = true; - } - } else { - result = this.parseExport(node, decorators); - if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") { - this.sawUnambiguousESM = true; - } - } - this.assertModuleNodeAllowed(result); - return result; - } - default: - { - if (this.isAsyncFunction()) { - if (!allowDeclaration) { - this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc); - } - this.next(); - return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration); - } - } - } - const maybeName = this.state.value; - const expr = this.parseExpression(); - if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) { - return this.parseLabeledStatement(node, maybeName, expr, flags); - } else { - return this.parseExpressionStatement(node, expr, decorators); - } - } - assertModuleNodeAllowed(node) { - if (!this.options.allowImportExportEverywhere && !this.inModule) { - this.raise(Errors.ImportOutsideModule, node); - } - } - decoratorsEnabledBeforeExport() { - if (this.hasPlugin("decorators-legacy")) return true; - return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false; - } - maybeTakeDecorators(maybeDecorators, classNode, exportNode) { - if (maybeDecorators) { - if (classNode.decorators && classNode.decorators.length > 0) { - if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") { - this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]); - } - classNode.decorators.unshift(...maybeDecorators); - } else { - classNode.decorators = maybeDecorators; - } - this.resetStartLocationFromNode(classNode, maybeDecorators[0]); - if (exportNode) this.resetStartLocationFromNode(exportNode, classNode); - } - return classNode; - } - canHaveLeadingDecorator() { - return this.match(80); - } - parseDecorators(allowExport) { - const decorators = []; - do { - decorators.push(this.parseDecorator()); - } while (this.match(26)); - if (this.match(82)) { - if (!allowExport) { - this.unexpected(); - } - if (!this.decoratorsEnabledBeforeExport()) { - this.raise(Errors.DecoratorExportClass, this.state.startLoc); - } - } else if (!this.canHaveLeadingDecorator()) { - throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc); - } - return decorators; - } - parseDecorator() { - this.expectOnePlugin(["decorators", "decorators-legacy"]); - const node = this.startNode(); - this.next(); - if (this.hasPlugin("decorators")) { - const startLoc = this.state.startLoc; - let expr; - if (this.match(10)) { - const startLoc = this.state.startLoc; - this.next(); - expr = this.parseExpression(); - this.expect(11); - expr = this.wrapParenthesis(startLoc, expr); - const paramsStartLoc = this.state.startLoc; - node.expression = this.parseMaybeDecoratorArguments(expr); - if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) { - this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc); - } - } else { - expr = this.parseIdentifier(false); - while (this.eat(16)) { - const node = this.startNodeAt(startLoc); - node.object = expr; - if (this.match(138)) { - this.classScope.usePrivateName(this.state.value, this.state.startLoc); - node.property = this.parsePrivateName(); - } else { - node.property = this.parseIdentifier(true); - } - node.computed = false; - expr = this.finishNode(node, "MemberExpression"); - } - node.expression = this.parseMaybeDecoratorArguments(expr); - } - } else { - node.expression = this.parseExprSubscripts(); - } - return this.finishNode(node, "Decorator"); - } - parseMaybeDecoratorArguments(expr) { - if (this.eat(10)) { - const node = this.startNodeAtNode(expr); - node.callee = expr; - node.arguments = this.parseCallExpressionArguments(11, false); - this.toReferencedList(node.arguments); - return this.finishNode(node, "CallExpression"); - } - return expr; - } - parseBreakContinueStatement(node, isBreak) { - this.next(); - if (this.isLineTerminator()) { - node.label = null; - } else { - node.label = this.parseIdentifier(); - this.semicolon(); - } - this.verifyBreakContinue(node, isBreak); - return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); - } - verifyBreakContinue(node, isBreak) { - let i; - for (i = 0; i < this.state.labels.length; ++i) { - const lab = this.state.labels[i]; - if (node.label == null || lab.name === node.label.name) { - if (lab.kind != null && (isBreak || lab.kind === 1)) { - break; - } - if (node.label && isBreak) break; - } - } - if (i === this.state.labels.length) { - const type = isBreak ? "BreakStatement" : "ContinueStatement"; - this.raise(Errors.IllegalBreakContinue, node, { - type - }); - } - } - parseDebuggerStatement(node) { - this.next(); - this.semicolon(); - return this.finishNode(node, "DebuggerStatement"); - } - parseHeaderExpression() { - this.expect(10); - const val = this.parseExpression(); - this.expect(11); - return val; - } - parseDoWhileStatement(node) { - this.next(); - this.state.labels.push(loopLabel); - node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); - this.state.labels.pop(); - this.expect(92); - node.test = this.parseHeaderExpression(); - this.eat(13); - return this.finishNode(node, "DoWhileStatement"); - } - parseForStatement(node) { - this.next(); - this.state.labels.push(loopLabel); - let awaitAt = null; - if (this.isAwaitAllowed() && this.eatContextual(96)) { - awaitAt = this.state.lastTokStartLoc; - } - this.scope.enter(0); - this.expect(10); - if (this.match(13)) { - if (awaitAt !== null) { - this.unexpected(awaitAt); - } - return this.parseFor(node, null); - } - const startsWithLet = this.isContextual(100); - { - const startsWithAwaitUsing = this.isContextual(96) && this.startsAwaitUsing(); - const starsWithUsingDeclaration = startsWithAwaitUsing || this.isContextual(107) && this.startsUsingForOf(); - const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration; - if (this.match(74) || this.match(75) || isLetOrUsing) { - const initNode = this.startNode(); - let kind; - if (startsWithAwaitUsing) { - kind = "await using"; - if (!this.isAwaitAllowed()) { - this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc); - } - this.next(); - } else { - kind = this.state.value; - } - this.next(); - this.parseVar(initNode, true, kind); - const init = this.finishNode(initNode, "VariableDeclaration"); - const isForIn = this.match(58); - if (isForIn && starsWithUsingDeclaration) { - this.raise(Errors.ForInUsing, init); - } - if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) { - return this.parseForIn(node, init, awaitAt); - } - if (awaitAt !== null) { - this.unexpected(awaitAt); - } - return this.parseFor(node, init); - } - } - const startsWithAsync = this.isContextual(95); - const refExpressionErrors = new ExpressionErrors(); - const init = this.parseExpression(true, refExpressionErrors); - const isForOf = this.isContextual(102); - if (isForOf) { - if (startsWithLet) { - this.raise(Errors.ForOfLet, init); - } - if (awaitAt === null && startsWithAsync && init.type === "Identifier") { - this.raise(Errors.ForOfAsync, init); - } - } - if (isForOf || this.match(58)) { - this.checkDestructuringPrivate(refExpressionErrors); - this.toAssignable(init, true); - const type = isForOf ? "ForOfStatement" : "ForInStatement"; - this.checkLVal(init, { - in: { - type - } - }); - return this.parseForIn(node, init, awaitAt); - } else { - this.checkExpressionErrors(refExpressionErrors, true); - } - if (awaitAt !== null) { - this.unexpected(awaitAt); - } - return this.parseFor(node, init); - } - parseFunctionStatement(node, isAsync, isHangingDeclaration) { - this.next(); - return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0)); - } - parseIfStatement(node) { - this.next(); - node.test = this.parseHeaderExpression(); - node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration(); - node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null; - return this.finishNode(node, "IfStatement"); - } - parseReturnStatement(node) { - if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) { - this.raise(Errors.IllegalReturn, this.state.startLoc); - } - this.next(); - if (this.isLineTerminator()) { - node.argument = null; - } else { - node.argument = this.parseExpression(); - this.semicolon(); - } - return this.finishNode(node, "ReturnStatement"); - } - parseSwitchStatement(node) { - this.next(); - node.discriminant = this.parseHeaderExpression(); - const cases = node.cases = []; - this.expect(5); - this.state.labels.push(switchLabel); - this.scope.enter(0); - let cur; - for (let sawDefault; !this.match(8);) { - if (this.match(61) || this.match(65)) { - const isCase = this.match(61); - if (cur) this.finishNode(cur, "SwitchCase"); - cases.push(cur = this.startNode()); - cur.consequent = []; - this.next(); - if (isCase) { - cur.test = this.parseExpression(); - } else { - if (sawDefault) { - this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc); - } - sawDefault = true; - cur.test = null; - } - this.expect(14); - } else { - if (cur) { - cur.consequent.push(this.parseStatementListItem()); - } else { - this.unexpected(); - } - } - } - this.scope.exit(); - if (cur) this.finishNode(cur, "SwitchCase"); - this.next(); - this.state.labels.pop(); - return this.finishNode(node, "SwitchStatement"); - } - parseThrowStatement(node) { - this.next(); - if (this.hasPrecedingLineBreak()) { - this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc); - } - node.argument = this.parseExpression(); - this.semicolon(); - return this.finishNode(node, "ThrowStatement"); - } - parseCatchClauseParam() { - const param = this.parseBindingAtom(); - this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0); - this.checkLVal(param, { - in: { - type: "CatchClause" - }, - binding: 9 - }); - return param; - } - parseTryStatement(node) { - this.next(); - node.block = this.parseBlock(); - node.handler = null; - if (this.match(62)) { - const clause = this.startNode(); - this.next(); - if (this.match(10)) { - this.expect(10); - clause.param = this.parseCatchClauseParam(); - this.expect(11); - } else { - clause.param = null; - this.scope.enter(0); - } - clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false)); - this.scope.exit(); - node.handler = this.finishNode(clause, "CatchClause"); - } - node.finalizer = this.eat(67) ? this.parseBlock() : null; - if (!node.handler && !node.finalizer) { - this.raise(Errors.NoCatchOrFinally, node); - } - return this.finishNode(node, "TryStatement"); - } - parseVarStatement(node, kind, allowMissingInitializer = false) { - this.next(); - this.parseVar(node, false, kind, allowMissingInitializer); - this.semicolon(); - return this.finishNode(node, "VariableDeclaration"); - } - parseWhileStatement(node) { - this.next(); - node.test = this.parseHeaderExpression(); - this.state.labels.push(loopLabel); - node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); - this.state.labels.pop(); - return this.finishNode(node, "WhileStatement"); - } - parseWithStatement(node) { - if (this.state.strict) { - this.raise(Errors.StrictWith, this.state.startLoc); - } - this.next(); - node.object = this.parseHeaderExpression(); - node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); - return this.finishNode(node, "WithStatement"); - } - parseEmptyStatement(node) { - this.next(); - return this.finishNode(node, "EmptyStatement"); - } - parseLabeledStatement(node, maybeName, expr, flags) { - for (const label of this.state.labels) { - if (label.name === maybeName) { - this.raise(Errors.LabelRedeclaration, expr, { - labelName: maybeName - }); - } - } - const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null; - for (let i = this.state.labels.length - 1; i >= 0; i--) { - const label = this.state.labels[i]; - if (label.statementStart === node.start) { - label.statementStart = this.state.start; - label.kind = kind; - } else { - break; - } - } - this.state.labels.push({ - name: maybeName, - kind: kind, - statementStart: this.state.start - }); - node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement(); - this.state.labels.pop(); - node.label = expr; - return this.finishNode(node, "LabeledStatement"); - } - parseExpressionStatement(node, expr, decorators) { - node.expression = expr; - this.semicolon(); - return this.finishNode(node, "ExpressionStatement"); - } - parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) { - const node = this.startNode(); - if (allowDirectives) { - this.state.strictErrors.clear(); - } - this.expect(5); - if (createNewLexicalScope) { - this.scope.enter(0); - } - this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse); - if (createNewLexicalScope) { - this.scope.exit(); - } - return this.finishNode(node, "BlockStatement"); - } - isValidDirective(stmt) { - return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; - } - parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { - const body = node.body = []; - const directives = node.directives = []; - this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse); - } - parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { - const oldStrict = this.state.strict; - let hasStrictModeDirective = false; - let parsedNonDirective = false; - while (!this.match(end)) { - const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem(); - if (directives && !parsedNonDirective) { - if (this.isValidDirective(stmt)) { - const directive = this.stmtToDirective(stmt); - directives.push(directive); - if (!hasStrictModeDirective && directive.value.value === "use strict") { - hasStrictModeDirective = true; - this.setStrict(true); - } - continue; - } - parsedNonDirective = true; - this.state.strictErrors.clear(); - } - body.push(stmt); - } - afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective); - if (!oldStrict) { - this.setStrict(false); - } - this.next(); - } - parseFor(node, init) { - node.init = init; - this.semicolon(false); - node.test = this.match(13) ? null : this.parseExpression(); - this.semicolon(false); - node.update = this.match(11) ? null : this.parseExpression(); - this.expect(11); - node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); - this.scope.exit(); - this.state.labels.pop(); - return this.finishNode(node, "ForStatement"); - } - parseForIn(node, init, awaitAt) { - const isForIn = this.match(58); - this.next(); - if (isForIn) { - if (awaitAt !== null) this.unexpected(awaitAt); - } else { - node.await = awaitAt !== null; - } - if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { - this.raise(Errors.ForInOfLoopInitializer, init, { - type: isForIn ? "ForInStatement" : "ForOfStatement" - }); - } - if (init.type === "AssignmentPattern") { - this.raise(Errors.InvalidLhs, init, { - ancestor: { - type: "ForStatement" - } - }); - } - node.left = init; - node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); - this.expect(11); - node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); - this.scope.exit(); - this.state.labels.pop(); - return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); - } - parseVar(node, isFor, kind, allowMissingInitializer = false) { - const declarations = node.declarations = []; - node.kind = kind; - for (; ;) { - const decl = this.startNode(); - this.parseVarId(decl, kind); - decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); - if (decl.init === null && !allowMissingInitializer) { - if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) { - this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { - kind: "destructuring" - }); - } else if (kind === "const" && !(this.match(58) || this.isContextual(102))) { - this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { - kind: "const" - }); - } - } - declarations.push(this.finishNode(decl, "VariableDeclarator")); - if (!this.eat(12)) break; - } - return node; - } - parseVarId(decl, kind) { - const id = this.parseBindingAtom(); - this.checkLVal(id, { - in: { - type: "VariableDeclarator" - }, - binding: kind === "var" ? 5 : 8201 - }); - decl.id = id; - } - parseAsyncFunctionExpression(node) { - return this.parseFunction(node, 8); - } - parseFunction(node, flags = 0) { - const hangingDeclaration = flags & 2; - const isDeclaration = !!(flags & 1); - const requireId = isDeclaration && !(flags & 4); - const isAsync = !!(flags & 8); - this.initFunction(node, isAsync); - if (this.match(55)) { - if (hangingDeclaration) { - this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc); - } - this.next(); - node.generator = true; - } - if (isDeclaration) { - node.id = this.parseFunctionId(requireId); - } - const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; - this.state.maybeInArrowParameters = false; - this.scope.enter(2); - this.prodParam.enter(functionFlags(isAsync, node.generator)); - if (!isDeclaration) { - node.id = this.parseFunctionId(); - } - this.parseFunctionParams(node, false); - this.withSmartMixTopicForbiddingContext(() => { - this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression"); - }); - this.prodParam.exit(); - this.scope.exit(); - if (isDeclaration && !hangingDeclaration) { - this.registerFunctionStatementId(node); - } - this.state.maybeInArrowParameters = oldMaybeInArrowParameters; - return node; - } - parseFunctionId(requireId) { - return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null; - } - parseFunctionParams(node, isConstructor) { - this.expect(10); - this.expressionScope.enter(newParameterDeclarationScope()); - node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0)); - this.expressionScope.exit(); - } - registerFunctionStatementId(node) { - if (!node.id) return; - this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start); - } - parseClass(node, isStatement, optionalId) { - this.next(); - const oldStrict = this.state.strict; - this.state.strict = true; - this.parseClassId(node, isStatement, optionalId); - this.parseClassSuper(node); - node.body = this.parseClassBody(!!node.superClass, oldStrict); - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); - } - isClassProperty() { - return this.match(29) || this.match(13) || this.match(8); - } - isClassMethod() { - return this.match(10); - } - isNonstaticConstructor(method) { - return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor"); - } - parseClassBody(hadSuperClass, oldStrict) { - this.classScope.enter(); - const state = { - hadConstructor: false, - hadSuperClass - }; - let decorators = []; - const classBody = this.startNode(); - classBody.body = []; - this.expect(5); - this.withSmartMixTopicForbiddingContext(() => { - while (!this.match(8)) { - if (this.eat(13)) { - if (decorators.length > 0) { - throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc); - } - continue; - } - if (this.match(26)) { - decorators.push(this.parseDecorator()); - continue; - } - const member = this.startNode(); - if (decorators.length) { - member.decorators = decorators; - this.resetStartLocationFromNode(member, decorators[0]); - decorators = []; - } - this.parseClassMember(classBody, member, state); - if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { - this.raise(Errors.DecoratorConstructor, member); - } - } - }); - this.state.strict = oldStrict; - this.next(); - if (decorators.length) { - throw this.raise(Errors.TrailingDecorator, this.state.startLoc); - } - this.classScope.exit(); - return this.finishNode(classBody, "ClassBody"); - } - parseClassMemberFromModifier(classBody, member) { - const key = this.parseIdentifier(true); - if (this.isClassMethod()) { - const method = member; - method.kind = "method"; - method.computed = false; - method.key = key; - method.static = false; - this.pushClassMethod(classBody, method, false, false, false, false); - return true; - } else if (this.isClassProperty()) { - const prop = member; - prop.computed = false; - prop.key = key; - prop.static = false; - classBody.body.push(this.parseClassProperty(prop)); - return true; - } - this.resetPreviousNodeTrailingComments(key); - return false; - } - parseClassMember(classBody, member, state) { - const isStatic = this.isContextual(106); - if (isStatic) { - if (this.parseClassMemberFromModifier(classBody, member)) { - return; - } - if (this.eat(5)) { - this.parseClassStaticBlock(classBody, member); - return; - } - } - this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); - } - parseClassMemberWithIsStatic(classBody, member, state, isStatic) { - const publicMethod = member; - const privateMethod = member; - const publicProp = member; - const privateProp = member; - const accessorProp = member; - const method = publicMethod; - const publicMember = publicMethod; - member.static = isStatic; - this.parsePropertyNamePrefixOperator(member); - if (this.eat(55)) { - method.kind = "method"; - const isPrivateName = this.match(138); - this.parseClassElementName(method); - if (isPrivateName) { - this.pushClassPrivateMethod(classBody, privateMethod, true, false); - return; - } - if (this.isNonstaticConstructor(publicMethod)) { - this.raise(Errors.ConstructorIsGenerator, publicMethod.key); - } - this.pushClassMethod(classBody, publicMethod, true, false, false, false); - return; - } - const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc; - const isPrivate = this.match(138); - const key = this.parseClassElementName(member); - const maybeQuestionTokenStartLoc = this.state.startLoc; - this.parsePostMemberNameModifiers(publicMember); - if (this.isClassMethod()) { - method.kind = "method"; - if (isPrivate) { - this.pushClassPrivateMethod(classBody, privateMethod, false, false); - return; - } - const isConstructor = this.isNonstaticConstructor(publicMethod); - let allowsDirectSuper = false; - if (isConstructor) { - publicMethod.kind = "constructor"; - if (state.hadConstructor && !this.hasPlugin("typescript")) { - this.raise(Errors.DuplicateConstructor, key); - } - if (isConstructor && this.hasPlugin("typescript") && member.override) { - this.raise(Errors.OverrideOnConstructor, key); - } - state.hadConstructor = true; - allowsDirectSuper = state.hadSuperClass; - } - this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); - } else if (this.isClassProperty()) { - if (isPrivate) { - this.pushClassPrivateProperty(classBody, privateProp); - } else { - this.pushClassProperty(classBody, publicProp); - } - } else if (isContextual && key.name === "async" && !this.isLineTerminator()) { - this.resetPreviousNodeTrailingComments(key); - const isGenerator = this.eat(55); - if (publicMember.optional) { - this.unexpected(maybeQuestionTokenStartLoc); - } - method.kind = "method"; - const isPrivate = this.match(138); - this.parseClassElementName(method); - this.parsePostMemberNameModifiers(publicMember); - if (isPrivate) { - this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); - } else { - if (this.isNonstaticConstructor(publicMethod)) { - this.raise(Errors.ConstructorIsAsync, publicMethod.key); - } - this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); - } - } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(55) && this.isLineTerminator())) { - this.resetPreviousNodeTrailingComments(key); - method.kind = key.name; - const isPrivate = this.match(138); - this.parseClassElementName(publicMethod); - if (isPrivate) { - this.pushClassPrivateMethod(classBody, privateMethod, false, false); - } else { - if (this.isNonstaticConstructor(publicMethod)) { - this.raise(Errors.ConstructorIsAccessor, publicMethod.key); - } - this.pushClassMethod(classBody, publicMethod, false, false, false, false); - } - this.checkGetterSetterParams(publicMethod); - } else if (isContextual && key.name === "accessor" && !this.isLineTerminator()) { - this.expectPlugin("decoratorAutoAccessors"); - this.resetPreviousNodeTrailingComments(key); - const isPrivate = this.match(138); - this.parseClassElementName(publicProp); - this.pushClassAccessorProperty(classBody, accessorProp, isPrivate); - } else if (this.isLineTerminator()) { - if (isPrivate) { - this.pushClassPrivateProperty(classBody, privateProp); - } else { - this.pushClassProperty(classBody, publicProp); - } - } else { - this.unexpected(); - } - } - parseClassElementName(member) { - const { - type, - value - } = this.state; - if ((type === 132 || type === 133) && member.static && value === "prototype") { - this.raise(Errors.StaticPrototype, this.state.startLoc); - } - if (type === 138) { - if (value === "constructor") { - this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc); - } - const key = this.parsePrivateName(); - member.key = key; - return key; - } - return this.parsePropertyName(member); - } - parseClassStaticBlock(classBody, member) { - var _member$decorators; - this.scope.enter(64 | 128 | 16); - const oldLabels = this.state.labels; - this.state.labels = []; - this.prodParam.enter(0); - const body = member.body = []; - this.parseBlockOrModuleBlockBody(body, undefined, false, 8); - this.prodParam.exit(); - this.scope.exit(); - this.state.labels = oldLabels; - classBody.body.push(this.finishNode(member, "StaticBlock")); - if ((_member$decorators = member.decorators) != null && _member$decorators.length) { - this.raise(Errors.DecoratorStaticBlock, member); - } - } - pushClassProperty(classBody, prop) { - if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) { - this.raise(Errors.ConstructorClassField, prop.key); - } - classBody.body.push(this.parseClassProperty(prop)); - } - pushClassPrivateProperty(classBody, prop) { - const node = this.parseClassPrivateProperty(prop); - classBody.body.push(node); - this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); - } - pushClassAccessorProperty(classBody, prop, isPrivate) { - if (!isPrivate && !prop.computed) { - const key = prop.key; - if (key.name === "constructor" || key.value === "constructor") { - this.raise(Errors.ConstructorClassField, key); - } - } - const node = this.parseClassAccessorProperty(prop); - classBody.body.push(node); - if (isPrivate) { - this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); - } - } - pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { - classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); - } - pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { - const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true); - classBody.body.push(node); - const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0; - this.declareClassPrivateMethodInScope(node, kind); - } - declareClassPrivateMethodInScope(node, kind) { - this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start); - } - parsePostMemberNameModifiers(methodOrProp) { } - parseClassPrivateProperty(node) { - this.parseInitializer(node); - this.semicolon(); - return this.finishNode(node, "ClassPrivateProperty"); - } - parseClassProperty(node) { - this.parseInitializer(node); - this.semicolon(); - return this.finishNode(node, "ClassProperty"); - } - parseClassAccessorProperty(node) { - this.parseInitializer(node); - this.semicolon(); - return this.finishNode(node, "ClassAccessorProperty"); - } - parseInitializer(node) { - this.scope.enter(64 | 16); - this.expressionScope.enter(newExpressionScope()); - this.prodParam.enter(0); - node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null; - this.expressionScope.exit(); - this.prodParam.exit(); - this.scope.exit(); - } - parseClassId(node, isStatement, optionalId, bindingType = 8331) { - if (tokenIsIdentifier(this.state.type)) { - node.id = this.parseIdentifier(); - if (isStatement) { - this.declareNameFromIdentifier(node.id, bindingType); - } - } else { - if (optionalId || !isStatement) { - node.id = null; - } else { - throw this.raise(Errors.MissingClassName, this.state.startLoc); - } - } - } - parseClassSuper(node) { - node.superClass = this.eat(81) ? this.parseExprSubscripts() : null; - } - parseExport(node, decorators) { - const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true); - const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); - const parseAfterDefault = !hasDefault || this.eat(12); - const hasStar = parseAfterDefault && this.eatExportStar(node); - const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); - const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12)); - const isFromRequired = hasDefault || hasStar; - if (hasStar && !hasNamespace) { - if (hasDefault) this.unexpected(); - if (decorators) { - throw this.raise(Errors.UnsupportedDecoratorExport, node); - } - this.parseExportFrom(node, true); - return this.finishNode(node, "ExportAllDeclaration"); - } - const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); - if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) { - this.unexpected(null, 5); - } - if (hasNamespace && parseAfterNamespace) { - this.unexpected(null, 98); - } - let hasDeclaration; - if (isFromRequired || hasSpecifiers) { - hasDeclaration = false; - if (decorators) { - throw this.raise(Errors.UnsupportedDecoratorExport, node); - } - this.parseExportFrom(node, isFromRequired); - } else { - hasDeclaration = this.maybeParseExportDeclaration(node); - } - if (isFromRequired || hasSpecifiers || hasDeclaration) { - var _node2$declaration; - const node2 = node; - this.checkExport(node2, true, false, !!node2.source); - if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") { - this.maybeTakeDecorators(decorators, node2.declaration, node2); - } else if (decorators) { - throw this.raise(Errors.UnsupportedDecoratorExport, node); - } - return this.finishNode(node2, "ExportNamedDeclaration"); - } - if (this.eat(65)) { - const node2 = node; - const decl = this.parseExportDefaultExpression(); - node2.declaration = decl; - if (decl.type === "ClassDeclaration") { - this.maybeTakeDecorators(decorators, decl, node2); - } else if (decorators) { - throw this.raise(Errors.UnsupportedDecoratorExport, node); - } - this.checkExport(node2, true, true); - return this.finishNode(node2, "ExportDefaultDeclaration"); - } - this.unexpected(null, 5); - } - eatExportStar(node) { - return this.eat(55); - } - maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { - if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) { - this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start); - const id = maybeDefaultIdentifier || this.parseIdentifier(true); - const specifier = this.startNodeAtNode(id); - specifier.exported = id; - node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; - return true; - } - return false; - } - maybeParseExportNamespaceSpecifier(node) { - if (this.isContextual(93)) { - if (!node.specifiers) node.specifiers = []; - const specifier = this.startNodeAt(this.state.lastTokStartLoc); - this.next(); - specifier.exported = this.parseModuleExportName(); - node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); - return true; - } - return false; - } - maybeParseExportNamedSpecifiers(node) { - if (this.match(5)) { - if (!node.specifiers) node.specifiers = []; - const isTypeExport = node.exportKind === "type"; - node.specifiers.push(...this.parseExportSpecifiers(isTypeExport)); - node.source = null; - node.declaration = null; - if (this.hasPlugin("importAssertions")) { - node.assertions = []; - } - return true; - } - return false; - } - maybeParseExportDeclaration(node) { - if (this.shouldParseExportDeclaration()) { - node.specifiers = []; - node.source = null; - if (this.hasPlugin("importAssertions")) { - node.assertions = []; - } - node.declaration = this.parseExportDeclaration(node); - return true; - } - return false; - } - isAsyncFunction() { - if (!this.isContextual(95)) return false; - const next = this.nextTokenInLineStart(); - return this.isUnparsedContextual(next, "function"); - } - parseExportDefaultExpression() { - const expr = this.startNode(); - if (this.match(68)) { - this.next(); - return this.parseFunction(expr, 1 | 4); - } else if (this.isAsyncFunction()) { - this.next(); - this.next(); - return this.parseFunction(expr, 1 | 4 | 8); - } - if (this.match(80)) { - return this.parseClass(expr, true, true); - } - if (this.match(26)) { - if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { - this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); - } - return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true); - } - if (this.match(75) || this.match(74) || this.isLet()) { - throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc); - } - const res = this.parseMaybeAssignAllowIn(); - this.semicolon(); - return res; - } - parseExportDeclaration(node) { - if (this.match(80)) { - const node = this.parseClass(this.startNode(), true, false); - return node; - } - return this.parseStatementListItem(); - } - isExportDefaultSpecifier() { - const { - type - } = this.state; - if (tokenIsIdentifier(type)) { - if (type === 95 && !this.state.containsEsc || type === 100) { - return false; - } - if ((type === 130 || type === 129) && !this.state.containsEsc) { - const { - type: nextType - } = this.lookahead(); - if (tokenIsIdentifier(nextType) && nextType !== 98 || nextType === 5) { - this.expectOnePlugin(["flow", "typescript"]); - return false; - } - } - } else if (!this.match(65)) { - return false; - } - const next = this.nextTokenStart(); - const hasFrom = this.isUnparsedContextual(next, "from"); - if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) { - return true; - } - if (this.match(65) && hasFrom) { - const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); - return nextAfterFrom === 34 || nextAfterFrom === 39; - } - return false; - } - parseExportFrom(node, expect) { - if (this.eatContextual(98)) { - node.source = this.parseImportSource(); - this.checkExport(node); - this.maybeParseImportAttributes(node); - this.checkJSONModuleImport(node); - } else if (expect) { - this.unexpected(); - } - this.semicolon(); - } - shouldParseExportDeclaration() { - const { - type - } = this.state; - if (type === 26) { - this.expectOnePlugin(["decorators", "decorators-legacy"]); - if (this.hasPlugin("decorators")) { - if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { - this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); - } - return true; - } - } - return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction(); - } - checkExport(node, checkNames, isDefault, isFrom) { - if (checkNames) { - var _node$specifiers; - if (isDefault) { - this.checkDuplicateExports(node, "default"); - if (this.hasPlugin("exportDefaultFrom")) { - var _declaration$extra; - const declaration = node.declaration; - if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { - this.raise(Errors.ExportDefaultFromAsIdentifier, declaration); - } - } - } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) { - for (const specifier of node.specifiers) { - const { - exported - } = specifier; - const exportName = exported.type === "Identifier" ? exported.name : exported.value; - this.checkDuplicateExports(specifier, exportName); - if (!isFrom && specifier.local) { - const { - local - } = specifier; - if (local.type !== "Identifier") { - this.raise(Errors.ExportBindingIsString, specifier, { - localName: local.value, - exportName - }); - } else { - this.checkReservedWord(local.name, local.loc.start, true, false); - this.scope.checkLocalExport(local); - } - } - } - } else if (node.declaration) { - if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { - const id = node.declaration.id; - if (!id) throw new Error("Assertion failure"); - this.checkDuplicateExports(node, id.name); - } else if (node.declaration.type === "VariableDeclaration") { - for (const declaration of node.declaration.declarations) { - this.checkDeclaration(declaration.id); - } - } - } - } - } - checkDeclaration(node) { - if (node.type === "Identifier") { - this.checkDuplicateExports(node, node.name); - } else if (node.type === "ObjectPattern") { - for (const prop of node.properties) { - this.checkDeclaration(prop); - } - } else if (node.type === "ArrayPattern") { - for (const elem of node.elements) { - if (elem) { - this.checkDeclaration(elem); - } - } - } else if (node.type === "ObjectProperty") { - this.checkDeclaration(node.value); - } else if (node.type === "RestElement") { - this.checkDeclaration(node.argument); - } else if (node.type === "AssignmentPattern") { - this.checkDeclaration(node.left); - } - } - checkDuplicateExports(node, exportName) { - if (this.exportedIdentifiers.has(exportName)) { - if (exportName === "default") { - this.raise(Errors.DuplicateDefaultExport, node); - } else { - this.raise(Errors.DuplicateExport, node, { - exportName - }); - } - } - this.exportedIdentifiers.add(exportName); - } - parseExportSpecifiers(isInTypeExport) { - const nodes = []; - let first = true; - this.expect(5); - while (!this.eat(8)) { - if (first) { - first = false; - } else { - this.expect(12); - if (this.eat(8)) break; - } - const isMaybeTypeOnly = this.isContextual(130); - const isString = this.match(133); - const node = this.startNode(); - node.local = this.parseModuleExportName(); - nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly)); - } - return nodes; - } - parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { - if (this.eatContextual(93)) { - node.exported = this.parseModuleExportName(); - } else if (isString) { - node.exported = cloneStringLiteral(node.local); - } else if (!node.exported) { - node.exported = cloneIdentifier(node.local); - } - return this.finishNode(node, "ExportSpecifier"); - } - parseModuleExportName() { - if (this.match(133)) { - const result = this.parseStringLiteral(this.state.value); - const surrogate = result.value.match(loneSurrogate); - if (surrogate) { - this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, { - surrogateCharCode: surrogate[0].charCodeAt(0) - }); - } - return result; - } - return this.parseIdentifier(true); - } - isJSONModuleImport(node) { - if (node.assertions != null) { - return node.assertions.some(({ - key, - value - }) => { - return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type"); - }); - } - return false; - } - checkImportReflection(node) { - const { - specifiers - } = node; - const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null; - if (node.phase === "source") { - if (singleBindingType !== "ImportDefaultSpecifier") { - this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start); - } - } else if (node.phase === "defer") { - if (singleBindingType !== "ImportNamespaceSpecifier") { - this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start); - } - } else if (node.module) { - var _node$assertions; - if (singleBindingType !== "ImportDefaultSpecifier") { - this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start); - } - if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) { - this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start); - } - } - } - checkJSONModuleImport(node) { - if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") { - const { - specifiers - } = node; - if (specifiers != null) { - const nonDefaultNamedSpecifier = specifiers.find(specifier => { - let imported; - if (specifier.type === "ExportSpecifier") { - imported = specifier.local; - } else if (specifier.type === "ImportSpecifier") { - imported = specifier.imported; - } - if (imported !== undefined) { - return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default"; - } - }); - if (nonDefaultNamedSpecifier !== undefined) { - this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start); - } - } - } - } - isPotentialImportPhase(isExport) { - if (isExport) return false; - return this.isContextual(105) || this.isContextual(97) || this.isContextual(127); - } - applyImportPhase(node, isExport, phase, loc) { - if (isExport) { - return; - } - if (phase === "module") { - this.expectPlugin("importReflection", loc); - node.module = true; - } else if (this.hasPlugin("importReflection")) { - node.module = false; - } - if (phase === "source") { - this.expectPlugin("sourcePhaseImports", loc); - node.phase = "source"; - } else if (phase === "defer") { - this.expectPlugin("deferredImportEvaluation", loc); - node.phase = "defer"; - } else if (this.hasPlugin("sourcePhaseImports")) { - node.phase = null; - } - } - parseMaybeImportPhase(node, isExport) { - if (!this.isPotentialImportPhase(isExport)) { - this.applyImportPhase(node, isExport, null); - return null; - } - const phaseIdentifier = this.parseIdentifier(true); - const { - type - } = this.state; - const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; - if (isImportPhase) { - this.resetPreviousIdentifierLeadingComments(phaseIdentifier); - this.applyImportPhase(node, isExport, phaseIdentifier.name, phaseIdentifier.loc.start); - return null; - } else { - this.applyImportPhase(node, isExport, null); - return phaseIdentifier; - } - } - isPrecedingIdImportPhase(phase) { - const { - type - } = this.state; - return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; - } - parseImport(node) { - if (this.match(133)) { - return this.parseImportSourceAndAttributes(node); - } - return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false)); - } - parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) { - node.specifiers = []; - const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier); - const parseNext = !hasDefault || this.eat(12); - const hasStar = parseNext && this.maybeParseStarImportSpecifier(node); - if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); - this.expectContextual(98); - return this.parseImportSourceAndAttributes(node); - } - parseImportSourceAndAttributes(node) { - var _node$specifiers2; - (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = []; - node.source = this.parseImportSource(); - this.maybeParseImportAttributes(node); - this.checkImportReflection(node); - this.checkJSONModuleImport(node); - this.semicolon(); - return this.finishNode(node, "ImportDeclaration"); - } - parseImportSource() { - if (!this.match(133)) this.unexpected(); - return this.parseExprAtom(); - } - parseImportSpecifierLocal(node, specifier, type) { - specifier.local = this.parseIdentifier(); - node.specifiers.push(this.finishImportSpecifier(specifier, type)); - } - finishImportSpecifier(specifier, type, bindingType = 8201) { - this.checkLVal(specifier.local, { - in: { - type - }, - binding: bindingType - }); - return this.finishNode(specifier, type); - } - parseImportAttributes() { - this.expect(5); - const attrs = []; - const attrNames = new Set(); - do { - if (this.match(8)) { - break; - } - const node = this.startNode(); - const keyName = this.state.value; - if (attrNames.has(keyName)) { - this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, { - key: keyName - }); - } - attrNames.add(keyName); - if (this.match(133)) { - node.key = this.parseStringLiteral(keyName); - } else { - node.key = this.parseIdentifier(true); - } - this.expect(14); - if (!this.match(133)) { - throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); - } - node.value = this.parseStringLiteral(this.state.value); - attrs.push(this.finishNode(node, "ImportAttribute")); - } while (this.eat(12)); - this.expect(8); - return attrs; - } - parseModuleAttributes() { - const attrs = []; - const attributes = new Set(); - do { - const node = this.startNode(); - node.key = this.parseIdentifier(true); - if (node.key.name !== "type") { - this.raise(Errors.ModuleAttributeDifferentFromType, node.key); - } - if (attributes.has(node.key.name)) { - this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, { - key: node.key.name - }); - } - attributes.add(node.key.name); - this.expect(14); - if (!this.match(133)) { - throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); - } - node.value = this.parseStringLiteral(this.state.value); - attrs.push(this.finishNode(node, "ImportAttribute")); - } while (this.eat(12)); - return attrs; - } - maybeParseImportAttributes(node) { - let attributes; - let useWith = false; - if (this.match(76)) { - if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) { - return; - } - this.next(); - { - if (this.hasPlugin("moduleAttributes")) { - attributes = this.parseModuleAttributes(); - } else { - this.expectImportAttributesPlugin(); - attributes = this.parseImportAttributes(); - } - } - useWith = true; - } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) { - if (this.hasPlugin("importAttributes")) { - if (this.getPluginOption("importAttributes", "deprecatedAssertSyntax") !== true) { - this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc); - } - this.addExtra(node, "deprecatedAssertSyntax", true); - } else { - this.expectOnePlugin(["importAttributes", "importAssertions"]); - } - this.next(); - attributes = this.parseImportAttributes(); - } else if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { - attributes = []; - } else { - if (this.hasPlugin("moduleAttributes")) { - attributes = []; - } else return; - } - if (!useWith && this.hasPlugin("importAssertions")) { - node.assertions = attributes; - } else { - node.attributes = attributes; - } - } - maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) { - if (maybeDefaultIdentifier) { - const specifier = this.startNodeAtNode(maybeDefaultIdentifier); - specifier.local = maybeDefaultIdentifier; - node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier")); - return true; - } else if (tokenIsKeywordOrIdentifier(this.state.type)) { - this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier"); - return true; - } - return false; - } - maybeParseStarImportSpecifier(node) { - if (this.match(55)) { - const specifier = this.startNode(); - this.next(); - this.expectContextual(93); - this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier"); - return true; - } - return false; - } - parseNamedImportSpecifiers(node) { - let first = true; - this.expect(5); - while (!this.eat(8)) { - if (first) { - first = false; - } else { - if (this.eat(14)) { - throw this.raise(Errors.DestructureNamedImport, this.state.startLoc); - } - this.expect(12); - if (this.eat(8)) break; - } - const specifier = this.startNode(); - const importedIsString = this.match(133); - const isMaybeTypeOnly = this.isContextual(130); - specifier.imported = this.parseModuleExportName(); - const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined); - node.specifiers.push(importSpecifier); - } - } - parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { - if (this.eatContextual(93)) { - specifier.local = this.parseIdentifier(); - } else { - const { - imported - } = specifier; - if (importedIsString) { - throw this.raise(Errors.ImportBindingIsString, specifier, { - importName: imported.value - }); - } - this.checkReservedWord(imported.name, specifier.loc.start, true, true); - if (!specifier.local) { - specifier.local = cloneIdentifier(imported); - } - } - return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType); - } - isThisParam(param) { - return param.type === "Identifier" && param.name === "this"; - } - } - let Parser$2 = class Parser extends StatementParser { - constructor(options, input) { - options = getOptions(options); - super(options, input); - this.options = options; - this.initializeScopes(); - this.plugins = pluginsMap(this.options.plugins); - this.filename = options.sourceFilename; - } - getScopeHandler() { - return ScopeHandler; - } - parse() { - this.enterInitialScopes(); - const file = this.startNode(); - const program = this.startNode(); - this.nextToken(); - file.errors = null; - this.parseTopLevel(file, program); - file.errors = this.state.errors; - file.comments.length = this.state.commentsLen; - return file; - } - }; - function pluginsMap(plugins) { - const pluginMap = new Map(); - for (const plugin of plugins) { - const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}]; - if (!pluginMap.has(name)) pluginMap.set(name, options || {}); - } - return pluginMap; - } - function parse$9(input, options) { - var _options; - if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { - options = Object.assign({}, options); - try { - options.sourceType = "module"; - const parser = getParser(options, input); - const ast = parser.parse(); - if (parser.sawUnambiguousESM) { - return ast; - } - if (parser.ambiguousScriptDifferentAst) { - try { - options.sourceType = "script"; - return getParser(options, input).parse(); - } catch (_unused) { } - } else { - ast.program.sourceType = "script"; - } - return ast; - } catch (moduleError) { - try { - options.sourceType = "script"; - return getParser(options, input).parse(); - } catch (_unused2) { } - throw moduleError; - } - } else { - return getParser(options, input).parse(); - } - } - function parseExpression(input, options) { - const parser = getParser(options, input); - if (parser.options.strictMode) { - parser.state.strict = true; - } - return parser.getExpression(); - } - function generateExportedTokenTypes(internalTokenTypes) { - const tokenTypes = {}; - for (const typeName of Object.keys(internalTokenTypes)) { - tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]); - } - return tokenTypes; - } - const tokTypes = generateExportedTokenTypes(tt); - function getParser(options, input) { - let cls = Parser$2; - if (options != null && options.plugins) { - validatePlugins(options.plugins); - cls = getParserClass(options.plugins); - } - return new cls(options, input); - } - const parserClassCache = {}; - function getParserClass(pluginsFromOptions) { - const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name)); - const key = pluginList.join("/"); - let cls = parserClassCache[key]; - if (!cls) { - cls = Parser$2; - for (const plugin of pluginList) { - cls = mixinPlugins[plugin](cls); - } - parserClassCache[key] = cls; - } - return cls; - } - var parse_1$1 = lib.parse = parse$9; - var parseExpression_1 = lib.parseExpression = parseExpression; - lib.tokTypes = tokTypes; - - // @ts-check - /** @typedef { import('estree').BaseNode} BaseNode */ - - /** @typedef {{ - skip: () => void; - remove: () => void; - replace: (node: BaseNode) => void; - }} WalkerContext */ - - class WalkerBase { - constructor() { - /** @type {boolean} */ - this.should_skip = false; - - /** @type {boolean} */ - this.should_remove = false; - - /** @type {BaseNode | null} */ - this.replacement = null; - - /** @type {WalkerContext} */ - this.context = { - skip: () => (this.should_skip = true), - remove: () => (this.should_remove = true), - replace: (node) => (this.replacement = node) - }; - } - - /** - * - * @param {any} parent - * @param {string} prop - * @param {number} index - * @param {BaseNode} node - */ - replace(parent, prop, index, node) { - if (parent) { - if (index !== null) { - parent[prop][index] = node; - } else { - parent[prop] = node; - } - } - } - - /** - * - * @param {any} parent - * @param {string} prop - * @param {number} index - */ - remove(parent, prop, index) { - if (parent) { - if (index !== null) { - parent[prop].splice(index, 1); - } else { - delete parent[prop]; - } - } - } - } - - // @ts-check - - /** @typedef { import('estree').BaseNode} BaseNode */ - /** @typedef { import('./walker.js').WalkerContext} WalkerContext */ - - /** @typedef {( - * this: WalkerContext, - * node: BaseNode, - * parent: BaseNode, - * key: string, - * index: number - * ) => void} SyncHandler */ - - class SyncWalker extends WalkerBase { - /** - * - * @param {SyncHandler} enter - * @param {SyncHandler} leave - */ - constructor(enter, leave) { - super(); - - /** @type {SyncHandler} */ - this.enter = enter; - - /** @type {SyncHandler} */ - this.leave = leave; - } - - /** - * - * @param {BaseNode} node - * @param {BaseNode} parent - * @param {string} [prop] - * @param {number} [index] - * @returns {BaseNode} - */ - visit(node, parent, prop, index) { - if (node) { - if (this.enter) { - const _should_skip = this.should_skip; - const _should_remove = this.should_remove; - const _replacement = this.replacement; - this.should_skip = false; - this.should_remove = false; - this.replacement = null; - - this.enter.call(this.context, node, parent, prop, index); - - if (this.replacement) { - node = this.replacement; - this.replace(parent, prop, index, node); - } - - if (this.should_remove) { - this.remove(parent, prop, index); - } - - const skipped = this.should_skip; - const removed = this.should_remove; - - this.should_skip = _should_skip; - this.should_remove = _should_remove; - this.replacement = _replacement; - - if (skipped) return node; - if (removed) return null; - } - - for (const key in node) { - const value = node[key]; - - if (typeof value !== "object") { - continue; - } else if (Array.isArray(value)) { - for (let i = 0; i < value.length; i += 1) { - if (value[i] !== null && typeof value[i].type === 'string') { - if (!this.visit(value[i], node, key, i)) { - // removed - i--; - } - } - } - } else if (value !== null && typeof value.type === "string") { - this.visit(value, node, key, null); - } - } - - if (this.leave) { - const _replacement = this.replacement; - const _should_remove = this.should_remove; - this.replacement = null; - this.should_remove = false; - - this.leave.call(this.context, node, parent, prop, index); - - if (this.replacement) { - node = this.replacement; - this.replace(parent, prop, index, node); - } - - if (this.should_remove) { - this.remove(parent, prop, index); - } - - const removed = this.should_remove; - - this.replacement = _replacement; - this.should_remove = _should_remove; - - if (removed) return null; - } - } - - return node; - } - } - - // @ts-check - - /** @typedef { import('estree').BaseNode} BaseNode */ - /** @typedef { import('./sync.js').SyncHandler} SyncHandler */ - /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ - - /** - * - * @param {BaseNode} ast - * @param {{ - * enter?: SyncHandler - * leave?: SyncHandler - * }} walker - * @returns {BaseNode} - */ - function walk$2(ast, { enter, leave }) { - const instance = new SyncWalker(enter, leave); - return instance.visit(ast, null); - } - - function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = /* @__PURE__ */ Object.create(null)) { - const rootExp = root.type === "Program" ? root.body[0].type === "ExpressionStatement" && root.body[0].expression : root; - walk$2(root, { - enter(node, parent) { - parent && parentStack.push(parent); - if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) { - return this.skip(); - } - if (node.type === "Identifier") { - const isLocal = !!knownIds[node.name]; - const isRefed = isReferencedIdentifier(node, parent, parentStack); - if (includeAll || isRefed && !isLocal) { - onIdentifier(node, parent, parentStack, isRefed, isLocal); - } - } else if (node.type === "ObjectProperty" && (parent == null ? void 0 : parent.type) === "ObjectPattern") { - node.inPattern = true; - } else if (isFunctionType(node)) { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - walkFunctionParams( - node, - (id) => markScopeIdentifier(node, id, knownIds) - ); - } - } else if (node.type === "BlockStatement") { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - walkBlockDeclarations( - node, - (id) => markScopeIdentifier(node, id, knownIds) - ); - } - } - }, - leave(node, parent) { - parent && parentStack.pop(); - if (node !== rootExp && node.scopeIds) { - for (const id of node.scopeIds) { - knownIds[id]--; - if (knownIds[id] === 0) { - delete knownIds[id]; - } - } - } - } - }); - } - function isReferencedIdentifier(id, parent, parentStack) { - if (!parent) { - return true; - } - if (id.name === "arguments") { - return false; - } - if (isReferenced(id, parent)) { - return true; - } - switch (parent.type) { - case "AssignmentExpression": - case "AssignmentPattern": - return true; - case "ObjectPattern": - case "ArrayPattern": - return isInDestructureAssignment(parent, parentStack); - } - return false; - } - function isInDestructureAssignment(parent, parentStack) { - if (parent && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) { - let i = parentStack.length; - while (i--) { - const p = parentStack[i]; - if (p.type === "AssignmentExpression") { - return true; - } else if (p.type !== "ObjectProperty" && !p.type.endsWith("Pattern")) { - break; - } - } - } - return false; - } - function isInNewExpression(parentStack) { - let i = parentStack.length; - while (i--) { - const p = parentStack[i]; - if (p.type === "NewExpression") { - return true; - } else if (p.type !== "MemberExpression") { - break; - } - } - return false; - } - function walkFunctionParams(node, onIdent) { - for (const p of node.params) { - for (const id of extractIdentifiers$1(p)) { - onIdent(id); - } - } - } - function walkBlockDeclarations(block, onIdent) { - for (const stmt of block.body) { - if (stmt.type === "VariableDeclaration") { - if (stmt.declare) - continue; - for (const decl of stmt.declarations) { - for (const id of extractIdentifiers$1(decl.id)) { - onIdent(id); - } - } - } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") { - if (stmt.declare || !stmt.id) - continue; - onIdent(stmt.id); - } else if (stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement") { - const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left; - if (variable && variable.type === "VariableDeclaration") { - for (const decl of variable.declarations) { - for (const id of extractIdentifiers$1(decl.id)) { - onIdent(id); - } - } - } - } - } - } - function extractIdentifiers$1(param, nodes = []) { - switch (param.type) { - case "Identifier": - nodes.push(param); - break; - case "MemberExpression": - let object = param; - while (object.type === "MemberExpression") { - object = object.object; - } - nodes.push(object); - break; - case "ObjectPattern": - for (const prop of param.properties) { - if (prop.type === "RestElement") { - extractIdentifiers$1(prop.argument, nodes); - } else { - extractIdentifiers$1(prop.value, nodes); - } - } - break; - case "ArrayPattern": - param.elements.forEach((element) => { - if (element) - extractIdentifiers$1(element, nodes); - }); - break; - case "RestElement": - extractIdentifiers$1(param.argument, nodes); - break; - case "AssignmentPattern": - extractIdentifiers$1(param.left, nodes); - break; - } - return nodes; - } - function markKnownIds(name, knownIds) { - if (name in knownIds) { - knownIds[name]++; - } else { - knownIds[name] = 1; - } - } - function markScopeIdentifier(node, child, knownIds) { - const { name } = child; - if (node.scopeIds && node.scopeIds.has(name)) { - return; - } - markKnownIds(name, knownIds); - (node.scopeIds || (node.scopeIds = /* @__PURE__ */ new Set())).add(name); - } - const isFunctionType = (node) => { - return /Function(?:Expression|Declaration)$|Method$/.test(node.type); - }; - const isStaticProperty = (node) => node && (node.type === "ObjectProperty" || node.type === "ObjectMethod") && !node.computed; - const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node; - function isReferenced(node, parent, grandparent) { - switch (parent.type) { - case "MemberExpression": - case "OptionalMemberExpression": - if (parent.property === node) { - return !!parent.computed; - } - return parent.object === node; - case "JSXMemberExpression": - return parent.object === node; - case "VariableDeclarator": - return parent.init === node; - case "ArrowFunctionExpression": - return parent.body === node; - case "PrivateName": - return false; - case "ClassMethod": - case "ClassPrivateMethod": - case "ObjectMethod": - if (parent.key === node) { - return !!parent.computed; - } - return false; - case "ObjectProperty": - if (parent.key === node) { - return !!parent.computed; - } - return !grandparent || grandparent.type !== "ObjectPattern"; - case "ClassProperty": - if (parent.key === node) { - return !!parent.computed; - } - return true; - case "ClassPrivateProperty": - return parent.key !== node; - case "ClassDeclaration": - case "ClassExpression": - return parent.superClass === node; - case "AssignmentExpression": - return parent.right === node; - case "AssignmentPattern": - return parent.right === node; - case "LabeledStatement": - return false; - case "CatchClause": - return false; - case "RestElement": - return false; - case "BreakStatement": - case "ContinueStatement": - return false; - case "FunctionDeclaration": - case "FunctionExpression": - return false; - case "ExportNamespaceSpecifier": - case "ExportDefaultSpecifier": - return false; - case "ExportSpecifier": - if (grandparent == null ? void 0 : grandparent.source) { - return false; - } - return parent.local === node; - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "ImportSpecifier": - return false; - case "ImportAttribute": - return false; - case "JSXAttribute": - return false; - case "ObjectPattern": - case "ArrayPattern": - return false; - case "MetaProperty": - return false; - case "ObjectTypeProperty": - return parent.key !== node; - case "TSEnumMember": - return parent.id !== node; - case "TSPropertySignature": - if (parent.key === node) { - return !!parent.computed; - } - return true; - } - return true; - } - const TS_NODE_TYPES = [ - "TSAsExpression", - // foo as number - "TSTypeAssertion", - // (<number>foo) - "TSNonNullExpression", - // foo! - "TSInstantiationExpression", - // foo<string> - "TSSatisfiesExpression" - // foo satisfies T - ]; - function unwrapTSNode(node) { - if (TS_NODE_TYPES.includes(node.type)) { - return unwrapTSNode(node.expression); - } else { - return node; - } - } - - const isStaticExp = (p) => p.type === 4 && p.isStatic; - function isCoreComponent(tag) { - switch (tag) { - case "Teleport": - case "teleport": - return TELEPORT; - case "Suspense": - case "suspense": - return SUSPENSE; - case "KeepAlive": - case "keep-alive": - return KEEP_ALIVE; - case "BaseTransition": - case "base-transition": - return BASE_TRANSITION; - } - } - const nonIdentifierRE = /^\d|[^\$\w]/; - const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name); - const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/; - const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/; - const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g; - const isMemberExpressionBrowser = (path) => { - path = path.trim().replace(whitespaceRE, (s) => s.trim()); - let state = 0 /* inMemberExp */; - let stateStack = []; - let currentOpenBracketCount = 0; - let currentOpenParensCount = 0; - let currentStringType = null; - for (let i = 0; i < path.length; i++) { - const char = path.charAt(i); - switch (state) { - case 0 /* inMemberExp */: - if (char === "[") { - stateStack.push(state); - state = 1 /* inBrackets */; - currentOpenBracketCount++; - } else if (char === "(") { - stateStack.push(state); - state = 2 /* inParens */; - currentOpenParensCount++; - } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) { - return false; - } - break; - case 1 /* inBrackets */: - if (char === `'` || char === `"` || char === "`") { - stateStack.push(state); - state = 3 /* inString */; - currentStringType = char; - } else if (char === `[`) { - currentOpenBracketCount++; - } else if (char === `]`) { - if (!--currentOpenBracketCount) { - state = stateStack.pop(); - } - } - break; - case 2 /* inParens */: - if (char === `'` || char === `"` || char === "`") { - stateStack.push(state); - state = 3 /* inString */; - currentStringType = char; - } else if (char === `(`) { - currentOpenParensCount++; - } else if (char === `)`) { - if (i === path.length - 1) { - return false; - } - if (!--currentOpenParensCount) { - state = stateStack.pop(); - } - } - break; - case 3 /* inString */: - if (char === currentStringType) { - state = stateStack.pop(); - currentStringType = null; - } - break; - } - } - return !currentOpenBracketCount && !currentOpenParensCount; - }; - const isMemberExpressionNode = (path, context) => { - try { - let ret = parseExpression_1(path, { - plugins: context.expressionPlugins - }); - ret = unwrapTSNode(ret); - return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier" && ret.name !== "undefined"; - } catch (e) { - return false; - } - }; - const isMemberExpression = isMemberExpressionNode; - function advancePositionWithClone(pos, source, numberOfCharacters = source.length) { - return advancePositionWithMutation( - { - offset: pos.offset, - line: pos.line, - column: pos.column - }, - source, - numberOfCharacters - ); - } - function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) { - let linesCount = 0; - let lastNewLinePos = -1; - for (let i = 0; i < numberOfCharacters; i++) { - if (source.charCodeAt(i) === 10) { - linesCount++; - lastNewLinePos = i; - } - } - pos.offset += numberOfCharacters; - pos.line += linesCount; - pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos; - return pos; - } - function assert(condition, msg) { - if (!condition) { - throw new Error(msg || `unexpected compiler condition`); - } - } - function findDir(node, name, allowEmpty = false) { - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i]; - if (p.type === 7 && (allowEmpty || p.exp) && (isString$2(name) ? p.name === name : name.test(p.name))) { - return p; - } - } - } - function findProp(node, name, dynamicOnly = false, allowEmpty = false) { - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i]; - if (p.type === 6) { - if (dynamicOnly) - continue; - if (p.name === name && (p.value || allowEmpty)) { - return p; - } - } else if (p.name === "bind" && (p.exp || allowEmpty) && isStaticArgOf(p.arg, name)) { - return p; - } - } - } - function isStaticArgOf(arg, name) { - return !!(arg && isStaticExp(arg) && arg.content === name); - } - function hasDynamicKeyVBind(node) { - return node.props.some( - (p) => p.type === 7 && p.name === "bind" && (!p.arg || // v-bind="obj" - p.arg.type !== 4 || // v-bind:[_ctx.foo] - !p.arg.isStatic) - // v-bind:[foo] - ); - } - function isText$1(node) { - return node.type === 5 || node.type === 2; - } - function isVSlot(p) { - return p.type === 7 && p.name === "slot"; - } - function isTemplateNode(node) { - return node.type === 1 && node.tagType === 3; - } - function isSlotOutlet(node) { - return node.type === 1 && node.tagType === 2; - } - const propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]); - function getUnnormalizedProps(props, callPath = []) { - if (props && !isString$2(props) && props.type === 14) { - const callee = props.callee; - if (!isString$2(callee) && propsHelperSet.has(callee)) { - return getUnnormalizedProps( - props.arguments[0], - callPath.concat(props) - ); - } - } - return [props, callPath]; - } - function injectProp(node, prop, context) { - let propsWithInjection; - let props = node.type === 13 ? node.props : node.arguments[2]; - let callPath = []; - let parentCall; - if (props && !isString$2(props) && props.type === 14) { - const ret = getUnnormalizedProps(props); - props = ret[0]; - callPath = ret[1]; - parentCall = callPath[callPath.length - 1]; - } - if (props == null || isString$2(props)) { - propsWithInjection = createObjectExpression([prop]); - } else if (props.type === 14) { - const first = props.arguments[0]; - if (!isString$2(first) && first.type === 15) { - if (!hasProp(prop, first)) { - first.properties.unshift(prop); - } - } else { - if (props.callee === TO_HANDLERS) { - propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [ - createObjectExpression([prop]), - props - ]); - } else { - props.arguments.unshift(createObjectExpression([prop])); - } - } - !propsWithInjection && (propsWithInjection = props); - } else if (props.type === 15) { - if (!hasProp(prop, props)) { - props.properties.unshift(prop); - } - propsWithInjection = props; - } else { - propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [ - createObjectExpression([prop]), - props - ]); - if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) { - parentCall = callPath[callPath.length - 2]; - } - } - if (node.type === 13) { - if (parentCall) { - parentCall.arguments[0] = propsWithInjection; - } else { - node.props = propsWithInjection; - } - } else { - if (parentCall) { - parentCall.arguments[0] = propsWithInjection; - } else { - node.arguments[2] = propsWithInjection; - } - } - } - function hasProp(prop, props) { - let result = false; - if (prop.key.type === 4) { - const propKeyName = prop.key.content; - result = props.properties.some( - (p) => p.key.type === 4 && p.key.content === propKeyName - ); - } - return result; - } - function toValidAssetId(name, type) { - return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => { - return searchValue === "-" ? "_" : name.charCodeAt(replaceValue).toString(); - })}`; - } - function hasScopeRef(node, ids) { - if (!node || Object.keys(ids).length === 0) { - return false; - } - switch (node.type) { - case 1: - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i]; - if (p.type === 7 && (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) { - return true; - } - } - return node.children.some((c) => hasScopeRef(c, ids)); - case 11: - if (hasScopeRef(node.source, ids)) { - return true; - } - return node.children.some((c) => hasScopeRef(c, ids)); - case 9: - return node.branches.some((b) => hasScopeRef(b, ids)); - case 10: - if (hasScopeRef(node.condition, ids)) { - return true; - } - return node.children.some((c) => hasScopeRef(c, ids)); - case 4: - return !node.isStatic && isSimpleIdentifier(node.content) && !!ids[node.content]; - case 8: - return node.children.some((c) => isObject$2(c) && hasScopeRef(c, ids)); - case 5: - case 12: - return hasScopeRef(node.content, ids); - case 2: - case 3: - return false; - default: - return false; - } - } - function getMemoedVNodeCall(node) { - if (node.type === 14 && node.callee === WITH_MEMO) { - return node.arguments[1].returns; - } else { - return node; - } - } - const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; - - const defaultParserOptions = { - parseMode: "base", - ns: 0, - delimiters: [`{{`, `}}`], - getNamespace: () => 0, - isVoidTag: NO, - isPreTag: NO, - isCustomElement: NO, - onError: defaultOnError, - onWarn: defaultOnWarn, - comments: true, - prefixIdentifiers: false - }; - let currentOptions = defaultParserOptions; - let currentRoot = null; - let currentInput = ""; - let currentOpenTag = null; - let currentProp = null; - let currentAttrValue = ""; - let currentAttrStartIndex = -1; - let currentAttrEndIndex = -1; - let inPre = 0; - let inVPre = false; - let currentVPreBoundary = null; - const stack = []; - const tokenizer$2 = new Tokenizer$1(stack, { - onerr: emitError, - ontext(start, end) { - onText(getSlice(start, end), start, end); - }, - ontextentity(char, start, end) { - onText(char, start, end); - }, - oninterpolation(start, end) { - if (inVPre) { - return onText(getSlice(start, end), start, end); - } - let innerStart = start + tokenizer$2.delimiterOpen.length; - let innerEnd = end - tokenizer$2.delimiterClose.length; - while (isWhitespace$1(currentInput.charCodeAt(innerStart))) { - innerStart++; - } - while (isWhitespace$1(currentInput.charCodeAt(innerEnd - 1))) { - innerEnd--; - } - let exp = getSlice(innerStart, innerEnd); - if (exp.includes("&")) { - { - exp = decodeHTML(exp); - } - } - addNode({ - type: 5, - content: createExp(exp, false, getLoc(innerStart, innerEnd)), - loc: getLoc(start, end) - }); - }, - onopentagname(start, end) { - const name = getSlice(start, end); - currentOpenTag = { - type: 1, - tag: name, - ns: currentOptions.getNamespace(name, stack[0], currentOptions.ns), - tagType: 0, - // will be refined on tag close - props: [], - children: [], - loc: getLoc(start - 1, end), - codegenNode: void 0 - }; - }, - onopentagend(end) { - endOpenTag(end); - }, - onclosetag(start, end) { - const name = getSlice(start, end); - if (!currentOptions.isVoidTag(name)) { - let found = false; - for (let i = 0; i < stack.length; i++) { - const e = stack[i]; - if (e.tag.toLowerCase() === name.toLowerCase()) { - found = true; - if (i > 0) { - emitError(24, stack[0].loc.start.offset); - } - for (let j = 0; j <= i; j++) { - const el = stack.shift(); - onCloseTag(el, end, j < i); - } - break; - } - } - if (!found) { - emitError(23, backTrack(start, 60)); - } - } - }, - onselfclosingtag(end) { - var _a; - const name = currentOpenTag.tag; - currentOpenTag.isSelfClosing = true; - endOpenTag(end); - if (((_a = stack[0]) == null ? void 0 : _a.tag) === name) { - onCloseTag(stack.shift(), end); - } - }, - onattribname(start, end) { - currentProp = { - type: 6, - name: getSlice(start, end), - nameLoc: getLoc(start, end), - value: void 0, - loc: getLoc(start) - }; - }, - ondirname(start, end) { - const raw = getSlice(start, end); - const name = raw === "." || raw === ":" ? "bind" : raw === "@" ? "on" : raw === "#" ? "slot" : raw.slice(2); - if (!inVPre && name === "") { - emitError(26, start); - } - if (inVPre || name === "") { - currentProp = { - type: 6, - name: raw, - nameLoc: getLoc(start, end), - value: void 0, - loc: getLoc(start) - }; - } else { - currentProp = { - type: 7, - name, - rawName: raw, - exp: void 0, - arg: void 0, - modifiers: raw === "." ? ["prop"] : [], - loc: getLoc(start) - }; - if (name === "pre") { - inVPre = tokenizer$2.inVPre = true; - currentVPreBoundary = currentOpenTag; - const props = currentOpenTag.props; - for (let i = 0; i < props.length; i++) { - if (props[i].type === 7) { - props[i] = dirToAttr(props[i]); - } - } - } - } - }, - ondirarg(start, end) { - if (start === end) - return; - const arg = getSlice(start, end); - if (inVPre) { - currentProp.name += arg; - setLocEnd(currentProp.nameLoc, end); - } else { - const isStatic = arg[0] !== `[`; - currentProp.arg = createExp( - isStatic ? arg : arg.slice(1, -1), - isStatic, - getLoc(start, end), - isStatic ? 3 : 0 - ); - } - }, - ondirmodifier(start, end) { - const mod = getSlice(start, end); - if (inVPre) { - currentProp.name += "." + mod; - setLocEnd(currentProp.nameLoc, end); - } else if (currentProp.name === "slot") { - const arg = currentProp.arg; - if (arg) { - arg.content += "." + mod; - setLocEnd(arg.loc, end); - } - } else { - currentProp.modifiers.push(mod); - } - }, - onattribdata(start, end) { - currentAttrValue += getSlice(start, end); - if (currentAttrStartIndex < 0) - currentAttrStartIndex = start; - currentAttrEndIndex = end; - }, - onattribentity(char, start, end) { - currentAttrValue += char; - if (currentAttrStartIndex < 0) - currentAttrStartIndex = start; - currentAttrEndIndex = end; - }, - onattribnameend(end) { - const start = currentProp.loc.start.offset; - const name = getSlice(start, end); - if (currentProp.type === 7) { - currentProp.rawName = name; - } - if (currentOpenTag.props.some( - (p) => (p.type === 7 ? p.rawName : p.name) === name - )) { - emitError(2, start); - } - }, - onattribend(quote, end) { - if (currentOpenTag && currentProp) { - setLocEnd(currentProp.loc, end); - if (quote !== 0) { - if (currentProp.type === 6) { - if (currentProp.name === "class") { - currentAttrValue = condense(currentAttrValue).trim(); - } - if (quote === 1 && !currentAttrValue) { - emitError(13, end); - } - currentProp.value = { - type: 2, - content: currentAttrValue, - loc: quote === 1 ? getLoc(currentAttrStartIndex, currentAttrEndIndex) : getLoc(currentAttrStartIndex - 1, currentAttrEndIndex + 1) - }; - if (tokenizer$2.inSFCRoot && currentOpenTag.tag === "template" && currentProp.name === "lang" && currentAttrValue && currentAttrValue !== "html") { - tokenizer$2.enterRCDATA(toCharCodes(`</template`), 0); - } - } else { - let expParseMode = 0 /* Normal */; - { - if (currentProp.name === "for") { - expParseMode = 3 /* Skip */; - } else if (currentProp.name === "slot") { - expParseMode = 1 /* Params */; - } else if (currentProp.name === "on" && currentAttrValue.includes(";")) { - expParseMode = 2 /* Statements */; - } - } - currentProp.exp = createExp( - currentAttrValue, - false, - getLoc(currentAttrStartIndex, currentAttrEndIndex), - 0, - expParseMode - ); - if (currentProp.name === "for") { - currentProp.forParseResult = parseForExpression(currentProp.exp); - } - } - } - if (currentProp.type !== 7 || currentProp.name !== "pre") { - currentOpenTag.props.push(currentProp); - } - } - currentAttrValue = ""; - currentAttrStartIndex = currentAttrEndIndex = -1; - }, - oncomment(start, end) { - if (currentOptions.comments) { - addNode({ - type: 3, - content: getSlice(start, end), - loc: getLoc(start - 4, end + 3) - }); - } - }, - onend() { - const end = currentInput.length; - if (tokenizer$2.state !== 1) { - switch (tokenizer$2.state) { - case 5: - case 8: - emitError(5, end); - break; - case 3: - case 4: - emitError( - 25, - tokenizer$2.sectionStart - ); - break; - case 28: - if (tokenizer$2.currentSequence === Sequences.CdataEnd) { - emitError(6, end); - } else { - emitError(7, end); - } - break; - case 6: - case 7: - case 9: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: - case 19: - case 20: - case 21: - emitError(9, end); - break; - } - } - for (let index = 0; index < stack.length; index++) { - onCloseTag(stack[index], end - 1); - emitError(24, stack[index].loc.start.offset); - } - }, - oncdata(start, end) { - if (stack[0].ns !== 0) { - onText(getSlice(start, end), start, end); - } else { - emitError(1, start - 9); - } - }, - onprocessinginstruction(start) { - if ((stack[0] ? stack[0].ns : currentOptions.ns) === 0) { - emitError( - 21, - start - 1 - ); - } - } - }); - const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; - const stripParensRE = /^\(|\)$/g; - function parseForExpression(input) { - const loc = input.loc; - const exp = input.content; - const inMatch = exp.match(forAliasRE); - if (!inMatch) - return; - const [, LHS, RHS] = inMatch; - const createAliasExpression = (content, offset, asParam = false) => { - const start = loc.start.offset + offset; - const end = start + content.length; - return createExp( - content, - false, - getLoc(start, end), - 0, - asParam ? 1 /* Params */ : 0 /* Normal */ - ); - }; - const result = { - source: createAliasExpression(RHS.trim(), exp.indexOf(RHS, LHS.length)), - value: void 0, - key: void 0, - index: void 0, - finalized: false - }; - let valueContent = LHS.trim().replace(stripParensRE, "").trim(); - const trimmedOffset = LHS.indexOf(valueContent); - const iteratorMatch = valueContent.match(forIteratorRE); - if (iteratorMatch) { - valueContent = valueContent.replace(forIteratorRE, "").trim(); - const keyContent = iteratorMatch[1].trim(); - let keyOffset; - if (keyContent) { - keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length); - result.key = createAliasExpression(keyContent, keyOffset, true); - } - if (iteratorMatch[2]) { - const indexContent = iteratorMatch[2].trim(); - if (indexContent) { - result.index = createAliasExpression( - indexContent, - exp.indexOf( - indexContent, - result.key ? keyOffset + keyContent.length : trimmedOffset + valueContent.length - ), - true - ); - } - } - } - if (valueContent) { - result.value = createAliasExpression(valueContent, trimmedOffset, true); - } - return result; - } - function getSlice(start, end) { - return currentInput.slice(start, end); - } - function endOpenTag(end) { - if (tokenizer$2.inSFCRoot) { - currentOpenTag.innerLoc = getLoc(end + 1, end + 1); - } - addNode(currentOpenTag); - const { tag, ns } = currentOpenTag; - if (ns === 0 && currentOptions.isPreTag(tag)) { - inPre++; - } - if (currentOptions.isVoidTag(tag)) { - onCloseTag(currentOpenTag, end); - } else { - stack.unshift(currentOpenTag); - if (ns === 1 || ns === 2) { - tokenizer$2.inXML = true; - } - } - currentOpenTag = null; - } - function onText(content, start, end) { - const parent = stack[0] || currentRoot; - const lastNode = parent.children[parent.children.length - 1]; - if ((lastNode == null ? void 0 : lastNode.type) === 2) { - lastNode.content += content; - setLocEnd(lastNode.loc, end); - } else { - parent.children.push({ - type: 2, - content, - loc: getLoc(start, end) - }); - } - } - function onCloseTag(el, end, isImplied = false) { - if (isImplied) { - setLocEnd(el.loc, backTrack(end, 60)); - } else { - setLocEnd(el.loc, end + 1); - } - if (tokenizer$2.inSFCRoot) { - if (el.children.length) { - el.innerLoc.end = extend({}, el.children[el.children.length - 1].loc.end); - } else { - el.innerLoc.end = extend({}, el.innerLoc.start); - } - el.innerLoc.source = getSlice( - el.innerLoc.start.offset, - el.innerLoc.end.offset - ); - } - const { tag, ns } = el; - if (!inVPre) { - if (tag === "slot") { - el.tagType = 2; - } else if (isFragmentTemplate(el)) { - el.tagType = 3; - } else if (isComponent(el)) { - el.tagType = 1; - } - } - if (!tokenizer$2.inRCDATA) { - el.children = condenseWhitespace(el.children, el.tag); - } - if (ns === 0 && currentOptions.isPreTag(tag)) { - inPre--; - } - if (currentVPreBoundary === el) { - inVPre = tokenizer$2.inVPre = false; - currentVPreBoundary = null; - } - if (tokenizer$2.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) { - tokenizer$2.inXML = false; - } - } - function backTrack(index, c) { - let i = index; - while (currentInput.charCodeAt(i) !== c && i >= 0) - i--; - return i; - } - const specialTemplateDir = /* @__PURE__ */ new Set(["if", "else", "else-if", "for", "slot"]); - function isFragmentTemplate({ tag, props }) { - if (tag === "template") { - for (let i = 0; i < props.length; i++) { - if (props[i].type === 7 && specialTemplateDir.has(props[i].name)) { - return true; - } - } - } - return false; - } - function isComponent({ tag, props }) { - var _a; - if (currentOptions.isCustomElement(tag)) { - return false; - } - if (tag === "component" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || ((_a = currentOptions.isBuiltInComponent) == null ? void 0 : _a.call(currentOptions, tag)) || currentOptions.isNativeTag && !currentOptions.isNativeTag(tag)) { - return true; - } - for (let i = 0; i < props.length; i++) { - const p = props[i]; - if (p.type === 6) { - if (p.name === "is" && p.value) { - if (p.value.content.startsWith("vue:")) { - return true; - } - } - } - } - return false; - } - function isUpperCase(c) { - return c > 64 && c < 91; - } - const windowsNewlineRE = /\r\n/g; - function condenseWhitespace(nodes, tag) { - var _a, _b; - const shouldCondense = currentOptions.whitespace !== "preserve"; - let removedWhitespace = false; - for (let i = 0; i < nodes.length; i++) { - const node = nodes[i]; - if (node.type === 2) { - if (!inPre) { - if (isAllWhitespace(node.content)) { - const prev = (_a = nodes[i - 1]) == null ? void 0 : _a.type; - const next = (_b = nodes[i + 1]) == null ? void 0 : _b.type; - if (!prev || !next || shouldCondense && (prev === 3 && (next === 3 || next === 1) || prev === 1 && (next === 3 || next === 1 && hasNewlineChar(node.content)))) { - removedWhitespace = true; - nodes[i] = null; - } else { - node.content = " "; - } - } else if (shouldCondense) { - node.content = condense(node.content); - } - } else { - node.content = node.content.replace(windowsNewlineRE, "\n"); - } - } - } - if (inPre && tag && currentOptions.isPreTag(tag)) { - const first = nodes[0]; - if (first && first.type === 2) { - first.content = first.content.replace(/^\r?\n/, ""); - } - } - return removedWhitespace ? nodes.filter(Boolean) : nodes; - } - function isAllWhitespace(str) { - for (let i = 0; i < str.length; i++) { - if (!isWhitespace$1(str.charCodeAt(i))) { - return false; - } - } - return true; - } - function hasNewlineChar(str) { - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - if (c === 10 || c === 13) { - return true; - } - } - return false; - } - function condense(str) { - let ret = ""; - let prevCharIsWhitespace = false; - for (let i = 0; i < str.length; i++) { - if (isWhitespace$1(str.charCodeAt(i))) { - if (!prevCharIsWhitespace) { - ret += " "; - prevCharIsWhitespace = true; - } - } else { - ret += str[i]; - prevCharIsWhitespace = false; - } - } - return ret; - } - function addNode(node) { - (stack[0] || currentRoot).children.push(node); - } - function getLoc(start, end) { - return { - start: tokenizer$2.getPos(start), - // @ts-expect-error allow late attachment - end: end == null ? end : tokenizer$2.getPos(end), - // @ts-expect-error allow late attachment - source: end == null ? end : getSlice(start, end) - }; - } - function setLocEnd(loc, end) { - loc.end = tokenizer$2.getPos(end); - loc.source = getSlice(loc.start.offset, end); - } - function dirToAttr(dir) { - const attr = { - type: 6, - name: dir.rawName, - nameLoc: getLoc( - dir.loc.start.offset, - dir.loc.start.offset + dir.rawName.length - ), - value: void 0, - loc: dir.loc - }; - if (dir.exp) { - const loc = dir.exp.loc; - if (loc.end.offset < dir.loc.end.offset) { - loc.start.offset--; - loc.start.column--; - loc.end.offset++; - loc.end.column++; - } - attr.value = { - type: 2, - content: dir.exp.content, - loc - }; - } - return attr; - } - function createExp(content, isStatic = false, loc, constType = 0, parseMode = 0 /* Normal */) { - const exp = createSimpleExpression(content, isStatic, loc, constType); - if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 /* Skip */ && content.trim()) { - if (isSimpleIdentifier(content)) { - exp.ast = null; - return exp; - } - try { - const plugins = currentOptions.expressionPlugins; - const options = { - plugins: plugins ? [...plugins, "typescript"] : ["typescript"] - }; - if (parseMode === 2 /* Statements */) { - exp.ast = parse_1$1(` ${content} `, options).program; - } else if (parseMode === 1 /* Params */) { - exp.ast = parseExpression_1(`(${content})=>{}`, options); - } else { - exp.ast = parseExpression_1(`(${content})`, options); - } - } catch (e) { - exp.ast = false; - emitError(45, loc.start.offset, e.message); - } - } - return exp; - } - function emitError(code, index, message) { - currentOptions.onError( - createCompilerError(code, getLoc(index, index), void 0, message) - ); - } - function reset() { - tokenizer$2.reset(); - currentOpenTag = null; - currentProp = null; - currentAttrValue = ""; - currentAttrStartIndex = -1; - currentAttrEndIndex = -1; - stack.length = 0; - } - function baseParse(input, options) { - reset(); - currentInput = input; - currentOptions = extend({}, defaultParserOptions); - if (options) { - let key; - for (key in options) { - if (options[key] != null) { - currentOptions[key] = options[key]; - } - } - } - { - if (currentOptions.decodeEntities) { - console.warn( - `[@vue/compiler-core] decodeEntities option is passed but will be ignored in non-browser builds.` - ); - } - } - tokenizer$2.mode = currentOptions.parseMode === "html" ? 1 : currentOptions.parseMode === "sfc" ? 2 : 0; - tokenizer$2.inXML = currentOptions.ns === 1 || currentOptions.ns === 2; - const delimiters = options == null ? void 0 : options.delimiters; - if (delimiters) { - tokenizer$2.delimiterOpen = toCharCodes(delimiters[0]); - tokenizer$2.delimiterClose = toCharCodes(delimiters[1]); - } - const root = currentRoot = createRoot([], input); - tokenizer$2.parse(currentInput); - root.loc = getLoc(0, input.length); - root.children = condenseWhitespace(root.children); - currentRoot = null; - return root; - } - - function hoistStatic(root, context) { - walk$1( - root, - context, - // Root node is unfortunately non-hoistable due to potential parent - // fallthrough attributes. - isSingleElementRoot(root, root.children[0]) - ); - } - function isSingleElementRoot(root, child) { - const { children } = root; - return children.length === 1 && child.type === 1 && !isSlotOutlet(child); - } - function walk$1(node, context, doNotHoistNode = false) { - const { children } = node; - const originalCount = children.length; - let hoistedCount = 0; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (child.type === 1 && child.tagType === 0) { - const constantType = doNotHoistNode ? 0 : getConstantType(child, context); - if (constantType > 0) { - if (constantType >= 2) { - child.codegenNode.patchFlag = -1 + (` /* HOISTED */`); - child.codegenNode = context.hoist(child.codegenNode); - hoistedCount++; - continue; - } - } else { - const codegenNode = child.codegenNode; - if (codegenNode.type === 13) { - const flag = getPatchFlag(codegenNode); - if ((!flag || flag === 512 || flag === 1) && getGeneratedPropsConstantType(child, context) >= 2) { - const props = getNodeProps(child); - if (props) { - codegenNode.props = context.hoist(props); - } - } - if (codegenNode.dynamicProps) { - codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps); - } - } - } - } - if (child.type === 1) { - const isComponent = child.tagType === 1; - if (isComponent) { - context.scopes.vSlot++; - } - walk$1(child, context); - if (isComponent) { - context.scopes.vSlot--; - } - } else if (child.type === 11) { - walk$1(child, context, child.children.length === 1); - } else if (child.type === 9) { - for (let i2 = 0; i2 < child.branches.length; i2++) { - walk$1( - child.branches[i2], - context, - child.branches[i2].children.length === 1 - ); - } - } - } - if (hoistedCount && context.transformHoist) { - context.transformHoist(children, context, node); - } - if (hoistedCount && hoistedCount === originalCount && node.type === 1 && node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && isArray$3(node.codegenNode.children)) { - const hoisted = context.hoist( - createArrayExpression(node.codegenNode.children) - ); - if (context.hmr) { - hoisted.content = `[...${hoisted.content}]`; - } - node.codegenNode.children = hoisted; - } - } - function getConstantType(node, context) { - const { constantCache } = context; - switch (node.type) { - case 1: - if (node.tagType !== 0) { - return 0; - } - const cached = constantCache.get(node); - if (cached !== void 0) { - return cached; - } - const codegenNode = node.codegenNode; - if (codegenNode.type !== 13) { - return 0; - } - if (codegenNode.isBlock && node.tag !== "svg" && node.tag !== "foreignObject") { - return 0; - } - const flag = getPatchFlag(codegenNode); - if (!flag) { - let returnType2 = 3; - const generatedPropsType = getGeneratedPropsConstantType(node, context); - if (generatedPropsType === 0) { - constantCache.set(node, 0); - return 0; - } - if (generatedPropsType < returnType2) { - returnType2 = generatedPropsType; - } - for (let i = 0; i < node.children.length; i++) { - const childType = getConstantType(node.children[i], context); - if (childType === 0) { - constantCache.set(node, 0); - return 0; - } - if (childType < returnType2) { - returnType2 = childType; - } - } - if (returnType2 > 1) { - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i]; - if (p.type === 7 && p.name === "bind" && p.exp) { - const expType = getConstantType(p.exp, context); - if (expType === 0) { - constantCache.set(node, 0); - return 0; - } - if (expType < returnType2) { - returnType2 = expType; - } - } - } - } - if (codegenNode.isBlock) { - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i]; - if (p.type === 7) { - constantCache.set(node, 0); - return 0; - } - } - context.removeHelper(OPEN_BLOCK); - context.removeHelper( - getVNodeBlockHelper(context.inSSR, codegenNode.isComponent) - ); - codegenNode.isBlock = false; - context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent)); - } - constantCache.set(node, returnType2); - return returnType2; - } else { - constantCache.set(node, 0); - return 0; - } - case 2: - case 3: - return 3; - case 9: - case 11: - case 10: - return 0; - case 5: - case 12: - return getConstantType(node.content, context); - case 4: - return node.constType; - case 8: - let returnType = 3; - for (let i = 0; i < node.children.length; i++) { - const child = node.children[i]; - if (isString$2(child) || isSymbol$1(child)) { - continue; - } - const childType = getConstantType(child, context); - if (childType === 0) { - return 0; - } else if (childType < returnType) { - returnType = childType; - } - } - return returnType; - default: - return 0; - } - } - const allowHoistedHelperSet = /* @__PURE__ */ new Set([ - NORMALIZE_CLASS, - NORMALIZE_STYLE, - NORMALIZE_PROPS, - GUARD_REACTIVE_PROPS - ]); - function getConstantTypeOfHelperCall(value, context) { - if (value.type === 14 && !isString$2(value.callee) && allowHoistedHelperSet.has(value.callee)) { - const arg = value.arguments[0]; - if (arg.type === 4) { - return getConstantType(arg, context); - } else if (arg.type === 14) { - return getConstantTypeOfHelperCall(arg, context); - } - } - return 0; - } - function getGeneratedPropsConstantType(node, context) { - let returnType = 3; - const props = getNodeProps(node); - if (props && props.type === 15) { - const { properties } = props; - for (let i = 0; i < properties.length; i++) { - const { key, value } = properties[i]; - const keyType = getConstantType(key, context); - if (keyType === 0) { - return keyType; - } - if (keyType < returnType) { - returnType = keyType; - } - let valueType; - if (value.type === 4) { - valueType = getConstantType(value, context); - } else if (value.type === 14) { - valueType = getConstantTypeOfHelperCall(value, context); - } else { - valueType = 0; - } - if (valueType === 0) { - return valueType; - } - if (valueType < returnType) { - returnType = valueType; - } - } - } - return returnType; - } - function getNodeProps(node) { - const codegenNode = node.codegenNode; - if (codegenNode.type === 13) { - return codegenNode.props; - } - } - function getPatchFlag(node) { - const flag = node.patchFlag; - return flag ? parseInt(flag, 10) : void 0; - } - - function createTransformContext(root, { - filename = "", - prefixIdentifiers = false, - hoistStatic: hoistStatic2 = false, - hmr = false, - cacheHandlers = false, - nodeTransforms = [], - directiveTransforms = {}, - transformHoist = null, - isBuiltInComponent = NOOP, - isCustomElement = NOOP, - expressionPlugins = [], - scopeId = null, - slotted = true, - ssr = false, - inSSR = false, - ssrCssVars = ``, - bindingMetadata = EMPTY_OBJ, - inline = false, - isTS = false, - onError = defaultOnError, - onWarn = defaultOnWarn, - compatConfig - }) { - const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/); - const context = { - // options - filename, - selfName: nameMatch && capitalize$1(camelize(nameMatch[1])), - prefixIdentifiers, - hoistStatic: hoistStatic2, - hmr, - cacheHandlers, - nodeTransforms, - directiveTransforms, - transformHoist, - isBuiltInComponent, - isCustomElement, - expressionPlugins, - scopeId, - slotted, - ssr, - inSSR, - ssrCssVars, - bindingMetadata, - inline, - isTS, - onError, - onWarn, - compatConfig, - // state - root, - helpers: /* @__PURE__ */ new Map(), - components: /* @__PURE__ */ new Set(), - directives: /* @__PURE__ */ new Set(), - hoists: [], - imports: [], - constantCache: /* @__PURE__ */ new WeakMap(), - temps: 0, - cached: 0, - identifiers: /* @__PURE__ */ Object.create(null), - scopes: { - vFor: 0, - vSlot: 0, - vPre: 0, - vOnce: 0 - }, - parent: null, - currentNode: root, - childIndex: 0, - inVOnce: false, - // methods - helper(name) { - const count = context.helpers.get(name) || 0; - context.helpers.set(name, count + 1); - return name; - }, - removeHelper(name) { - const count = context.helpers.get(name); - if (count) { - const currentCount = count - 1; - if (!currentCount) { - context.helpers.delete(name); - } else { - context.helpers.set(name, currentCount); - } - } - }, - helperString(name) { - return `_${helperNameMap[context.helper(name)]}`; - }, - replaceNode(node) { - { - if (!context.currentNode) { - throw new Error(`Node being replaced is already removed.`); - } - if (!context.parent) { - throw new Error(`Cannot replace root node.`); - } - } - context.parent.children[context.childIndex] = context.currentNode = node; - }, - removeNode(node) { - if (!context.parent) { - throw new Error(`Cannot remove root node.`); - } - const list = context.parent.children; - const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1; - if (removalIndex < 0) { - throw new Error(`node being removed is not a child of current parent`); - } - if (!node || node === context.currentNode) { - context.currentNode = null; - context.onNodeRemoved(); - } else { - if (context.childIndex > removalIndex) { - context.childIndex--; - context.onNodeRemoved(); - } - } - context.parent.children.splice(removalIndex, 1); - }, - onNodeRemoved: NOOP, - addIdentifiers(exp) { - { - if (isString$2(exp)) { - addId(exp); - } else if (exp.identifiers) { - exp.identifiers.forEach(addId); - } else if (exp.type === 4) { - addId(exp.content); - } - } - }, - removeIdentifiers(exp) { - { - if (isString$2(exp)) { - removeId(exp); - } else if (exp.identifiers) { - exp.identifiers.forEach(removeId); - } else if (exp.type === 4) { - removeId(exp.content); - } - } - }, - hoist(exp) { - if (isString$2(exp)) - exp = createSimpleExpression(exp); - context.hoists.push(exp); - const identifier = createSimpleExpression( - `_hoisted_${context.hoists.length}`, - false, - exp.loc, - 2 - ); - identifier.hoisted = exp; - return identifier; - }, - cache(exp, isVNode = false) { - return createCacheExpression(context.cached++, exp, isVNode); - } - }; - function addId(id) { - const { identifiers } = context; - if (identifiers[id] === void 0) { - identifiers[id] = 0; - } - identifiers[id]++; - } - function removeId(id) { - context.identifiers[id]--; - } - return context; - } - function transform(root, options) { - const context = createTransformContext(root, options); - traverseNode(root, context); - if (options.hoistStatic) { - hoistStatic(root, context); - } - if (!options.ssr) { - createRootCodegen(root, context); - } - root.helpers = /* @__PURE__ */ new Set([...context.helpers.keys()]); - root.components = [...context.components]; - root.directives = [...context.directives]; - root.imports = context.imports; - root.hoists = context.hoists; - root.temps = context.temps; - root.cached = context.cached; - root.transformed = true; - } - function createRootCodegen(root, context) { - const { helper } = context; - const { children } = root; - if (children.length === 1) { - const child = children[0]; - if (isSingleElementRoot(root, child) && child.codegenNode) { - const codegenNode = child.codegenNode; - if (codegenNode.type === 13) { - convertToBlock(codegenNode, context); - } - root.codegenNode = codegenNode; - } else { - root.codegenNode = child; - } - } else if (children.length > 1) { - let patchFlag = 64; - let patchFlagText = PatchFlagNames[64]; - if (children.filter((c) => c.type !== 3).length === 1) { - patchFlag |= 2048; - patchFlagText += `, ${PatchFlagNames[2048]}`; - } - root.codegenNode = createVNodeCall( - context, - helper(FRAGMENT), - void 0, - root.children, - patchFlag + (` /* ${patchFlagText} */`), - void 0, - void 0, - true, - void 0, - false - ); - } else; - } - function traverseChildren(parent, context) { - let i = 0; - const nodeRemoved = () => { - i--; - }; - for (; i < parent.children.length; i++) { - const child = parent.children[i]; - if (isString$2(child)) - continue; - context.parent = parent; - context.childIndex = i; - context.onNodeRemoved = nodeRemoved; - traverseNode(child, context); - } - } - function traverseNode(node, context) { - context.currentNode = node; - const { nodeTransforms } = context; - const exitFns = []; - for (let i2 = 0; i2 < nodeTransforms.length; i2++) { - const onExit = nodeTransforms[i2](node, context); - if (onExit) { - if (isArray$3(onExit)) { - exitFns.push(...onExit); - } else { - exitFns.push(onExit); - } - } - if (!context.currentNode) { - return; - } else { - node = context.currentNode; - } - } - switch (node.type) { - case 3: - if (!context.ssr) { - context.helper(CREATE_COMMENT); - } - break; - case 5: - if (!context.ssr) { - context.helper(TO_DISPLAY_STRING); - } - break; - case 9: - for (let i2 = 0; i2 < node.branches.length; i2++) { - traverseNode(node.branches[i2], context); - } - break; - case 10: - case 11: - case 1: - case 0: - traverseChildren(node, context); - break; - } - context.currentNode = node; - let i = exitFns.length; - while (i--) { - exitFns[i](); - } - } - function createStructuralDirectiveTransform(name, fn) { - const matches = isString$2(name) ? (n) => n === name : (n) => name.test(n); - return (node, context) => { - if (node.type === 1) { - const { props } = node; - if (node.tagType === 3 && props.some(isVSlot)) { - return; - } - const exitFns = []; - for (let i = 0; i < props.length; i++) { - const prop = props[i]; - if (prop.type === 7 && matches(prop.name)) { - props.splice(i, 1); - i--; - const onExit = fn(node, prop, context); - if (onExit) - exitFns.push(onExit); - } - } - return exitFns; - } - }; - } - - var sourceMap$2 = {}; - - var sourceMapGenerator$1 = {}; - - var base64Vlq$1 = {}; - - var base64$3 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var intToCharMap$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - - /** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ - base64$3.encode = function (number) { - if (0 <= number && number < intToCharMap$1.length) { - return intToCharMap$1[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); - }; - - /** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ - base64$3.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; - }; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - var base64$2 = base64$3; - - // A single base 64 digit can contain 6 bits of data. For the base 64 variable - // length quantities we use in the source map spec, the first bit is the sign, - // the next four bits are the actual value, and the 6th bit is the - // continuation bit. The continuation bit tells us whether there are more - // digits in this value following this digit. - // - // Continuation - // | Sign - // | | - // V V - // 101011 - - var VLQ_BASE_SHIFT$1 = 5; - - // binary: 100000 - var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1; - - // binary: 011111 - var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1; - - // binary: 100000 - var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1; - - /** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ - function toVLQSigned$1(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; - } - - /** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ - function fromVLQSigned$1(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; - } - - /** - * Returns the base 64 VLQ encoded value. - */ - base64Vlq$1.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned$1(aValue); - - do { - digit = vlq & VLQ_BASE_MASK$1; - vlq >>>= VLQ_BASE_SHIFT$1; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT$1; - } - encoded += base64$2.encode(digit); - } while (vlq > 0); - - return encoded; - }; - - /** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ - base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64$2.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT$1); - digit &= VLQ_BASE_MASK$1; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT$1; - } while (continuation); - - aOutParam.value = fromVLQSigned$1(result); - aOutParam.rest = aIndex; - }; - - var util$c = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - (function (exports) { - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - /** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ - function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } - } - exports.getArg = getArg; - - var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; - var dataUrlRegexp = /^data:.+\,.+$/; - - function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; - } - exports.urlParse = urlParse; - - function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port; - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; - } - exports.urlGenerate = urlGenerate; - - var MAX_CACHED_INPUTS = 32; - - /** - * Takes some function `f(input) -> result` and returns a memoized version of - * `f`. - * - * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The - * memoization is a dumb-simple, linear least-recently-used cache. - */ - function lruMemoize(f) { - var cache = []; - - return function (input) { - for (var i = 0; i < cache.length; i++) { - if (cache[i].input === input) { - var temp = cache[0]; - cache[0] = cache[i]; - cache[i] = temp; - return cache[0].result; - } - } - - var result = f(input); - - cache.unshift({ - input, - result, - }); - - if (cache.length > MAX_CACHED_INPUTS) { - cache.pop(); - } - - return result; - }; - } - - /** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '<dir>/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ - var normalize = lruMemoize(function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - // Split the path into parts between `/` characters. This is much faster than - // using `.split(/\/+/g)`. - var parts = []; - var start = 0; - var i = 0; - while (true) { - start = i; - i = path.indexOf("/", start); - if (i === -1) { - parts.push(path.slice(start)); - break; - } else { - parts.push(path.slice(start, i)); - while (i < path.length && path[i] === "/") { - i++; - } - } - } - - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; - }); - exports.normalize = normalize; - - /** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ - function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; - } - exports.join = join; - - exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || urlRegexp.test(aPath); - }; - - /** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ - function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); - } - exports.relative = relative; - - var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); - }()); - - function identity(s) { - return s; - } - - /** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ - function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; - } - exports.toSetString = supportsNullProto ? identity : toSetString; - - function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; - } - exports.fromSetString = supportsNullProto ? identity : fromSetString; - - function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; - } - - /** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ - function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByOriginalPositions = compareByOriginalPositions; - - function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { - var cmp; - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; - - /** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ - function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - - function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; - - function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 === null) { - return 1; // aStr2 !== null - } - - if (aStr2 === null) { - return -1; // aStr1 !== null - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; - } - - /** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ - function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - - /** - * Strip any JSON XSSI avoidance prefix from the string (as documented - * in the source maps specification), and then parse the string as - * JSON. - */ - function parseSourceMapInput(str) { - return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); - } - exports.parseSourceMapInput = parseSourceMapInput; - - /** - * Compute the URL of a source given the the source root, the source's - * URL, and the source map's URL. - */ - function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { - sourceURL = sourceURL || ''; - - if (sourceRoot) { - // This follows what Chrome does. - if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { - sourceRoot += '/'; - } - // The spec says: - // Line 4: An optional source root, useful for relocating source - // files on a server or removing repeated values in the - // “sources” entry. This value is prepended to the individual - // entries in the “source” field. - sourceURL = sourceRoot + sourceURL; - } - - // Historically, SourceMapConsumer did not take the sourceMapURL as - // a parameter. This mode is still somewhat supported, which is why - // this code block is conditional. However, it's preferable to pass - // the source map URL to SourceMapConsumer, so that this function - // can implement the source URL resolution algorithm as outlined in - // the spec. This block is basically the equivalent of: - // new URL(sourceURL, sourceMapURL).toString() - // ... except it avoids using URL, which wasn't available in the - // older releases of node still supported by this library. - // - // The spec says: - // If the sources are not absolute URLs after prepending of the - // “sourceRoot”, the sources are resolved relative to the - // SourceMap (like resolving script src in a html document). - if (sourceMapURL) { - var parsed = urlParse(sourceMapURL); - if (!parsed) { - throw new Error("sourceMapURL could not be parsed"); - } - if (parsed.path) { - // Strip the last path component, but keep the "/". - var index = parsed.path.lastIndexOf('/'); - if (index >= 0) { - parsed.path = parsed.path.substring(0, index + 1); - } - } - sourceURL = join(urlGenerate(parsed), sourceURL); - } - - return normalize(sourceURL); - } - exports.computeSourceURL = computeSourceURL; - }(util$c)); - - var arraySet$1 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util$b = util$c; - var has$1 = Object.prototype.hasOwnProperty; - var hasNativeMap$1 = typeof Map !== "undefined"; - - /** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ - function ArraySet$5() { - this._array = []; - this._set = hasNativeMap$1 ? new Map() : Object.create(null); - } - - /** - * Static method for creating ArraySet instances from an existing array. - */ - ArraySet$5.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet$5(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; - }; - - /** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ - ArraySet$5.prototype.size = function ArraySet_size() { - return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length; - }; - - /** - * Add the given string to this set. - * - * @param String aStr - */ - ArraySet$5.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap$1 ? aStr : util$b.toSetString(aStr); - var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$1.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap$1) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; - } - } - }; - - /** - * Is the given string a member of this set? - * - * @param String aStr - */ - ArraySet$5.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap$1) { - return this._set.has(aStr); - } else { - var sStr = util$b.toSetString(aStr); - return has$1.call(this._set, sStr); - } - }; - - /** - * What is the index of the given string in the array? - * - * @param String aStr - */ - ArraySet$5.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap$1) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util$b.toSetString(aStr); - if (has$1.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); - }; - - /** - * What is the element at the given index? - * - * @param Number aIdx - */ - ArraySet$5.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); - }; - - /** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ - ArraySet$5.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); - }; - - arraySet$1.ArraySet = ArraySet$5; - - var mappingList$1 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util$a = util$c; - - /** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ - function generatedPositionAfter$1(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util$a.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; - } - - /** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ - function MappingList$3() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = { generatedLine: -1, generatedColumn: 0 }; - } - - /** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ - MappingList$3.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - - /** - * Add the given source mapping. - * - * @param Object aMapping - */ - MappingList$3.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter$1(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } - }; - - /** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ - MappingList$3.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util$a.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; - }; - - mappingList$1.MappingList = MappingList$3; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var base64VLQ$3 = base64Vlq$1; - var util$9 = util$c; - var ArraySet$4 = arraySet$1.ArraySet; - var MappingList$2 = mappingList$1.MappingList; - - /** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ - function SourceMapGenerator$8(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util$9.getArg(aArgs, 'file', null); - this._sourceRoot = util$9.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util$9.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet$4(); - this._names = new ArraySet$4(); - this._mappings = new MappingList$2(); - this._sourcesContents = null; - } - - SourceMapGenerator$8.prototype._version = 3; - - /** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ - SourceMapGenerator$8.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator$8({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util$9.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var sourceRelative = sourceFile; - if (sourceRoot !== null) { - sourceRelative = util$9.relative(sourceRoot, sourceFile); - } - - if (!generator._sources.has(sourceRelative)) { - generator._sources.add(sourceRelative); - } - - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - - /** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ - SourceMapGenerator$8.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util$9.getArg(aArgs, 'generated'); - var original = util$9.getArg(aArgs, 'original', null); - var source = util$9.getArg(aArgs, 'source', null); - var name = util$9.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - - /** - * Set the source content for a source file. - */ - SourceMapGenerator$8.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util$9.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util$9.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util$9.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - - /** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ - SourceMapGenerator$8.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util$9.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet$4(); - var newNames = new ArraySet$4(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util$9.join(aSourceMapPath, mapping.source); - } - if (sourceRoot != null) { - mapping.source = util$9.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util$9.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util$9.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - - /** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ - SourceMapGenerator$8.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - - /** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ - SourceMapGenerator$8.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = ''; - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util$9.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ$3.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ$3.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ$3.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ$3.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ$3.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - - SourceMapGenerator$8.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util$9.relative(aSourceRoot, source); - } - var key = util$9.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - - /** - * Externalize the source map. - */ - SourceMapGenerator$8.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - - /** - * Render the source map being generated to a string. - */ - SourceMapGenerator$8.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - - sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator$8; - - var sourceMapConsumer$1 = {}; - - var binarySearch$3 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - (function (exports) { - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - exports.GREATEST_LOWER_BOUND = 1; - exports.LEAST_UPPER_BOUND = 2; - - /** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ - function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } - } - - /** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ - exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; - }; - }(binarySearch$3)); - - var quickSort$3 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - // It turns out that some (most?) JavaScript engines don't self-host - // `Array.prototype.sort`. This makes sense because C++ will likely remain - // faster than JS when doing raw CPU-intensive sorting. However, when using a - // custom comparator function, calling back and forth between the VM's C++ and - // JIT'd JS is rather slow *and* loses JIT type information, resulting in - // worse generated code for the comparator function than would be optimal. In - // fact, when sorting with a comparator, these costs outweigh the benefits of - // sorting in C++. By using our own JS-implemented Quick Sort (below), we get - // a ~3500ms mean speed-up in `bench/bench.html`. - - function SortTemplate(comparator) { - - /** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ - function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; - } - - /** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ - function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); - } - - /** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ - function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot, false) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } - } - - return doQuickSort; - } - - function cloneSort(comparator) { - let template = SortTemplate.toString(); - let templateFn = new Function(`return ${template}`)(); - return templateFn(comparator); - } - - /** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ - - let sortCache = new WeakMap(); - quickSort$3.quickSort = function (ary, comparator, start = 0) { - let doQuickSort = sortCache.get(comparator); - if (doQuickSort === void 0) { - doQuickSort = cloneSort(comparator); - sortCache.set(comparator, doQuickSort); - } - doQuickSort(ary, comparator, start, ary.length - 1); - }; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util$8 = util$c; - var binarySearch$2 = binarySearch$3; - var ArraySet$3 = arraySet$1.ArraySet; - var base64VLQ$2 = base64Vlq$1; - var quickSort$2 = quickSort$3.quickSort; - - function SourceMapConsumer$6(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$8.parseSourceMapInput(aSourceMap); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL) - : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL); - } - - SourceMapConsumer$6.fromSourceMap = function (aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL); - }; - - /** - * The version of the source mapping spec that we are consuming. - */ - SourceMapConsumer$6.prototype._version = 3; - - // `__generatedMappings` and `__originalMappings` are arrays that hold the - // parsed mapping coordinates from the source map's "mappings" attribute. They - // are lazily instantiated, accessed via the `_generatedMappings` and - // `_originalMappings` getters respectively, and we only parse the mappings - // and create these arrays once queried for a source location. We jump through - // these hoops because there can be many thousands of mappings, and parsing - // them is expensive, so we only want to do it if we must. - // - // Each object in the arrays is of the form: - // - // { - // generatedLine: The line number in the generated code, - // generatedColumn: The column number in the generated code, - // source: The path to the original source file that generated this - // chunk of code, - // originalLine: The line number in the original source that - // corresponds to this chunk of generated code, - // originalColumn: The column number in the original source that - // corresponds to this chunk of generated code, - // name: The name of the original symbol which generated this chunk of - // code. - // } - // - // All properties except for `generatedLine` and `generatedColumn` can be - // `null`. - // - // `_generatedMappings` is ordered by the generated positions. - // - // `_originalMappings` is ordered by the original positions. - - SourceMapConsumer$6.prototype.__generatedMappings = null; - Object.defineProperty(SourceMapConsumer$6.prototype, '_generatedMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } - }); - - SourceMapConsumer$6.prototype.__originalMappings = null; - Object.defineProperty(SourceMapConsumer$6.prototype, '_originalMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } - }); - - SourceMapConsumer$6.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - SourceMapConsumer$6.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - - SourceMapConsumer$6.GENERATED_ORDER = 1; - SourceMapConsumer$6.ORIGINAL_ORDER = 2; - - SourceMapConsumer$6.GREATEST_LOWER_BOUND = 1; - SourceMapConsumer$6.LEAST_UPPER_BOUND = 2; - - /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ - SourceMapConsumer$6.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer$6.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer$6.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer$6.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - var boundCallback = aCallback.bind(context); - var names = this._names; - var sources = this._sources; - var sourceMapURL = this._sourceMapURL; - - for (var i = 0, n = mappings.length; i < n; i++) { - var mapping = mappings[i]; - var source = mapping.source === null ? null : sources.at(mapping.source); - source = util$8.computeSourceURL(sourceRoot, source, sourceMapURL); - boundCallback({ - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : names.at(mapping.name) - }); - } - }; - - /** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number is 1-based. - * - column: Optional. the column number in the original source. - * The column number is 0-based. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - SourceMapConsumer$6.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util$8.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util$8.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util$8.getArg(aArgs, 'column', 0) - }; - - needle.source = this._findSourceIndex(needle.source); - if (needle.source < 0) { - return []; - } - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util$8.compareByOriginalPositions, - binarySearch$2.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util$8.getArg(mapping, 'generatedLine', null), - column: util$8.getArg(mapping, 'generatedColumn', null), - lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util$8.getArg(mapping, 'generatedLine', null), - column: util$8.getArg(mapping, 'generatedColumn', null), - lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - - sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer$6; - - /** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The first parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ - function BasicSourceMapConsumer$1(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$8.parseSourceMapInput(aSourceMap); - } - - var version = util$8.getArg(sourceMap, 'version'); - var sources = util$8.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util$8.getArg(sourceMap, 'names', []); - var sourceRoot = util$8.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util$8.getArg(sourceMap, 'sourcesContent', null); - var mappings = util$8.getArg(sourceMap, 'mappings'); - var file = util$8.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - if (sourceRoot) { - sourceRoot = util$8.normalize(sourceRoot); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util$8.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util$8.isAbsolute(sourceRoot) && util$8.isAbsolute(source) - ? util$8.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet$3.fromArray(names.map(String), true); - this._sources = ArraySet$3.fromArray(sources, true); - - this._absoluteSources = this._sources.toArray().map(function (s) { - return util$8.computeSourceURL(sourceRoot, s, aSourceMapURL); - }); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this._sourceMapURL = aSourceMapURL; - this.file = file; - } - - BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype); - BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$6; - - /** - * Utility function to find the index of a source. Returns -1 if not - * found. - */ - BasicSourceMapConsumer$1.prototype._findSourceIndex = function (aSource) { - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util$8.relative(this.sourceRoot, relativeSource); - } - - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - - // Maybe aSource is an absolute URL as returned by |sources|. In - // this case we can't simply undo the transform. - var i; - for (i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } - - return -1; - }; - - /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @param String aSourceMapURL - * The URL at which the source map can be found (optional) - * @returns BasicSourceMapConsumer - */ - BasicSourceMapConsumer$1.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { - var smc = Object.create(BasicSourceMapConsumer$1.prototype); - - var names = smc._names = ArraySet$3.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet$3.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - smc._sourceMapURL = aSourceMapURL; - smc._absoluteSources = smc._sources.toArray().map(function (s) { - return util$8.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); - }); - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping$1; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort$2(smc.__originalMappings, util$8.compareByOriginalPositions); - - return smc; - }; - - /** - * The version of the source mapping spec that we are consuming. - */ - BasicSourceMapConsumer$1.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(BasicSourceMapConsumer$1.prototype, 'sources', { - get: function () { - return this._absoluteSources.slice(); - } - }); - - /** - * Provide the JIT with a nice shape / hidden class. - */ - function Mapping$1() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; - } - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - - const compareGenerated = util$8.compareByGeneratedPositionsDeflatedNoLine; - function sortGenerated(array, start) { - let l = array.length; - let n = array.length - start; - if (n <= 1) { - return; - } else if (n == 2) { - let a = array[start]; - let b = array[start + 1]; - if (compareGenerated(a, b) > 0) { - array[start] = b; - array[start + 1] = a; - } - } else if (n < 20) { - for (let i = start; i < l; i++) { - for (let j = i; j > start; j--) { - let a = array[j - 1]; - let b = array[j]; - if (compareGenerated(a, b) <= 0) { - break; - } - array[j - 1] = b; - array[j] = a; - } - } - } else { - quickSort$2(array, compareGenerated, start); - } - } - BasicSourceMapConsumer$1.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, segment, end, value; - - let subarrayStart = 0; - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - - sortGenerated(generatedMappings, subarrayStart); - subarrayStart = generatedMappings.length; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping$1(); - mapping.generatedLine = generatedLine; - - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - aStr.slice(index, end); - - segment = []; - while (index < end) { - base64VLQ$2.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - let currentSource = mapping.source; - while (originalMappings.length <= currentSource) { - originalMappings.push(null); - } - if (originalMappings[currentSource] === null) { - originalMappings[currentSource] = []; - } - originalMappings[currentSource].push(mapping); - } - } - } - - sortGenerated(generatedMappings, subarrayStart); - this.__generatedMappings = generatedMappings; - - for (var i = 0; i < originalMappings.length; i++) { - if (originalMappings[i] != null) { - quickSort$2(originalMappings[i], util$8.compareByOriginalPositionsNoSource); - } - } - this.__originalMappings = [].concat(...originalMappings); - }; - - /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ - BasicSourceMapConsumer$1.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch$2.search(aNeedle, aMappings, aComparator, aBias); - }; - - /** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ - BasicSourceMapConsumer$1.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ - BasicSourceMapConsumer$1.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util$8.getArg(aArgs, 'line'), - generatedColumn: util$8.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util$8.compareByGeneratedPositionsDeflated, - util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util$8.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - source = util$8.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - var name = util$8.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util$8.getArg(mapping, 'originalLine', null), - column: util$8.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - BasicSourceMapConsumer$1.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - BasicSourceMapConsumer$1.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - var index = this._findSourceIndex(aSource); - if (index >= 0) { - return this.sourcesContent[index]; - } - - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util$8.relative(this.sourceRoot, relativeSource); - } - - var url; - if (this.sourceRoot != null - && (url = util$8.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + relativeSource)) { - return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - BasicSourceMapConsumer$1.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util$8.getArg(aArgs, 'source'); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - - var needle = { - source: source, - originalLine: util$8.getArg(aArgs, 'line'), - originalColumn: util$8.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util$8.compareByOriginalPositions, - util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util$8.getArg(mapping, 'generatedLine', null), - column: util$8.getArg(mapping, 'generatedColumn', null), - lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - - sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer$1; - - /** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The first parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ - function IndexedSourceMapConsumer$1(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$8.parseSourceMapInput(aSourceMap); - } - - var version = util$8.getArg(sourceMap, 'version'); - var sections = util$8.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet$3(); - this._names = new ArraySet$3(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util$8.getArg(s, 'offset'); - var offsetLine = util$8.getArg(offset, 'line'); - var offsetColumn = util$8.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer$6(util$8.getArg(s, 'map'), aSourceMapURL) - } - }); - } - - IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype); - IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$6; - - /** - * The version of the source mapping spec that we are consuming. - */ - IndexedSourceMapConsumer$1.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(IndexedSourceMapConsumer$1.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } - }); - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ - IndexedSourceMapConsumer$1.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util$8.getArg(aArgs, 'line'), - generatedColumn: util$8.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch$2.search(needle, this._sections, - function (needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - IndexedSourceMapConsumer$1.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - IndexedSourceMapConsumer$1.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - IndexedSourceMapConsumer$1.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer._findSourceIndex(util$8.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - IndexedSourceMapConsumer$1.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - source = util$8.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = null; - if (mapping.name) { - name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - } - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort$2(this.__generatedMappings, util$8.compareByGeneratedPositionsDeflated); - quickSort$2(this.__originalMappings, util$8.compareByOriginalPositions); - }; - - sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer$1; - - var sourceNode$1 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var SourceMapGenerator$7 = sourceMapGenerator$1.SourceMapGenerator; - var util$7 = util$c; - - // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other - // operating systems these days (capturing the result). - var REGEX_NEWLINE$1 = /(\r?\n)/; - - // Newline character code for charCodeAt() comparisons - var NEWLINE_CODE$1 = 10; - - // Private symbol for identifying `SourceNode`s when multiple versions of - // the source-map library are loaded. This MUST NOT CHANGE across - // versions! - var isSourceNode$1 = "$$$isSourceNode$$$"; - - /** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ - function SourceNode$1(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode$1] = true; - if (aChunks != null) this.add(aChunks); - } - - /** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ - SourceNode$1.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode$1(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE$1); - var remainingLinesIndex = 0; - var shiftNextLine = function () { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex] || ''; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex] || ''; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util$7.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util$7.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode$1(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - - /** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode$1.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode$1] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode$1.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length - 1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode$1] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ - SourceNode$1.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode$1]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { - source: this.source, - line: this.line, - column: this.column, - name: this.name - }); - } - } - } - }; - - /** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ - SourceNode$1.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len - 1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; - }; - - /** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ - SourceNode$1.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode$1]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; - }; - - /** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ - SourceNode$1.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util$7.toSetString(aSourceFile)] = aSourceContent; - }; - - /** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ - SourceNode$1.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode$1]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util$7.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - - /** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ - SourceNode$1.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; - }; - - /** - * Returns the string representation of this source node along with a source - * map. - */ - SourceNode$1.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator$7(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if (lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE$1) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; - }; - - sourceNode$1.SourceNode = SourceNode$1; - - /* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var SourceMapGenerator$6 = sourceMap$2.SourceMapGenerator = sourceMapGenerator$1.SourceMapGenerator; - var SourceMapConsumer$5 = sourceMap$2.SourceMapConsumer = sourceMapConsumer$1.SourceMapConsumer; - sourceMap$2.SourceNode = sourceNode$1.SourceNode; - - const PURE_ANNOTATION = `/*#__PURE__*/`; - const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`; - function createCodegenContext(ast, { - mode = "function", - prefixIdentifiers = mode === "module", - sourceMap = false, - filename = `template.vue.html`, - scopeId = null, - optimizeImports = false, - runtimeGlobalName = `Vue`, - runtimeModuleName = `vue`, - ssrRuntimeModuleName = "vue/server-renderer", - ssr = false, - isTS = false, - inSSR = false - }) { - const context = { - mode, - prefixIdentifiers, - sourceMap, - filename, - scopeId, - optimizeImports, - runtimeGlobalName, - runtimeModuleName, - ssrRuntimeModuleName, - ssr, - isTS, - inSSR, - source: ast.source, - code: ``, - column: 1, - line: 1, - offset: 0, - indentLevel: 0, - pure: false, - map: void 0, - helper(key) { - return `_${helperNameMap[key]}`; - }, - push(code, newlineIndex = -2 /* None */, node) { - context.code += code; - if (context.map) { - if (node) { - let name; - if (node.type === 4 && !node.isStatic) { - const content = node.content.replace(/^_ctx\./, ""); - if (content !== node.content && isSimpleIdentifier(content)) { - name = content; - } - } - addMapping(node.loc.start, name); - } - if (newlineIndex === -3 /* Unknown */) { - advancePositionWithMutation(context, code); - } else { - context.offset += code.length; - if (newlineIndex === -2 /* None */) { - context.column += code.length; - } else { - if (newlineIndex === -1 /* End */) { - newlineIndex = code.length - 1; - } - context.line++; - context.column = code.length - newlineIndex; - } - } - if (node && node.loc !== locStub) { - addMapping(node.loc.end); - } - } - }, - indent() { - newline(++context.indentLevel); - }, - deindent(withoutNewLine = false) { - if (withoutNewLine) { - --context.indentLevel; - } else { - newline(--context.indentLevel); - } - }, - newline() { - newline(context.indentLevel); - } - }; - function newline(n) { - context.push("\n" + ` `.repeat(n), 0 /* Start */); - } - function addMapping(loc, name = null) { - const { _names, _mappings } = context.map; - if (name !== null && !_names.has(name)) - _names.add(name); - _mappings.add({ - originalLine: loc.line, - originalColumn: loc.column - 1, - // source-map column is 0 based - generatedLine: context.line, - generatedColumn: context.column - 1, - source: filename, - // @ts-expect-error it is possible to be null - name - }); - } - if (sourceMap) { - context.map = new SourceMapGenerator$6(); - context.map.setSourceContent(filename, context.source); - context.map._sources.add(filename); - } - return context; - } - function generate(ast, options = {}) { - const context = createCodegenContext(ast, options); - if (options.onContextCreated) - options.onContextCreated(context); - const { - mode, - push, - prefixIdentifiers, - indent, - deindent, - newline, - scopeId, - ssr - } = context; - const helpers = Array.from(ast.helpers); - const hasHelpers = helpers.length > 0; - const useWithBlock = !prefixIdentifiers && mode !== "module"; - const genScopeId = scopeId != null && mode === "module"; - const isSetupInlined = !!options.inline; - const preambleContext = isSetupInlined ? createCodegenContext(ast, options) : context; - if (mode === "module") { - genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined); - } else { - genFunctionPreamble(ast, preambleContext); - } - const functionName = ssr ? `ssrRender` : `render`; - const args = ssr ? ["_ctx", "_push", "_parent", "_attrs"] : ["_ctx", "_cache"]; - if (options.bindingMetadata && !options.inline) { - args.push("$props", "$setup", "$data", "$options"); - } - const signature = options.isTS ? args.map((arg) => `${arg}: any`).join(",") : args.join(", "); - if (isSetupInlined) { - push(`(${signature}) => {`); - } else { - push(`function ${functionName}(${signature}) {`); - } - indent(); - if (useWithBlock) { - push(`with (_ctx) {`); - indent(); - if (hasHelpers) { - push( - `const { ${helpers.map(aliasHelper).join(", ")} } = _Vue -`, - -1 /* End */ - ); - newline(); - } - } - if (ast.components.length) { - genAssets(ast.components, "component", context); - if (ast.directives.length || ast.temps > 0) { - newline(); - } - } - if (ast.directives.length) { - genAssets(ast.directives, "directive", context); - if (ast.temps > 0) { - newline(); - } - } - if (ast.temps > 0) { - push(`let `); - for (let i = 0; i < ast.temps; i++) { - push(`${i > 0 ? `, ` : ``}_temp${i}`); - } - } - if (ast.components.length || ast.directives.length || ast.temps) { - push(` -`, 0 /* Start */); - newline(); - } - if (!ssr) { - push(`return `); - } - if (ast.codegenNode) { - genNode(ast.codegenNode, context); - } else { - push(`null`); - } - if (useWithBlock) { - deindent(); - push(`}`); - } - deindent(); - push(`}`); - return { - ast, - code: context.code, - preamble: isSetupInlined ? preambleContext.code : ``, - map: context.map ? context.map.toJSON() : void 0 - }; - } - function genFunctionPreamble(ast, context) { - const { - ssr, - prefixIdentifiers, - push, - newline, - runtimeModuleName, - runtimeGlobalName, - ssrRuntimeModuleName - } = context; - const VueBinding = ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName; - const helpers = Array.from(ast.helpers); - if (helpers.length > 0) { - if (prefixIdentifiers) { - push( - `const { ${helpers.map(aliasHelper).join(", ")} } = ${VueBinding} -`, - -1 /* End */ - ); - } else { - push(`const _Vue = ${VueBinding} -`, -1 /* End */); - if (ast.hoists.length) { - const staticHelpers = [ - CREATE_VNODE, - CREATE_ELEMENT_VNODE, - CREATE_COMMENT, - CREATE_TEXT, - CREATE_STATIC - ].filter((helper) => helpers.includes(helper)).map(aliasHelper).join(", "); - push(`const { ${staticHelpers} } = _Vue -`, -1 /* End */); - } - } - } - if (ast.ssrHelpers && ast.ssrHelpers.length) { - push( - `const { ${ast.ssrHelpers.map(aliasHelper).join(", ")} } = require("${ssrRuntimeModuleName}") -`, - -1 /* End */ - ); - } - genHoists(ast.hoists, context); - newline(); - push(`return `); - } - function genModulePreamble(ast, context, genScopeId, inline) { - const { - push, - newline, - optimizeImports, - runtimeModuleName, - ssrRuntimeModuleName - } = context; - if (genScopeId && ast.hoists.length) { - ast.helpers.add(PUSH_SCOPE_ID); - ast.helpers.add(POP_SCOPE_ID); - } - if (ast.helpers.size) { - const helpers = Array.from(ast.helpers); - if (optimizeImports) { - push( - `import { ${helpers.map((s) => helperNameMap[s]).join(", ")} } from ${JSON.stringify(runtimeModuleName)} -`, - -1 /* End */ - ); - push( - ` -// Binding optimization for webpack code-split -const ${helpers.map((s) => `_${helperNameMap[s]} = ${helperNameMap[s]}`).join(", ")} -`, - -1 /* End */ - ); - } else { - push( - `import { ${helpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from ${JSON.stringify(runtimeModuleName)} -`, - -1 /* End */ - ); - } - } - if (ast.ssrHelpers && ast.ssrHelpers.length) { - push( - `import { ${ast.ssrHelpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from "${ssrRuntimeModuleName}" -`, - -1 /* End */ - ); - } - if (ast.imports.length) { - genImports(ast.imports, context); - newline(); - } - genHoists(ast.hoists, context); - newline(); - if (!inline) { - push(`export `); - } - } - function genAssets(assets, type, { helper, push, newline, isTS }) { - const resolver = helper( - type === "component" ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE - ); - for (let i = 0; i < assets.length; i++) { - let id = assets[i]; - const maybeSelfReference = id.endsWith("__self"); - if (maybeSelfReference) { - id = id.slice(0, -6); - } - push( - `const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}` - ); - if (i < assets.length - 1) { - newline(); - } - } - } - function genHoists(hoists, context) { - if (!hoists.length) { - return; - } - context.pure = true; - const { push, newline, helper, scopeId, mode } = context; - const genScopeId = scopeId != null && mode !== "function"; - newline(); - if (genScopeId) { - push( - `const _withScopeId = n => (${helper( - PUSH_SCOPE_ID - )}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)` - ); - newline(); - } - for (let i = 0; i < hoists.length; i++) { - const exp = hoists[i]; - if (exp) { - const needScopeIdWrapper = genScopeId && exp.type === 13; - push( - `const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}` - ); - genNode(exp, context); - if (needScopeIdWrapper) { - push(`)`); - } - newline(); - } - } - context.pure = false; - } - function genImports(importsOptions, context) { - if (!importsOptions.length) { - return; - } - importsOptions.forEach((imports) => { - context.push(`import `); - genNode(imports.exp, context); - context.push(` from '${imports.path}'`); - context.newline(); - }); - } - function isText(n) { - return isString$2(n) || n.type === 4 || n.type === 2 || n.type === 5 || n.type === 8; - } - function genNodeListAsArray(nodes, context) { - const multilines = nodes.length > 3 || nodes.some((n) => isArray$3(n) || !isText(n)); - context.push(`[`); - multilines && context.indent(); - genNodeList(nodes, context, multilines); - multilines && context.deindent(); - context.push(`]`); - } - function genNodeList(nodes, context, multilines = false, comma = true) { - const { push, newline } = context; - for (let i = 0; i < nodes.length; i++) { - const node = nodes[i]; - if (isString$2(node)) { - push(node, -3 /* Unknown */); - } else if (isArray$3(node)) { - genNodeListAsArray(node, context); - } else { - genNode(node, context); - } - if (i < nodes.length - 1) { - if (multilines) { - comma && push(","); - newline(); - } else { - comma && push(", "); - } - } - } - } - function genNode(node, context) { - if (isString$2(node)) { - context.push(node, -3 /* Unknown */); - return; - } - if (isSymbol$1(node)) { - context.push(context.helper(node)); - return; - } - switch (node.type) { - case 1: - case 9: - case 11: - assert( - node.codegenNode != null, - `Codegen node is missing for element/if/for node. Apply appropriate transforms first.` - ); - genNode(node.codegenNode, context); - break; - case 2: - genText(node, context); - break; - case 4: - genExpression(node, context); - break; - case 5: - genInterpolation(node, context); - break; - case 12: - genNode(node.codegenNode, context); - break; - case 8: - genCompoundExpression(node, context); - break; - case 3: - genComment(node, context); - break; - case 13: - genVNodeCall(node, context); - break; - case 14: - genCallExpression(node, context); - break; - case 15: - genObjectExpression(node, context); - break; - case 17: - genArrayExpression(node, context); - break; - case 18: - genFunctionExpression(node, context); - break; - case 19: - genConditionalExpression(node, context); - break; - case 20: - genCacheExpression(node, context); - break; - case 21: - genNodeList(node.body, context, true, false); - break; - case 22: - genTemplateLiteral(node, context); - break; - case 23: - genIfStatement(node, context); - break; - case 24: - genAssignmentExpression(node, context); - break; - case 25: - genSequenceExpression(node, context); - break; - case 26: - genReturnStatement(node, context); - break; - case 10: - break; - default: - { - assert(false, `unhandled codegen node type: ${node.type}`); - const exhaustiveCheck = node; - return exhaustiveCheck; - } - } - } - function genText(node, context) { - context.push(JSON.stringify(node.content), -3 /* Unknown */, node); - } - function genExpression(node, context) { - const { content, isStatic } = node; - context.push( - isStatic ? JSON.stringify(content) : content, - -3 /* Unknown */, - node - ); - } - function genInterpolation(node, context) { - const { push, helper, pure } = context; - if (pure) - push(PURE_ANNOTATION); - push(`${helper(TO_DISPLAY_STRING)}(`); - genNode(node.content, context); - push(`)`); - } - function genCompoundExpression(node, context) { - for (let i = 0; i < node.children.length; i++) { - const child = node.children[i]; - if (isString$2(child)) { - context.push(child, -3 /* Unknown */); - } else { - genNode(child, context); - } - } - } - function genExpressionAsPropertyKey(node, context) { - const { push } = context; - if (node.type === 8) { - push(`[`); - genCompoundExpression(node, context); - push(`]`); - } else if (node.isStatic) { - const text = isSimpleIdentifier(node.content) ? node.content : JSON.stringify(node.content); - push(text, -2 /* None */, node); - } else { - push(`[${node.content}]`, -3 /* Unknown */, node); - } - } - function genComment(node, context) { - const { push, helper, pure } = context; - if (pure) { - push(PURE_ANNOTATION); - } - push( - `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, - -3 /* Unknown */, - node - ); - } - function genVNodeCall(node, context) { - const { push, helper, pure } = context; - const { - tag, - props, - children, - patchFlag, - dynamicProps, - directives, - isBlock, - disableTracking, - isComponent - } = node; - if (directives) { - push(helper(WITH_DIRECTIVES) + `(`); - } - if (isBlock) { - push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `); - } - if (pure) { - push(PURE_ANNOTATION); - } - const callHelper = isBlock ? getVNodeBlockHelper(context.inSSR, isComponent) : getVNodeHelper(context.inSSR, isComponent); - push(helper(callHelper) + `(`, -2 /* None */, node); - genNodeList( - genNullableArgs([tag, props, children, patchFlag, dynamicProps]), - context - ); - push(`)`); - if (isBlock) { - push(`)`); - } - if (directives) { - push(`, `); - genNode(directives, context); - push(`)`); - } - } - function genNullableArgs(args) { - let i = args.length; - while (i--) { - if (args[i] != null) - break; - } - return args.slice(0, i + 1).map((arg) => arg || `null`); - } - function genCallExpression(node, context) { - const { push, helper, pure } = context; - const callee = isString$2(node.callee) ? node.callee : helper(node.callee); - if (pure) { - push(PURE_ANNOTATION); - } - push(callee + `(`, -2 /* None */, node); - genNodeList(node.arguments, context); - push(`)`); - } - function genObjectExpression(node, context) { - const { push, indent, deindent, newline } = context; - const { properties } = node; - if (!properties.length) { - push(`{}`, -2 /* None */, node); - return; - } - const multilines = properties.length > 1 || properties.some((p) => p.value.type !== 4); - push(multilines ? `{` : `{ `); - multilines && indent(); - for (let i = 0; i < properties.length; i++) { - const { key, value } = properties[i]; - genExpressionAsPropertyKey(key, context); - push(`: `); - genNode(value, context); - if (i < properties.length - 1) { - push(`,`); - newline(); - } - } - multilines && deindent(); - push(multilines ? `}` : ` }`); - } - function genArrayExpression(node, context) { - genNodeListAsArray(node.elements, context); - } - function genFunctionExpression(node, context) { - const { push, indent, deindent } = context; - const { params, returns, body, newline, isSlot } = node; - if (isSlot) { - push(`_${helperNameMap[WITH_CTX]}(`); - } - push(`(`, -2 /* None */, node); - if (isArray$3(params)) { - genNodeList(params, context); - } else if (params) { - genNode(params, context); - } - push(`) => `); - if (newline || body) { - push(`{`); - indent(); - } - if (returns) { - if (newline) { - push(`return `); - } - if (isArray$3(returns)) { - genNodeListAsArray(returns, context); - } else { - genNode(returns, context); - } - } else if (body) { - genNode(body, context); - } - if (newline || body) { - deindent(); - push(`}`); - } - if (isSlot) { - push(`)`); - } - } - function genConditionalExpression(node, context) { - const { test, consequent, alternate, newline: needNewline } = node; - const { push, indent, deindent, newline } = context; - if (test.type === 4) { - const needsParens = !isSimpleIdentifier(test.content); - needsParens && push(`(`); - genExpression(test, context); - needsParens && push(`)`); - } else { - push(`(`); - genNode(test, context); - push(`)`); - } - needNewline && indent(); - context.indentLevel++; - needNewline || push(` `); - push(`? `); - genNode(consequent, context); - context.indentLevel--; - needNewline && newline(); - needNewline || push(` `); - push(`: `); - const isNested = alternate.type === 19; - if (!isNested) { - context.indentLevel++; - } - genNode(alternate, context); - if (!isNested) { - context.indentLevel--; - } - needNewline && deindent( - true - /* without newline */ - ); - } - function genCacheExpression(node, context) { - const { push, helper, indent, deindent, newline } = context; - push(`_cache[${node.index}] || (`); - if (node.isVNode) { - indent(); - push(`${helper(SET_BLOCK_TRACKING)}(-1),`); - newline(); - } - push(`_cache[${node.index}] = `); - genNode(node.value, context); - if (node.isVNode) { - push(`,`); - newline(); - push(`${helper(SET_BLOCK_TRACKING)}(1),`); - newline(); - push(`_cache[${node.index}]`); - deindent(); - } - push(`)`); - } - function genTemplateLiteral(node, context) { - const { push, indent, deindent } = context; - push("`"); - const l = node.elements.length; - const multilines = l > 3; - for (let i = 0; i < l; i++) { - const e = node.elements[i]; - if (isString$2(e)) { - push(e.replace(/(`|\$|\\)/g, "\\$1"), -3 /* Unknown */); - } else { - push("${"); - if (multilines) - indent(); - genNode(e, context); - if (multilines) - deindent(); - push("}"); - } - } - push("`"); - } - function genIfStatement(node, context) { - const { push, indent, deindent } = context; - const { test, consequent, alternate } = node; - push(`if (`); - genNode(test, context); - push(`) {`); - indent(); - genNode(consequent, context); - deindent(); - push(`}`); - if (alternate) { - push(` else `); - if (alternate.type === 23) { - genIfStatement(alternate, context); - } else { - push(`{`); - indent(); - genNode(alternate, context); - deindent(); - push(`}`); - } - } - } - function genAssignmentExpression(node, context) { - genNode(node.left, context); - context.push(` = `); - genNode(node.right, context); - } - function genSequenceExpression(node, context) { - context.push(`(`); - genNodeList(node.expressions, context); - context.push(`)`); - } - function genReturnStatement({ returns }, context) { - context.push(`return `); - if (isArray$3(returns)) { - genNodeListAsArray(returns, context); - } else { - genNode(returns, context); - } - } - - const isLiteralWhitelisted = /* @__PURE__ */ makeMap("true,false,null,this"); - const constantBailRE = /\w\s*\(|\.[^\d]/; - const transformExpression = (node, context) => { - if (node.type === 5) { - node.content = processExpression( - node.content, - context - ); - } else if (node.type === 1) { - for (let i = 0; i < node.props.length; i++) { - const dir = node.props[i]; - if (dir.type === 7 && dir.name !== "for") { - const exp = dir.exp; - const arg = dir.arg; - if (exp && exp.type === 4 && !(dir.name === "on" && arg)) { - dir.exp = processExpression( - exp, - context, - // slot args must be processed as function params - dir.name === "slot" - ); - } - if (arg && arg.type === 4 && !arg.isStatic) { - dir.arg = processExpression(arg, context); - } - } - } - } - }; - function processExpression(node, context, asParams = false, asRawStatements = false, localVars = Object.create(context.identifiers)) { - if (!context.prefixIdentifiers || !node.content.trim()) { - return node; - } - const { inline, bindingMetadata } = context; - const rewriteIdentifier = (raw, parent, id) => { - const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw]; - if (inline) { - const isAssignmentLVal = parent && parent.type === "AssignmentExpression" && parent.left === id; - const isUpdateArg = parent && parent.type === "UpdateExpression" && parent.argument === id; - const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack); - const isNewExpression = parent && isInNewExpression(parentStack); - const wrapWithUnref = (raw2) => { - const wrapped = `${context.helperString(UNREF)}(${raw2})`; - return isNewExpression ? `(${wrapped})` : wrapped; - }; - if (isConst(type) || type === "setup-reactive-const" || localVars[raw]) { - return raw; - } else if (type === "setup-ref") { - return `${raw}.value`; - } else if (type === "setup-maybe-ref") { - return isAssignmentLVal || isUpdateArg || isDestructureAssignment ? `${raw}.value` : wrapWithUnref(raw); - } else if (type === "setup-let") { - if (isAssignmentLVal) { - const { right: rVal, operator } = parent; - const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1); - const rExpString = stringifyExpression( - processExpression( - createSimpleExpression(rExp, false), - context, - false, - false, - knownIds - ) - ); - return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore -` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`; - } else if (isUpdateArg) { - id.start = parent.start; - id.end = parent.end; - const { prefix: isPrefix, operator } = parent; - const prefix = isPrefix ? operator : ``; - const postfix = isPrefix ? `` : operator; - return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore -` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`; - } else if (isDestructureAssignment) { - return raw; - } else { - return wrapWithUnref(raw); - } - } else if (type === "props") { - return genPropsAccessExp(raw); - } else if (type === "props-aliased") { - return genPropsAccessExp(bindingMetadata.__propsAliases[raw]); - } - } else { - if (type && type.startsWith("setup") || type === "literal-const") { - return `$setup.${raw}`; - } else if (type === "props-aliased") { - return `$props['${bindingMetadata.__propsAliases[raw]}']`; - } else if (type) { - return `$${type}.${raw}`; - } - } - return `_ctx.${raw}`; - }; - const rawExp = node.content; - const bailConstant = constantBailRE.test(rawExp); - let ast = node.ast; - if (ast === false) { - return node; - } - if (ast === null || !ast && isSimpleIdentifier(rawExp)) { - const isScopeVarReference = context.identifiers[rawExp]; - const isAllowedGlobal = isGloballyAllowed(rawExp); - const isLiteral = isLiteralWhitelisted(rawExp); - if (!asParams && !isScopeVarReference && !isLiteral && (!isAllowedGlobal || bindingMetadata[rawExp])) { - if (isConst(bindingMetadata[rawExp])) { - node.constType = 1; - } - node.content = rewriteIdentifier(rawExp); - } else if (!isScopeVarReference) { - if (isLiteral) { - node.constType = 3; - } else { - node.constType = 2; - } - } - return node; - } - if (!ast) { - const source = asRawStatements ? ` ${rawExp} ` : `(${rawExp})${asParams ? `=>{}` : ``}`; - try { - ast = parse_1$1(source, { - plugins: context.expressionPlugins - }).program; - } catch (e) { - context.onError( - createCompilerError( - 45, - node.loc, - void 0, - e.message - ) - ); - return node; - } - } - const ids = []; - const parentStack = []; - const knownIds = Object.create(context.identifiers); - walkIdentifiers( - ast, - (node2, parent, _, isReferenced, isLocal) => { - if (isStaticPropertyKey(node2, parent)) { - return; - } - const needPrefix = isReferenced && canPrefix(node2); - if (needPrefix && !isLocal) { - if (isStaticProperty(parent) && parent.shorthand) { - node2.prefix = `${node2.name}: `; - } - node2.name = rewriteIdentifier(node2.name, parent, node2); - ids.push(node2); - } else { - if (!(needPrefix && isLocal) && !bailConstant) { - node2.isConstant = true; - } - ids.push(node2); - } - }, - true, - // invoke on ALL identifiers - parentStack, - knownIds - ); - const children = []; - ids.sort((a, b) => a.start - b.start); - ids.forEach((id, i) => { - const start = id.start - 1; - const end = id.end - 1; - const last = ids[i - 1]; - const leadingText = rawExp.slice(last ? last.end - 1 : 0, start); - if (leadingText.length || id.prefix) { - children.push(leadingText + (id.prefix || ``)); - } - const source = rawExp.slice(start, end); - children.push( - createSimpleExpression( - id.name, - false, - { - start: advancePositionWithClone(node.loc.start, source, start), - end: advancePositionWithClone(node.loc.start, source, end), - source - }, - id.isConstant ? 3 : 0 - ) - ); - if (i === ids.length - 1 && end < rawExp.length) { - children.push(rawExp.slice(end)); - } - }); - let ret; - if (children.length) { - ret = createCompoundExpression(children, node.loc); - ret.ast = ast; - } else { - ret = node; - ret.constType = bailConstant ? 0 : 3; - } - ret.identifiers = Object.keys(knownIds); - return ret; - } - function canPrefix(id) { - if (isGloballyAllowed(id.name)) { - return false; - } - if (id.name === "require") { - return false; - } - return true; - } - function stringifyExpression(exp) { - if (isString$2(exp)) { - return exp; - } else if (exp.type === 4) { - return exp.content; - } else { - return exp.children.map(stringifyExpression).join(""); - } - } - function isConst(type) { - return type === "setup-const" || type === "literal-const"; - } - - const transformIf = createStructuralDirectiveTransform( - /^(if|else|else-if)$/, - (node, dir, context) => { - return processIf(node, dir, context, (ifNode, branch, isRoot) => { - const siblings = context.parent.children; - let i = siblings.indexOf(ifNode); - let key = 0; - while (i-- >= 0) { - const sibling = siblings[i]; - if (sibling && sibling.type === 9) { - key += sibling.branches.length; - } - } - return () => { - if (isRoot) { - ifNode.codegenNode = createCodegenNodeForBranch( - branch, - key, - context - ); - } else { - const parentCondition = getParentCondition(ifNode.codegenNode); - parentCondition.alternate = createCodegenNodeForBranch( - branch, - key + ifNode.branches.length - 1, - context - ); - } - }; - }); - } - ); - function processIf(node, dir, context, processCodegen) { - if (dir.name !== "else" && (!dir.exp || !dir.exp.content.trim())) { - const loc = dir.exp ? dir.exp.loc : node.loc; - context.onError( - createCompilerError(28, dir.loc) - ); - dir.exp = createSimpleExpression(`true`, false, loc); - } - if (context.prefixIdentifiers && dir.exp) { - dir.exp = processExpression(dir.exp, context); - } - if (dir.name === "if") { - const branch = createIfBranch(node, dir); - const ifNode = { - type: 9, - loc: node.loc, - branches: [branch] - }; - context.replaceNode(ifNode); - if (processCodegen) { - return processCodegen(ifNode, branch, true); - } - } else { - const siblings = context.parent.children; - const comments = []; - let i = siblings.indexOf(node); - while (i-- >= -1) { - const sibling = siblings[i]; - if (sibling && sibling.type === 3) { - context.removeNode(sibling); - comments.unshift(sibling); - continue; - } - if (sibling && sibling.type === 2 && !sibling.content.trim().length) { - context.removeNode(sibling); - continue; - } - if (sibling && sibling.type === 9) { - if (dir.name === "else-if" && sibling.branches[sibling.branches.length - 1].condition === void 0) { - context.onError( - createCompilerError(30, node.loc) - ); - } - context.removeNode(); - const branch = createIfBranch(node, dir); - if (comments.length && // #3619 ignore comments if the v-if is direct child of <transition> - !(context.parent && context.parent.type === 1 && (context.parent.tag === "transition" || context.parent.tag === "Transition"))) { - branch.children = [...comments, ...branch.children]; - } - { - const key = branch.userKey; - if (key) { - sibling.branches.forEach(({ userKey }) => { - if (isSameKey(userKey, key)) { - context.onError( - createCompilerError( - 29, - branch.userKey.loc - ) - ); - } - }); - } - } - sibling.branches.push(branch); - const onExit = processCodegen && processCodegen(sibling, branch, false); - traverseNode(branch, context); - if (onExit) - onExit(); - context.currentNode = null; - } else { - context.onError( - createCompilerError(30, node.loc) - ); - } - break; - } - } - } - function createIfBranch(node, dir) { - const isTemplateIf = node.tagType === 3; - return { - type: 10, - loc: node.loc, - condition: dir.name === "else" ? void 0 : dir.exp, - children: isTemplateIf && !findDir(node, "for") ? node.children : [node], - userKey: findProp(node, `key`), - isTemplateIf - }; - } - function createCodegenNodeForBranch(branch, keyIndex, context) { - if (branch.condition) { - return createConditionalExpression( - branch.condition, - createChildrenCodegenNode(branch, keyIndex, context), - // make sure to pass in asBlock: true so that the comment node call - // closes the current block. - createCallExpression(context.helper(CREATE_COMMENT), [ - '"v-if"', - "true" - ]) - ); - } else { - return createChildrenCodegenNode(branch, keyIndex, context); - } - } - function createChildrenCodegenNode(branch, keyIndex, context) { - const { helper } = context; - const keyProperty = createObjectProperty( - `key`, - createSimpleExpression( - `${keyIndex}`, - false, - locStub, - 2 - ) - ); - const { children } = branch; - const firstChild = children[0]; - const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1; - if (needFragmentWrapper) { - if (children.length === 1 && firstChild.type === 11) { - const vnodeCall = firstChild.codegenNode; - injectProp(vnodeCall, keyProperty, context); - return vnodeCall; - } else { - let patchFlag = 64; - let patchFlagText = PatchFlagNames[64]; - if (!branch.isTemplateIf && children.filter((c) => c.type !== 3).length === 1) { - patchFlag |= 2048; - patchFlagText += `, ${PatchFlagNames[2048]}`; - } - return createVNodeCall( - context, - helper(FRAGMENT), - createObjectExpression([keyProperty]), - children, - patchFlag + (` /* ${patchFlagText} */`), - void 0, - void 0, - true, - false, - false, - branch.loc - ); - } - } else { - const ret = firstChild.codegenNode; - const vnodeCall = getMemoedVNodeCall(ret); - if (vnodeCall.type === 13) { - convertToBlock(vnodeCall, context); - } - injectProp(vnodeCall, keyProperty, context); - return ret; - } - } - function isSameKey(a, b) { - if (!a || a.type !== b.type) { - return false; - } - if (a.type === 6) { - if (a.value.content !== b.value.content) { - return false; - } - } else { - const exp = a.exp; - const branchExp = b.exp; - if (exp.type !== branchExp.type) { - return false; - } - if (exp.type !== 4 || exp.isStatic !== branchExp.isStatic || exp.content !== branchExp.content) { - return false; - } - } - return true; - } - function getParentCondition(node) { - while (true) { - if (node.type === 19) { - if (node.alternate.type === 19) { - node = node.alternate; - } else { - return node; - } - } else if (node.type === 20) { - node = node.value; - } - } - } - - const transformFor = createStructuralDirectiveTransform( - "for", - (node, dir, context) => { - const { helper, removeHelper } = context; - return processFor(node, dir, context, (forNode) => { - const renderExp = createCallExpression(helper(RENDER_LIST), [ - forNode.source - ]); - const isTemplate = isTemplateNode(node); - const memo = findDir(node, "memo"); - const keyProp = findProp(node, `key`); - const keyExp = keyProp && (keyProp.type === 6 ? createSimpleExpression(keyProp.value.content, true) : keyProp.exp); - const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null; - if (isTemplate) { - if (memo) { - memo.exp = processExpression( - memo.exp, - context - ); - } - if (keyProperty && keyProp.type !== 6) { - keyProperty.value = processExpression( - keyProperty.value, - context - ); - } - } - const isStableFragment = forNode.source.type === 4 && forNode.source.constType > 0; - const fragmentFlag = isStableFragment ? 64 : keyProp ? 128 : 256; - forNode.codegenNode = createVNodeCall( - context, - helper(FRAGMENT), - void 0, - renderExp, - fragmentFlag + (` /* ${PatchFlagNames[fragmentFlag]} */`), - void 0, - void 0, - true, - !isStableFragment, - false, - node.loc - ); - return () => { - let childBlock; - const { children } = forNode; - if (isTemplate) { - node.children.some((c) => { - if (c.type === 1) { - const key = findProp(c, "key"); - if (key) { - context.onError( - createCompilerError( - 33, - key.loc - ) - ); - return true; - } - } - }); - } - const needFragmentWrapper = children.length !== 1 || children[0].type !== 1; - const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? node.children[0] : null; - if (slotOutlet) { - childBlock = slotOutlet.codegenNode; - if (isTemplate && keyProperty) { - injectProp(childBlock, keyProperty, context); - } - } else if (needFragmentWrapper) { - childBlock = createVNodeCall( - context, - helper(FRAGMENT), - keyProperty ? createObjectExpression([keyProperty]) : void 0, - node.children, - 64 + (` /* ${PatchFlagNames[64]} */`), - void 0, - void 0, - true, - void 0, - false - ); - } else { - childBlock = children[0].codegenNode; - if (isTemplate && keyProperty) { - injectProp(childBlock, keyProperty, context); - } - if (childBlock.isBlock !== !isStableFragment) { - if (childBlock.isBlock) { - removeHelper(OPEN_BLOCK); - removeHelper( - getVNodeBlockHelper(context.inSSR, childBlock.isComponent) - ); - } else { - removeHelper( - getVNodeHelper(context.inSSR, childBlock.isComponent) - ); - } - } - childBlock.isBlock = !isStableFragment; - if (childBlock.isBlock) { - helper(OPEN_BLOCK); - helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent)); - } else { - helper(getVNodeHelper(context.inSSR, childBlock.isComponent)); - } - } - if (memo) { - const loop = createFunctionExpression( - createForLoopParams(forNode.parseResult, [ - createSimpleExpression(`_cached`) - ]) - ); - loop.body = createBlockStatement([ - createCompoundExpression([`const _memo = (`, memo.exp, `)`]), - createCompoundExpression([ - `if (_cached`, - ...keyExp ? [` && _cached.key === `, keyExp] : [], - ` && ${context.helperString( - IS_MEMO_SAME - )}(_cached, _memo)) return _cached` - ]), - createCompoundExpression([`const _item = `, childBlock]), - createSimpleExpression(`_item.memo = _memo`), - createSimpleExpression(`return _item`) - ]); - renderExp.arguments.push( - loop, - createSimpleExpression(`_cache`), - createSimpleExpression(String(context.cached++)) - ); - } else { - renderExp.arguments.push( - createFunctionExpression( - createForLoopParams(forNode.parseResult), - childBlock, - true - ) - ); - } - }; - }); - } - ); - function processFor(node, dir, context, processCodegen) { - if (!dir.exp) { - context.onError( - createCompilerError(31, dir.loc) - ); - return; - } - const parseResult = dir.forParseResult; - if (!parseResult) { - context.onError( - createCompilerError(32, dir.loc) - ); - return; - } - finalizeForParseResult(parseResult, context); - const { addIdentifiers, removeIdentifiers, scopes } = context; - const { source, value, key, index } = parseResult; - const forNode = { - type: 11, - loc: dir.loc, - source, - valueAlias: value, - keyAlias: key, - objectIndexAlias: index, - parseResult, - children: isTemplateNode(node) ? node.children : [node] - }; - context.replaceNode(forNode); - scopes.vFor++; - if (context.prefixIdentifiers) { - value && addIdentifiers(value); - key && addIdentifiers(key); - index && addIdentifiers(index); - } - const onExit = processCodegen && processCodegen(forNode); - return () => { - scopes.vFor--; - if (context.prefixIdentifiers) { - value && removeIdentifiers(value); - key && removeIdentifiers(key); - index && removeIdentifiers(index); - } - if (onExit) - onExit(); - }; - } - function finalizeForParseResult(result, context) { - if (result.finalized) - return; - if (context.prefixIdentifiers) { - result.source = processExpression( - result.source, - context - ); - if (result.key) { - result.key = processExpression( - result.key, - context, - true - ); - } - if (result.index) { - result.index = processExpression( - result.index, - context, - true - ); - } - if (result.value) { - result.value = processExpression( - result.value, - context, - true - ); - } - } - result.finalized = true; - } - function createForLoopParams({ value, key, index }, memoArgs = []) { - return createParamsList([value, key, index, ...memoArgs]); - } - function createParamsList(args) { - let i = args.length; - while (i--) { - if (args[i]) - break; - } - return args.slice(0, i + 1).map((arg, i2) => arg || createSimpleExpression(`_`.repeat(i2 + 1), false)); - } - - const defaultFallback = createSimpleExpression(`undefined`, false); - const trackSlotScopes = (node, context) => { - if (node.type === 1 && (node.tagType === 1 || node.tagType === 3)) { - const vSlot = findDir(node, "slot"); - if (vSlot) { - const slotProps = vSlot.exp; - if (context.prefixIdentifiers) { - slotProps && context.addIdentifiers(slotProps); - } - context.scopes.vSlot++; - return () => { - if (context.prefixIdentifiers) { - slotProps && context.removeIdentifiers(slotProps); - } - context.scopes.vSlot--; - }; - } - } - }; - const trackVForSlotScopes = (node, context) => { - let vFor; - if (isTemplateNode(node) && node.props.some(isVSlot) && (vFor = findDir(node, "for"))) { - const result = vFor.forParseResult; - if (result) { - finalizeForParseResult(result, context); - const { value, key, index } = result; - const { addIdentifiers, removeIdentifiers } = context; - value && addIdentifiers(value); - key && addIdentifiers(key); - index && addIdentifiers(index); - return () => { - value && removeIdentifiers(value); - key && removeIdentifiers(key); - index && removeIdentifiers(index); - }; - } - } - }; - const buildClientSlotFn = (props, _vForExp, children, loc) => createFunctionExpression( - props, - children, - false, - true, - children.length ? children[0].loc : loc - ); - function buildSlots(node, context, buildSlotFn = buildClientSlotFn) { - context.helper(WITH_CTX); - const { children, loc } = node; - const slotsProperties = []; - const dynamicSlots = []; - let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0; - if (!context.ssr && context.prefixIdentifiers) { - hasDynamicSlots = hasScopeRef(node, context.identifiers); - } - const onComponentSlot = findDir(node, "slot", true); - if (onComponentSlot) { - const { arg, exp } = onComponentSlot; - if (arg && !isStaticExp(arg)) { - hasDynamicSlots = true; - } - slotsProperties.push( - createObjectProperty( - arg || createSimpleExpression("default", true), - buildSlotFn(exp, void 0, children, loc) - ) - ); - } - let hasTemplateSlots = false; - let hasNamedDefaultSlot = false; - const implicitDefaultChildren = []; - const seenSlotNames = /* @__PURE__ */ new Set(); - let conditionalBranchIndex = 0; - for (let i = 0; i < children.length; i++) { - const slotElement = children[i]; - let slotDir; - if (!isTemplateNode(slotElement) || !(slotDir = findDir(slotElement, "slot", true))) { - if (slotElement.type !== 3) { - implicitDefaultChildren.push(slotElement); - } - continue; - } - if (onComponentSlot) { - context.onError( - createCompilerError(37, slotDir.loc) - ); - break; - } - hasTemplateSlots = true; - const { children: slotChildren, loc: slotLoc } = slotElement; - const { - arg: slotName = createSimpleExpression(`default`, true), - exp: slotProps, - loc: dirLoc - } = slotDir; - let staticSlotName; - if (isStaticExp(slotName)) { - staticSlotName = slotName ? slotName.content : `default`; - } else { - hasDynamicSlots = true; - } - const vFor = findDir(slotElement, "for"); - const slotFunction = buildSlotFn(slotProps, vFor, slotChildren, slotLoc); - let vIf; - let vElse; - if (vIf = findDir(slotElement, "if")) { - hasDynamicSlots = true; - dynamicSlots.push( - createConditionalExpression( - vIf.exp, - buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), - defaultFallback - ) - ); - } else if (vElse = findDir( - slotElement, - /^else(-if)?$/, - true - /* allowEmpty */ - )) { - let j = i; - let prev; - while (j--) { - prev = children[j]; - if (prev.type !== 3) { - break; - } - } - if (prev && isTemplateNode(prev) && findDir(prev, "if")) { - children.splice(i, 1); - i--; - let conditional = dynamicSlots[dynamicSlots.length - 1]; - while (conditional.alternate.type === 19) { - conditional = conditional.alternate; - } - conditional.alternate = vElse.exp ? createConditionalExpression( - vElse.exp, - buildDynamicSlot( - slotName, - slotFunction, - conditionalBranchIndex++ - ), - defaultFallback - ) : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++); - } else { - context.onError( - createCompilerError(30, vElse.loc) - ); - } - } else if (vFor) { - hasDynamicSlots = true; - const parseResult = vFor.forParseResult; - if (parseResult) { - finalizeForParseResult(parseResult, context); - dynamicSlots.push( - createCallExpression(context.helper(RENDER_LIST), [ - parseResult.source, - createFunctionExpression( - createForLoopParams(parseResult), - buildDynamicSlot(slotName, slotFunction), - true - ) - ]) - ); - } else { - context.onError( - createCompilerError( - 32, - vFor.loc - ) - ); - } - } else { - if (staticSlotName) { - if (seenSlotNames.has(staticSlotName)) { - context.onError( - createCompilerError( - 38, - dirLoc - ) - ); - continue; - } - seenSlotNames.add(staticSlotName); - if (staticSlotName === "default") { - hasNamedDefaultSlot = true; - } - } - slotsProperties.push(createObjectProperty(slotName, slotFunction)); - } - } - if (!onComponentSlot) { - const buildDefaultSlotProperty = (props, children2) => { - const fn = buildSlotFn(props, void 0, children2, loc); - return createObjectProperty(`default`, fn); - }; - if (!hasTemplateSlots) { - slotsProperties.push(buildDefaultSlotProperty(void 0, children)); - } else if (implicitDefaultChildren.length && // #3766 - // with whitespace: 'preserve', whitespaces between slots will end up in - // implicitDefaultChildren. Ignore if all implicit children are whitespaces. - implicitDefaultChildren.some((node2) => isNonWhitespaceContent(node2))) { - if (hasNamedDefaultSlot) { - context.onError( - createCompilerError( - 39, - implicitDefaultChildren[0].loc - ) - ); - } else { - slotsProperties.push( - buildDefaultSlotProperty(void 0, implicitDefaultChildren) - ); - } - } - } - const slotFlag = hasDynamicSlots ? 2 : hasForwardedSlots(node.children) ? 3 : 1; - let slots = createObjectExpression( - slotsProperties.concat( - createObjectProperty( - `_`, - // 2 = compiled but dynamic = can skip normalization, but must run diff - // 1 = compiled and static = can skip normalization AND diff as optimized - createSimpleExpression( - slotFlag + (` /* ${slotFlagsText[slotFlag]} */`), - false - ) - ) - ), - loc - ); - if (dynamicSlots.length) { - slots = createCallExpression(context.helper(CREATE_SLOTS), [ - slots, - createArrayExpression(dynamicSlots) - ]); - } - return { - slots, - hasDynamicSlots - }; - } - function buildDynamicSlot(name, fn, index) { - const props = [ - createObjectProperty(`name`, name), - createObjectProperty(`fn`, fn) - ]; - if (index != null) { - props.push( - createObjectProperty(`key`, createSimpleExpression(String(index), true)) - ); - } - return createObjectExpression(props); - } - function hasForwardedSlots(children) { - for (let i = 0; i < children.length; i++) { - const child = children[i]; - switch (child.type) { - case 1: - if (child.tagType === 2 || hasForwardedSlots(child.children)) { - return true; - } - break; - case 9: - if (hasForwardedSlots(child.branches)) - return true; - break; - case 10: - case 11: - if (hasForwardedSlots(child.children)) - return true; - break; - } - } - return false; - } - function isNonWhitespaceContent(node) { - if (node.type !== 2 && node.type !== 12) - return true; - return node.type === 2 ? !!node.content.trim() : isNonWhitespaceContent(node.content); - } - - const directiveImportMap = /* @__PURE__ */ new WeakMap(); - const transformElement = (node, context) => { - return function postTransformElement() { - node = context.currentNode; - if (!(node.type === 1 && (node.tagType === 0 || node.tagType === 1))) { - return; - } - const { tag, props } = node; - const isComponent = node.tagType === 1; - let vnodeTag = isComponent ? resolveComponentType(node, context) : `"${tag}"`; - const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT; - let vnodeProps; - let vnodeChildren; - let vnodePatchFlag; - let patchFlag = 0; - let vnodeDynamicProps; - let dynamicPropNames; - let vnodeDirectives; - let shouldUseBlock = ( - // dynamic component may resolve to plain elements - isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent && // <svg> and <foreignObject> must be forced into blocks so that block - // updates inside get proper isSVG flag at runtime. (#639, #643) - // This is technically web-specific, but splitting the logic out of core - // leads to too much unnecessary complexity. - (tag === "svg" || tag === "foreignObject") - ); - if (props.length > 0) { - const propsBuildResult = buildProps( - node, - context, - void 0, - isComponent, - isDynamicComponent - ); - vnodeProps = propsBuildResult.props; - patchFlag = propsBuildResult.patchFlag; - dynamicPropNames = propsBuildResult.dynamicPropNames; - const directives = propsBuildResult.directives; - vnodeDirectives = directives && directives.length ? createArrayExpression( - directives.map((dir) => buildDirectiveArgs(dir, context)) - ) : void 0; - if (propsBuildResult.shouldUseBlock) { - shouldUseBlock = true; - } - } - if (node.children.length > 0) { - if (vnodeTag === KEEP_ALIVE) { - shouldUseBlock = true; - patchFlag |= 1024; - if (node.children.length > 1) { - context.onError( - createCompilerError(46, { - start: node.children[0].loc.start, - end: node.children[node.children.length - 1].loc.end, - source: "" - }) - ); - } - } - const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling - vnodeTag !== TELEPORT && // explained above. - vnodeTag !== KEEP_ALIVE; - if (shouldBuildAsSlots) { - const { slots, hasDynamicSlots } = buildSlots(node, context); - vnodeChildren = slots; - if (hasDynamicSlots) { - patchFlag |= 1024; - } - } else if (node.children.length === 1 && vnodeTag !== TELEPORT) { - const child = node.children[0]; - const type = child.type; - const hasDynamicTextChild = type === 5 || type === 8; - if (hasDynamicTextChild && getConstantType(child, context) === 0) { - patchFlag |= 1; - } - if (hasDynamicTextChild || type === 2) { - vnodeChildren = child; - } else { - vnodeChildren = node.children; - } - } else { - vnodeChildren = node.children; - } - } - if (patchFlag !== 0) { - { - if (patchFlag < 0) { - vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`; - } else { - const flagNames = Object.keys(PatchFlagNames).map(Number).filter((n) => n > 0 && patchFlag & n).map((n) => PatchFlagNames[n]).join(`, `); - vnodePatchFlag = patchFlag + ` /* ${flagNames} */`; - } - } - if (dynamicPropNames && dynamicPropNames.length) { - vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames); - } - } - node.codegenNode = createVNodeCall( - context, - vnodeTag, - vnodeProps, - vnodeChildren, - vnodePatchFlag, - vnodeDynamicProps, - vnodeDirectives, - !!shouldUseBlock, - false, - isComponent, - node.loc - ); - }; - }; - function resolveComponentType(node, context, ssr = false) { - let { tag } = node; - const isExplicitDynamic = isComponentTag(tag); - const isProp = findProp(node, "is"); - if (isProp) { - if (isExplicitDynamic || false) { - const exp = isProp.type === 6 ? isProp.value && createSimpleExpression(isProp.value.content, true) : isProp.exp; - if (exp) { - return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [ - exp - ]); - } - } else if (isProp.type === 6 && isProp.value.content.startsWith("vue:")) { - tag = isProp.value.content.slice(4); - } - } - const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag); - if (builtIn) { - if (!ssr) - context.helper(builtIn); - return builtIn; - } - { - const fromSetup = resolveSetupReference(tag, context); - if (fromSetup) { - return fromSetup; - } - const dotIndex = tag.indexOf("."); - if (dotIndex > 0) { - const ns = resolveSetupReference(tag.slice(0, dotIndex), context); - if (ns) { - return ns + tag.slice(dotIndex); - } - } - } - if (context.selfName && capitalize$1(camelize(tag)) === context.selfName) { - context.helper(RESOLVE_COMPONENT); - context.components.add(tag + `__self`); - return toValidAssetId(tag, `component`); - } - context.helper(RESOLVE_COMPONENT); - context.components.add(tag); - return toValidAssetId(tag, `component`); - } - function resolveSetupReference(name, context) { - const bindings = context.bindingMetadata; - if (!bindings || bindings.__isScriptSetup === false) { - return; - } - const camelName = camelize(name); - const PascalName = capitalize$1(camelName); - const checkType = (type) => { - if (bindings[name] === type) { - return name; - } - if (bindings[camelName] === type) { - return camelName; - } - if (bindings[PascalName] === type) { - return PascalName; - } - }; - const fromConst = checkType("setup-const") || checkType("setup-reactive-const") || checkType("literal-const"); - if (fromConst) { - return context.inline ? ( - // in inline mode, const setup bindings (e.g. imports) can be used as-is - fromConst - ) : `$setup[${JSON.stringify(fromConst)}]`; - } - const fromMaybeRef = checkType("setup-let") || checkType("setup-ref") || checkType("setup-maybe-ref"); - if (fromMaybeRef) { - return context.inline ? ( - // setup scope bindings that may be refs need to be unrefed - `${context.helperString(UNREF)}(${fromMaybeRef})` - ) : `$setup[${JSON.stringify(fromMaybeRef)}]`; - } - const fromProps = checkType("props"); - if (fromProps) { - return `${context.helperString(UNREF)}(${context.inline ? "__props" : "$props"}[${JSON.stringify(fromProps)}])`; - } - } - function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) { - const { tag, loc: elementLoc, children } = node; - let properties = []; - const mergeArgs = []; - const runtimeDirectives = []; - const hasChildren = children.length > 0; - let shouldUseBlock = false; - let patchFlag = 0; - let hasRef = false; - let hasClassBinding = false; - let hasStyleBinding = false; - let hasHydrationEventBinding = false; - let hasDynamicKeys = false; - let hasVnodeHook = false; - const dynamicPropNames = []; - const pushMergeArg = (arg) => { - if (properties.length) { - mergeArgs.push( - createObjectExpression(dedupeProperties(properties), elementLoc) - ); - properties = []; - } - if (arg) - mergeArgs.push(arg); - }; - const analyzePatchFlag = ({ key, value }) => { - if (isStaticExp(key)) { - const name = key.content; - const isEventHandler = isOn(name); - if (isEventHandler && (!isComponent || isDynamicComponent) && // omit the flag for click handlers because hydration gives click - // dedicated fast path. - name.toLowerCase() !== "onclick" && // omit v-model handlers - name !== "onUpdate:modelValue" && // omit onVnodeXXX hooks - !isReservedProp(name)) { - hasHydrationEventBinding = true; - } - if (isEventHandler && isReservedProp(name)) { - hasVnodeHook = true; - } - if (isEventHandler && value.type === 14) { - value = value.arguments[0]; - } - if (value.type === 20 || (value.type === 4 || value.type === 8) && getConstantType(value, context) > 0) { - return; - } - if (name === "ref") { - hasRef = true; - } else if (name === "class") { - hasClassBinding = true; - } else if (name === "style") { - hasStyleBinding = true; - } else if (name !== "key" && !dynamicPropNames.includes(name)) { - dynamicPropNames.push(name); - } - if (isComponent && (name === "class" || name === "style") && !dynamicPropNames.includes(name)) { - dynamicPropNames.push(name); - } - } else { - hasDynamicKeys = true; - } - }; - for (let i = 0; i < props.length; i++) { - const prop = props[i]; - if (prop.type === 6) { - const { loc, name, nameLoc, value } = prop; - let isStatic = true; - if (name === "ref") { - hasRef = true; - if (context.scopes.vFor > 0) { - properties.push( - createObjectProperty( - createSimpleExpression("ref_for", true), - createSimpleExpression("true") - ) - ); - } - if (value && context.inline) { - const binding = context.bindingMetadata[value.content]; - if (binding === "setup-let" || binding === "setup-ref" || binding === "setup-maybe-ref") { - isStatic = false; - properties.push( - createObjectProperty( - createSimpleExpression("ref_key", true), - createSimpleExpression(value.content, true, value.loc) - ) - ); - } - } - } - if (name === "is" && (isComponentTag(tag) || value && value.content.startsWith("vue:") || false)) { - continue; - } - properties.push( - createObjectProperty( - createSimpleExpression(name, true, nameLoc), - createSimpleExpression( - value ? value.content : "", - isStatic, - value ? value.loc : loc - ) - ) - ); - } else { - const { name, arg, exp, loc, modifiers } = prop; - const isVBind = name === "bind"; - const isVOn = name === "on"; - if (name === "slot") { - if (!isComponent) { - context.onError( - createCompilerError(40, loc) - ); - } - continue; - } - if (name === "once" || name === "memo") { - continue; - } - if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag) || false)) { - continue; - } - if (isVOn && ssr) { - continue; - } - if ( - // #938: elements with dynamic keys should be forced into blocks - isVBind && isStaticArgOf(arg, "key") || // inline before-update hooks need to force block so that it is invoked - // before children - isVOn && hasChildren && isStaticArgOf(arg, "vue:before-update") - ) { - shouldUseBlock = true; - } - if (isVBind && isStaticArgOf(arg, "ref") && context.scopes.vFor > 0) { - properties.push( - createObjectProperty( - createSimpleExpression("ref_for", true), - createSimpleExpression("true") - ) - ); - } - if (!arg && (isVBind || isVOn)) { - hasDynamicKeys = true; - if (exp) { - if (isVBind) { - pushMergeArg(); - mergeArgs.push(exp); - } else { - pushMergeArg({ - type: 14, - loc, - callee: context.helper(TO_HANDLERS), - arguments: isComponent ? [exp] : [exp, `true`] - }); - } - } else { - context.onError( - createCompilerError( - isVBind ? 34 : 35, - loc - ) - ); - } - continue; - } - if (isVBind && modifiers.includes("prop")) { - patchFlag |= 32; - } - const directiveTransform = context.directiveTransforms[name]; - if (directiveTransform) { - const { props: props2, needRuntime } = directiveTransform(prop, node, context); - !ssr && props2.forEach(analyzePatchFlag); - if (isVOn && arg && !isStaticExp(arg)) { - pushMergeArg(createObjectExpression(props2, elementLoc)); - } else { - properties.push(...props2); - } - if (needRuntime) { - runtimeDirectives.push(prop); - if (isSymbol$1(needRuntime)) { - directiveImportMap.set(prop, needRuntime); - } - } - } else if (!isBuiltInDirective(name)) { - runtimeDirectives.push(prop); - if (hasChildren) { - shouldUseBlock = true; - } - } - } - } - let propsExpression = void 0; - if (mergeArgs.length) { - pushMergeArg(); - if (mergeArgs.length > 1) { - propsExpression = createCallExpression( - context.helper(MERGE_PROPS), - mergeArgs, - elementLoc - ); - } else { - propsExpression = mergeArgs[0]; - } - } else if (properties.length) { - propsExpression = createObjectExpression( - dedupeProperties(properties), - elementLoc - ); - } - if (hasDynamicKeys) { - patchFlag |= 16; - } else { - if (hasClassBinding && !isComponent) { - patchFlag |= 2; - } - if (hasStyleBinding && !isComponent) { - patchFlag |= 4; - } - if (dynamicPropNames.length) { - patchFlag |= 8; - } - if (hasHydrationEventBinding) { - patchFlag |= 32; - } - } - if (!shouldUseBlock && (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) { - patchFlag |= 512; - } - if (!context.inSSR && propsExpression) { - switch (propsExpression.type) { - case 15: - let classKeyIndex = -1; - let styleKeyIndex = -1; - let hasDynamicKey = false; - for (let i = 0; i < propsExpression.properties.length; i++) { - const key = propsExpression.properties[i].key; - if (isStaticExp(key)) { - if (key.content === "class") { - classKeyIndex = i; - } else if (key.content === "style") { - styleKeyIndex = i; - } - } else if (!key.isHandlerKey) { - hasDynamicKey = true; - } - } - const classProp = propsExpression.properties[classKeyIndex]; - const styleProp = propsExpression.properties[styleKeyIndex]; - if (!hasDynamicKey) { - if (classProp && !isStaticExp(classProp.value)) { - classProp.value = createCallExpression( - context.helper(NORMALIZE_CLASS), - [classProp.value] - ); - } - if (styleProp && // the static style is compiled into an object, - // so use `hasStyleBinding` to ensure that it is a dynamic style binding - (hasStyleBinding || styleProp.value.type === 4 && styleProp.value.content.trim()[0] === `[` || // v-bind:style and style both exist, - // v-bind:style with static literal object - styleProp.value.type === 17)) { - styleProp.value = createCallExpression( - context.helper(NORMALIZE_STYLE), - [styleProp.value] - ); - } - } else { - propsExpression = createCallExpression( - context.helper(NORMALIZE_PROPS), - [propsExpression] - ); - } - break; - case 14: - break; - default: - propsExpression = createCallExpression( - context.helper(NORMALIZE_PROPS), - [ - createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [ - propsExpression - ]) - ] - ); - break; - } - } - return { - props: propsExpression, - directives: runtimeDirectives, - patchFlag, - dynamicPropNames, - shouldUseBlock - }; - } - function dedupeProperties(properties) { - const knownProps = /* @__PURE__ */ new Map(); - const deduped = []; - for (let i = 0; i < properties.length; i++) { - const prop = properties[i]; - if (prop.key.type === 8 || !prop.key.isStatic) { - deduped.push(prop); - continue; - } - const name = prop.key.content; - const existing = knownProps.get(name); - if (existing) { - if (name === "style" || name === "class" || isOn(name)) { - mergeAsArray(existing, prop); - } - } else { - knownProps.set(name, prop); - deduped.push(prop); - } - } - return deduped; - } - function mergeAsArray(existing, incoming) { - if (existing.value.type === 17) { - existing.value.elements.push(incoming.value); - } else { - existing.value = createArrayExpression( - [existing.value, incoming.value], - existing.loc - ); - } - } - function buildDirectiveArgs(dir, context) { - const dirArgs = []; - const runtime = directiveImportMap.get(dir); - if (runtime) { - dirArgs.push(context.helperString(runtime)); - } else { - const fromSetup = resolveSetupReference("v-" + dir.name, context); - if (fromSetup) { - dirArgs.push(fromSetup); - } else { - context.helper(RESOLVE_DIRECTIVE); - context.directives.add(dir.name); - dirArgs.push(toValidAssetId(dir.name, `directive`)); - } - } - const { loc } = dir; - if (dir.exp) - dirArgs.push(dir.exp); - if (dir.arg) { - if (!dir.exp) { - dirArgs.push(`void 0`); - } - dirArgs.push(dir.arg); - } - if (Object.keys(dir.modifiers).length) { - if (!dir.arg) { - if (!dir.exp) { - dirArgs.push(`void 0`); - } - dirArgs.push(`void 0`); - } - const trueExpression = createSimpleExpression(`true`, false, loc); - dirArgs.push( - createObjectExpression( - dir.modifiers.map( - (modifier) => createObjectProperty(modifier, trueExpression) - ), - loc - ) - ); - } - return createArrayExpression(dirArgs, dir.loc); - } - function stringifyDynamicPropNames(props) { - let propsNamesString = `[`; - for (let i = 0, l = props.length; i < l; i++) { - propsNamesString += JSON.stringify(props[i]); - if (i < l - 1) - propsNamesString += ", "; - } - return propsNamesString + `]`; - } - function isComponentTag(tag) { - return tag === "component" || tag === "Component"; - } - - const transformSlotOutlet = (node, context) => { - if (isSlotOutlet(node)) { - const { children, loc } = node; - const { slotName, slotProps } = processSlotOutlet(node, context); - const slotArgs = [ - context.prefixIdentifiers ? `_ctx.$slots` : `$slots`, - slotName, - "{}", - "undefined", - "true" - ]; - let expectedLen = 2; - if (slotProps) { - slotArgs[2] = slotProps; - expectedLen = 3; - } - if (children.length) { - slotArgs[3] = createFunctionExpression([], children, false, false, loc); - expectedLen = 4; - } - if (context.scopeId && !context.slotted) { - expectedLen = 5; - } - slotArgs.splice(expectedLen); - node.codegenNode = createCallExpression( - context.helper(RENDER_SLOT), - slotArgs, - loc - ); - } - }; - function processSlotOutlet(node, context) { - let slotName = `"default"`; - let slotProps = void 0; - const nonNameProps = []; - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i]; - if (p.type === 6) { - if (p.value) { - if (p.name === "name") { - slotName = JSON.stringify(p.value.content); - } else { - p.name = camelize(p.name); - nonNameProps.push(p); - } - } - } else { - if (p.name === "bind" && isStaticArgOf(p.arg, "name")) { - if (p.exp) { - slotName = p.exp; - } else if (p.arg && p.arg.type === 4) { - const name = camelize(p.arg.content); - slotName = p.exp = createSimpleExpression(name, false, p.arg.loc); - { - slotName = p.exp = processExpression(p.exp, context); - } - } - } else { - if (p.name === "bind" && p.arg && isStaticExp(p.arg)) { - p.arg.content = camelize(p.arg.content); - } - nonNameProps.push(p); - } - } - } - if (nonNameProps.length > 0) { - const { props, directives } = buildProps( - node, - context, - nonNameProps, - false, - false - ); - slotProps = props; - if (directives.length) { - context.onError( - createCompilerError( - 36, - directives[0].loc - ) - ); - } - } - return { - slotName, - slotProps - }; - } - - const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/; - const transformOn$1 = (dir, node, context, augmentor) => { - const { loc, modifiers, arg } = dir; - if (!dir.exp && !modifiers.length) { - context.onError(createCompilerError(35, loc)); - } - let eventName; - if (arg.type === 4) { - if (arg.isStatic) { - let rawName = arg.content; - if (rawName.startsWith("vnode")) { - context.onError(createCompilerError(51, arg.loc)); - } - if (rawName.startsWith("vue:")) { - rawName = `vnode-${rawName.slice(4)}`; - } - const eventString = node.tagType !== 0 || rawName.startsWith("vnode") || !/[A-Z]/.test(rawName) ? ( - // for non-element and vnode lifecycle event listeners, auto convert - // it to camelCase. See issue #2249 - toHandlerKey(camelize(rawName)) - ) : ( - // preserve case for plain element listeners that have uppercase - // letters, as these may be custom elements' custom events - `on:${rawName}` - ); - eventName = createSimpleExpression(eventString, true, arg.loc); - } else { - eventName = createCompoundExpression([ - `${context.helperString(TO_HANDLER_KEY)}(`, - arg, - `)` - ]); - } - } else { - eventName = arg; - eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`); - eventName.children.push(`)`); - } - let exp = dir.exp; - if (exp && !exp.content.trim()) { - exp = void 0; - } - let shouldCache = context.cacheHandlers && !exp && !context.inVOnce; - if (exp) { - const isMemberExp = isMemberExpression(exp.content, context); - const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content)); - const hasMultipleStatements = exp.content.includes(`;`); - if (context.prefixIdentifiers) { - isInlineStatement && context.addIdentifiers(`$event`); - exp = dir.exp = processExpression( - exp, - context, - false, - hasMultipleStatements - ); - isInlineStatement && context.removeIdentifiers(`$event`); - shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once - !context.inVOnce && // runtime constants don't need to be cached - // (this is analyzed by compileScript in SFC <script setup>) - !(exp.type === 4 && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component - - // we need to use the original function to preserve arity, - // e.g. <transition> relies on checking cb.length to determine - // transition end handling. Inline function is ok since its arity - // is preserved even when cached. - !(isMemberExp && node.tagType === 1) && // bail if the function references closure variables (v-for, v-slot) - // it must be passed fresh to avoid stale values. - !hasScopeRef(exp, context.identifiers); - if (shouldCache && isMemberExp) { - if (exp.type === 4) { - exp.content = `${exp.content} && ${exp.content}(...args)`; - } else { - exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`]; - } - } - } - if (isInlineStatement || shouldCache && isMemberExp) { - exp = createCompoundExpression([ - `${isInlineStatement ? context.isTS ? `($event: any)` : `$event` : `${context.isTS ? ` -//@ts-ignore -` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`, - exp, - hasMultipleStatements ? `}` : `)` - ]); - } - } - let ret = { - props: [ - createObjectProperty( - eventName, - exp || createSimpleExpression(`() => {}`, false, loc) - ) - ] - }; - if (augmentor) { - ret = augmentor(ret); - } - if (shouldCache) { - ret.props[0].value = context.cache(ret.props[0].value); - } - ret.props.forEach((p) => p.key.isHandlerKey = true); - return ret; - }; - - const transformBind = (dir, _node, context) => { - const { modifiers, loc } = dir; - const arg = dir.arg; - let { exp } = dir; - if (exp && exp.type === 4 && !exp.content.trim()) { - { - context.onError( - createCompilerError(34, loc) - ); - return { - props: [ - createObjectProperty(arg, createSimpleExpression("", true, loc)) - ] - }; - } - } - if (!exp) { - if (arg.type !== 4 || !arg.isStatic) { - context.onError( - createCompilerError( - 52, - arg.loc - ) - ); - return { - props: [ - createObjectProperty(arg, createSimpleExpression("", true, loc)) - ] - }; - } - const propName = camelize(arg.content); - exp = dir.exp = createSimpleExpression(propName, false, arg.loc); - { - exp = dir.exp = processExpression(exp, context); - } - } - if (arg.type !== 4) { - arg.children.unshift(`(`); - arg.children.push(`) || ""`); - } else if (!arg.isStatic) { - arg.content = `${arg.content} || ""`; - } - if (modifiers.includes("camel")) { - if (arg.type === 4) { - if (arg.isStatic) { - arg.content = camelize(arg.content); - } else { - arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`; - } - } else { - arg.children.unshift(`${context.helperString(CAMELIZE)}(`); - arg.children.push(`)`); - } - } - if (!context.inSSR) { - if (modifiers.includes("prop")) { - injectPrefix(arg, "."); - } - if (modifiers.includes("attr")) { - injectPrefix(arg, "^"); - } - } - return { - props: [createObjectProperty(arg, exp)] - }; - }; - const injectPrefix = (arg, prefix) => { - if (arg.type === 4) { - if (arg.isStatic) { - arg.content = prefix + arg.content; - } else { - arg.content = `\`${prefix}\${${arg.content}}\``; - } - } else { - arg.children.unshift(`'${prefix}' + (`); - arg.children.push(`)`); - } - }; - - const transformText = (node, context) => { - if (node.type === 0 || node.type === 1 || node.type === 11 || node.type === 10) { - return () => { - const children = node.children; - let currentContainer = void 0; - let hasText = false; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (isText$1(child)) { - hasText = true; - for (let j = i + 1; j < children.length; j++) { - const next = children[j]; - if (isText$1(next)) { - if (!currentContainer) { - currentContainer = children[i] = createCompoundExpression( - [child], - child.loc - ); - } - currentContainer.children.push(` + `, next); - children.splice(j, 1); - j--; - } else { - currentContainer = void 0; - break; - } - } - } - } - if (!hasText || // if this is a plain element with a single text child, leave it - // as-is since the runtime has dedicated fast path for this by directly - // setting textContent of the element. - // for component root it's always normalized anyway. - children.length === 1 && (node.type === 0 || node.type === 1 && node.tagType === 0 && // #3756 - // custom directives can potentially add DOM elements arbitrarily, - // we need to avoid setting textContent of the element at runtime - // to avoid accidentally overwriting the DOM elements added - // by the user through custom directives. - !node.props.find( - (p) => p.type === 7 && !context.directiveTransforms[p.name] - ) && // in compat mode, <template> tags with no special directives - // will be rendered as a fragment so its children must be - // converted into vnodes. - true)) { - return; - } - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (isText$1(child) || child.type === 8) { - const callArgs = []; - if (child.type !== 2 || child.content !== " ") { - callArgs.push(child); - } - if (!context.ssr && getConstantType(child, context) === 0) { - callArgs.push( - 1 + (` /* ${PatchFlagNames[1]} */`) - ); - } - children[i] = { - type: 12, - content: child, - loc: child.loc, - codegenNode: createCallExpression( - context.helper(CREATE_TEXT), - callArgs - ) - }; - } - } - }; - } - }; - - const seen$1 = /* @__PURE__ */ new WeakSet(); - const transformOnce = (node, context) => { - if (node.type === 1 && findDir(node, "once", true)) { - if (seen$1.has(node) || context.inVOnce || context.inSSR) { - return; - } - seen$1.add(node); - context.inVOnce = true; - context.helper(SET_BLOCK_TRACKING); - return () => { - context.inVOnce = false; - const cur = context.currentNode; - if (cur.codegenNode) { - cur.codegenNode = context.cache( - cur.codegenNode, - true - /* isVNode */ - ); - } - }; - } - }; - - const transformModel$1 = (dir, node, context) => { - const { exp, arg } = dir; - if (!exp) { - context.onError( - createCompilerError(41, dir.loc) - ); - return createTransformProps(); - } - const rawExp = exp.loc.source; - const expString = exp.type === 4 ? exp.content : rawExp; - const bindingType = context.bindingMetadata[rawExp]; - if (bindingType === "props" || bindingType === "props-aliased") { - context.onError(createCompilerError(44, exp.loc)); - return createTransformProps(); - } - const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref"); - if (!expString.trim() || !isMemberExpression(expString, context) && !maybeRef) { - context.onError( - createCompilerError(42, exp.loc) - ); - return createTransformProps(); - } - if (context.prefixIdentifiers && isSimpleIdentifier(expString) && context.identifiers[expString]) { - context.onError( - createCompilerError(43, exp.loc) - ); - return createTransformProps(); - } - const propName = arg ? arg : createSimpleExpression("modelValue", true); - const eventName = arg ? isStaticExp(arg) ? `onUpdate:${camelize(arg.content)}` : createCompoundExpression(['"onUpdate:" + ', arg]) : `onUpdate:modelValue`; - let assignmentExp; - const eventArg = context.isTS ? `($event: any)` : `$event`; - if (maybeRef) { - if (bindingType === "setup-ref") { - assignmentExp = createCompoundExpression([ - `${eventArg} => ((`, - createSimpleExpression(rawExp, false, exp.loc), - `).value = $event)` - ]); - } else { - const altAssignment = bindingType === "setup-let" ? `${rawExp} = $event` : `null`; - assignmentExp = createCompoundExpression([ - `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`, - createSimpleExpression(rawExp, false, exp.loc), - `).value = $event : ${altAssignment})` - ]); - } - } else { - assignmentExp = createCompoundExpression([ - `${eventArg} => ((`, - exp, - `) = $event)` - ]); - } - const props = [ - // modelValue: foo - createObjectProperty(propName, dir.exp), - // "onUpdate:modelValue": $event => (foo = $event) - createObjectProperty(eventName, assignmentExp) - ]; - if (context.prefixIdentifiers && !context.inVOnce && context.cacheHandlers && !hasScopeRef(exp, context.identifiers)) { - props[1].value = context.cache(props[1].value); - } - if (dir.modifiers.length && node.tagType === 1) { - const modifiers = dir.modifiers.map((m) => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`).join(`, `); - const modifiersKey = arg ? isStaticExp(arg) ? `${arg.content}Modifiers` : createCompoundExpression([arg, ' + "Modifiers"']) : `modelModifiers`; - props.push( - createObjectProperty( - modifiersKey, - createSimpleExpression( - `{ ${modifiers} }`, - false, - dir.loc, - 2 - ) - ) - ); - } - return createTransformProps(props); - }; - function createTransformProps(props = []) { - return { props }; - } - - const seen = /* @__PURE__ */ new WeakSet(); - const transformMemo = (node, context) => { - if (node.type === 1) { - const dir = findDir(node, "memo"); - if (!dir || seen.has(node)) { - return; - } - seen.add(node); - return () => { - const codegenNode = node.codegenNode || context.currentNode.codegenNode; - if (codegenNode && codegenNode.type === 13) { - if (node.tagType !== 1) { - convertToBlock(codegenNode, context); - } - node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [ - dir.exp, - createFunctionExpression(void 0, codegenNode), - `_cache`, - String(context.cached++) - ]); - } - }; - } - }; - - function getBaseTransformPreset(prefixIdentifiers) { - return [ - [ - transformOnce, - transformIf, - transformMemo, - transformFor, - ...[], - ...prefixIdentifiers ? [ - // order is important - trackVForSlotScopes, - transformExpression - ] : [], - transformSlotOutlet, - transformElement, - trackSlotScopes, - transformText - ], - { - on: transformOn$1, - bind: transformBind, - model: transformModel$1 - } - ]; - } - function baseCompile(source, options = {}) { - const onError = options.onError || defaultOnError; - const isModuleMode = options.mode === "module"; - const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode; - if (!prefixIdentifiers && options.cacheHandlers) { - onError(createCompilerError(49)); - } - if (options.scopeId && !isModuleMode) { - onError(createCompilerError(50)); - } - const resolvedOptions = extend({}, options, { - prefixIdentifiers - }); - const ast = isString$2(source) ? baseParse(source, resolvedOptions) : source; - const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers); - if (options.isTS) { - const { expressionPlugins } = options; - if (!expressionPlugins || !expressionPlugins.includes("typescript")) { - options.expressionPlugins = [...expressionPlugins || [], "typescript"]; - } - } - transform( - ast, - extend({}, resolvedOptions, { - nodeTransforms: [ - ...nodeTransforms, - ...options.nodeTransforms || [] - // user transforms - ], - directiveTransforms: extend( - {}, - directiveTransforms, - options.directiveTransforms || {} - // user transforms - ) - }) - ); - return generate(ast, resolvedOptions); - } - - const BindingTypes = { - "DATA": "data", - "PROPS": "props", - "PROPS_ALIASED": "props-aliased", - "SETUP_LET": "setup-let", - "SETUP_CONST": "setup-const", - "SETUP_REACTIVE_CONST": "setup-reactive-const", - "SETUP_MAYBE_REF": "setup-maybe-ref", - "SETUP_REF": "setup-ref", - "OPTIONS": "options", - "LITERAL_CONST": "literal-const" - }; - - const noopDirectiveTransform = () => ({ props: [] }); - - const V_MODEL_RADIO = Symbol(`vModelRadio`); - const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox`); - const V_MODEL_TEXT = Symbol(`vModelText`); - const V_MODEL_SELECT = Symbol(`vModelSelect`); - const V_MODEL_DYNAMIC = Symbol(`vModelDynamic`); - const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard`); - const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard`); - const V_SHOW = Symbol(`vShow`); - const TRANSITION = Symbol(`Transition`); - const TRANSITION_GROUP = Symbol(`TransitionGroup`); - registerRuntimeHelpers({ - [V_MODEL_RADIO]: `vModelRadio`, - [V_MODEL_CHECKBOX]: `vModelCheckbox`, - [V_MODEL_TEXT]: `vModelText`, - [V_MODEL_SELECT]: `vModelSelect`, - [V_MODEL_DYNAMIC]: `vModelDynamic`, - [V_ON_WITH_MODIFIERS]: `withModifiers`, - [V_ON_WITH_KEYS]: `withKeys`, - [V_SHOW]: `vShow`, - [TRANSITION]: `Transition`, - [TRANSITION_GROUP]: `TransitionGroup` - }); - - const parserOptions = { - parseMode: "html", - isVoidTag, - isNativeTag: (tag) => isHTMLTag(tag) || isSVGTag(tag) || isMathMLTag(tag), - isPreTag: (tag) => tag === "pre", - decodeEntities: void 0, - isBuiltInComponent: (tag) => { - if (tag === "Transition" || tag === "transition") { - return TRANSITION; - } else if (tag === "TransitionGroup" || tag === "transition-group") { - return TRANSITION_GROUP; - } - }, - // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher - getNamespace(tag, parent, rootNamespace) { - let ns = parent ? parent.ns : rootNamespace; - if (parent && ns === 2) { - if (parent.tag === "annotation-xml") { - if (tag === "svg") { - return 1; - } - if (parent.props.some( - (a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml") - )) { - ns = 0; - } - } else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") { - ns = 0; - } - } else if (parent && ns === 1) { - if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") { - ns = 0; - } - } - if (ns === 0) { - if (tag === "svg") { - return 1; - } - if (tag === "math") { - return 2; - } - } - return ns; - } - }; - - const transformStyle = (node) => { - if (node.type === 1) { - node.props.forEach((p, i) => { - if (p.type === 6 && p.name === "style" && p.value) { - node.props[i] = { - type: 7, - name: `bind`, - arg: createSimpleExpression(`style`, true, p.loc), - exp: parseInlineCSS(p.value.content, p.loc), - modifiers: [], - loc: p.loc - }; - } - }); - } - }; - const parseInlineCSS = (cssText, loc) => { - const normalized = parseStringStyle(cssText); - return createSimpleExpression( - JSON.stringify(normalized), - false, - loc, - 3 - ); - }; - - function createDOMCompilerError(code, loc) { - return createCompilerError( - code, - loc, - DOMErrorMessages - ); - } - const DOMErrorCodes = { - "X_V_HTML_NO_EXPRESSION": 53, - "53": "X_V_HTML_NO_EXPRESSION", - "X_V_HTML_WITH_CHILDREN": 54, - "54": "X_V_HTML_WITH_CHILDREN", - "X_V_TEXT_NO_EXPRESSION": 55, - "55": "X_V_TEXT_NO_EXPRESSION", - "X_V_TEXT_WITH_CHILDREN": 56, - "56": "X_V_TEXT_WITH_CHILDREN", - "X_V_MODEL_ON_INVALID_ELEMENT": 57, - "57": "X_V_MODEL_ON_INVALID_ELEMENT", - "X_V_MODEL_ARG_ON_ELEMENT": 58, - "58": "X_V_MODEL_ARG_ON_ELEMENT", - "X_V_MODEL_ON_FILE_INPUT_ELEMENT": 59, - "59": "X_V_MODEL_ON_FILE_INPUT_ELEMENT", - "X_V_MODEL_UNNECESSARY_VALUE": 60, - "60": "X_V_MODEL_UNNECESSARY_VALUE", - "X_V_SHOW_NO_EXPRESSION": 61, - "61": "X_V_SHOW_NO_EXPRESSION", - "X_TRANSITION_INVALID_CHILDREN": 62, - "62": "X_TRANSITION_INVALID_CHILDREN", - "X_IGNORED_SIDE_EFFECT_TAG": 63, - "63": "X_IGNORED_SIDE_EFFECT_TAG", - "__EXTEND_POINT__": 64, - "64": "__EXTEND_POINT__" - }; - const DOMErrorMessages = { - [53]: `v-html is missing expression.`, - [54]: `v-html will override element children.`, - [55]: `v-text is missing expression.`, - [56]: `v-text will override element children.`, - [57]: `v-model can only be used on <input>, <textarea> and <select> elements.`, - [58]: `v-model argument is not supported on plain elements.`, - [59]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`, - [60]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`, - [61]: `v-show is missing expression.`, - [62]: `<Transition> expects exactly one child element or component.`, - [63]: `Tags with side effect (<script> and <style>) are ignored in client component templates.` - }; - - const transformVHtml = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(53, loc) - ); - } - if (node.children.length) { - context.onError( - createDOMCompilerError(54, loc) - ); - node.children.length = 0; - } - return { - props: [ - createObjectProperty( - createSimpleExpression(`innerHTML`, true, loc), - exp || createSimpleExpression("", true) - ) - ] - }; - }; - - const transformVText = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(55, loc) - ); - } - if (node.children.length) { - context.onError( - createDOMCompilerError(56, loc) - ); - node.children.length = 0; - } - return { - props: [ - createObjectProperty( - createSimpleExpression(`textContent`, true), - exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression( - context.helperString(TO_DISPLAY_STRING), - [exp], - loc - ) : createSimpleExpression("", true) - ) - ] - }; - }; - - const transformModel = (dir, node, context) => { - const baseResult = transformModel$1(dir, node, context); - if (!baseResult.props.length || node.tagType === 1) { - return baseResult; - } - if (dir.arg) { - context.onError( - createDOMCompilerError( - 58, - dir.arg.loc - ) - ); - } - function checkDuplicatedValue() { - const value = findDir(node, "bind"); - if (value && isStaticArgOf(value.arg, "value")) { - context.onError( - createDOMCompilerError( - 60, - value.loc - ) - ); - } - } - const { tag } = node; - const isCustomElement = context.isCustomElement(tag); - if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) { - let directiveToUse = V_MODEL_TEXT; - let isInvalidType = false; - if (tag === "input" || isCustomElement) { - const type = findProp(node, `type`); - if (type) { - if (type.type === 7) { - directiveToUse = V_MODEL_DYNAMIC; - } else if (type.value) { - switch (type.value.content) { - case "radio": - directiveToUse = V_MODEL_RADIO; - break; - case "checkbox": - directiveToUse = V_MODEL_CHECKBOX; - break; - case "file": - isInvalidType = true; - context.onError( - createDOMCompilerError( - 59, - dir.loc - ) - ); - break; - default: - checkDuplicatedValue(); - break; - } - } - } else if (hasDynamicKeyVBind(node)) { - directiveToUse = V_MODEL_DYNAMIC; - } else { - checkDuplicatedValue(); - } - } else if (tag === "select") { - directiveToUse = V_MODEL_SELECT; - } else { - checkDuplicatedValue(); - } - if (!isInvalidType) { - baseResult.needRuntime = context.helper(directiveToUse); - } - } else { - context.onError( - createDOMCompilerError( - 57, - dir.loc - ) - ); - } - baseResult.props = baseResult.props.filter( - (p) => !(p.key.type === 4 && p.key.content === "modelValue") - ); - return baseResult; - }; - - const isEventOptionModifier = /* @__PURE__ */ makeMap(`passive,once,capture`); - const isNonKeyModifier = /* @__PURE__ */ makeMap( - // event propagation management - `stop,prevent,self,ctrl,shift,alt,meta,exact,middle` - ); - const maybeKeyModifier = /* @__PURE__ */ makeMap("left,right"); - const isKeyboardEvent = /* @__PURE__ */ makeMap( - `onkeyup,onkeydown,onkeypress`, - true - ); - const resolveModifiers = (key, modifiers, context, loc) => { - const keyModifiers = []; - const nonKeyModifiers = []; - const eventOptionModifiers = []; - for (let i = 0; i < modifiers.length; i++) { - const modifier = modifiers[i]; - if (isEventOptionModifier(modifier)) { - eventOptionModifiers.push(modifier); - } else { - if (maybeKeyModifier(modifier)) { - if (isStaticExp(key)) { - if (isKeyboardEvent(key.content)) { - keyModifiers.push(modifier); - } else { - nonKeyModifiers.push(modifier); - } - } else { - keyModifiers.push(modifier); - nonKeyModifiers.push(modifier); - } - } else { - if (isNonKeyModifier(modifier)) { - nonKeyModifiers.push(modifier); - } else { - keyModifiers.push(modifier); - } - } - } - } - return { - keyModifiers, - nonKeyModifiers, - eventOptionModifiers - }; - }; - const transformClick = (key, event) => { - const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === "onclick"; - return isStaticClick ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([ - `(`, - key, - `) === "onClick" ? "${event}" : (`, - key, - `)` - ]) : key; - }; - const transformOn = (dir, node, context) => { - return transformOn$1(dir, node, context, (baseResult) => { - const { modifiers } = dir; - if (!modifiers.length) - return baseResult; - let { key, value: handlerExp } = baseResult.props[0]; - const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc); - if (nonKeyModifiers.includes("right")) { - key = transformClick(key, `onContextmenu`); - } - if (nonKeyModifiers.includes("middle")) { - key = transformClick(key, `onMouseup`); - } - if (nonKeyModifiers.length) { - handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [ - handlerExp, - JSON.stringify(nonKeyModifiers) - ]); - } - if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard - (!isStaticExp(key) || isKeyboardEvent(key.content))) { - handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [ - handlerExp, - JSON.stringify(keyModifiers) - ]); - } - if (eventOptionModifiers.length) { - const modifierPostfix = eventOptionModifiers.map(capitalize$1).join(""); - key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]); - } - return { - props: [createObjectProperty(key, handlerExp)] - }; - }); - }; - - const transformShow = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(61, loc) - ); - } - return { - props: [], - needRuntime: context.helper(V_SHOW) - }; - }; - - const transformTransition = (node, context) => { - if (node.type === 1 && node.tagType === 1) { - const component = context.isBuiltInComponent(node.tag); - if (component === TRANSITION) { - return () => { - if (!node.children.length) { - return; - } - if (hasMultipleChildren(node)) { - context.onError( - createDOMCompilerError( - 62, - { - start: node.children[0].loc.start, - end: node.children[node.children.length - 1].loc.end, - source: "" - } - ) - ); - } - const child = node.children[0]; - if (child.type === 1) { - for (const p of child.props) { - if (p.type === 7 && p.name === "show") { - node.props.push({ - type: 6, - name: "persisted", - nameLoc: node.loc, - value: void 0, - loc: node.loc - }); - } - } - } - }; - } - } - }; - function hasMultipleChildren(node) { - const children = node.children = node.children.filter( - (c) => c.type !== 3 && !(c.type === 2 && !c.content.trim()) - ); - const child = children[0]; - return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren); - } - - const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g; - const stringifyStatic = (children, context, parent) => { - if (context.scopes.vSlot > 0) { - return; - } - let nc = 0; - let ec = 0; - const currentChunk = []; - const stringifyCurrentChunk = (currentIndex) => { - if (nc >= 20 || ec >= 5) { - const staticCall = createCallExpression(context.helper(CREATE_STATIC), [ - JSON.stringify( - currentChunk.map((node) => stringifyNode(node, context)).join("") - ).replace(expReplaceRE, `" + $1 + "`), - // the 2nd argument indicates the number of DOM nodes this static vnode - // will insert / hydrate - String(currentChunk.length) - ]); - replaceHoist(currentChunk[0], staticCall, context); - if (currentChunk.length > 1) { - for (let i2 = 1; i2 < currentChunk.length; i2++) { - replaceHoist(currentChunk[i2], null, context); - } - const deleteCount = currentChunk.length - 1; - children.splice(currentIndex - currentChunk.length + 1, deleteCount); - return deleteCount; - } - } - return 0; - }; - let i = 0; - for (; i < children.length; i++) { - const child = children[i]; - const hoisted = getHoistedNode(child); - if (hoisted) { - const node = child; - const result = analyzeNode(node); - if (result) { - nc += result[0]; - ec += result[1]; - currentChunk.push(node); - continue; - } - } - i -= stringifyCurrentChunk(i); - nc = 0; - ec = 0; - currentChunk.length = 0; - } - stringifyCurrentChunk(i); - }; - const getHoistedNode = (node) => (node.type === 1 && node.tagType === 0 || node.type == 12) && node.codegenNode && node.codegenNode.type === 4 && node.codegenNode.hoisted; - const dataAriaRE = /^(data|aria)-/; - const isStringifiableAttr = (name, ns) => { - return (ns === 0 ? isKnownHtmlAttr(name) : ns === 1 ? isKnownSvgAttr(name) : false) || dataAriaRE.test(name); - }; - const replaceHoist = (node, replacement, context) => { - const hoistToReplace = node.codegenNode.hoisted; - context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement; - }; - const isNonStringifiable = /* @__PURE__ */ makeMap( - `caption,thead,tr,th,tbody,td,tfoot,colgroup,col` - ); - function analyzeNode(node) { - if (node.type === 1 && isNonStringifiable(node.tag)) { - return false; - } - if (node.type === 12) { - return [1, 0]; - } - let nc = 1; - let ec = node.props.length > 0 ? 1 : 0; - let bailed = false; - const bail = () => { - bailed = true; - return false; - }; - function walk(node2) { - for (let i = 0; i < node2.props.length; i++) { - const p = node2.props[i]; - if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) { - return bail(); - } - if (p.type === 7 && p.name === "bind") { - if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) { - return bail(); - } - if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) { - return bail(); - } - } - } - for (let i = 0; i < node2.children.length; i++) { - nc++; - const child = node2.children[i]; - if (child.type === 1) { - if (child.props.length > 0) { - ec++; - } - walk(child); - if (bailed) { - return false; - } - } - } - return true; - } - return walk(node) ? [nc, ec] : false; - } - function stringifyNode(node, context) { - if (isString$2(node)) { - return node; - } - if (isSymbol$1(node)) { - return ``; - } - switch (node.type) { - case 1: - return stringifyElement(node, context); - case 2: - return escapeHtml(node.content); - case 3: - return `<!--${escapeHtml(node.content)}-->`; - case 5: - return escapeHtml(toDisplayString(evaluateConstant(node.content))); - case 8: - return escapeHtml(evaluateConstant(node)); - case 12: - return stringifyNode(node.content, context); - default: - return ""; - } - } - function stringifyElement(node, context) { - let res = `<${node.tag}`; - let innerHTML = ""; - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i]; - if (p.type === 6) { - res += ` ${p.name}`; - if (p.value) { - res += `="${escapeHtml(p.value.content)}"`; - } - } else if (p.type === 7) { - if (p.name === "bind") { - const exp = p.exp; - if (exp.content[0] === "_") { - res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`; - continue; - } - if (isBooleanAttr(p.arg.content) && exp.content === "false") { - continue; - } - let evaluated = evaluateConstant(exp); - if (evaluated != null) { - const arg = p.arg && p.arg.content; - if (arg === "class") { - evaluated = normalizeClass(evaluated); - } else if (arg === "style") { - evaluated = stringifyStyle(normalizeStyle(evaluated)); - } - res += ` ${p.arg.content}="${escapeHtml( - evaluated - )}"`; - } - } else if (p.name === "html") { - innerHTML = evaluateConstant(p.exp); - } else if (p.name === "text") { - innerHTML = escapeHtml( - toDisplayString(evaluateConstant(p.exp)) - ); - } - } - } - if (context.scopeId) { - res += ` ${context.scopeId}`; - } - res += `>`; - if (innerHTML) { - res += innerHTML; - } else { - for (let i = 0; i < node.children.length; i++) { - res += stringifyNode(node.children[i], context); - } - } - if (!isVoidTag(node.tag)) { - res += `</${node.tag}>`; - } - return res; - } - function evaluateConstant(exp) { - if (exp.type === 4) { - return new Function(`return (${exp.content})`)(); - } else { - let res = ``; - exp.children.forEach((c) => { - if (isString$2(c) || isSymbol$1(c)) { - return; - } - if (c.type === 2) { - res += c.content; - } else if (c.type === 5) { - res += toDisplayString(evaluateConstant(c.content)); - } else { - res += evaluateConstant(c); - } - }); - return res; - } - } - - const ignoreSideEffectTags = (node, context) => { - if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) { - context.onError( - createDOMCompilerError( - 63, - node.loc - ) - ); - context.removeNode(); - } - }; - - const DOMNodeTransforms = [ - transformStyle, - ...[transformTransition] - ]; - const DOMDirectiveTransforms = { - cloak: noopDirectiveTransform, - html: transformVHtml, - text: transformVText, - model: transformModel, - // override compiler-core - on: transformOn, - // override compiler-core - show: transformShow - }; - function compile$1(src, options = {}) { - return baseCompile( - src, - extend({}, parserOptions, options, { - nodeTransforms: [ - // ignore <script> and <tag> - // this is not put inside DOMNodeTransforms because that list is used - // by compiler-ssr to generate vnode fallback branches - ignoreSideEffectTags, - ...DOMNodeTransforms, - ...options.nodeTransforms || [] - ], - directiveTransforms: extend( - {}, - DOMDirectiveTransforms, - options.directiveTransforms || {} - ), - transformHoist: stringifyStatic - }) - ); - } - function parse$8(template, options = {}) { - return baseParse(template, extend({}, parserOptions, options)); - } - - var CompilerDOM = /*#__PURE__*/Object.freeze({ - __proto__: null, - BASE_TRANSITION: BASE_TRANSITION, - BindingTypes: BindingTypes, - CAMELIZE: CAMELIZE, - CAPITALIZE: CAPITALIZE, - CREATE_BLOCK: CREATE_BLOCK, - CREATE_COMMENT: CREATE_COMMENT, - CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK, - CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE, - CREATE_SLOTS: CREATE_SLOTS, - CREATE_STATIC: CREATE_STATIC, - CREATE_TEXT: CREATE_TEXT, - CREATE_VNODE: CREATE_VNODE, - CompilerDeprecationTypes: CompilerDeprecationTypes, - ConstantTypes: ConstantTypes, - DOMDirectiveTransforms: DOMDirectiveTransforms, - DOMErrorCodes: DOMErrorCodes, - DOMErrorMessages: DOMErrorMessages, - DOMNodeTransforms: DOMNodeTransforms, - ElementTypes: ElementTypes, - ErrorCodes: ErrorCodes, - FRAGMENT: FRAGMENT, - GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS, - IS_MEMO_SAME: IS_MEMO_SAME, - IS_REF: IS_REF, - KEEP_ALIVE: KEEP_ALIVE, - MERGE_PROPS: MERGE_PROPS, - NORMALIZE_CLASS: NORMALIZE_CLASS, - NORMALIZE_PROPS: NORMALIZE_PROPS, - NORMALIZE_STYLE: NORMALIZE_STYLE, - Namespaces: Namespaces, - NodeTypes: NodeTypes, - OPEN_BLOCK: OPEN_BLOCK, - POP_SCOPE_ID: POP_SCOPE_ID, - PUSH_SCOPE_ID: PUSH_SCOPE_ID, - RENDER_LIST: RENDER_LIST, - RENDER_SLOT: RENDER_SLOT, - RESOLVE_COMPONENT: RESOLVE_COMPONENT, - RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE, - RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT, - RESOLVE_FILTER: RESOLVE_FILTER, - SET_BLOCK_TRACKING: SET_BLOCK_TRACKING, - SUSPENSE: SUSPENSE, - TELEPORT: TELEPORT, - TO_DISPLAY_STRING: TO_DISPLAY_STRING, - TO_HANDLERS: TO_HANDLERS, - TO_HANDLER_KEY: TO_HANDLER_KEY, - TRANSITION: TRANSITION, - TRANSITION_GROUP: TRANSITION_GROUP, - TS_NODE_TYPES: TS_NODE_TYPES, - UNREF: UNREF, - V_MODEL_CHECKBOX: V_MODEL_CHECKBOX, - V_MODEL_DYNAMIC: V_MODEL_DYNAMIC, - V_MODEL_RADIO: V_MODEL_RADIO, - V_MODEL_SELECT: V_MODEL_SELECT, - V_MODEL_TEXT: V_MODEL_TEXT, - V_ON_WITH_KEYS: V_ON_WITH_KEYS, - V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS, - V_SHOW: V_SHOW, - WITH_CTX: WITH_CTX, - WITH_DIRECTIVES: WITH_DIRECTIVES, - WITH_MEMO: WITH_MEMO, - advancePositionWithClone: advancePositionWithClone, - advancePositionWithMutation: advancePositionWithMutation, - assert: assert, - baseCompile: baseCompile, - baseParse: baseParse, - buildDirectiveArgs: buildDirectiveArgs, - buildProps: buildProps, - buildSlots: buildSlots, - checkCompatEnabled: checkCompatEnabled, - compile: compile$1, - convertToBlock: convertToBlock, - createArrayExpression: createArrayExpression, - createAssignmentExpression: createAssignmentExpression, - createBlockStatement: createBlockStatement, - createCacheExpression: createCacheExpression, - createCallExpression: createCallExpression, - createCompilerError: createCompilerError, - createCompoundExpression: createCompoundExpression, - createConditionalExpression: createConditionalExpression, - createDOMCompilerError: createDOMCompilerError, - createForLoopParams: createForLoopParams, - createFunctionExpression: createFunctionExpression, - createIfStatement: createIfStatement, - createInterpolation: createInterpolation, - createObjectExpression: createObjectExpression, - createObjectProperty: createObjectProperty, - createReturnStatement: createReturnStatement, - createRoot: createRoot, - createSequenceExpression: createSequenceExpression, - createSimpleExpression: createSimpleExpression, - createStructuralDirectiveTransform: createStructuralDirectiveTransform, - createTemplateLiteral: createTemplateLiteral, - createTransformContext: createTransformContext, - createVNodeCall: createVNodeCall, - errorMessages: errorMessages$1, - extractIdentifiers: extractIdentifiers$1, - findDir: findDir, - findProp: findProp, - forAliasRE: forAliasRE, - generate: generate, - generateCodeFrame: generateCodeFrame, - getBaseTransformPreset: getBaseTransformPreset, - getConstantType: getConstantType, - getMemoedVNodeCall: getMemoedVNodeCall, - getVNodeBlockHelper: getVNodeBlockHelper, - getVNodeHelper: getVNodeHelper, - hasDynamicKeyVBind: hasDynamicKeyVBind, - hasScopeRef: hasScopeRef, - helperNameMap: helperNameMap, - injectProp: injectProp, - isCoreComponent: isCoreComponent, - isFunctionType: isFunctionType, - isInDestructureAssignment: isInDestructureAssignment, - isInNewExpression: isInNewExpression, - isMemberExpression: isMemberExpression, - isMemberExpressionBrowser: isMemberExpressionBrowser, - isMemberExpressionNode: isMemberExpressionNode, - isReferencedIdentifier: isReferencedIdentifier, - isSimpleIdentifier: isSimpleIdentifier, - isSlotOutlet: isSlotOutlet, - isStaticArgOf: isStaticArgOf, - isStaticExp: isStaticExp, - isStaticProperty: isStaticProperty, - isStaticPropertyKey: isStaticPropertyKey, - isTemplateNode: isTemplateNode, - isText: isText$1, - isVSlot: isVSlot, - locStub: locStub, - noopDirectiveTransform: noopDirectiveTransform, - parse: parse$8, - parserOptions: parserOptions, - processExpression: processExpression, - processFor: processFor, - processIf: processIf, - processSlotOutlet: processSlotOutlet, - registerRuntimeHelpers: registerRuntimeHelpers, - resolveComponentType: resolveComponentType, - stringifyExpression: stringifyExpression, - toValidAssetId: toValidAssetId, - trackSlotScopes: trackSlotScopes, - trackVForSlotScopes: trackVForSlotScopes, - transform: transform, - transformBind: transformBind, - transformElement: transformElement, - transformExpression: transformExpression, - transformModel: transformModel$1, - transformOn: transformOn$1, - transformStyle: transformStyle, - traverseNode: traverseNode, - unwrapTSNode: unwrapTSNode, - walkBlockDeclarations: walkBlockDeclarations, - walkFunctionParams: walkFunctionParams, - walkIdentifiers: walkIdentifiers, - warnDeprecation: warnDeprecation - }); - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - // resolves . and .. elements in a path array with directory names there - // must be no slashes, empty elements, or device names (c:\) in the array - // (so also no leading and trailing slashes - it does not distinguish - // relative and absolute paths) - function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; - } - - // Split a filename into [root, dir, basename, ext], unix version - // 'root' is just a slash, or nothing. - var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; - var splitPath = function (filename) { - return splitPathRe.exec(filename).slice(1); - }; - - // path.resolve([from ...], to) - // posix version - function resolve$2() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : '/'; - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function (p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; - } - // path.normalize(path) - // posix version - function normalize$1(path) { - var isPathAbsolute = isAbsolute$1(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function (p) { - return !!p; - }), !isPathAbsolute).join('/'); - - if (!path && !isPathAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isPathAbsolute ? '/' : '') + path; - } - // posix version - function isAbsolute$1(path) { - return path.charAt(0) === '/'; - } - - // posix version - function join$1() { - var paths = Array.prototype.slice.call(arguments, 0); - return normalize$1(filter(paths, function (p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); - } - - - // path.relative(from, to) - // posix version - function relative$1(from, to) { - from = resolve$2(from).substr(1); - to = resolve$2(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); - } - - var sep$1 = '/'; - var delimiter$1 = ':'; - - function dirname$2(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; - } - - function basename(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; - } - - - function extname(path) { - return splitPath(path)[3]; - } - var path = { - extname: extname, - basename: basename, - dirname: dirname$2, - sep: sep$1, - delimiter: delimiter$1, - relative: relative$1, - join: join$1, - isAbsolute: isAbsolute$1, - normalize: normalize$1, - resolve: resolve$2 - }; - function filter(xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; - } - - // String.prototype.substr - negative index don't work in IE8 - var substr = 'ab'.substr(-1) === 'b' ? - function (str, start, len) { return str.substr(start, len) } : - function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } - ; - - var _polyfillNode_path = /*#__PURE__*/Object.freeze({ - __proto__: null, - basename: basename, - default: path, - delimiter: delimiter$1, - dirname: dirname$2, - extname: extname, - isAbsolute: isAbsolute$1, - join: join$1, - normalize: normalize$1, - relative: relative$1, - resolve: resolve$2, - sep: sep$1 - }); - - const UNKNOWN_TYPE = "Unknown"; - function resolveObjectKey(node, computed) { - switch (node.type) { - case "StringLiteral": - case "NumericLiteral": - return String(node.value); - case "Identifier": - if (!computed) - return node.name; - } - return void 0; - } - function concatStrings(strs) { - return strs.filter((s) => !!s).join(", "); - } - function isLiteralNode(node) { - return node.type.endsWith("Literal"); - } - function isCallOf(node, test) { - return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name))); - } - function toRuntimeTypeString(types) { - return types.length > 1 ? `[${types.join(", ")}]` : types[0]; - } - function getImportedName(specifier) { - if (specifier.type === "ImportSpecifier") - return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value; - else if (specifier.type === "ImportNamespaceSpecifier") - return "*"; - return "default"; - } - function getId(node) { - return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null; - } - const normalize = (path.posix || path).normalize; - const windowsSlashRE = /\\/g; - function normalizePath(p) { - return normalize(p.replace(windowsSlashRE, "/")); - } - const joinPaths = (path.posix || path).join; - const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/; - function getEscapedPropName(key) { - return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key; - } - const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g; - function getEscapedCssVarName(key, doubleEscape) { - return key.replace( - cssVarNameEscapeSymbolsRE, - (s) => doubleEscape ? `\\\\${s}` : `\\${s}` - ); - } - - function pad$1(hash, len) { - while (hash.length < len) { - hash = '0' + hash; - } - return hash; - } - - function fold(hash, text) { - var i; - var chr; - var len; - if (text.length === 0) { - return hash; - } - for (i = 0, len = text.length; i < len; i++) { - chr = text.charCodeAt(i); - hash = ((hash << 5) - hash) + chr; - hash |= 0; - } - return hash < 0 ? hash * -2 : hash; - } - - function foldObject(hash, o, seen) { - return Object.keys(o).sort().reduce(foldKey, hash); - function foldKey(hash, key) { - return foldValue(hash, o[key], key, seen); - } - } - - function foldValue(input, value, key, seen) { - var hash = fold(fold(fold(input, key), toString$2(value)), typeof value); - if (value === null) { - return fold(hash, 'null'); - } - if (value === undefined) { - return fold(hash, 'undefined'); - } - if (typeof value === 'object' || typeof value === 'function') { - if (seen.indexOf(value) !== -1) { - return fold(hash, '[Circular]' + key); - } - seen.push(value); - - var objHash = foldObject(hash, value, seen); - - if (!('valueOf' in value) || typeof value.valueOf !== 'function') { - return objHash; - } - - try { - return fold(objHash, String(value.valueOf())) - } catch (err) { - return fold(objHash, '[valueOf exception]' + (err.stack || err.message)) - } - } - return fold(hash, value.toString()); - } - - function toString$2(o) { - return Object.prototype.toString.call(o); - } - - function sum(o) { - return pad$1(foldValue(0, o, '', []).toString(16), 8); - } - - var hashSum = sum; - - var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSum); - - const CSS_VARS_HELPER = `useCssVars`; - function genCssVarsFromList(vars, id, isProd, isSSR = false) { - return `{ - ${vars.map( - (key) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})` - ).join(",\n ")} -}`; - } - function genVarName(id, raw, isProd, isSSR = false) { - if (isProd) { - return hash(id + raw); - } else { - return `${id}-${getEscapedCssVarName(raw, isSSR)}`; - } - } - function normalizeExpression(exp) { - exp = exp.trim(); - if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) { - return exp.slice(1, -1); - } - return exp; - } - const vBindRE = /v-bind\s*\(/g; - function parseCssVars(sfc) { - const vars = []; - sfc.styles.forEach((style) => { - let match; - const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, ""); - while (match = vBindRE.exec(content)) { - const start = match.index + match[0].length; - const end = lexBinding(content, start); - if (end !== null) { - const variable = normalizeExpression(content.slice(start, end)); - if (!vars.includes(variable)) { - vars.push(variable); - } - } - } - }); - return vars; - } - function lexBinding(content, start) { - let state = 0 /* inParens */; - let parenDepth = 0; - for (let i = start; i < content.length; i++) { - const char = content.charAt(i); - switch (state) { - case 0 /* inParens */: - if (char === `'`) { - state = 1 /* inSingleQuoteString */; - } else if (char === `"`) { - state = 2 /* inDoubleQuoteString */; - } else if (char === `(`) { - parenDepth++; - } else if (char === `)`) { - if (parenDepth > 0) { - parenDepth--; - } else { - return i; - } - } - break; - case 1 /* inSingleQuoteString */: - if (char === `'`) { - state = 0 /* inParens */; - } - break; - case 2 /* inDoubleQuoteString */: - if (char === `"`) { - state = 0 /* inParens */; - } - break; - } - } - return null; - } - const cssVarsPlugin = (opts) => { - const { id, isProd } = opts; - return { - postcssPlugin: "vue-sfc-vars", - Declaration(decl) { - const value = decl.value; - if (vBindRE.test(value)) { - vBindRE.lastIndex = 0; - let transformed = ""; - let lastIndex = 0; - let match; - while (match = vBindRE.exec(value)) { - const start = match.index + match[0].length; - const end = lexBinding(value, start); - if (end !== null) { - const variable = normalizeExpression(value.slice(start, end)); - transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`; - lastIndex = end + 1; - } - } - decl.value = transformed + value.slice(lastIndex); - } - } - }; - }; - cssVarsPlugin.postcss = true; - function genCssVarsCode(vars, bindings, id, isProd) { - const varsExp = genCssVarsFromList(vars, id, isProd); - const exp = createSimpleExpression(varsExp, false); - const context = createTransformContext(createRoot([]), { - prefixIdentifiers: true, - inline: true, - bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings - }); - const transformed = processExpression(exp, context); - const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => { - return typeof c === "string" ? c : c.content; - }).join(""); - return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`; - } - function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) { - return ` -import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue' -const __injectCSSVars__ = () => { -${genCssVarsCode( - cssVars, - bindings, - id, - isProd - )}} -const __setup__ = ${defaultVar}.setup -${defaultVar}.setup = __setup__ - ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) } - : __injectCSSVars__ -`; - } - - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout() { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } - - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while (len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser = true; - var env = {}; - var argv = []; - var version$1 = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - - function noop() { } - - var on = noop; - var addListener = noop; - var once = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; - - function binding(name) { - throw new Error('process.binding is not supported'); - } - - function cwd() { return '/' } - function chdir(dir) { - throw new Error('process.chdir is not supported'); - } function umask() { return 0; } - - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function () { return (new Date()).getTime() }; - - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp) { - var clocktime = performanceNow.call(performance) * 1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime % 1) * 1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds < 0) { - seconds--; - nanoseconds += 1e9; - } - } - return [seconds, nanoseconds] - } - - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; - } - - var browser$1 = { - nextTick: nextTick, - title: title, - browser: browser, - env: env, - argv: argv, - version: version$1, - versions: versions, - on: on, - addListener: addListener, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; - - function createCache(max = 500) { - { - return /* @__PURE__ */ new Map(); - } - } - - function isImportUsed(local, sfc) { - return resolveTemplateUsedIdentifiers(sfc).has(local); - } - const templateUsageCheckCache = createCache(); - function resolveTemplateUsedIdentifiers(sfc) { - const { content, ast } = sfc.template; - const cached = templateUsageCheckCache.get(content); - if (cached) { - return cached; - } - const ids = /* @__PURE__ */ new Set(); - ast.children.forEach(walk); - function walk(node) { - var _a; - switch (node.type) { - case 1: - let tag = node.tag; - if (tag.includes(".")) - tag = tag.split(".")[0].trim(); - if (!parserOptions.isNativeTag(tag) && !parserOptions.isBuiltInComponent(tag)) { - ids.add(camelize(tag)); - ids.add(capitalize$1(camelize(tag))); - } - for (let i = 0; i < node.props.length; i++) { - const prop = node.props[i]; - if (prop.type === 7) { - if (!isBuiltInDirective(prop.name)) { - ids.add(`v${capitalize$1(camelize(prop.name))}`); - } - if (prop.arg && !prop.arg.isStatic) { - extractIdentifiers(ids, prop.arg); - } - if (prop.name === "for") { - extractIdentifiers(ids, prop.forParseResult.source); - } else if (prop.exp) { - extractIdentifiers(ids, prop.exp); - } - } - if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) { - ids.add(prop.value.content); - } - } - node.children.forEach(walk); - break; - case 5: - extractIdentifiers(ids, node.content); - break; - } - } - templateUsageCheckCache.set(content, ids); - return ids; - } - function extractIdentifiers(ids, node) { - if (node.ast) { - walkIdentifiers(node.ast, (n) => ids.add(n.name)); - } else if (node.ast === null) { - ids.add(node.content); - } - } - - var __defProp$a = Object.defineProperty; - var __defProps$9 = Object.defineProperties; - var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$a = Object.getOwnPropertySymbols; - var __hasOwnProp$a = Object.prototype.hasOwnProperty; - var __propIsEnum$a = Object.prototype.propertyIsEnumerable; - var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$a = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$a.call(b, prop)) - __defNormalProp$a(a, prop, b[prop]); - if (__getOwnPropSymbols$a) - for (var prop of __getOwnPropSymbols$a(b)) { - if (__propIsEnum$a.call(b, prop)) - __defNormalProp$a(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b)); - const DEFAULT_FILENAME = "anonymous.vue"; - const parseCache$1 = createCache(); - function genCacheKey(source, options) { - var _a; - return source + JSON.stringify( - __spreadProps$9(__spreadValues$a({}, options), { - compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse } - }), - (_, val) => typeof val === "function" ? val.toString() : val - ); - } - function parse$7(source, options = {}) { - const sourceKey = genCacheKey(source, options); - const cache = parseCache$1.get(sourceKey); - if (cache) { - return cache; - } - const { - sourceMap = true, - filename = DEFAULT_FILENAME, - sourceRoot = "", - pad = false, - ignoreEmpty = true, - compiler = CompilerDOM, - templateParseOptions = {}, - parseExpressions = true - } = options; - const descriptor = { - filename, - source, - template: null, - script: null, - scriptSetup: null, - styles: [], - customBlocks: [], - cssVars: [], - slotted: false, - shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor) - }; - const errors = []; - const ast = compiler.parse(source, __spreadProps$9(__spreadValues$a({ - parseMode: "sfc", - prefixIdentifiers: parseExpressions - }, templateParseOptions), { - onError: (e) => { - errors.push(e); - } - })); - ast.children.forEach((node) => { - if (node.type !== 1) { - return; - } - if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) { - return; - } - switch (node.tag) { - case "template": - if (!descriptor.template) { - const templateBlock = descriptor.template = createBlock( - node, - source, - false - ); - if (!templateBlock.attrs.src) { - templateBlock.ast = createRoot(node.children, source); - } - if (templateBlock.attrs.functional) { - const err = new SyntaxError( - `<template functional> is no longer supported in Vue 3, since functional components no longer have significant performance difference from stateful ones. Just use a normal <template> instead.` - ); - err.loc = node.props.find( - (p) => p.type === 6 && p.name === "functional" - ).loc; - errors.push(err); - } - } else { - errors.push(createDuplicateBlockError(node)); - } - break; - case "script": - const scriptBlock = createBlock(node, source, pad); - const isSetup = !!scriptBlock.attrs.setup; - if (isSetup && !descriptor.scriptSetup) { - descriptor.scriptSetup = scriptBlock; - break; - } - if (!isSetup && !descriptor.script) { - descriptor.script = scriptBlock; - break; - } - errors.push(createDuplicateBlockError(node, isSetup)); - break; - case "style": - const styleBlock = createBlock(node, source, pad); - if (styleBlock.attrs.vars) { - errors.push( - new SyntaxError( - `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231` - ) - ); - } - descriptor.styles.push(styleBlock); - break; - default: - descriptor.customBlocks.push(createBlock(node, source, pad)); - break; - } - }); - if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) { - errors.push( - new SyntaxError( - `At least one <template> or <script> is required in a single file component.` - ) - ); - } - if (descriptor.scriptSetup) { - if (descriptor.scriptSetup.src) { - errors.push( - new SyntaxError( - `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.` - ) - ); - descriptor.scriptSetup = null; - } - if (descriptor.script && descriptor.script.src) { - errors.push( - new SyntaxError( - `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.` - ) - ); - descriptor.script = null; - } - } - let templateColumnOffset = 0; - if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) { - [descriptor.template.content, templateColumnOffset] = dedent( - descriptor.template.content - ); - } - if (sourceMap) { - const genMap = (block, columnOffset = 0) => { - if (block && !block.src) { - block.map = generateSourceMap( - filename, - source, - block.content, - sourceRoot, - !pad || block.type === "template" ? block.loc.start.line - 1 : 0, - columnOffset - ); - } - }; - genMap(descriptor.template, templateColumnOffset); - genMap(descriptor.script); - descriptor.styles.forEach((s) => genMap(s)); - descriptor.customBlocks.forEach((s) => genMap(s)); - } - descriptor.cssVars = parseCssVars(descriptor); - const slottedRE = /(?:::v-|:)slotted\(/; - descriptor.slotted = descriptor.styles.some( - (s) => s.scoped && slottedRE.test(s.content) - ); - const result = { - descriptor, - errors - }; - parseCache$1.set(sourceKey, result); - return result; - } - function createDuplicateBlockError(node, isScriptSetup = false) { - const err = new SyntaxError( - `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element` - ); - err.loc = node.loc; - return err; - } - function createBlock(node, source, pad) { - const type = node.tag; - const loc = node.innerLoc; - const attrs = {}; - const block = { - type, - content: source.slice(loc.start.offset, loc.end.offset), - loc, - attrs - }; - if (pad) { - block.content = padContent(source, block, pad) + block.content; - } - node.props.forEach((p) => { - if (p.type === 6) { - const name = p.name; - attrs[name] = p.value ? p.value.content || true : true; - if (name === "lang") { - block.lang = p.value && p.value.content; - } else if (name === "src") { - block.src = p.value && p.value.content; - } else if (type === "style") { - if (name === "scoped") { - block.scoped = true; - } else if (name === "module") { - block.module = attrs[name]; - } - } else if (type === "script" && name === "setup") { - block.setup = attrs.setup; - } - } - }); - return block; - } - const splitRE = /\r?\n/g; - const emptyRE = /^(?:\/\/)?\s*$/; - const replaceRE = /./g; - function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) { - const map = new SourceMapGenerator$6({ - file: filename.replace(/\\/g, "/"), - sourceRoot: sourceRoot.replace(/\\/g, "/") - }); - map.setSourceContent(filename, source); - map._sources.add(filename); - generated.split(splitRE).forEach((line, index) => { - if (!emptyRE.test(line)) { - const originalLine = index + 1 + lineOffset; - const generatedLine = index + 1; - for (let i = 0; i < line.length; i++) { - if (!/\s/.test(line[i])) { - map._mappings.add({ - originalLine, - originalColumn: i + columnOffset, - generatedLine, - generatedColumn: i, - source: filename, - // @ts-expect-error - name: null - }); - } - } - } - }); - return map.toJSON(); - } - function padContent(content, block, pad) { - content = content.slice(0, block.loc.start.offset); - if (pad === "space") { - return content.replace(replaceRE, " "); - } else { - const offset = content.split(splitRE).length; - const padChar = block.type === "script" && !block.lang ? "//\n" : "\n"; - return Array(offset).join(padChar); - } - } - function hasSrc(node) { - return node.props.some((p) => { - if (p.type !== 6) { - return false; - } - return p.name === "src"; - }); - } - function isEmpty(node) { - for (let i = 0; i < node.children.length; i++) { - const child = node.children[i]; - if (child.type !== 2 || child.content.trim() !== "") { - return false; - } - } - return true; - } - function hmrShouldReload(prevImports, next) { - if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") { - return false; - } - for (const key in prevImports) { - if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) { - return true; - } - } - return false; - } - function dedent(s) { - const lines = s.split("\n"); - const minIndent = lines.reduce(function (minIndent2, line) { - var _a, _b; - if (line.trim() === "") { - return minIndent2; - } - const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0; - return Math.min(indent, minIndent2); - }, Infinity); - if (minIndent === 0) { - return [s, minIndent]; - } - return [ - lines.map(function (line) { - return line.slice(minIndent); - }).join("\n"), - minIndent - ]; - } - - /*! https://mths.be/punycode v1.4.1 by @mathias */ - - - /** Highest positive signed 32-bit float value */ - var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - var base = 36; - var tMin = 1; - var tMax = 26; - var skew = 38; - var damp = 700; - var initialBias = 72; - var initialN = 128; // 0x80 - var delimiter = '-'; // '\x2D' - var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars - var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators - - /** Error messages */ - var errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }; - - /** Convenience shortcuts */ - var baseMinusTMin = base - tMin; - var floor = Math.floor; - var stringFromCharCode = String.fromCharCode; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw new RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map$1(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map$1(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see <https://mathiasbynens.be/notes/javascript-encoding> - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for ( /* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode$1(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? - 'xn--' + encode$1(string) : - string; - }); - } - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - function init() { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - } - - function toByteArray(b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - return arr - } - - function tripletToBase64(num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] - } - - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') - } - - function fromByteArray(uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } - - parts.push(output); - - return parts.join('') - } - - function read(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { } - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { } - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - function write(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) { } - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) { } - - buffer[offset + i - d] |= s * 128; - } - - var toString$1 = {}.toString; - - var isArray$2 = Array.isArray || function (arr) { - return toString$1.call(arr) == '[object Array]'; - }; - - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> - * @license MIT - */ - /* eslint-disable no-proto */ - - - var INSPECT_MAX_BYTES = 50; - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; - - /* - * Export kMaxLength after typed array support is determined. - */ - kMaxLength(); - - function kMaxLength() { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer(that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer$1(arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer$1.poolSize = 8192; // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr - }; - - function from(that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer$1.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - }; - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer$1[Symbol.species] === Buffer$1); - } - - function assertSize(size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc(that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - }; - - function allocUnsafe(that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - }; - - function fromString(that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); - - var actual = that.write(string, encoding); - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } - - return that - } - - function fromArrayLike(that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that - } - - function fromArrayBuffer(that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that - } - - function fromObject(that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len); - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray$2(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked(length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - Buffer$1.isBuffer = isBuffer$1; - function internalIsBuffer(b) { - return !!(b != null && b._isBuffer) - } - - Buffer$1.compare = function compare(a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; - - Buffer$1.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - }; - - Buffer$1.concat = function concat(list, length) { - if (!isArray$2(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer$1.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; - - function byteLength(string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (; ;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer$1.byteLength = byteLength; - - function slowToString(encoding, start, end) { - var loweredCase = false; - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8'; - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer$1.prototype._isBuffer = true; - - function swap$1(b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer$1.prototype.swap16 = function swap16() { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap$1(this, i, i + 1); - } - return this - }; - - Buffer$1.prototype.swap32 = function swap32() { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap$1(this, i, i + 3); - swap$1(this, i + 1, i + 2); - } - return this - }; - - Buffer$1.prototype.swap64 = function swap64() { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap$1(this, i, i + 7); - swap$1(this, i + 1, i + 6); - swap$1(this, i + 2, i + 5); - swap$1(this, i + 3, i + 4); - } - return this - }; - - Buffer$1.prototype.toString = function toString() { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - }; - - Buffer$1.prototype.equals = function equals(b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 - }; - - Buffer$1.prototype.inspect = function inspect() { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '<Buffer ' + str + '>' - }; - - Buffer$1.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - - if (this === target) return 0 - - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$1.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - - function read(buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer$1.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; - - Buffer$1.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - }; - - Buffer$1.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - }; - - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i - } - - function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write(buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer$1.prototype.write = function write(string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8'; - - var loweredCase = false; - for (; ;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - - Buffer$1.prototype.toJSON = function toJSON() { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - }; - - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res - } - - function asciiSlice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret - } - - function latin1Slice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret - } - - function hexSlice(buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - return out - } - - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res - } - - Buffer$1.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - return newBuf - }; - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset(offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer$1.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val - }; - - Buffer$1.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val - }; - - Buffer$1.prototype.readUInt8 = function readUInt8(offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] - }; - - Buffer$1.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; - - Buffer$1.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] - }; - - Buffer$1.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; - - Buffer$1.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; - - Buffer$1.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val - }; - - Buffer$1.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val - }; - - Buffer$1.prototype.readInt8 = function readInt8(offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; - - Buffer$1.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; - - Buffer$1.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; - - Buffer$1.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; - - Buffer$1.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) - }; - - Buffer$1.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; - - Buffer$1.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; - - function checkInt(buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer$1.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; - - function objectWriteUInt16(buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - function objectWriteUInt32(buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } - } - - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - Buffer$1.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; - - Buffer$1.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 - }; - - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } - - Buffer$1.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - }; - - function writeDouble(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 - } - - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - }; - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$1.prototype.copy = function copy(target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } - - return len - }; - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$1.prototype.fill = function fill(val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - - if (!val) val = 0; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this - }; - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - - function base64clean(str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; - } - return str - } - - function stringtrim(str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex(n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } - - // valid lead - leadSurrogate = codePoint; - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes(str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - return byteArray - } - - function utf16leToBytes(str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray - } - - - function base64ToBytes(str) { - return toByteArray(base64clean(str)) - } - - function blitBuffer(src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i - } - - function isnan(val) { - return val !== val // eslint-disable-line no-self-compare - } - - - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer$1(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) - } - - function isFastBuffer(obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) - } - - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer(obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) - } - - var inherits; - if (typeof Object.create === 'function') { - inherits = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () { }; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - var inherits$1 = inherits; - - var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - - var formatRegExp = /%[sdj%]/g; - function format$1(f) { - if (!isString$1(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function (x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject$1(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - } - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global$1.process)) { - return function () { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - if (browser$1.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (browser$1.throwDeprecation) { - throw new Error(msg); - } else if (browser$1.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - } - - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = browser$1.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function () { - var msg = format$1.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function () { }; - } - } - return debugs[set]; - } - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold': [1, 22], - 'italic': [3, 23], - 'underline': [4, 24], - 'inverse': [7, 27], - 'white': [37, 39], - 'grey': [90, 39], - 'black': [30, 39], - 'blue': [34, 39], - 'cyan': [36, 39], - 'green': [32, 39], - 'magenta': [35, 39], - 'red': [31, 39], - 'yellow': [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function (val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString$1(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray$1(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function (key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString$1(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty$2(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function (key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty$2(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function (line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function (line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function (prev, cur) { - if (cur.indexOf('\n') >= 0); - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray$1(ar) { - return Array.isArray(ar); - } - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - - function isNull(arg) { - return arg === null; - } - - function isNullOrUndefined(arg) { - return arg == null; - } - - function isNumber(arg) { - return typeof arg === 'number'; - } - - function isString$1(arg) { - return typeof arg === 'string'; - } - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - - function isUndefined(arg) { - return arg === void 0; - } - - function isRegExp(re) { - return isObject$1(re) && objectToString(re) === '[object RegExp]'; - } - - function isObject$1(arg) { - return typeof arg === 'object' && arg !== null; - } - - function isDate(d) { - return isObject$1(d) && objectToString(d) === '[object Date]'; - } - - function isError(e) { - return isObject$1(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - - function isFunction(arg) { - return typeof arg === 'function'; - } - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - - function isBuffer(maybeBuf) { - return Buffer$1.isBuffer(maybeBuf); - } - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - function log() { - console.log('%s - %s', timestamp(), format$1.apply(null, arguments)); - } - - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject$1(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - } - function hasOwnProperty$2(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - - function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); - } - - promisify.custom = kCustomPromisifiedSymbol; - - function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); - } - - function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function () { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function (ret) { browser$1.nextTick(cb.bind(null, null, ret)); }, - function (rej) { browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); - return callbackified; - } - - var _polyfillNode_util = { - inherits: inherits$1, - _extend: _extend, - log: log, - isBuffer: isBuffer, - isPrimitive: isPrimitive, - isFunction: isFunction, - isError: isError, - isDate: isDate, - isObject: isObject$1, - isRegExp: isRegExp, - isUndefined: isUndefined, - isSymbol: isSymbol, - isString: isString$1, - isNumber: isNumber, - isNullOrUndefined: isNullOrUndefined, - isNull: isNull, - isBoolean: isBoolean, - isArray: isArray$1, - inspect: inspect, - deprecate: deprecate, - format: format$1, - debuglog: debuglog, - promisify: promisify, - callbackify: callbackify, - }; - - var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - _extend: _extend, - callbackify: callbackify, - debuglog: debuglog, - default: _polyfillNode_util, - deprecate: deprecate, - format: format$1, - inherits: inherits$1, - inspect: inspect, - isArray: isArray$1, - isBoolean: isBoolean, - isBuffer: isBuffer, - isDate: isDate, - isError: isError, - isFunction: isFunction, - isNull: isNull, - isNullOrUndefined: isNullOrUndefined, - isNumber: isNumber, - isObject: isObject$1, - isPrimitive: isPrimitive, - isRegExp: isRegExp, - isString: isString$1, - isSymbol: isSymbol, - isUndefined: isUndefined, - log: log, - promisify: promisify - }); - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - - // If obj.hasOwnProperty has been overridden, then calling - // obj.hasOwnProperty(prop) will break. - // See: https://github.com/joyent/node/issues/1707 - function hasOwnProperty$1(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; - }; - function stringifyPrimitive(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } - } - - function stringify$5(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return map(objectKeys(obj), function (k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (isArray(obj[k])) { - return map(obj[k], function (v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); - } - function map(xs, f) { - if (xs.map) return xs.map(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - res.push(f(xs[i], i)); - } - return res; - } - - var objectKeys = Object.keys || function (obj) { - var res = []; - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); - } - return res; - }; - - function parse$6(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty$1(obj, k)) { - obj[k] = v; - } else if (isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; - } - - // WHATWG API - const URL$1 = global$1.URL; - const URLSearchParams = global$1.URLSearchParams; - var _polyfillNode_url = { - parse: urlParse, - resolve: urlResolve, - resolveObject: urlResolveObject, - fileURLToPath: urlFileURLToPath, - format: urlFormat, - Url: Url, - - // WHATWG API - URL: URL$1, - URLSearchParams, - }; - function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; - } - - // Reference: RFC 3986, RFC 1808, RFC 2396 - - // define these here so at least they only have to be - // compiled once on the first module load. - var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }; - - function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && isObject$1(url) && url instanceof Url) return url; - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; - } - Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { - return parse$5(this, url, parseQueryString, slashesDenoteHost); - }; - - function parse$5(self, url, parseQueryString, slashesDenoteHost) { - if (!isString$1(url)) { - throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url); - } - - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 - var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; - uSplit[0] = uSplit[0].replace(slashRegex, '/'); - url = uSplit.join(splitter); - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - self.path = rest; - self.href = rest; - self.pathname = simplePath[1]; - if (simplePath[2]) { - self.search = simplePath[2]; - if (parseQueryString) { - self.query = parse$6(self.search.substr(1)); - } else { - self.query = self.search.substr(1); - } - } else if (parseQueryString) { - self.search = ''; - self.query = {}; - } - return self; - } - } - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - self.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - self.slashes = true; - } - } - var i, hec, l, p; - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (i = 0; i < hostEndingChars.length; i++) { - hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - self.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (i = 0; i < nonHostChars.length; i++) { - hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - self.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - parseHost(self); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - self.hostname = self.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = self.hostname[0] === '[' && - self.hostname[self.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = self.hostname.split(/\./); - for (i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - self.hostname = validParts.join('.'); - break; - } - } - } - } - - if (self.hostname.length > hostnameMaxLen) { - self.hostname = ''; - } else { - // hostnames are always lower case. - self.hostname = self.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - self.hostname = toASCII(self.hostname); - } - - p = self.port ? ':' + self.port : ''; - var h = self.hostname || ''; - self.host = h + p; - self.href += self.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - self.hostname = self.hostname.substr(1, self.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - continue; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - self.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - self.search = rest.substr(qm); - self.query = rest.substr(qm + 1); - if (parseQueryString) { - self.query = parse$6(self.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - self.search = ''; - self.query = {}; - } - if (rest) self.pathname = rest; - if (slashedProtocol[lowerProto] && - self.hostname && !self.pathname) { - self.pathname = '/'; - } - - //to support http.request - if (self.pathname || self.search) { - p = self.pathname || ''; - var s = self.search || ''; - self.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - self.href = format(self); - return self; - } - - function urlFileURLToPath(path) { - if (typeof path === 'string') - path = new Url().parse(path); - else if (!(path instanceof Url)) - throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path)); - if (path.protocol !== 'file:') - throw new TypeError('The URL must be of scheme file'); - return getPathFromURLPosix(path); - } - - function getPathFromURLPosix(url) { - const pathname = url.pathname; - for (let n = 0; n < pathname.length; n++) { - if (pathname[n] === '%') { - const third = pathname.codePointAt(n + 2) | 0x20; - if (pathname[n + 1] === '2' && third === 102) { - throw new TypeError( - 'must not include encoded / characters' - ); - } - } - } - return decodeURIComponent(pathname); - } - - // format a parsed object into a url string - function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (isString$1(obj)) obj = parse$5({}, obj); - return format(obj); - } - - function format(self) { - var auth = self.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = self.protocol || '', - pathname = self.pathname || '', - hash = self.hash || '', - host = false, - query = ''; - - if (self.host) { - host = auth + self.host; - } else if (self.hostname) { - host = auth + (self.hostname.indexOf(':') === -1 ? - self.hostname : - '[' + this.hostname + ']'); - if (self.port) { - host += ':' + self.port; - } - } - - if (self.query && - isObject$1(self.query) && - Object.keys(self.query).length) { - query = stringify$5(self.query); - } - - var search = self.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (self.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; - - pathname = pathname.replace(/[?#]/g, function (match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; - } - - Url.prototype.format = function () { - return format(this); - }; - - function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); - } - - Url.prototype.resolve = function (relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); - }; - - function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); - } - - Url.prototype.resolveObject = function (relative) { - if (isString$1(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - var tkeys = Object.keys(this); - for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; - } - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - var relPath; - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; - } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - relPath = relative.pathname && relative.pathname.split('/') || []; - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - var authInHost; - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!isNull(result.pathname) || !isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!isNull(result.pathname) || !isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - }; - - Url.prototype.parseHost = function () { - return parseHost(this); - }; - - function parseHost(self) { - var host = self.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - self.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) self.hostname = host; - } - - var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - URL: URL$1, - URLSearchParams: URLSearchParams, - Url: Url, - default: _polyfillNode_url, - fileURLToPath: urlFileURLToPath, - format: urlFormat, - parse: urlParse, - resolve: urlResolve, - resolveObject: urlResolveObject - }); - - function isRelativeUrl(url) { - const firstChar = url.charAt(0); - return firstChar === "." || firstChar === "~" || firstChar === "@"; - } - const externalRE = /^(https?:)?\/\//; - function isExternalUrl(url) { - return externalRE.test(url); - } - const dataUrlRE = /^\s*data:/i; - function isDataUrl(url) { - return dataUrlRE.test(url); - } - function parseUrl(url) { - const firstChar = url.charAt(0); - if (firstChar === "~") { - const secondChar = url.charAt(1); - url = url.slice(secondChar === "/" ? 2 : 1); - } - return parseUriParts(url); - } - function parseUriParts(urlString) { - return urlParse(isString$2(urlString) ? urlString : "", false, true); - } - - var __defProp$9 = Object.defineProperty; - var __defProps$8 = Object.defineProperties; - var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols; - var __hasOwnProp$9 = Object.prototype.hasOwnProperty; - var __propIsEnum$9 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$9 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$9.call(b, prop)) - __defNormalProp$9(a, prop, b[prop]); - if (__getOwnPropSymbols$9) - for (var prop of __getOwnPropSymbols$9(b)) { - if (__propIsEnum$9.call(b, prop)) - __defNormalProp$9(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b)); - const defaultAssetUrlOptions = { - base: null, - includeAbsolute: false, - tags: { - video: ["src", "poster"], - source: ["src"], - img: ["src"], - image: ["xlink:href", "href"], - use: ["xlink:href", "href"] - } - }; - const normalizeOptions = (options) => { - if (Object.keys(options).some((key) => isArray$3(options[key]))) { - return __spreadProps$8(__spreadValues$9({}, defaultAssetUrlOptions), { - tags: options - }); - } - return __spreadValues$9(__spreadValues$9({}, defaultAssetUrlOptions), options); - }; - const createAssetUrlTransformWithOptions = (options) => { - return (node, context) => transformAssetUrl(node, context, options); - }; - const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => { - if (node.type === 1) { - if (!node.props.length) { - return; - } - const tags = options.tags || defaultAssetUrlOptions.tags; - const attrs = tags[node.tag]; - const wildCardAttrs = tags["*"]; - if (!attrs && !wildCardAttrs) { - return; - } - const assetAttrs = (attrs || []).concat(wildCardAttrs || []); - node.props.forEach((attr, index) => { - if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value || isExternalUrl(attr.value.content) || isDataUrl(attr.value.content) || attr.value.content[0] === "#" || !options.includeAbsolute && !isRelativeUrl(attr.value.content)) { - return; - } - const url = parseUrl(attr.value.content); - if (options.base && attr.value.content[0] === ".") { - const base = parseUrl(options.base); - const protocol = base.protocol || ""; - const host = base.host ? protocol + "//" + base.host : ""; - const basePath = base.path || "/"; - attr.value.content = host + (path.posix || path).join(basePath, url.path + (url.hash || "")); - return; - } - const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context); - node.props[index] = { - type: 7, - name: "bind", - arg: createSimpleExpression(attr.name, true, attr.loc), - exp, - modifiers: [], - loc: attr.loc - }; - }); - } - }; - function getImportsExpressionExp(path2, hash, loc, context) { - if (path2) { - let name; - let exp; - const existingIndex = context.imports.findIndex((i) => i.path === path2); - if (existingIndex > -1) { - name = `_imports_${existingIndex}`; - exp = context.imports[existingIndex].exp; - } else { - name = `_imports_${context.imports.length}`; - exp = createSimpleExpression( - name, - false, - loc, - 3 - ); - context.imports.push({ - exp, - path: decodeURIComponent(path2) - }); - } - if (!hash) { - return exp; - } - const hashExp = `${name} + '${hash}'`; - const finalExp = createSimpleExpression( - hashExp, - false, - loc, - 3 - ); - if (!context.hoistStatic) { - return finalExp; - } - const existingHoistIndex = context.hoists.findIndex((h) => { - return h && h.type === 4 && !h.isStatic && h.content === hashExp; - }); - if (existingHoistIndex > -1) { - return createSimpleExpression( - `_hoisted_${existingHoistIndex + 1}`, - false, - loc, - 3 - ); - } - return context.hoist(finalExp); - } else { - return createSimpleExpression(`''`, false, loc, 3); - } - } - - const srcsetTags = ["img", "source"]; - const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; - const createSrcsetTransformWithOptions = (options) => { - return (node, context) => transformSrcset(node, context, options); - }; - const transformSrcset = (node, context, options = defaultAssetUrlOptions) => { - if (node.type === 1) { - if (srcsetTags.includes(node.tag) && node.props.length) { - node.props.forEach((attr, index) => { - if (attr.name === "srcset" && attr.type === 6) { - if (!attr.value) - return; - const value = attr.value.content; - if (!value) - return; - const imageCandidates = value.split(",").map((s) => { - const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2); - return { url, descriptor }; - }); - for (let i = 0; i < imageCandidates.length; i++) { - const { url } = imageCandidates[i]; - if (isDataUrl(url)) { - imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url; - imageCandidates.splice(i, 1); - } - } - const shouldProcessUrl = (url) => { - return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url)); - }; - if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) { - return; - } - if (options.base) { - const base = options.base; - const set = []; - let needImportTransform = false; - imageCandidates.forEach((candidate) => { - let { url, descriptor } = candidate; - descriptor = descriptor ? ` ${descriptor}` : ``; - if (url[0] === ".") { - candidate.url = (path.posix || path).join(base, url); - set.push(candidate.url + descriptor); - } else if (shouldProcessUrl(url)) { - needImportTransform = true; - } else { - set.push(url + descriptor); - } - }); - if (!needImportTransform) { - attr.value.content = set.join(", "); - return; - } - } - const compoundExpression = createCompoundExpression([], attr.loc); - imageCandidates.forEach(({ url, descriptor }, index2) => { - if (shouldProcessUrl(url)) { - const { path: path2 } = parseUrl(url); - let exp2; - if (path2) { - const existingImportsIndex = context.imports.findIndex( - (i) => i.path === path2 - ); - if (existingImportsIndex > -1) { - exp2 = createSimpleExpression( - `_imports_${existingImportsIndex}`, - false, - attr.loc, - 3 - ); - } else { - exp2 = createSimpleExpression( - `_imports_${context.imports.length}`, - false, - attr.loc, - 3 - ); - context.imports.push({ exp: exp2, path: path2 }); - } - compoundExpression.children.push(exp2); - } - } else { - const exp2 = createSimpleExpression( - `"${url}"`, - false, - attr.loc, - 3 - ); - compoundExpression.children.push(exp2); - } - const isNotLast = imageCandidates.length - 1 > index2; - if (descriptor && isNotLast) { - compoundExpression.children.push(` + ' ${descriptor}, ' + `); - } else if (descriptor) { - compoundExpression.children.push(` + ' ${descriptor}'`); - } else if (isNotLast) { - compoundExpression.children.push(` + ', ' + `); - } - }); - let exp = compoundExpression; - if (context.hoistStatic) { - exp = context.hoist(compoundExpression); - exp.constType = 3; - } - node.props[index] = { - type: 7, - name: "bind", - arg: createSimpleExpression("srcset", true, attr.loc), - exp, - modifiers: [], - loc: attr.loc - }; - } - }); - } - } - }; - - const SSR_INTERPOLATE = Symbol(`ssrInterpolate`); - const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`); - const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`); - const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`); - const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`); - const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`); - const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`); - const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`); - const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`); - const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`); - const SSR_RENDER_LIST = Symbol(`ssrRenderList`); - const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`); - const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`); - const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`); - const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`); - const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`); - const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`); - const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`); - const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`); - const ssrHelpers = { - [SSR_INTERPOLATE]: `ssrInterpolate`, - [SSR_RENDER_VNODE]: `ssrRenderVNode`, - [SSR_RENDER_COMPONENT]: `ssrRenderComponent`, - [SSR_RENDER_SLOT]: `ssrRenderSlot`, - [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`, - [SSR_RENDER_CLASS]: `ssrRenderClass`, - [SSR_RENDER_STYLE]: `ssrRenderStyle`, - [SSR_RENDER_ATTRS]: `ssrRenderAttrs`, - [SSR_RENDER_ATTR]: `ssrRenderAttr`, - [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`, - [SSR_RENDER_LIST]: `ssrRenderList`, - [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`, - [SSR_LOOSE_EQUAL]: `ssrLooseEqual`, - [SSR_LOOSE_CONTAIN]: `ssrLooseContain`, - [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`, - [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`, - [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`, - [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`, - [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps` - }; - registerRuntimeHelpers(ssrHelpers); - - const ssrTransformIf = createStructuralDirectiveTransform( - /^(if|else|else-if)$/, - processIf - ); - function ssrProcessIf(node, context, disableNestedFragments = false) { - const [rootBranch] = node.branches; - const ifStatement = createIfStatement( - rootBranch.condition, - processIfBranch(rootBranch, context, disableNestedFragments) - ); - context.pushStatement(ifStatement); - let currentIf = ifStatement; - for (let i = 1; i < node.branches.length; i++) { - const branch = node.branches[i]; - const branchBlockStatement = processIfBranch( - branch, - context, - disableNestedFragments - ); - if (branch.condition) { - currentIf = currentIf.alternate = createIfStatement( - branch.condition, - branchBlockStatement - ); - } else { - currentIf.alternate = branchBlockStatement; - } - } - if (!currentIf.alternate) { - currentIf.alternate = createBlockStatement([ - createCallExpression(`_push`, ["`<!---->`"]) - ]); - } - } - function processIfBranch(branch, context, disableNestedFragments = false) { - const { children } = branch; - const needFragmentWrapper = !disableNestedFragments && (children.length !== 1 || children[0].type !== 1) && // optimize away nested fragments when the only child is a ForNode - !(children.length === 1 && children[0].type === 11); - return processChildrenAsStatement(branch, context, needFragmentWrapper); - } - - const ssrTransformFor = createStructuralDirectiveTransform( - "for", - processFor - ); - function ssrProcessFor(node, context, disableNestedFragments = false) { - const needFragmentWrapper = !disableNestedFragments && (node.children.length !== 1 || node.children[0].type !== 1); - const renderLoop = createFunctionExpression( - createForLoopParams(node.parseResult) - ); - renderLoop.body = processChildrenAsStatement( - node, - context, - needFragmentWrapper - ); - if (!disableNestedFragments) { - context.pushStringPart(`<!--[-->`); - } - context.pushStatement( - createCallExpression(context.helper(SSR_RENDER_LIST), [ - node.source, - renderLoop - ]) - ); - if (!disableNestedFragments) { - context.pushStringPart(`<!--]-->`); - } - } - - const ssrTransformSlotOutlet = (node, context) => { - if (isSlotOutlet(node)) { - const { slotName, slotProps } = processSlotOutlet(node, context); - const args = [ - `_ctx.$slots`, - slotName, - slotProps || `{}`, - // fallback content placeholder. will be replaced in the process phase - `null`, - `_push`, - `_parent` - ]; - if (context.scopeId && context.slotted !== false) { - args.push(`"${context.scopeId}-s"`); - } - let method = SSR_RENDER_SLOT; - const parent = context.parent; - let componentType; - if (parent && parent.type === 1 && parent.tagType === 1 && ((componentType = resolveComponentType(parent, context, true)) === TRANSITION || componentType === TRANSITION_GROUP) && parent.children.filter((c) => c.type === 1).length === 1) { - method = SSR_RENDER_SLOT_INNER; - if (!(context.scopeId && context.slotted !== false)) { - args.push("null"); - } - args.push("true"); - } - node.ssrCodegenNode = createCallExpression(context.helper(method), args); - } - }; - function ssrProcessSlotOutlet(node, context) { - const renderCall = node.ssrCodegenNode; - if (node.children.length) { - const fallbackRenderFn = createFunctionExpression([]); - fallbackRenderFn.body = processChildrenAsStatement(node, context); - renderCall.arguments[3] = fallbackRenderFn; - } - if (context.withSlotScopeId) { - const slotScopeId = renderCall.arguments[6]; - renderCall.arguments[6] = slotScopeId ? `${slotScopeId} + _scopeId` : `_scopeId`; - } - context.pushStatement(node.ssrCodegenNode); - } - - function createSSRCompilerError(code, loc) { - return createCompilerError(code, loc, SSRErrorMessages); - } - const SSRErrorMessages = { - [65]: `Unsafe attribute name for SSR.`, - [66]: `Missing the 'to' prop on teleport element.`, - [67]: `Invalid AST node during SSR transform.` - }; - - function ssrProcessTeleport(node, context) { - const targetProp = findProp(node, "to"); - if (!targetProp) { - context.onError( - createSSRCompilerError(66, node.loc) - ); - return; - } - let target; - if (targetProp.type === 6) { - target = targetProp.value && createSimpleExpression(targetProp.value.content, true); - } else { - target = targetProp.exp; - } - if (!target) { - context.onError( - createSSRCompilerError( - 66, - targetProp.loc - ) - ); - return; - } - const disabledProp = findProp( - node, - "disabled", - false, - true - /* allow empty */ - ); - const disabled = disabledProp ? disabledProp.type === 6 ? `true` : disabledProp.exp || `false` : `false`; - const contentRenderFn = createFunctionExpression( - [`_push`], - void 0, - // Body is added later - true, - // newline - false, - // isSlot - node.loc - ); - contentRenderFn.body = processChildrenAsStatement(node, context); - context.pushStatement( - createCallExpression(context.helper(SSR_RENDER_TELEPORT), [ - `_push`, - contentRenderFn, - target, - disabled, - `_parent` - ]) - ); - } - - const wipMap$3 = /* @__PURE__ */ new WeakMap(); - function ssrTransformSuspense(node, context) { - return () => { - if (node.children.length) { - const wipEntry = { - slotsExp: null, - // to be immediately set - wipSlots: [] - }; - wipMap$3.set(node, wipEntry); - wipEntry.slotsExp = buildSlots( - node, - context, - (_props, _vForExp, children, loc) => { - const fn = createFunctionExpression( - [], - void 0, - // no return, assign body later - true, - // newline - false, - // suspense slots are not treated as normal slots - loc - ); - wipEntry.wipSlots.push({ - fn, - children - }); - return fn; - } - ).slots; - } - }; - } - function ssrProcessSuspense(node, context) { - const wipEntry = wipMap$3.get(node); - if (!wipEntry) { - return; - } - const { slotsExp, wipSlots } = wipEntry; - for (let i = 0; i < wipSlots.length; i++) { - const slot = wipSlots[i]; - slot.fn.body = processChildrenAsStatement(slot, context); - } - context.pushStatement( - createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [ - `_push`, - slotsExp - ]) - ); - } - - const rawChildrenMap = /* @__PURE__ */ new WeakMap(); - const ssrTransformElement = (node, context) => { - if (node.type !== 1 || node.tagType !== 0) { - return; - } - return function ssrPostTransformElement() { - const openTag = [`<${node.tag}`]; - const needTagForRuntime = node.tag === "textarea" || node.tag.indexOf("-") > 0; - const hasDynamicVBind = hasDynamicKeyVBind(node); - const hasCustomDir = node.props.some( - (p) => p.type === 7 && !isBuiltInDirective(p.name) - ); - const needMergeProps = hasDynamicVBind || hasCustomDir; - if (needMergeProps) { - const { props, directives } = buildProps( - node, - context, - node.props, - false, - false, - true - ); - if (props || directives.length) { - const mergedProps = buildSSRProps(props, directives, context); - const propsExp = createCallExpression( - context.helper(SSR_RENDER_ATTRS), - [mergedProps] - ); - if (node.tag === "textarea") { - const existingText = node.children[0]; - if (!existingText || existingText.type !== 5) { - const tempId = `_temp${context.temps++}`; - propsExp.arguments = [ - createAssignmentExpression( - createSimpleExpression(tempId, false), - mergedProps - ) - ]; - rawChildrenMap.set( - node, - createCallExpression(context.helper(SSR_INTERPOLATE), [ - createConditionalExpression( - createSimpleExpression(`"value" in ${tempId}`, false), - createSimpleExpression(`${tempId}.value`, false), - createSimpleExpression( - existingText ? existingText.content : ``, - true - ), - false - ) - ]) - ); - } - } else if (node.tag === "input") { - const vModel = findVModel(node); - if (vModel) { - const tempId = `_temp${context.temps++}`; - const tempExp = createSimpleExpression(tempId, false); - propsExp.arguments = [ - createSequenceExpression([ - createAssignmentExpression(tempExp, mergedProps), - createCallExpression(context.helper(MERGE_PROPS), [ - tempExp, - createCallExpression( - context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), - [ - tempExp, - // existing props - vModel.exp - // model - ] - ) - ]) - ]) - ]; - } - } - if (needTagForRuntime) { - propsExp.arguments.push(`"${node.tag}"`); - } - openTag.push(propsExp); - } - } - let dynamicClassBinding = void 0; - let staticClassBinding = void 0; - let dynamicStyleBinding = void 0; - for (let i = 0; i < node.props.length; i++) { - const prop = node.props[i]; - if (node.tag === "input" && isTrueFalseValue(prop)) { - continue; - } - if (prop.type === 7) { - if (prop.name === "html" && prop.exp) { - rawChildrenMap.set(node, prop.exp); - } else if (prop.name === "text" && prop.exp) { - node.children = [createInterpolation(prop.exp, prop.loc)]; - } else if (prop.name === "slot") { - context.onError( - createCompilerError(40, prop.loc) - ); - } else if (isTextareaWithValue(node, prop) && prop.exp) { - if (!needMergeProps) { - node.children = [createInterpolation(prop.exp, prop.loc)]; - } - } else if (!needMergeProps && prop.name !== "on") { - const directiveTransform = context.directiveTransforms[prop.name]; - if (directiveTransform) { - const { props, ssrTagParts } = directiveTransform( - prop, - node, - context - ); - if (ssrTagParts) { - openTag.push(...ssrTagParts); - } - for (let j = 0; j < props.length; j++) { - const { key, value } = props[j]; - if (isStaticExp(key)) { - let attrName = key.content; - if (attrName === "key" || attrName === "ref") { - continue; - } - if (attrName === "class") { - openTag.push( - ` class="`, - dynamicClassBinding = createCallExpression( - context.helper(SSR_RENDER_CLASS), - [value] - ), - `"` - ); - } else if (attrName === "style") { - if (dynamicStyleBinding) { - mergeCall(dynamicStyleBinding, value); - } else { - openTag.push( - ` style="`, - dynamicStyleBinding = createCallExpression( - context.helper(SSR_RENDER_STYLE), - [value] - ), - `"` - ); - } - } else { - attrName = node.tag.indexOf("-") > 0 ? attrName : propsToAttrMap[attrName] || attrName.toLowerCase(); - if (isBooleanAttr(attrName)) { - openTag.push( - createConditionalExpression( - createCallExpression( - context.helper(SSR_INCLUDE_BOOLEAN_ATTR), - [value] - ), - createSimpleExpression(" " + attrName, true), - createSimpleExpression("", true), - false - ) - ); - } else if (isSSRSafeAttrName(attrName)) { - openTag.push( - createCallExpression(context.helper(SSR_RENDER_ATTR), [ - key, - value - ]) - ); - } else { - context.onError( - createSSRCompilerError( - 65, - key.loc - ) - ); - } - } - } else { - const args = [key, value]; - if (needTagForRuntime) { - args.push(`"${node.tag}"`); - } - openTag.push( - createCallExpression( - context.helper(SSR_RENDER_DYNAMIC_ATTR), - args - ) - ); - } - } - } - } - } else { - const name = prop.name; - if (node.tag === "textarea" && name === "value" && prop.value) { - rawChildrenMap.set(node, escapeHtml(prop.value.content)); - } else if (!needMergeProps) { - if (name === "key" || name === "ref") { - continue; - } - if (name === "class" && prop.value) { - staticClassBinding = JSON.stringify(prop.value.content); - } - openTag.push( - ` ${prop.name}` + (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``) - ); - } - } - } - if (dynamicClassBinding && staticClassBinding) { - mergeCall(dynamicClassBinding, staticClassBinding); - removeStaticBinding(openTag, "class"); - } - if (context.scopeId) { - openTag.push(` ${context.scopeId}`); - } - node.ssrCodegenNode = createTemplateLiteral(openTag); - }; - }; - function buildSSRProps(props, directives, context) { - let mergePropsArgs = []; - if (props) { - if (props.type === 14) { - mergePropsArgs = props.arguments; - } else { - mergePropsArgs.push(props); - } - } - if (directives.length) { - for (const dir of directives) { - mergePropsArgs.push( - createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [ - `_ctx`, - ...buildDirectiveArgs(dir, context).elements - ]) - ); - } - } - return mergePropsArgs.length > 1 ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs) : mergePropsArgs[0]; - } - function isTrueFalseValue(prop) { - if (prop.type === 7) { - return prop.name === "bind" && prop.arg && isStaticExp(prop.arg) && (prop.arg.content === "true-value" || prop.arg.content === "false-value"); - } else { - return prop.name === "true-value" || prop.name === "false-value"; - } - } - function isTextareaWithValue(node, prop) { - return !!(node.tag === "textarea" && prop.name === "bind" && isStaticArgOf(prop.arg, "value")); - } - function mergeCall(call, arg) { - const existing = call.arguments[0]; - if (existing.type === 17) { - existing.elements.push(arg); - } else { - call.arguments[0] = createArrayExpression([existing, arg]); - } - } - function removeStaticBinding(tag, binding) { - const regExp = new RegExp(`^ ${binding}=".+"$`); - const i = tag.findIndex((e) => typeof e === "string" && regExp.test(e)); - if (i > -1) { - tag.splice(i, 1); - } - } - function findVModel(node) { - return node.props.find( - (p) => p.type === 7 && p.name === "model" && p.exp - ); - } - function ssrProcessElement(node, context) { - const isVoidTag = context.options.isVoidTag || NO; - const elementsToAdd = node.ssrCodegenNode.elements; - for (let j = 0; j < elementsToAdd.length; j++) { - context.pushStringPart(elementsToAdd[j]); - } - if (context.withSlotScopeId) { - context.pushStringPart(createSimpleExpression(`_scopeId`, false)); - } - context.pushStringPart(`>`); - const rawChildren = rawChildrenMap.get(node); - if (rawChildren) { - context.pushStringPart(rawChildren); - } else if (node.children.length) { - processChildren(node, context); - } - if (!isVoidTag(node.tag)) { - context.pushStringPart(`</${node.tag}>`); - } - } - - const wipMap$2 = /* @__PURE__ */ new WeakMap(); - function ssrTransformTransitionGroup(node, context) { - return () => { - const tag = findProp(node, "tag"); - if (tag) { - const otherProps = node.props.filter((p) => p !== tag); - const { props, directives } = buildProps( - node, - context, - otherProps, - true, - false, - true - ); - let propsExp = null; - if (props || directives.length) { - propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [ - buildSSRProps(props, directives, context) - ]); - } - wipMap$2.set(node, { - tag, - propsExp, - scopeId: context.scopeId || null - }); - } - }; - } - function ssrProcessTransitionGroup(node, context) { - const entry = wipMap$2.get(node); - if (entry) { - const { tag, propsExp, scopeId } = entry; - if (tag.type === 7) { - context.pushStringPart(`<`); - context.pushStringPart(tag.exp); - if (propsExp) { - context.pushStringPart(propsExp); - } - if (scopeId) { - context.pushStringPart(` ${scopeId}`); - } - context.pushStringPart(`>`); - processChildren( - node, - context, - false, - /** - * TransitionGroup has the special runtime behavior of flattening and - * concatenating all children into a single fragment (in order for them to - * be patched using the same key map) so we need to account for that here - * by disabling nested fragment wrappers from being generated. - */ - true - ); - context.pushStringPart(`</`); - context.pushStringPart(tag.exp); - context.pushStringPart(`>`); - } else { - context.pushStringPart(`<${tag.value.content}`); - if (propsExp) { - context.pushStringPart(propsExp); - } - if (scopeId) { - context.pushStringPart(` ${scopeId}`); - } - context.pushStringPart(`>`); - processChildren(node, context, false, true); - context.pushStringPart(`</${tag.value.content}>`); - } - } else { - processChildren(node, context, true, true); - } - } - - const wipMap$1 = /* @__PURE__ */ new WeakMap(); - function ssrTransformTransition(node, context) { - return () => { - const appear = findProp(node, "appear", false, true); - wipMap$1.set(node, !!appear); - }; - } - function ssrProcessTransition(node, context) { - node.children = node.children.filter((c) => c.type !== 3); - const appear = wipMap$1.get(node); - if (appear) { - context.pushStringPart(`<template>`); - processChildren(node, context, false, true); - context.pushStringPart(`</template>`); - } else { - processChildren(node, context, false, true); - } - } - - var __defProp$8 = Object.defineProperty; - var __defProps$7 = Object.defineProperties; - var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols; - var __hasOwnProp$8 = Object.prototype.hasOwnProperty; - var __propIsEnum$8 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$8 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$8.call(b, prop)) - __defNormalProp$8(a, prop, b[prop]); - if (__getOwnPropSymbols$8) - for (var prop of __getOwnPropSymbols$8(b)) { - if (__propIsEnum$8.call(b, prop)) - __defNormalProp$8(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b)); - const wipMap = /* @__PURE__ */ new WeakMap(); - const WIP_SLOT = Symbol(); - const componentTypeMap = /* @__PURE__ */ new WeakMap(); - const ssrTransformComponent = (node, context) => { - if (node.type !== 1 || node.tagType !== 1) { - return; - } - const component = resolveComponentType( - node, - context, - true - /* ssr */ - ); - const isDynamicComponent = isObject$2(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT; - componentTypeMap.set(node, component); - if (isSymbol$1(component)) { - if (component === SUSPENSE) { - return ssrTransformSuspense(node, context); - } else if (component === TRANSITION_GROUP) { - return ssrTransformTransitionGroup(node, context); - } else if (component === TRANSITION) { - return ssrTransformTransition(node); - } - return; - } - const vnodeBranches = []; - const clonedNode = clone(node); - return function ssrPostTransformComponent() { - if (clonedNode.children.length) { - buildSlots(clonedNode, context, (props, vFor, children) => { - vnodeBranches.push( - createVNodeSlotBranch(props, vFor, children, context) - ); - return createFunctionExpression(void 0); - }); - } - let propsExp = `null`; - if (node.props.length) { - const { props, directives } = buildProps( - node, - context, - void 0, - true, - isDynamicComponent - ); - if (props || directives.length) { - propsExp = buildSSRProps(props, directives, context); - } - } - const wipEntries = []; - wipMap.set(node, wipEntries); - const buildSSRSlotFn = (props, _vForExp, children, loc) => { - const param0 = props && stringifyExpression(props) || `_`; - const fn = createFunctionExpression( - [param0, `_push`, `_parent`, `_scopeId`], - void 0, - // no return, assign body later - true, - // newline - true, - // isSlot - loc - ); - wipEntries.push({ - type: WIP_SLOT, - fn, - children, - // also collect the corresponding vnode branch built earlier - vnodeBranch: vnodeBranches[wipEntries.length] - }); - return fn; - }; - const slots = node.children.length ? buildSlots(node, context, buildSSRSlotFn).slots : `null`; - if (typeof component !== "string") { - node.ssrCodegenNode = createCallExpression( - context.helper(SSR_RENDER_VNODE), - [ - `_push`, - createCallExpression(context.helper(CREATE_VNODE), [ - component, - propsExp, - slots - ]), - `_parent` - ] - ); - } else { - node.ssrCodegenNode = createCallExpression( - context.helper(SSR_RENDER_COMPONENT), - [component, propsExp, slots, `_parent`] - ); - } - }; - }; - function ssrProcessComponent(node, context, parent) { - const component = componentTypeMap.get(node); - if (!node.ssrCodegenNode) { - if (component === TELEPORT) { - return ssrProcessTeleport(node, context); - } else if (component === SUSPENSE) { - return ssrProcessSuspense(node, context); - } else if (component === TRANSITION_GROUP) { - return ssrProcessTransitionGroup(node, context); - } else { - if (parent.type === WIP_SLOT) { - context.pushStringPart(``); - } - if (component === TRANSITION) { - return ssrProcessTransition(node, context); - } - processChildren(node, context); - } - } else { - const wipEntries = wipMap.get(node) || []; - for (let i = 0; i < wipEntries.length; i++) { - const { fn, vnodeBranch } = wipEntries[i]; - fn.body = createIfStatement( - createSimpleExpression(`_push`, false), - processChildrenAsStatement( - wipEntries[i], - context, - false, - true - ), - vnodeBranch - ); - } - if (context.withSlotScopeId) { - node.ssrCodegenNode.arguments.push(`_scopeId`); - } - if (typeof component === "string") { - context.pushStatement( - createCallExpression(`_push`, [node.ssrCodegenNode]) - ); - } else { - context.pushStatement(node.ssrCodegenNode); - } - } - } - const rawOptionsMap = /* @__PURE__ */ new WeakMap(); - const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true); - const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms]; - const vnodeDirectiveTransforms = __spreadValues$8(__spreadValues$8({}, baseDirectiveTransforms), DOMDirectiveTransforms); - function createVNodeSlotBranch(slotProps, vFor, children, parentContext) { - const rawOptions = rawOptionsMap.get(parentContext.root); - const subOptions = __spreadProps$7(__spreadValues$8({}, rawOptions), { - // overwrite with vnode-based transforms - nodeTransforms: [ - ...vnodeNodeTransforms, - ...rawOptions.nodeTransforms || [] - ], - directiveTransforms: __spreadValues$8(__spreadValues$8({}, vnodeDirectiveTransforms), rawOptions.directiveTransforms || {}) - }); - const wrapperProps = []; - if (slotProps) { - wrapperProps.push({ - type: 7, - name: "slot", - exp: slotProps, - arg: void 0, - modifiers: [], - loc: locStub - }); - } - if (vFor) { - wrapperProps.push(extend({}, vFor)); - } - const wrapperNode = { - type: 1, - ns: 0, - tag: "template", - tagType: 3, - props: wrapperProps, - children, - loc: locStub, - codegenNode: void 0 - }; - subTransform(wrapperNode, subOptions, parentContext); - return createReturnStatement(children); - } - function subTransform(node, options, parentContext) { - const childRoot = createRoot([node]); - const childContext = createTransformContext(childRoot, options); - childContext.ssr = false; - childContext.scopes = __spreadValues$8({}, parentContext.scopes); - childContext.identifiers = __spreadValues$8({}, parentContext.identifiers); - childContext.imports = parentContext.imports; - traverseNode(childRoot, childContext); - ["helpers", "components", "directives"].forEach((key) => { - childContext[key].forEach((value, helperKey) => { - if (key === "helpers") { - const parentCount = parentContext.helpers.get(helperKey); - if (parentCount === void 0) { - parentContext.helpers.set(helperKey, value); - } else { - parentContext.helpers.set(helperKey, value + parentCount); - } - } else { - parentContext[key].add(value); - } - }); - }); - } - function clone(v) { - if (isArray$3(v)) { - return v.map(clone); - } else if (isPlainObject(v)) { - const res = {}; - for (const key in v) { - res[key] = clone(v[key]); - } - return res; - } else { - return v; - } - } - - function ssrCodegenTransform(ast, options) { - const context = createSSRTransformContext(ast, options); - if (options.ssrCssVars) { - const cssContext = createTransformContext(createRoot([]), options); - const varsExp = processExpression( - createSimpleExpression(options.ssrCssVars, false), - cssContext - ); - context.body.push( - createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]) - ); - Array.from(cssContext.helpers.keys()).forEach((helper) => { - ast.helpers.add(helper); - }); - } - const isFragment = ast.children.length > 1 && ast.children.some((c) => !isText$1(c)); - processChildren(ast, context, isFragment); - ast.codegenNode = createBlockStatement(context.body); - ast.ssrHelpers = Array.from( - /* @__PURE__ */ new Set([ - ...Array.from(ast.helpers).filter((h) => h in ssrHelpers), - ...context.helpers - ]) - ); - ast.helpers = new Set(Array.from(ast.helpers).filter((h) => !(h in ssrHelpers))); - } - function createSSRTransformContext(root, options, helpers = /* @__PURE__ */ new Set(), withSlotScopeId = false) { - const body = []; - let currentString = null; - return { - root, - options, - body, - helpers, - withSlotScopeId, - onError: options.onError || ((e) => { - throw e; - }), - helper(name) { - helpers.add(name); - return name; - }, - pushStringPart(part) { - if (!currentString) { - const currentCall = createCallExpression(`_push`); - body.push(currentCall); - currentString = createTemplateLiteral([]); - currentCall.arguments.push(currentString); - } - const bufferedElements = currentString.elements; - const lastItem = bufferedElements[bufferedElements.length - 1]; - if (isString$2(part) && isString$2(lastItem)) { - bufferedElements[bufferedElements.length - 1] += part; - } else { - bufferedElements.push(part); - } - }, - pushStatement(statement) { - currentString = null; - body.push(statement); - } - }; - } - function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) { - return createSSRTransformContext( - parent.root, - parent.options, - parent.helpers, - withSlotScopeId - ); - } - function processChildren(parent, context, asFragment = false, disableNestedFragments = false) { - if (asFragment) { - context.pushStringPart(`<!--[-->`); - } - const { children } = parent; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - switch (child.type) { - case 1: - switch (child.tagType) { - case 0: - ssrProcessElement(child, context); - break; - case 1: - ssrProcessComponent(child, context, parent); - break; - case 2: - ssrProcessSlotOutlet(child, context); - break; - case 3: - break; - default: - context.onError( - createSSRCompilerError( - 67, - child.loc - ) - ); - const exhaustiveCheck2 = child; - return exhaustiveCheck2; - } - break; - case 2: - context.pushStringPart(escapeHtml(child.content)); - break; - case 3: - context.pushStringPart(`<!--${child.content}-->`); - break; - case 5: - context.pushStringPart( - createCallExpression(context.helper(SSR_INTERPOLATE), [ - child.content - ]) - ); - break; - case 9: - ssrProcessIf(child, context, disableNestedFragments); - break; - case 11: - ssrProcessFor(child, context, disableNestedFragments); - break; - case 10: - break; - case 12: - case 8: - break; - default: - context.onError( - createSSRCompilerError( - 67, - child.loc - ) - ); - const exhaustiveCheck = child; - return exhaustiveCheck; - } - } - if (asFragment) { - context.pushStringPart(`<!--]-->`); - } - } - function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) { - const childContext = createChildContext(parentContext, withSlotScopeId); - processChildren(parent, childContext, asFragment); - return createBlockStatement(childContext.body); - } - - const ssrTransformModel = (dir, node, context) => { - const model = dir.exp; - function checkDuplicatedValue() { - const value = findProp(node, "value"); - if (value) { - context.onError( - createDOMCompilerError( - 60, - value.loc - ) - ); - } - } - function processOption(plainNode) { - if (plainNode.tag === "option") { - if (plainNode.props.findIndex((p) => p.name === "selected") === -1) { - const value = findValueBinding(plainNode); - plainNode.ssrCodegenNode.elements.push( - createConditionalExpression( - createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [ - createConditionalExpression( - createCallExpression(`Array.isArray`, [model]), - createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [ - model, - value - ]), - createCallExpression(context.helper(SSR_LOOSE_EQUAL), [ - model, - value - ]) - ) - ]), - createSimpleExpression(" selected", true), - createSimpleExpression("", true), - false - ) - ); - } - } else if (plainNode.tag === "optgroup") { - plainNode.children.forEach( - (option) => processOption(option) - ); - } - } - if (node.tagType === 0) { - const res = { props: [] }; - const defaultProps = [ - // default value binding for text type inputs - createObjectProperty(`value`, model) - ]; - if (node.tag === "input") { - const type = findProp(node, "type"); - if (type) { - const value = findValueBinding(node); - if (type.type === 7) { - res.ssrTagParts = [ - createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [ - type.exp, - model, - value - ]) - ]; - } else if (type.value) { - switch (type.value.content) { - case "radio": - res.props = [ - createObjectProperty( - `checked`, - createCallExpression(context.helper(SSR_LOOSE_EQUAL), [ - model, - value - ]) - ) - ]; - break; - case "checkbox": - const trueValueBinding = findProp(node, "true-value"); - if (trueValueBinding) { - const trueValue = trueValueBinding.type === 6 ? JSON.stringify(trueValueBinding.value.content) : trueValueBinding.exp; - res.props = [ - createObjectProperty( - `checked`, - createCallExpression(context.helper(SSR_LOOSE_EQUAL), [ - model, - trueValue - ]) - ) - ]; - } else { - res.props = [ - createObjectProperty( - `checked`, - createConditionalExpression( - createCallExpression(`Array.isArray`, [model]), - createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [ - model, - value - ]), - model - ) - ) - ]; - } - break; - case "file": - context.onError( - createDOMCompilerError( - 59, - dir.loc - ) - ); - break; - default: - checkDuplicatedValue(); - res.props = defaultProps; - break; - } - } - } else if (hasDynamicKeyVBind(node)); else { - checkDuplicatedValue(); - res.props = defaultProps; - } - } else if (node.tag === "textarea") { - checkDuplicatedValue(); - node.children = [createInterpolation(model, model.loc)]; - } else if (node.tag === "select") { - node.children.forEach((child) => { - if (child.type === 1) { - processOption(child); - } - }); - } else { - context.onError( - createDOMCompilerError( - 57, - dir.loc - ) - ); - } - return res; - } else { - return transformModel$1(dir, node, context); - } - }; - function findValueBinding(node) { - const valueBinding = findProp(node, "value"); - return valueBinding ? valueBinding.type === 7 ? valueBinding.exp : createSimpleExpression(valueBinding.value.content, true) : createSimpleExpression(`null`, false); - } - - const ssrTransformShow = (dir, node, context) => { - if (!dir.exp) { - context.onError( - createDOMCompilerError(61) - ); - } - return { - props: [ - createObjectProperty( - `style`, - createConditionalExpression( - dir.exp, - createSimpleExpression(`null`, false), - createObjectExpression([ - createObjectProperty( - `display`, - createSimpleExpression(`none`, true) - ) - ]), - false - ) - ) - ] - }; - }; - - const filterChild = (node) => node.children.filter((n) => n.type !== 3); - const hasSingleChild = (node) => filterChild(node).length === 1; - const ssrInjectFallthroughAttrs = (node, context) => { - if (node.type === 0) { - context.identifiers._attrs = 1; - } - if (node.type === 1 && node.tagType === 1 && (node.tag === "transition" || node.tag === "Transition" || node.tag === "KeepAlive" || node.tag === "keep-alive")) { - const rootChildren = filterChild(context.root); - if (rootChildren.length === 1 && rootChildren[0] === node) { - if (hasSingleChild(node)) { - injectFallthroughAttrs(node.children[0]); - } - return; - } - } - const parent = context.parent; - if (!parent || parent.type !== 0) { - return; - } - if (node.type === 10 && hasSingleChild(node)) { - let hasEncounteredIf = false; - for (const c of filterChild(parent)) { - if (c.type === 9 || c.type === 1 && findDir(c, "if")) { - if (hasEncounteredIf) - return; - hasEncounteredIf = true; - } else if ( - // node before v-if - !hasEncounteredIf || // non else nodes - !(c.type === 1 && findDir(c, /else/, true)) - ) { - return; - } - } - injectFallthroughAttrs(node.children[0]); - } else if (hasSingleChild(parent)) { - injectFallthroughAttrs(node); - } - }; - function injectFallthroughAttrs(node) { - if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) { - node.props.push({ - type: 7, - name: "bind", - arg: void 0, - exp: createSimpleExpression(`_attrs`, false), - modifiers: [], - loc: locStub - }); - } - } - - const ssrInjectCssVars = (node, context) => { - if (!context.ssrCssVars) { - return; - } - if (node.type === 0) { - context.identifiers._cssVars = 1; - } - const parent = context.parent; - if (!parent || parent.type !== 0) { - return; - } - if (node.type === 10) { - for (const child of node.children) { - injectCssVars(child); - } - } else { - injectCssVars(node); - } - }; - function injectCssVars(node) { - if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) { - if (node.tag === "suspense" || node.tag === "Suspense") { - for (const child of node.children) { - if (child.type === 1 && child.tagType === 3) { - child.children.forEach(injectCssVars); - } else { - injectCssVars(child); - } - } - } else { - node.props.push({ - type: 7, - name: "bind", - arg: void 0, - exp: createSimpleExpression(`_cssVars`, false), - modifiers: [], - loc: locStub - }); - } - } - } - - var __defProp$7 = Object.defineProperty; - var __defProps$6 = Object.defineProperties; - var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols; - var __hasOwnProp$7 = Object.prototype.hasOwnProperty; - var __propIsEnum$7 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$7 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$7.call(b, prop)) - __defNormalProp$7(a, prop, b[prop]); - if (__getOwnPropSymbols$7) - for (var prop of __getOwnPropSymbols$7(b)) { - if (__propIsEnum$7.call(b, prop)) - __defNormalProp$7(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b)); - function compile(source, options = {}) { - options = __spreadProps$6(__spreadValues$7(__spreadValues$7({}, options), parserOptions), { - ssr: true, - inSSR: true, - scopeId: options.mode === "function" ? null : options.scopeId, - // always prefix since compiler-ssr doesn't have size concern - prefixIdentifiers: true, - // disable optimizations that are unnecessary for ssr - cacheHandlers: false, - hoistStatic: false - }); - const ast = typeof source === "string" ? baseParse(source, options) : source; - rawOptionsMap.set(ast, options); - transform(ast, __spreadProps$6(__spreadValues$7({}, options), { - hoistStatic: false, - nodeTransforms: [ - ssrTransformIf, - ssrTransformFor, - trackVForSlotScopes, - transformExpression, - ssrTransformSlotOutlet, - ssrInjectFallthroughAttrs, - ssrInjectCssVars, - ssrTransformElement, - ssrTransformComponent, - trackSlotScopes, - transformStyle, - ...options.nodeTransforms || [] - // user transforms - ], - directiveTransforms: __spreadValues$7({ - // reusing core v-bind - bind: transformBind, - on: transformOn$1, - // model and show have dedicated SSR handling - model: ssrTransformModel, - show: ssrTransformShow, - // the following are ignored during SSR - // on: noopDirectiveTransform, - cloak: noopDirectiveTransform, - once: noopDirectiveTransform, - memo: noopDirectiveTransform - }, options.directiveTransforms || {}) - })); - ssrCodegenTransform(ast, options); - return generate(ast, options); - } - - var CompilerSSR = /*#__PURE__*/Object.freeze({ - __proto__: null, - compile: compile - }); - - var _polyfillNode_fs = {}; - - var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - default: _polyfillNode_fs - }); - - var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1); - - var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path); - - var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1); - - const hasWarned = {}; - function warnOnce$3(msg) { - const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production"; - if (!isNodeProd && true && !hasWarned[msg]) { - hasWarned[msg] = true; - warn(msg); - } - } - function warn(msg) { - console.warn( - `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m -` - ); - } - - var __defProp$6 = Object.defineProperty; - var __defProps$5 = Object.defineProperties; - var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols; - var __hasOwnProp$6 = Object.prototype.hasOwnProperty; - var __propIsEnum$6 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$6 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$6.call(b, prop)) - __defNormalProp$6(a, prop, b[prop]); - if (__getOwnPropSymbols$6) - for (var prop of __getOwnPropSymbols$6(b)) { - if (__propIsEnum$6.call(b, prop)) - __defNormalProp$6(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b)); - function preprocess$1({ source, filename, preprocessOptions }, preprocessor) { - let res = ""; - let err = null; - preprocessor.render( - source, - __spreadValues$6({ filename }, preprocessOptions), - (_err, _res) => { - if (_err) - err = _err; - res = _res; - } - ); - if (err) - throw err; - return res; - } - function compileTemplate(options) { - const { preprocessLang, preprocessCustomRequire } = options; - if (preprocessLang && !preprocessCustomRequire) { - throw new Error( - `[@vue/compiler-sfc] Template preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor in the shape of { render(): string }.` - ); - } - const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : void 0 : false; - if (preprocessor) { - try { - return doCompileTemplate(__spreadProps$5(__spreadValues$6({}, options), { - source: preprocess$1(options, preprocessor), - ast: void 0 - // invalidate AST if template goes through preprocessor - })); - } catch (e) { - return { - code: `export default function render() {}`, - source: options.source, - tips: [], - errors: [e] - }; - } - } else if (preprocessLang) { - return { - code: `export default function render() {}`, - source: options.source, - tips: [ - `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.` - ], - errors: [ - `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.` - ] - }; - } else { - return doCompileTemplate(options); - } - } - function doCompileTemplate({ - filename, - id, - scoped, - slotted, - inMap, - source, - ast: inAST, - ssr = false, - ssrCssVars, - isProd = false, - compiler, - compilerOptions = {}, - transformAssetUrls - }) { - const errors = []; - const warnings = []; - let nodeTransforms = []; - if (isObject$2(transformAssetUrls)) { - const assetOptions = normalizeOptions(transformAssetUrls); - nodeTransforms = [ - createAssetUrlTransformWithOptions(assetOptions), - createSrcsetTransformWithOptions(assetOptions) - ]; - } else if (transformAssetUrls !== false) { - nodeTransforms = [transformAssetUrl, transformSrcset]; - } - if (ssr && !ssrCssVars) { - warnOnce$3( - `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.\`.` - ); - } - if (!id) { - warnOnce$3(`compileTemplate now requires the \`id\` option.\`.`); - id = ""; - } - const shortId = id.replace(/^data-v-/, ""); - const longId = `data-v-${shortId}`; - const defaultCompiler = ssr ? CompilerSSR : CompilerDOM; - compiler = compiler || defaultCompiler; - if (compiler !== defaultCompiler) { - inAST = void 0; - } - if (inAST == null ? void 0 : inAST.transformed) { - const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, __spreadProps$5(__spreadValues$6({ - prefixIdentifiers: true - }, compilerOptions), { - parseMode: "sfc", - onError: (e) => errors.push(e) - })); - const template = newAST.children.find( - (node) => node.type === 1 && node.tag === "template" - ); - inAST = createRoot(template.children, inAST.source); - } - let { code, ast, preamble, map } = compiler.compile(inAST || source, __spreadProps$5(__spreadValues$6({ - mode: "module", - prefixIdentifiers: true, - hoistStatic: true, - cacheHandlers: true, - ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "", - scopeId: scoped ? longId : void 0, - slotted, - sourceMap: true - }, compilerOptions), { - hmr: !isProd, - nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), - filename, - onError: (e) => errors.push(e), - onWarn: (w) => warnings.push(w) - })); - if (inMap && !inAST) { - if (map) { - map = mapLines(inMap, map); - } - if (errors.length) { - patchErrors(errors, source, inMap); - } - } - const tips = warnings.map((w) => { - let msg = w.message; - if (w.loc) { - msg += ` -${generateCodeFrame( - (inAST == null ? void 0 : inAST.source) || source, - w.loc.start.offset, - w.loc.end.offset - )}`; - } - return msg; - }); - return { code, ast, preamble, source, errors, tips, map }; - } - function mapLines(oldMap, newMap) { - if (!oldMap) - return newMap; - if (!newMap) - return oldMap; - const oldMapConsumer = new SourceMapConsumer$5(oldMap); - const newMapConsumer = new SourceMapConsumer$5(newMap); - const mergedMapGenerator = new SourceMapGenerator$6(); - newMapConsumer.eachMapping((m) => { - if (m.originalLine == null) { - return; - } - const origPosInOldMap = oldMapConsumer.originalPositionFor({ - line: m.originalLine, - column: m.originalColumn - }); - if (origPosInOldMap.source == null) { - return; - } - mergedMapGenerator.addMapping({ - generated: { - line: m.generatedLine, - column: m.generatedColumn - }, - original: { - line: origPosInOldMap.line, - // map line - // use current column, since the oldMap produced by @vue/compiler-sfc - // does not - column: m.originalColumn - }, - source: origPosInOldMap.source, - name: origPosInOldMap.name - }); - }); - const generator = mergedMapGenerator; - oldMapConsumer.sources.forEach((sourceFile) => { - generator._sources.add(sourceFile); - const sourceContent = oldMapConsumer.sourceContentFor(sourceFile); - if (sourceContent != null) { - mergedMapGenerator.setSourceContent(sourceFile, sourceContent); - } - }); - generator._sourceRoot = oldMap.sourceRoot; - generator._file = oldMap.file; - return generator.toJSON(); - } - function patchErrors(errors, source, inMap) { - const originalSource = inMap.sourcesContent[0]; - const offset = originalSource.indexOf(source); - const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1; - errors.forEach((err) => { - if (err.loc) { - err.loc.start.line += lineOffset; - err.loc.start.offset += offset; - if (err.loc.end !== err.loc.start) { - err.loc.end.line += lineOffset; - err.loc.end.offset += offset; - } - } - }); - } - - var picocolors = { exports: {} }; - - // MIT lisence - // from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js - - function isatty() { - return false; - } - - function ReadStream() { - throw new Error('tty.ReadStream is not implemented'); - } - - function WriteStream() { - throw new Error('tty.ReadStream is not implemented'); - } - - var _polyfillNode_tty = { - isatty: isatty, - ReadStream: ReadStream, - WriteStream: WriteStream - }; - - var _polyfillNode_tty$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - ReadStream: ReadStream, - WriteStream: WriteStream, - default: _polyfillNode_tty, - isatty: isatty - }); - - var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_tty$1); - - let tty = require$$0; - - let isColorSupported = - !("NO_COLOR" in ({}) || browser$1.argv.includes("--no-color")) && - ("FORCE_COLOR" in ({}) || - browser$1.argv.includes("--color") || - "" === "win32" || - (tty.isatty(1) && browser$1.env.TERM !== "dumb") || - "CI" in ({})); - - let formatter = - (open, close, replace = open) => - input => { - let string = "" + input; - let index = string.indexOf(close, open.length); - return ~index - ? open + replaceClose(string, close, replace, index) + close - : open + string + close - }; - - let replaceClose = (string, close, replace, index) => { - let start = string.substring(0, index) + replace; - let end = string.substring(index + close.length); - let nextIndex = end.indexOf(close); - return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end - }; - - let createColors = (enabled = isColorSupported) => ({ - isColorSupported: enabled, - reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, - bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, - dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, - italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, - underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, - inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, - hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, - strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, - black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, - red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, - green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, - yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, - blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, - magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, - cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, - white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, - gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, - bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, - bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, - bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, - bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, - bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, - bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, - bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, - bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, - }); - - picocolors.exports = createColors(); - picocolors.exports.createColors = createColors; - - var picocolorsExports = picocolors.exports; - - const SINGLE_QUOTE = "'".charCodeAt(0); - const DOUBLE_QUOTE = '"'.charCodeAt(0); - const BACKSLASH = '\\'.charCodeAt(0); - const SLASH = '/'.charCodeAt(0); - const NEWLINE = '\n'.charCodeAt(0); - const SPACE = ' '.charCodeAt(0); - const FEED = '\f'.charCodeAt(0); - const TAB = '\t'.charCodeAt(0); - const CR = '\r'.charCodeAt(0); - const OPEN_SQUARE = '['.charCodeAt(0); - const CLOSE_SQUARE = ']'.charCodeAt(0); - const OPEN_PARENTHESES = '('.charCodeAt(0); - const CLOSE_PARENTHESES = ')'.charCodeAt(0); - const OPEN_CURLY = '{'.charCodeAt(0); - const CLOSE_CURLY = '}'.charCodeAt(0); - const SEMICOLON = ';'.charCodeAt(0); - const ASTERISK = '*'.charCodeAt(0); - const COLON = ':'.charCodeAt(0); - const AT = '@'.charCodeAt(0); - - const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g; - const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g; - const RE_BAD_BRACKET = /.[\r\n"'(/\\]/; - const RE_HEX_ESCAPE = /[\da-f]/i; - - var tokenize$1 = function tokenizer(input, options = {}) { - let css = input.css.valueOf(); - let ignore = options.ignoreErrors; - - let code, next, quote, content, escape; - let escaped, escapePos, prev, n, currentToken; - - let length = css.length; - let pos = 0; - let buffer = []; - let returned = []; - - function position() { - return pos - } - - function unclosed(what) { - throw input.error('Unclosed ' + what, pos) - } - - function endOfFile() { - return returned.length === 0 && pos >= length - } - - function nextToken(opts) { - if (returned.length) return returned.pop() - if (pos >= length) return - - let ignoreUnclosed = opts ? opts.ignoreUnclosed : false; - - code = css.charCodeAt(pos); - - switch (code) { - case NEWLINE: - case SPACE: - case TAB: - case CR: - case FEED: { - next = pos; - do { - next += 1; - code = css.charCodeAt(next); - } while ( - code === SPACE || - code === NEWLINE || - code === TAB || - code === CR || - code === FEED - ) - - currentToken = ['space', css.slice(pos, next)]; - pos = next - 1; - break - } - - case OPEN_SQUARE: - case CLOSE_SQUARE: - case OPEN_CURLY: - case CLOSE_CURLY: - case COLON: - case SEMICOLON: - case CLOSE_PARENTHESES: { - let controlChar = String.fromCharCode(code); - currentToken = [controlChar, controlChar, pos]; - break - } - - case OPEN_PARENTHESES: { - prev = buffer.length ? buffer.pop()[1] : ''; - n = css.charCodeAt(pos + 1); - if ( - prev === 'url' && - n !== SINGLE_QUOTE && - n !== DOUBLE_QUOTE && - n !== SPACE && - n !== NEWLINE && - n !== TAB && - n !== FEED && - n !== CR - ) { - next = pos; - do { - escaped = false; - next = css.indexOf(')', next + 1); - if (next === -1) { - if (ignore || ignoreUnclosed) { - next = pos; - break - } else { - unclosed('bracket'); - } - } - escapePos = next; - while (css.charCodeAt(escapePos - 1) === BACKSLASH) { - escapePos -= 1; - escaped = !escaped; - } - } while (escaped) - - currentToken = ['brackets', css.slice(pos, next + 1), pos, next]; - - pos = next; - } else { - next = css.indexOf(')', pos + 1); - content = css.slice(pos, next + 1); - - if (next === -1 || RE_BAD_BRACKET.test(content)) { - currentToken = ['(', '(', pos]; - } else { - currentToken = ['brackets', content, pos, next]; - pos = next; - } - } - - break - } - - case SINGLE_QUOTE: - case DOUBLE_QUOTE: { - quote = code === SINGLE_QUOTE ? "'" : '"'; - next = pos; - do { - escaped = false; - next = css.indexOf(quote, next + 1); - if (next === -1) { - if (ignore || ignoreUnclosed) { - next = pos + 1; - break - } else { - unclosed('string'); - } - } - escapePos = next; - while (css.charCodeAt(escapePos - 1) === BACKSLASH) { - escapePos -= 1; - escaped = !escaped; - } - } while (escaped) - - currentToken = ['string', css.slice(pos, next + 1), pos, next]; - pos = next; - break - } - - case AT: { - RE_AT_END.lastIndex = pos + 1; - RE_AT_END.test(css); - if (RE_AT_END.lastIndex === 0) { - next = css.length - 1; - } else { - next = RE_AT_END.lastIndex - 2; - } - - currentToken = ['at-word', css.slice(pos, next + 1), pos, next]; - - pos = next; - break - } - - case BACKSLASH: { - next = pos; - escape = true; - while (css.charCodeAt(next + 1) === BACKSLASH) { - next += 1; - escape = !escape; - } - code = css.charCodeAt(next + 1); - if ( - escape && - code !== SLASH && - code !== SPACE && - code !== NEWLINE && - code !== TAB && - code !== CR && - code !== FEED - ) { - next += 1; - if (RE_HEX_ESCAPE.test(css.charAt(next))) { - while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) { - next += 1; - } - if (css.charCodeAt(next + 1) === SPACE) { - next += 1; - } - } - } - - currentToken = ['word', css.slice(pos, next + 1), pos, next]; - - pos = next; - break - } - - default: { - if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { - next = css.indexOf('*/', pos + 2) + 1; - if (next === 0) { - if (ignore || ignoreUnclosed) { - next = css.length; - } else { - unclosed('comment'); - } - } - - currentToken = ['comment', css.slice(pos, next + 1), pos, next]; - pos = next; - } else { - RE_WORD_END.lastIndex = pos + 1; - RE_WORD_END.test(css); - if (RE_WORD_END.lastIndex === 0) { - next = css.length - 1; - } else { - next = RE_WORD_END.lastIndex - 2; - } - - currentToken = ['word', css.slice(pos, next + 1), pos, next]; - buffer.push(currentToken); - pos = next; - } - - break - } - } - - pos++; - return currentToken - } - - function back(token) { - returned.push(token); - } - - return { - back, - endOfFile, - nextToken, - position - } - }; - - let pico$1 = picocolorsExports; - - let tokenizer$1 = tokenize$1; - - let Input$5; - - function registerInput(dependant) { - Input$5 = dependant; - } - - const HIGHLIGHT_THEME = { - ';': pico$1.yellow, - ':': pico$1.yellow, - '(': pico$1.cyan, - ')': pico$1.cyan, - '[': pico$1.yellow, - ']': pico$1.yellow, - '{': pico$1.yellow, - '}': pico$1.yellow, - 'at-word': pico$1.cyan, - 'brackets': pico$1.cyan, - 'call': pico$1.cyan, - 'class': pico$1.yellow, - 'comment': pico$1.gray, - 'hash': pico$1.magenta, - 'string': pico$1.green - }; - - function getTokenType([type, value], processor) { - if (type === 'word') { - if (value[0] === '.') { - return 'class' - } - if (value[0] === '#') { - return 'hash' - } - } - - if (!processor.endOfFile()) { - let next = processor.nextToken(); - processor.back(next); - if (next[0] === 'brackets' || next[0] === '(') return 'call' - } - - return type - } - - function terminalHighlight$2(css) { - let processor = tokenizer$1(new Input$5(css), { ignoreErrors: true }); - let result = ''; - while (!processor.endOfFile()) { - let token = processor.nextToken(); - let color = HIGHLIGHT_THEME[getTokenType(token, processor)]; - if (color) { - result += token[1] - .split(/\r?\n/) - .map(i => color(i)) - .join('\n'); - } else { - result += token[1]; - } - } - return result - } - - terminalHighlight$2.registerInput = registerInput; - - var terminalHighlight_1 = terminalHighlight$2; - - let pico = picocolorsExports; - - let terminalHighlight$1 = terminalHighlight_1; - - let CssSyntaxError$3 = class CssSyntaxError extends Error { - constructor(message, line, column, source, file, plugin) { - super(message); - this.name = 'CssSyntaxError'; - this.reason = message; - - if (file) { - this.file = file; - } - if (source) { - this.source = source; - } - if (plugin) { - this.plugin = plugin; - } - if (typeof line !== 'undefined' && typeof column !== 'undefined') { - if (typeof line === 'number') { - this.line = line; - this.column = column; - } else { - this.line = line.line; - this.column = line.column; - this.endLine = column.line; - this.endColumn = column.column; - } - } - - this.setMessage(); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, CssSyntaxError); - } - } - - setMessage() { - this.message = this.plugin ? this.plugin + ': ' : ''; - this.message += this.file ? this.file : '<css input>'; - if (typeof this.line !== 'undefined') { - this.message += ':' + this.line + ':' + this.column; - } - this.message += ': ' + this.reason; - } - - showSourceCode(color) { - if (!this.source) return '' - - let css = this.source; - if (color == null) color = pico.isColorSupported; - if (terminalHighlight$1) { - if (color) css = terminalHighlight$1(css); - } - - let lines = css.split(/\r?\n/); - let start = Math.max(this.line - 3, 0); - let end = Math.min(this.line + 2, lines.length); - - let maxWidth = String(end).length; - - let mark, aside; - if (color) { - let { bold, gray, red } = pico.createColors(true); - mark = text => bold(red(text)); - aside = text => gray(text); - } else { - mark = aside = str => str; - } - - return lines - .slice(start, end) - .map((line, index) => { - let number = start + 1 + index; - let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '; - if (number === this.line) { - let spacing = - aside(gutter.replace(/\d/g, ' ')) + - line.slice(0, this.column - 1).replace(/[^\t]/g, ' '); - return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^') - } - return ' ' + aside(gutter) + line - }) - .join('\n') - } - - toString() { - let code = this.showSourceCode(); - if (code) { - code = '\n\n' + code + '\n'; - } - return this.name + ': ' + this.message + code - } - }; - - var cssSyntaxError = CssSyntaxError$3; - CssSyntaxError$3.default = CssSyntaxError$3; - - var symbols = {}; - - symbols.isClean = Symbol('isClean'); - - symbols.my = Symbol('my'); - - const DEFAULT_RAW = { - after: '\n', - beforeClose: '\n', - beforeComment: '\n', - beforeDecl: '\n', - beforeOpen: ' ', - beforeRule: '\n', - colon: ': ', - commentLeft: ' ', - commentRight: ' ', - emptyBody: '', - indent: ' ', - semicolon: false - }; - - function capitalize(str) { - return str[0].toUpperCase() + str.slice(1) - } - - let Stringifier$2 = class Stringifier { - constructor(builder) { - this.builder = builder; - } - - atrule(node, semicolon) { - let name = '@' + node.name; - let params = node.params ? this.rawValue(node, 'params') : ''; - - if (typeof node.raws.afterName !== 'undefined') { - name += node.raws.afterName; - } else if (params) { - name += ' '; - } - - if (node.nodes) { - this.block(node, name + params); - } else { - let end = (node.raws.between || '') + (semicolon ? ';' : ''); - this.builder(name + params + end, node); - } - } - - beforeAfter(node, detect) { - let value; - if (node.type === 'decl') { - value = this.raw(node, null, 'beforeDecl'); - } else if (node.type === 'comment') { - value = this.raw(node, null, 'beforeComment'); - } else if (detect === 'before') { - value = this.raw(node, null, 'beforeRule'); - } else { - value = this.raw(node, null, 'beforeClose'); - } - - let buf = node.parent; - let depth = 0; - while (buf && buf.type !== 'root') { - depth += 1; - buf = buf.parent; - } - - if (value.includes('\n')) { - let indent = this.raw(node, null, 'indent'); - if (indent.length) { - for (let step = 0; step < depth; step++) value += indent; - } - } - - return value - } - - block(node, start) { - let between = this.raw(node, 'between', 'beforeOpen'); - this.builder(start + between + '{', node, 'start'); - - let after; - if (node.nodes && node.nodes.length) { - this.body(node); - after = this.raw(node, 'after'); - } else { - after = this.raw(node, 'after', 'emptyBody'); - } - - if (after) this.builder(after); - this.builder('}', node, 'end'); - } - - body(node) { - let last = node.nodes.length - 1; - while (last > 0) { - if (node.nodes[last].type !== 'comment') break - last -= 1; - } - - let semicolon = this.raw(node, 'semicolon'); - for (let i = 0; i < node.nodes.length; i++) { - let child = node.nodes[i]; - let before = this.raw(child, 'before'); - if (before) this.builder(before); - this.stringify(child, last !== i || semicolon); - } - } - - comment(node) { - let left = this.raw(node, 'left', 'commentLeft'); - let right = this.raw(node, 'right', 'commentRight'); - this.builder('/*' + left + node.text + right + '*/', node); - } - - decl(node, semicolon) { - let between = this.raw(node, 'between', 'colon'); - let string = node.prop + between + this.rawValue(node, 'value'); - - if (node.important) { - string += node.raws.important || ' !important'; - } - - if (semicolon) string += ';'; - this.builder(string, node); - } - - document(node) { - this.body(node); - } - - raw(node, own, detect) { - let value; - if (!detect) detect = own; - - // Already had - if (own) { - value = node.raws[own]; - if (typeof value !== 'undefined') return value - } - - let parent = node.parent; - - if (detect === 'before') { - // Hack for first rule in CSS - if (!parent || (parent.type === 'root' && parent.first === node)) { - return '' - } - - // `root` nodes in `document` should use only their own raws - if (parent && parent.type === 'document') { - return '' - } - } - - // Floating child without parent - if (!parent) return DEFAULT_RAW[detect] - - // Detect style by other nodes - let root = node.root(); - if (!root.rawCache) root.rawCache = {}; - if (typeof root.rawCache[detect] !== 'undefined') { - return root.rawCache[detect] - } - - if (detect === 'before' || detect === 'after') { - return this.beforeAfter(node, detect) - } else { - let method = 'raw' + capitalize(detect); - if (this[method]) { - value = this[method](root, node); - } else { - root.walk(i => { - value = i.raws[own]; - if (typeof value !== 'undefined') return false - }); - } - } - - if (typeof value === 'undefined') value = DEFAULT_RAW[detect]; - - root.rawCache[detect] = value; - return value - } - - rawBeforeClose(root) { - let value; - root.walk(i => { - if (i.nodes && i.nodes.length > 0) { - if (typeof i.raws.after !== 'undefined') { - value = i.raws.after; - if (value.includes('\n')) { - value = value.replace(/[^\n]+$/, ''); - } - return false - } - } - }); - if (value) value = value.replace(/\S/g, ''); - return value - } - - rawBeforeComment(root, node) { - let value; - root.walkComments(i => { - if (typeof i.raws.before !== 'undefined') { - value = i.raws.before; - if (value.includes('\n')) { - value = value.replace(/[^\n]+$/, ''); - } - return false - } - }); - if (typeof value === 'undefined') { - value = this.raw(node, null, 'beforeDecl'); - } else if (value) { - value = value.replace(/\S/g, ''); - } - return value - } - - rawBeforeDecl(root, node) { - let value; - root.walkDecls(i => { - if (typeof i.raws.before !== 'undefined') { - value = i.raws.before; - if (value.includes('\n')) { - value = value.replace(/[^\n]+$/, ''); - } - return false - } - }); - if (typeof value === 'undefined') { - value = this.raw(node, null, 'beforeRule'); - } else if (value) { - value = value.replace(/\S/g, ''); - } - return value - } - - rawBeforeOpen(root) { - let value; - root.walk(i => { - if (i.type !== 'decl') { - value = i.raws.between; - if (typeof value !== 'undefined') return false - } - }); - return value - } - - rawBeforeRule(root) { - let value; - root.walk(i => { - if (i.nodes && (i.parent !== root || root.first !== i)) { - if (typeof i.raws.before !== 'undefined') { - value = i.raws.before; - if (value.includes('\n')) { - value = value.replace(/[^\n]+$/, ''); - } - return false - } - } - }); - if (value) value = value.replace(/\S/g, ''); - return value - } - - rawColon(root) { - let value; - root.walkDecls(i => { - if (typeof i.raws.between !== 'undefined') { - value = i.raws.between.replace(/[^\s:]/g, ''); - return false - } - }); - return value - } - - rawEmptyBody(root) { - let value; - root.walk(i => { - if (i.nodes && i.nodes.length === 0) { - value = i.raws.after; - if (typeof value !== 'undefined') return false - } - }); - return value - } - - rawIndent(root) { - if (root.raws.indent) return root.raws.indent - let value; - root.walk(i => { - let p = i.parent; - if (p && p !== root && p.parent && p.parent === root) { - if (typeof i.raws.before !== 'undefined') { - let parts = i.raws.before.split('\n'); - value = parts[parts.length - 1]; - value = value.replace(/\S/g, ''); - return false - } - } - }); - return value - } - - rawSemicolon(root) { - let value; - root.walk(i => { - if (i.nodes && i.nodes.length && i.last.type === 'decl') { - value = i.raws.semicolon; - if (typeof value !== 'undefined') return false - } - }); - return value - } - - rawValue(node, prop) { - let value = node[prop]; - let raw = node.raws[prop]; - if (raw && raw.value === value) { - return raw.raw - } - - return value - } - - root(node) { - this.body(node); - if (node.raws.after) this.builder(node.raws.after); - } - - rule(node) { - this.block(node, this.rawValue(node, 'selector')); - if (node.raws.ownSemicolon) { - this.builder(node.raws.ownSemicolon, node, 'end'); - } - } - - stringify(node, semicolon) { - /* c8 ignore start */ - if (!this[node.type]) { - throw new Error( - 'Unknown AST node type ' + - node.type + - '. ' + - 'Maybe you need to change PostCSS stringifier.' - ) - } - /* c8 ignore stop */ - this[node.type](node, semicolon); - } - }; - - var stringifier = Stringifier$2; - Stringifier$2.default = Stringifier$2; - - let Stringifier$1 = stringifier; - - function stringify$4(node, builder) { - let str = new Stringifier$1(builder); - str.stringify(node); - } - - var stringify_1 = stringify$4; - stringify$4.default = stringify$4; - - let { isClean: isClean$2, my: my$2 } = symbols; - let CssSyntaxError$2 = cssSyntaxError; - let Stringifier = stringifier; - let stringify$3 = stringify_1; - - function cloneNode(obj, parent) { - let cloned = new obj.constructor(); - - for (let i in obj) { - if (!Object.prototype.hasOwnProperty.call(obj, i)) { - /* c8 ignore next 2 */ - continue - } - if (i === 'proxyCache') continue - let value = obj[i]; - let type = typeof value; - - if (i === 'parent' && type === 'object') { - if (parent) cloned[i] = parent; - } else if (i === 'source') { - cloned[i] = value; - } else if (Array.isArray(value)) { - cloned[i] = value.map(j => cloneNode(j, cloned)); - } else { - if (type === 'object' && value !== null) value = cloneNode(value); - cloned[i] = value; - } - } - - return cloned - } - - let Node$4 = class Node { - constructor(defaults = {}) { - this.raws = {}; - this[isClean$2] = false; - this[my$2] = true; - - for (let name in defaults) { - if (name === 'nodes') { - this.nodes = []; - for (let node of defaults[name]) { - if (typeof node.clone === 'function') { - this.append(node.clone()); - } else { - this.append(node); - } - } - } else { - this[name] = defaults[name]; - } - } - } - - addToError(error) { - error.postcssNode = this; - if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { - let s = this.source; - error.stack = error.stack.replace( - /\n\s{4}at /, - `$&${s.input.from}:${s.start.line}:${s.start.column}$&` - ); - } - return error - } - - after(add) { - this.parent.insertAfter(this, add); - return this - } - - assign(overrides = {}) { - for (let name in overrides) { - this[name] = overrides[name]; - } - return this - } - - before(add) { - this.parent.insertBefore(this, add); - return this - } - - cleanRaws(keepBetween) { - delete this.raws.before; - delete this.raws.after; - if (!keepBetween) delete this.raws.between; - } - - clone(overrides = {}) { - let cloned = cloneNode(this); - for (let name in overrides) { - cloned[name] = overrides[name]; - } - return cloned - } - - cloneAfter(overrides = {}) { - let cloned = this.clone(overrides); - this.parent.insertAfter(this, cloned); - return cloned - } - - cloneBefore(overrides = {}) { - let cloned = this.clone(overrides); - this.parent.insertBefore(this, cloned); - return cloned - } - - error(message, opts = {}) { - if (this.source) { - let { end, start } = this.rangeBy(opts); - return this.source.input.error( - message, - { column: start.column, line: start.line }, - { column: end.column, line: end.line }, - opts - ) - } - return new CssSyntaxError$2(message) - } - - getProxyProcessor() { - return { - get(node, prop) { - if (prop === 'proxyOf') { - return node - } else if (prop === 'root') { - return () => node.root().toProxy() - } else { - return node[prop] - } - }, - - set(node, prop, value) { - if (node[prop] === value) return true - node[prop] = value; - if ( - prop === 'prop' || - prop === 'value' || - prop === 'name' || - prop === 'params' || - prop === 'important' || - /* c8 ignore next */ - prop === 'text' - ) { - node.markDirty(); - } - return true - } - } - } - - markDirty() { - if (this[isClean$2]) { - this[isClean$2] = false; - let next = this; - while ((next = next.parent)) { - next[isClean$2] = false; - } - } - } - - next() { - if (!this.parent) return undefined - let index = this.parent.index(this); - return this.parent.nodes[index + 1] - } - - positionBy(opts, stringRepresentation) { - let pos = this.source.start; - if (opts.index) { - pos = this.positionInside(opts.index, stringRepresentation); - } else if (opts.word) { - stringRepresentation = this.toString(); - let index = stringRepresentation.indexOf(opts.word); - if (index !== -1) pos = this.positionInside(index, stringRepresentation); - } - return pos - } - - positionInside(index, stringRepresentation) { - let string = stringRepresentation || this.toString(); - let column = this.source.start.column; - let line = this.source.start.line; - - for (let i = 0; i < index; i++) { - if (string[i] === '\n') { - column = 1; - line += 1; - } else { - column += 1; - } - } - - return { column, line } - } - - prev() { - if (!this.parent) return undefined - let index = this.parent.index(this); - return this.parent.nodes[index - 1] - } - - rangeBy(opts) { - let start = { - column: this.source.start.column, - line: this.source.start.line - }; - let end = this.source.end - ? { - column: this.source.end.column + 1, - line: this.source.end.line - } - : { - column: start.column + 1, - line: start.line - }; - - if (opts.word) { - let stringRepresentation = this.toString(); - let index = stringRepresentation.indexOf(opts.word); - if (index !== -1) { - start = this.positionInside(index, stringRepresentation); - end = this.positionInside(index + opts.word.length, stringRepresentation); - } - } else { - if (opts.start) { - start = { - column: opts.start.column, - line: opts.start.line - }; - } else if (opts.index) { - start = this.positionInside(opts.index); - } - - if (opts.end) { - end = { - column: opts.end.column, - line: opts.end.line - }; - } else if (opts.endIndex) { - end = this.positionInside(opts.endIndex); - } else if (opts.index) { - end = this.positionInside(opts.index + 1); - } - } - - if ( - end.line < start.line || - (end.line === start.line && end.column <= start.column) - ) { - end = { column: start.column + 1, line: start.line }; - } - - return { end, start } - } - - raw(prop, defaultType) { - let str = new Stringifier(); - return str.raw(this, prop, defaultType) - } - - remove() { - if (this.parent) { - this.parent.removeChild(this); - } - this.parent = undefined; - return this - } - - replaceWith(...nodes) { - if (this.parent) { - let bookmark = this; - let foundSelf = false; - for (let node of nodes) { - if (node === this) { - foundSelf = true; - } else if (foundSelf) { - this.parent.insertAfter(bookmark, node); - bookmark = node; - } else { - this.parent.insertBefore(bookmark, node); - } - } - - if (!foundSelf) { - this.remove(); - } - } - - return this - } - - root() { - let result = this; - while (result.parent && result.parent.type !== 'document') { - result = result.parent; - } - return result - } - - toJSON(_, inputs) { - let fixed = {}; - let emitInputs = inputs == null; - inputs = inputs || new Map(); - let inputsNextIndex = 0; - - for (let name in this) { - if (!Object.prototype.hasOwnProperty.call(this, name)) { - /* c8 ignore next 2 */ - continue - } - if (name === 'parent' || name === 'proxyCache') continue - let value = this[name]; - - if (Array.isArray(value)) { - fixed[name] = value.map(i => { - if (typeof i === 'object' && i.toJSON) { - return i.toJSON(null, inputs) - } else { - return i - } - }); - } else if (typeof value === 'object' && value.toJSON) { - fixed[name] = value.toJSON(null, inputs); - } else if (name === 'source') { - let inputId = inputs.get(value.input); - if (inputId == null) { - inputId = inputsNextIndex; - inputs.set(value.input, inputsNextIndex); - inputsNextIndex++; - } - fixed[name] = { - end: value.end, - inputId, - start: value.start - }; - } else { - fixed[name] = value; - } - } - - if (emitInputs) { - fixed.inputs = [...inputs.keys()].map(input => input.toJSON()); - } - - return fixed - } - - toProxy() { - if (!this.proxyCache) { - this.proxyCache = new Proxy(this, this.getProxyProcessor()); - } - return this.proxyCache - } - - toString(stringifier = stringify$3) { - if (stringifier.stringify) stringifier = stringifier.stringify; - let result = ''; - stringifier(this, i => { - result += i; - }); - return result - } - - warn(result, text, opts) { - let data = { node: this }; - for (let i in opts) data[i] = opts[i]; - return result.warn(text, data) - } - - get proxyOf() { - return this - } - }; - - var node$2 = Node$4; - Node$4.default = Node$4; - - let Node$3 = node$2; - - let Declaration$4 = class Declaration extends Node$3 { - constructor(defaults) { - if ( - defaults && - typeof defaults.value !== 'undefined' && - typeof defaults.value !== 'string' - ) { - defaults = { ...defaults, value: String(defaults.value) }; - } - super(defaults); - this.type = 'decl'; - } - - get variable() { - return this.prop.startsWith('--') || this.prop[0] === '$' - } - }; - - var declaration = Declaration$4; - Declaration$4.default = Declaration$4; - - var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1); - - let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let customAlphabet = (alphabet, defaultSize = 21) => { - return (size = defaultSize) => { - let id = ''; - let i = size; - while (i--) { - id += alphabet[(Math.random() * alphabet.length) | 0]; - } - return id - } - }; - let nanoid$1 = (size = 21) => { - let id = ''; - let i = size; - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id - }; - var nonSecure = { nanoid: nanoid$1, customAlphabet }; - - let { SourceMapConsumer: SourceMapConsumer$4, SourceMapGenerator: SourceMapGenerator$5 } = sourceMap$2; - let { existsSync, readFileSync } = require$$0$2; - let { dirname: dirname$1, join } = require$$1; - - function fromBase64(str) { - if (Buffer$1) { - return Buffer$1.from(str, 'base64').toString() - } else { - /* c8 ignore next 2 */ - return window.atob(str) - } - } - - let PreviousMap$2 = class PreviousMap { - constructor(css, opts) { - if (opts.map === false) return - this.loadAnnotation(css); - this.inline = this.startWith(this.annotation, 'data:'); - - let prev = opts.map ? opts.map.prev : undefined; - let text = this.loadMap(opts.from, prev); - if (!this.mapFile && opts.from) { - this.mapFile = opts.from; - } - if (this.mapFile) this.root = dirname$1(this.mapFile); - if (text) this.text = text; - } - - consumer() { - if (!this.consumerCache) { - this.consumerCache = new SourceMapConsumer$4(this.text); - } - return this.consumerCache - } - - decodeInline(text) { - let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/; - let baseUri = /^data:application\/json;base64,/; - let charsetUri = /^data:application\/json;charset=utf-?8,/; - let uri = /^data:application\/json,/; - - if (charsetUri.test(text) || uri.test(text)) { - return decodeURIComponent(text.substr(RegExp.lastMatch.length)) - } - - if (baseCharsetUri.test(text) || baseUri.test(text)) { - return fromBase64(text.substr(RegExp.lastMatch.length)) - } - - let encoding = text.match(/data:application\/json;([^,]+),/)[1]; - throw new Error('Unsupported source map encoding ' + encoding) - } - - getAnnotationURL(sourceMapString) { - return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim() - } - - isMap(map) { - if (typeof map !== 'object') return false - return ( - typeof map.mappings === 'string' || - typeof map._mappings === 'string' || - Array.isArray(map.sections) - ) - } - - loadAnnotation(css) { - let comments = css.match(/\/\*\s*# sourceMappingURL=/gm); - if (!comments) return - - // sourceMappingURLs from comments, strings, etc. - let start = css.lastIndexOf(comments.pop()); - let end = css.indexOf('*/', start); - - if (start > -1 && end > -1) { - // Locate the last sourceMappingURL to avoid pickin - this.annotation = this.getAnnotationURL(css.substring(start, end)); - } - } - - loadFile(path) { - this.root = dirname$1(path); - if (existsSync(path)) { - this.mapFile = path; - return readFileSync(path, 'utf-8').toString().trim() - } - } - - loadMap(file, prev) { - if (prev === false) return false - - if (prev) { - if (typeof prev === 'string') { - return prev - } else if (typeof prev === 'function') { - let prevPath = prev(file); - if (prevPath) { - let map = this.loadFile(prevPath); - if (!map) { - throw new Error( - 'Unable to load previous source map: ' + prevPath.toString() - ) - } - return map - } - } else if (prev instanceof SourceMapConsumer$4) { - return SourceMapGenerator$5.fromSourceMap(prev).toString() - } else if (prev instanceof SourceMapGenerator$5) { - return prev.toString() - } else if (this.isMap(prev)) { - return JSON.stringify(prev) - } else { - throw new Error( - 'Unsupported previous source map format: ' + prev.toString() - ) - } - } else if (this.inline) { - return this.decodeInline(this.annotation) - } else if (this.annotation) { - let map = this.annotation; - if (file) map = join(dirname$1(file), map); - return this.loadFile(map) - } - } - - startWith(string, start) { - if (!string) return false - return string.substr(0, start.length) === start - } - - withContent() { - return !!( - this.consumer().sourcesContent && - this.consumer().sourcesContent.length > 0 - ) - } - }; - - var previousMap = PreviousMap$2; - PreviousMap$2.default = PreviousMap$2; - - let { SourceMapConsumer: SourceMapConsumer$3, SourceMapGenerator: SourceMapGenerator$4 } = sourceMap$2; - let { fileURLToPath, pathToFileURL: pathToFileURL$1 } = require$$2; - let { isAbsolute, resolve: resolve$1 } = require$$1; - let { nanoid } = nonSecure; - - let terminalHighlight = terminalHighlight_1; - let CssSyntaxError$1 = cssSyntaxError; - let PreviousMap$1 = previousMap; - - let fromOffsetCache = Symbol('fromOffsetCache'); - - let sourceMapAvailable$1 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$4); - let pathAvailable$1 = Boolean(resolve$1 && isAbsolute); - - let Input$4 = class Input { - constructor(css, opts = {}) { - if ( - css === null || - typeof css === 'undefined' || - (typeof css === 'object' && !css.toString) - ) { - throw new Error(`PostCSS received ${css} instead of CSS string`) - } - - this.css = css.toString(); - - if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { - this.hasBOM = true; - this.css = this.css.slice(1); - } else { - this.hasBOM = false; - } - - if (opts.from) { - if ( - !pathAvailable$1 || - /^\w+:\/\//.test(opts.from) || - isAbsolute(opts.from) - ) { - this.file = opts.from; - } else { - this.file = resolve$1(opts.from); - } - } - - if (pathAvailable$1 && sourceMapAvailable$1) { - let map = new PreviousMap$1(this.css, opts); - if (map.text) { - this.map = map; - let file = map.consumer().file; - if (!this.file && file) this.file = this.mapResolve(file); - } - } - - if (!this.file) { - this.id = '<input css ' + nanoid(6) + '>'; - } - if (this.map) this.map.file = this.from; - } - - error(message, line, column, opts = {}) { - let result, endLine, endColumn; - - if (line && typeof line === 'object') { - let start = line; - let end = column; - if (typeof start.offset === 'number') { - let pos = this.fromOffset(start.offset); - line = pos.line; - column = pos.col; - } else { - line = start.line; - column = start.column; - } - if (typeof end.offset === 'number') { - let pos = this.fromOffset(end.offset); - endLine = pos.line; - endColumn = pos.col; - } else { - endLine = end.line; - endColumn = end.column; - } - } else if (!column) { - let pos = this.fromOffset(line); - line = pos.line; - column = pos.col; - } - - let origin = this.origin(line, column, endLine, endColumn); - if (origin) { - result = new CssSyntaxError$1( - message, - origin.endLine === undefined - ? origin.line - : { column: origin.column, line: origin.line }, - origin.endLine === undefined - ? origin.column - : { column: origin.endColumn, line: origin.endLine }, - origin.source, - origin.file, - opts.plugin - ); - } else { - result = new CssSyntaxError$1( - message, - endLine === undefined ? line : { column, line }, - endLine === undefined ? column : { column: endColumn, line: endLine }, - this.css, - this.file, - opts.plugin - ); - } - - result.input = { column, endColumn, endLine, line, source: this.css }; - if (this.file) { - if (pathToFileURL$1) { - result.input.url = pathToFileURL$1(this.file).toString(); - } - result.input.file = this.file; - } - - return result - } - - fromOffset(offset) { - let lastLine, lineToIndex; - if (!this[fromOffsetCache]) { - let lines = this.css.split('\n'); - lineToIndex = new Array(lines.length); - let prevIndex = 0; - - for (let i = 0, l = lines.length; i < l; i++) { - lineToIndex[i] = prevIndex; - prevIndex += lines[i].length + 1; - } - - this[fromOffsetCache] = lineToIndex; - } else { - lineToIndex = this[fromOffsetCache]; - } - lastLine = lineToIndex[lineToIndex.length - 1]; - - let min = 0; - if (offset >= lastLine) { - min = lineToIndex.length - 1; - } else { - let max = lineToIndex.length - 2; - let mid; - while (min < max) { - mid = min + ((max - min) >> 1); - if (offset < lineToIndex[mid]) { - max = mid - 1; - } else if (offset >= lineToIndex[mid + 1]) { - min = mid + 1; - } else { - min = mid; - break - } - } - } - return { - col: offset - lineToIndex[min] + 1, - line: min + 1 - } - } - - mapResolve(file) { - if (/^\w+:\/\//.test(file)) { - return file - } - return resolve$1(this.map.consumer().sourceRoot || this.map.root || '.', file) - } - - origin(line, column, endLine, endColumn) { - if (!this.map) return false - let consumer = this.map.consumer(); - - let from = consumer.originalPositionFor({ column, line }); - if (!from.source) return false - - let to; - if (typeof endLine === 'number') { - to = consumer.originalPositionFor({ column: endColumn, line: endLine }); - } - - let fromUrl; - - if (isAbsolute(from.source)) { - fromUrl = pathToFileURL$1(from.source); - } else { - fromUrl = new URL( - from.source, - this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile) - ); - } - - let result = { - column: from.column, - endColumn: to && to.column, - endLine: to && to.line, - line: from.line, - url: fromUrl.toString() - }; - - if (fromUrl.protocol === 'file:') { - if (fileURLToPath) { - result.file = fileURLToPath(fromUrl); - } else { - /* c8 ignore next 2 */ - throw new Error(`file: protocol is not available in this PostCSS build`) - } - } - - let source = consumer.sourceContentFor(from.source); - if (source) result.source = source; - - return result - } - - toJSON() { - let json = {}; - for (let name of ['hasBOM', 'css', 'file', 'id']) { - if (this[name] != null) { - json[name] = this[name]; - } - } - if (this.map) { - json.map = { ...this.map }; - if (json.map.consumerCache) { - json.map.consumerCache = undefined; - } - } - return json - } - - get from() { - return this.file || this.id - } - }; - - var input = Input$4; - Input$4.default = Input$4; - - if (terminalHighlight && terminalHighlight.registerInput) { - terminalHighlight.registerInput(Input$4); - } - - let { SourceMapConsumer: SourceMapConsumer$2, SourceMapGenerator: SourceMapGenerator$3 } = sourceMap$2; - let { dirname, relative, resolve, sep } = require$$1; - let { pathToFileURL } = require$$2; - - let Input$3 = input; - - let sourceMapAvailable = Boolean(SourceMapConsumer$2 && SourceMapGenerator$3); - let pathAvailable = Boolean(dirname && resolve && relative && sep); - - let MapGenerator$2 = class MapGenerator { - constructor(stringify, root, opts, cssString) { - this.stringify = stringify; - this.mapOpts = opts.map || {}; - this.root = root; - this.opts = opts; - this.css = cssString; - this.originalCSS = cssString; - this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute; - - this.memoizedFileURLs = new Map(); - this.memoizedPaths = new Map(); - this.memoizedURLs = new Map(); - } - - addAnnotation() { - let content; - - if (this.isInline()) { - content = - 'data:application/json;base64,' + this.toBase64(this.map.toString()); - } else if (typeof this.mapOpts.annotation === 'string') { - content = this.mapOpts.annotation; - } else if (typeof this.mapOpts.annotation === 'function') { - content = this.mapOpts.annotation(this.opts.to, this.root); - } else { - content = this.outputFile() + '.map'; - } - let eol = '\n'; - if (this.css.includes('\r\n')) eol = '\r\n'; - - this.css += eol + '/*# sourceMappingURL=' + content + ' */'; - } - - applyPrevMaps() { - for (let prev of this.previous()) { - let from = this.toUrl(this.path(prev.file)); - let root = prev.root || dirname(prev.file); - let map; - - if (this.mapOpts.sourcesContent === false) { - map = new SourceMapConsumer$2(prev.text); - if (map.sourcesContent) { - map.sourcesContent = null; - } - } else { - map = prev.consumer(); - } - - this.map.applySourceMap(map, from, this.toUrl(this.path(root))); - } - } - - clearAnnotation() { - if (this.mapOpts.annotation === false) return - - if (this.root) { - let node; - for (let i = this.root.nodes.length - 1; i >= 0; i--) { - node = this.root.nodes[i]; - if (node.type !== 'comment') continue - if (node.text.indexOf('# sourceMappingURL=') === 0) { - this.root.removeChild(i); - } - } - } else if (this.css) { - this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, ''); - } - } - - generate() { - this.clearAnnotation(); - if (pathAvailable && sourceMapAvailable && this.isMap()) { - return this.generateMap() - } else { - let result = ''; - this.stringify(this.root, i => { - result += i; - }); - return [result] - } - } - - generateMap() { - if (this.root) { - this.generateString(); - } else if (this.previous().length === 1) { - let prev = this.previous()[0].consumer(); - prev.file = this.outputFile(); - this.map = SourceMapGenerator$3.fromSourceMap(prev); - } else { - this.map = new SourceMapGenerator$3({ file: this.outputFile() }); - this.map.addMapping({ - generated: { column: 0, line: 1 }, - original: { column: 0, line: 1 }, - source: this.opts.from - ? this.toUrl(this.path(this.opts.from)) - : '<no source>' - }); - } - - if (this.isSourcesContent()) this.setSourcesContent(); - if (this.root && this.previous().length > 0) this.applyPrevMaps(); - if (this.isAnnotation()) this.addAnnotation(); - - if (this.isInline()) { - return [this.css] - } else { - return [this.css, this.map] - } - } - - generateString() { - this.css = ''; - this.map = new SourceMapGenerator$3({ file: this.outputFile() }); - - let line = 1; - let column = 1; - - let noSource = '<no source>'; - let mapping = { - generated: { column: 0, line: 0 }, - original: { column: 0, line: 0 }, - source: '' - }; - - let lines, last; - this.stringify(this.root, (str, node, type) => { - this.css += str; - - if (node && type !== 'end') { - mapping.generated.line = line; - mapping.generated.column = column - 1; - if (node.source && node.source.start) { - mapping.source = this.sourcePath(node); - mapping.original.line = node.source.start.line; - mapping.original.column = node.source.start.column - 1; - this.map.addMapping(mapping); - } else { - mapping.source = noSource; - mapping.original.line = 1; - mapping.original.column = 0; - this.map.addMapping(mapping); - } - } - - lines = str.match(/\n/g); - if (lines) { - line += lines.length; - last = str.lastIndexOf('\n'); - column = str.length - last; - } else { - column += str.length; - } - - if (node && type !== 'start') { - let p = node.parent || { raws: {} }; - let childless = - node.type === 'decl' || (node.type === 'atrule' && !node.nodes); - if (!childless || node !== p.last || p.raws.semicolon) { - if (node.source && node.source.end) { - mapping.source = this.sourcePath(node); - mapping.original.line = node.source.end.line; - mapping.original.column = node.source.end.column - 1; - mapping.generated.line = line; - mapping.generated.column = column - 2; - this.map.addMapping(mapping); - } else { - mapping.source = noSource; - mapping.original.line = 1; - mapping.original.column = 0; - mapping.generated.line = line; - mapping.generated.column = column - 1; - this.map.addMapping(mapping); - } - } - } - }); - } - - isAnnotation() { - if (this.isInline()) { - return true - } - if (typeof this.mapOpts.annotation !== 'undefined') { - return this.mapOpts.annotation - } - if (this.previous().length) { - return this.previous().some(i => i.annotation) - } - return true - } - - isInline() { - if (typeof this.mapOpts.inline !== 'undefined') { - return this.mapOpts.inline - } - - let annotation = this.mapOpts.annotation; - if (typeof annotation !== 'undefined' && annotation !== true) { - return false - } - - if (this.previous().length) { - return this.previous().some(i => i.inline) - } - return true - } - - isMap() { - if (typeof this.opts.map !== 'undefined') { - return !!this.opts.map - } - return this.previous().length > 0 - } - - isSourcesContent() { - if (typeof this.mapOpts.sourcesContent !== 'undefined') { - return this.mapOpts.sourcesContent - } - if (this.previous().length) { - return this.previous().some(i => i.withContent()) - } - return true - } - - outputFile() { - if (this.opts.to) { - return this.path(this.opts.to) - } else if (this.opts.from) { - return this.path(this.opts.from) - } else { - return 'to.css' - } - } - - path(file) { - if (this.mapOpts.absolute) return file - if (file.charCodeAt(0) === 60 /* `<` */) return file - if (/^\w+:\/\//.test(file)) return file - let cached = this.memoizedPaths.get(file); - if (cached) return cached - - let from = this.opts.to ? dirname(this.opts.to) : '.'; - - if (typeof this.mapOpts.annotation === 'string') { - from = dirname(resolve(from, this.mapOpts.annotation)); - } - - let path = relative(from, file); - this.memoizedPaths.set(file, path); - - return path - } - - previous() { - if (!this.previousMaps) { - this.previousMaps = []; - if (this.root) { - this.root.walk(node => { - if (node.source && node.source.input.map) { - let map = node.source.input.map; - if (!this.previousMaps.includes(map)) { - this.previousMaps.push(map); - } - } - }); - } else { - let input = new Input$3(this.originalCSS, this.opts); - if (input.map) this.previousMaps.push(input.map); - } - } - - return this.previousMaps - } - - setSourcesContent() { - let already = {}; - if (this.root) { - this.root.walk(node => { - if (node.source) { - let from = node.source.input.from; - if (from && !already[from]) { - already[from] = true; - let fromUrl = this.usesFileUrls - ? this.toFileUrl(from) - : this.toUrl(this.path(from)); - this.map.setSourceContent(fromUrl, node.source.input.css); - } - } - }); - } else if (this.css) { - let from = this.opts.from - ? this.toUrl(this.path(this.opts.from)) - : '<no source>'; - this.map.setSourceContent(from, this.css); - } - } - - sourcePath(node) { - if (this.mapOpts.from) { - return this.toUrl(this.mapOpts.from) - } else if (this.usesFileUrls) { - return this.toFileUrl(node.source.input.from) - } else { - return this.toUrl(this.path(node.source.input.from)) - } - } - - toBase64(str) { - if (Buffer$1) { - return Buffer$1.from(str).toString('base64') - } else { - return window.btoa(unescape(encodeURIComponent(str))) - } - } - - toFileUrl(path) { - let cached = this.memoizedFileURLs.get(path); - if (cached) return cached - - if (pathToFileURL) { - let fileURL = pathToFileURL(path).toString(); - this.memoizedFileURLs.set(path, fileURL); - - return fileURL - } else { - throw new Error( - '`map.absolute` option is not available in this PostCSS build' - ) - } - } - - toUrl(path) { - let cached = this.memoizedURLs.get(path); - if (cached) return cached - - if (sep === '\\') { - path = path.replace(/\\/g, '/'); - } - - let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent); - this.memoizedURLs.set(path, url); - - return url - } - }; - - var mapGenerator = MapGenerator$2; - - let Node$2 = node$2; - - let Comment$4 = class Comment extends Node$2 { - constructor(defaults) { - super(defaults); - this.type = 'comment'; - } - }; - - var comment$3 = Comment$4; - Comment$4.default = Comment$4; - - let { isClean: isClean$1, my: my$1 } = symbols; - let Declaration$3 = declaration; - let Comment$3 = comment$3; - let Node$1 = node$2; - - let parse$4, Rule$4, AtRule$4, Root$6; - - function cleanSource(nodes) { - return nodes.map(i => { - if (i.nodes) i.nodes = cleanSource(i.nodes); - delete i.source; - return i - }) - } - - function markDirtyUp(node) { - node[isClean$1] = false; - if (node.proxyOf.nodes) { - for (let i of node.proxyOf.nodes) { - markDirtyUp(i); - } - } - } - - let Container$7 = class Container extends Node$1 { - append(...children) { - for (let child of children) { - let nodes = this.normalize(child, this.last); - for (let node of nodes) this.proxyOf.nodes.push(node); - } - - this.markDirty(); - - return this - } - - cleanRaws(keepBetween) { - super.cleanRaws(keepBetween); - if (this.nodes) { - for (let node of this.nodes) node.cleanRaws(keepBetween); - } - } - - each(callback) { - if (!this.proxyOf.nodes) return undefined - let iterator = this.getIterator(); - - let index, result; - while (this.indexes[iterator] < this.proxyOf.nodes.length) { - index = this.indexes[iterator]; - result = callback(this.proxyOf.nodes[index], index); - if (result === false) break - - this.indexes[iterator] += 1; - } - - delete this.indexes[iterator]; - return result - } - - every(condition) { - return this.nodes.every(condition) - } - - getIterator() { - if (!this.lastEach) this.lastEach = 0; - if (!this.indexes) this.indexes = {}; - - this.lastEach += 1; - let iterator = this.lastEach; - this.indexes[iterator] = 0; - - return iterator - } - - getProxyProcessor() { - return { - get(node, prop) { - if (prop === 'proxyOf') { - return node - } else if (!node[prop]) { - return node[prop] - } else if ( - prop === 'each' || - (typeof prop === 'string' && prop.startsWith('walk')) - ) { - return (...args) => { - return node[prop]( - ...args.map(i => { - if (typeof i === 'function') { - return (child, index) => i(child.toProxy(), index) - } else { - return i - } - }) - ) - } - } else if (prop === 'every' || prop === 'some') { - return cb => { - return node[prop]((child, ...other) => - cb(child.toProxy(), ...other) - ) - } - } else if (prop === 'root') { - return () => node.root().toProxy() - } else if (prop === 'nodes') { - return node.nodes.map(i => i.toProxy()) - } else if (prop === 'first' || prop === 'last') { - return node[prop].toProxy() - } else { - return node[prop] - } - }, - - set(node, prop, value) { - if (node[prop] === value) return true - node[prop] = value; - if (prop === 'name' || prop === 'params' || prop === 'selector') { - node.markDirty(); - } - return true - } - } - } - - index(child) { - if (typeof child === 'number') return child - if (child.proxyOf) child = child.proxyOf; - return this.proxyOf.nodes.indexOf(child) - } - - insertAfter(exist, add) { - let existIndex = this.index(exist); - let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse(); - existIndex = this.index(exist); - for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node); - - let index; - for (let id in this.indexes) { - index = this.indexes[id]; - if (existIndex < index) { - this.indexes[id] = index + nodes.length; - } - } - - this.markDirty(); - - return this - } - - insertBefore(exist, add) { - let existIndex = this.index(exist); - let type = existIndex === 0 ? 'prepend' : false; - let nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse(); - existIndex = this.index(exist); - for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node); - - let index; - for (let id in this.indexes) { - index = this.indexes[id]; - if (existIndex <= index) { - this.indexes[id] = index + nodes.length; - } - } - - this.markDirty(); - - return this - } - - normalize(nodes, sample) { - if (typeof nodes === 'string') { - nodes = cleanSource(parse$4(nodes).nodes); - } else if (typeof nodes === 'undefined') { - nodes = []; - } else if (Array.isArray(nodes)) { - nodes = nodes.slice(0); - for (let i of nodes) { - if (i.parent) i.parent.removeChild(i, 'ignore'); - } - } else if (nodes.type === 'root' && this.type !== 'document') { - nodes = nodes.nodes.slice(0); - for (let i of nodes) { - if (i.parent) i.parent.removeChild(i, 'ignore'); - } - } else if (nodes.type) { - nodes = [nodes]; - } else if (nodes.prop) { - if (typeof nodes.value === 'undefined') { - throw new Error('Value field is missed in node creation') - } else if (typeof nodes.value !== 'string') { - nodes.value = String(nodes.value); - } - nodes = [new Declaration$3(nodes)]; - } else if (nodes.selector) { - nodes = [new Rule$4(nodes)]; - } else if (nodes.name) { - nodes = [new AtRule$4(nodes)]; - } else if (nodes.text) { - nodes = [new Comment$3(nodes)]; - } else { - throw new Error('Unknown node type in node creation') - } - - let processed = nodes.map(i => { - /* c8 ignore next */ - if (!i[my$1]) Container.rebuild(i); - i = i.proxyOf; - if (i.parent) i.parent.removeChild(i); - if (i[isClean$1]) markDirtyUp(i); - if (typeof i.raws.before === 'undefined') { - if (sample && typeof sample.raws.before !== 'undefined') { - i.raws.before = sample.raws.before.replace(/\S/g, ''); - } - } - i.parent = this.proxyOf; - return i - }); - - return processed - } - - prepend(...children) { - children = children.reverse(); - for (let child of children) { - let nodes = this.normalize(child, this.first, 'prepend').reverse(); - for (let node of nodes) this.proxyOf.nodes.unshift(node); - for (let id in this.indexes) { - this.indexes[id] = this.indexes[id] + nodes.length; - } - } - - this.markDirty(); - - return this - } - - push(child) { - child.parent = this; - this.proxyOf.nodes.push(child); - return this - } - - removeAll() { - for (let node of this.proxyOf.nodes) node.parent = undefined; - this.proxyOf.nodes = []; - - this.markDirty(); - - return this - } - - removeChild(child) { - child = this.index(child); - this.proxyOf.nodes[child].parent = undefined; - this.proxyOf.nodes.splice(child, 1); - - let index; - for (let id in this.indexes) { - index = this.indexes[id]; - if (index >= child) { - this.indexes[id] = index - 1; - } - } - - this.markDirty(); - - return this - } - - replaceValues(pattern, opts, callback) { - if (!callback) { - callback = opts; - opts = {}; - } - - this.walkDecls(decl => { - if (opts.props && !opts.props.includes(decl.prop)) return - if (opts.fast && !decl.value.includes(opts.fast)) return - - decl.value = decl.value.replace(pattern, callback); - }); - - this.markDirty(); - - return this - } - - some(condition) { - return this.nodes.some(condition) - } - - walk(callback) { - return this.each((child, i) => { - let result; - try { - result = callback(child, i); - } catch (e) { - throw child.addToError(e) - } - if (result !== false && child.walk) { - result = child.walk(callback); - } - - return result - }) - } - - walkAtRules(name, callback) { - if (!callback) { - callback = name; - return this.walk((child, i) => { - if (child.type === 'atrule') { - return callback(child, i) - } - }) - } - if (name instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'atrule' && name.test(child.name)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'atrule' && child.name === name) { - return callback(child, i) - } - }) - } - - walkComments(callback) { - return this.walk((child, i) => { - if (child.type === 'comment') { - return callback(child, i) - } - }) - } - - walkDecls(prop, callback) { - if (!callback) { - callback = prop; - return this.walk((child, i) => { - if (child.type === 'decl') { - return callback(child, i) - } - }) - } - if (prop instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'decl' && prop.test(child.prop)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'decl' && child.prop === prop) { - return callback(child, i) - } - }) - } - - walkRules(selector, callback) { - if (!callback) { - callback = selector; - - return this.walk((child, i) => { - if (child.type === 'rule') { - return callback(child, i) - } - }) - } - if (selector instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'rule' && selector.test(child.selector)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'rule' && child.selector === selector) { - return callback(child, i) - } - }) - } - - get first() { - if (!this.proxyOf.nodes) return undefined - return this.proxyOf.nodes[0] - } - - get last() { - if (!this.proxyOf.nodes) return undefined - return this.proxyOf.nodes[this.proxyOf.nodes.length - 1] - } - }; - - Container$7.registerParse = dependant => { - parse$4 = dependant; - }; - - Container$7.registerRule = dependant => { - Rule$4 = dependant; - }; - - Container$7.registerAtRule = dependant => { - AtRule$4 = dependant; - }; - - Container$7.registerRoot = dependant => { - Root$6 = dependant; - }; - - var container$1 = Container$7; - Container$7.default = Container$7; - - /* c8 ignore start */ - Container$7.rebuild = node => { - if (node.type === 'atrule') { - Object.setPrototypeOf(node, AtRule$4.prototype); - } else if (node.type === 'rule') { - Object.setPrototypeOf(node, Rule$4.prototype); - } else if (node.type === 'decl') { - Object.setPrototypeOf(node, Declaration$3.prototype); - } else if (node.type === 'comment') { - Object.setPrototypeOf(node, Comment$3.prototype); - } else if (node.type === 'root') { - Object.setPrototypeOf(node, Root$6.prototype); - } - - node[my$1] = true; - - if (node.nodes) { - node.nodes.forEach(child => { - Container$7.rebuild(child); - }); - } - }; - - let Container$6 = container$1; - - let LazyResult$4, Processor$3; - - let Document$3 = class Document extends Container$6 { - constructor(defaults) { - // type needs to be passed to super, otherwise child roots won't be normalized correctly - super({ type: 'document', ...defaults }); - - if (!this.nodes) { - this.nodes = []; - } - } - - toResult(opts = {}) { - let lazy = new LazyResult$4(new Processor$3(), this, opts); - - return lazy.stringify() - } - }; - - Document$3.registerLazyResult = dependant => { - LazyResult$4 = dependant; - }; - - Document$3.registerProcessor = dependant => { - Processor$3 = dependant; - }; - - var document = Document$3; - Document$3.default = Document$3; - - /* eslint-disable no-console */ - - let printed = {}; - - var warnOnce$2 = function warnOnce(message) { - if (printed[message]) return - printed[message] = true; - - if (typeof console !== 'undefined' && console.warn) { - console.warn(message); - } - }; - - let Warning$2 = class Warning { - constructor(text, opts = {}) { - this.type = 'warning'; - this.text = text; - - if (opts.node && opts.node.source) { - let range = opts.node.rangeBy(opts); - this.line = range.start.line; - this.column = range.start.column; - this.endLine = range.end.line; - this.endColumn = range.end.column; - } - - for (let opt in opts) this[opt] = opts[opt]; - } - - toString() { - if (this.node) { - return this.node.error(this.text, { - index: this.index, - plugin: this.plugin, - word: this.word - }).message - } - - if (this.plugin) { - return this.plugin + ': ' + this.text - } - - return this.text - } - }; - - var warning = Warning$2; - Warning$2.default = Warning$2; - - let Warning$1 = warning; - - let Result$3 = class Result { - constructor(processor, root, opts) { - this.processor = processor; - this.messages = []; - this.root = root; - this.opts = opts; - this.css = undefined; - this.map = undefined; - } - - toString() { - return this.css - } - - warn(text, opts = {}) { - if (!opts.plugin) { - if (this.lastPlugin && this.lastPlugin.postcssPlugin) { - opts.plugin = this.lastPlugin.postcssPlugin; - } - } - - let warning = new Warning$1(text, opts); - this.messages.push(warning); - - return warning - } - - warnings() { - return this.messages.filter(i => i.type === 'warning') - } - - get content() { - return this.css - } - }; - - var result = Result$3; - Result$3.default = Result$3; - - let Container$5 = container$1; - - let AtRule$3 = class AtRule extends Container$5 { - constructor(defaults) { - super(defaults); - this.type = 'atrule'; - } - - append(...children) { - if (!this.proxyOf.nodes) this.nodes = []; - return super.append(...children) - } - - prepend(...children) { - if (!this.proxyOf.nodes) this.nodes = []; - return super.prepend(...children) - } - }; - - var atRule = AtRule$3; - AtRule$3.default = AtRule$3; - - Container$5.registerAtRule(AtRule$3); - - let Container$4 = container$1; - - let LazyResult$3, Processor$2; - - let Root$5 = class Root extends Container$4 { - constructor(defaults) { - super(defaults); - this.type = 'root'; - if (!this.nodes) this.nodes = []; - } - - normalize(child, sample, type) { - let nodes = super.normalize(child); - - if (sample) { - if (type === 'prepend') { - if (this.nodes.length > 1) { - sample.raws.before = this.nodes[1].raws.before; - } else { - delete sample.raws.before; - } - } else if (this.first !== sample) { - for (let node of nodes) { - node.raws.before = sample.raws.before; - } - } - } - - return nodes - } - - removeChild(child, ignore) { - let index = this.index(child); - - if (!ignore && index === 0 && this.nodes.length > 1) { - this.nodes[1].raws.before = this.nodes[index].raws.before; - } - - return super.removeChild(child) - } - - toResult(opts = {}) { - let lazy = new LazyResult$3(new Processor$2(), this, opts); - return lazy.stringify() - } - }; - - Root$5.registerLazyResult = dependant => { - LazyResult$3 = dependant; - }; - - Root$5.registerProcessor = dependant => { - Processor$2 = dependant; - }; - - var root$2 = Root$5; - Root$5.default = Root$5; - - Container$4.registerRoot(Root$5); - - let list$2 = { - comma(string) { - return list$2.split(string, [','], true) - }, - - space(string) { - let spaces = [' ', '\n', '\t']; - return list$2.split(string, spaces) - }, - - split(string, separators, last) { - let array = []; - let current = ''; - let split = false; - - let func = 0; - let inQuote = false; - let prevQuote = ''; - let escape = false; - - for (let letter of string) { - if (escape) { - escape = false; - } else if (letter === '\\') { - escape = true; - } else if (inQuote) { - if (letter === prevQuote) { - inQuote = false; - } - } else if (letter === '"' || letter === "'") { - inQuote = true; - prevQuote = letter; - } else if (letter === '(') { - func += 1; - } else if (letter === ')') { - if (func > 0) func -= 1; - } else if (func === 0) { - if (separators.includes(letter)) split = true; - } - - if (split) { - if (current !== '') array.push(current.trim()); - current = ''; - split = false; - } else { - current += letter; - } - } - - if (last || current !== '') array.push(current.trim()); - return array - } - }; - - var list_1 = list$2; - list$2.default = list$2; - - let Container$3 = container$1; - let list$1 = list_1; - - let Rule$3 = class Rule extends Container$3 { - constructor(defaults) { - super(defaults); - this.type = 'rule'; - if (!this.nodes) this.nodes = []; - } - - get selectors() { - return list$1.comma(this.selector) - } - - set selectors(values) { - let match = this.selector ? this.selector.match(/,\s*/) : null; - let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen'); - this.selector = values.join(sep); - } - }; - - var rule = Rule$3; - Rule$3.default = Rule$3; - - Container$3.registerRule(Rule$3); - - let Declaration$2 = declaration; - let tokenizer = tokenize$1; - let Comment$2 = comment$3; - let AtRule$2 = atRule; - let Root$4 = root$2; - let Rule$2 = rule; - - const SAFE_COMMENT_NEIGHBOR = { - empty: true, - space: true - }; - - function findLastWithPosition(tokens) { - for (let i = tokens.length - 1; i >= 0; i--) { - let token = tokens[i]; - let pos = token[3] || token[2]; - if (pos) return pos - } - } - - let Parser$1 = class Parser { - constructor(input) { - this.input = input; - - this.root = new Root$4(); - this.current = this.root; - this.spaces = ''; - this.semicolon = false; - - this.createTokenizer(); - this.root.source = { input, start: { column: 1, line: 1, offset: 0 } }; - } - - atrule(token) { - let node = new AtRule$2(); - node.name = token[1].slice(1); - if (node.name === '') { - this.unnamedAtrule(node, token); - } - this.init(node, token[2]); - - let type; - let prev; - let shift; - let last = false; - let open = false; - let params = []; - let brackets = []; - - while (!this.tokenizer.endOfFile()) { - token = this.tokenizer.nextToken(); - type = token[0]; - - if (type === '(' || type === '[') { - brackets.push(type === '(' ? ')' : ']'); - } else if (type === '{' && brackets.length > 0) { - brackets.push('}'); - } else if (type === brackets[brackets.length - 1]) { - brackets.pop(); - } - - if (brackets.length === 0) { - if (type === ';') { - node.source.end = this.getPosition(token[2]); - node.source.end.offset++; - this.semicolon = true; - break - } else if (type === '{') { - open = true; - break - } else if (type === '}') { - if (params.length > 0) { - shift = params.length - 1; - prev = params[shift]; - while (prev && prev[0] === 'space') { - prev = params[--shift]; - } - if (prev) { - node.source.end = this.getPosition(prev[3] || prev[2]); - node.source.end.offset++; - } - } - this.end(token); - break - } else { - params.push(token); - } - } else { - params.push(token); - } - - if (this.tokenizer.endOfFile()) { - last = true; - break - } - } - - node.raws.between = this.spacesAndCommentsFromEnd(params); - if (params.length) { - node.raws.afterName = this.spacesAndCommentsFromStart(params); - this.raw(node, 'params', params); - if (last) { - token = params[params.length - 1]; - node.source.end = this.getPosition(token[3] || token[2]); - node.source.end.offset++; - this.spaces = node.raws.between; - node.raws.between = ''; - } - } else { - node.raws.afterName = ''; - node.params = ''; - } - - if (open) { - node.nodes = []; - this.current = node; - } - } - - checkMissedSemicolon(tokens) { - let colon = this.colon(tokens); - if (colon === false) return - - let founded = 0; - let token; - for (let j = colon - 1; j >= 0; j--) { - token = tokens[j]; - if (token[0] !== 'space') { - founded += 1; - if (founded === 2) break - } - } - // If the token is a word, e.g. `!important`, `red` or any other valid property's value. - // Then we need to return the colon after that word token. [3] is the "end" colon of that word. - // And because we need it after that one we do +1 to get the next one. - throw this.input.error( - 'Missed semicolon', - token[0] === 'word' ? token[3] + 1 : token[2] - ) - } - - colon(tokens) { - let brackets = 0; - let token, type, prev; - for (let [i, element] of tokens.entries()) { - token = element; - type = token[0]; - - if (type === '(') { - brackets += 1; - } - if (type === ')') { - brackets -= 1; - } - if (brackets === 0 && type === ':') { - if (!prev) { - this.doubleColon(token); - } else if (prev[0] === 'word' && prev[1] === 'progid') { - continue - } else { - return i - } - } - - prev = token; - } - return false - } - - comment(token) { - let node = new Comment$2(); - this.init(node, token[2]); - node.source.end = this.getPosition(token[3] || token[2]); - node.source.end.offset++; - - let text = token[1].slice(2, -2); - if (/^\s*$/.test(text)) { - node.text = ''; - node.raws.left = text; - node.raws.right = ''; - } else { - let match = text.match(/^(\s*)([^]*\S)(\s*)$/); - node.text = match[2]; - node.raws.left = match[1]; - node.raws.right = match[3]; - } - } - - createTokenizer() { - this.tokenizer = tokenizer(this.input); - } - - decl(tokens, customProperty) { - let node = new Declaration$2(); - this.init(node, tokens[0][2]); - - let last = tokens[tokens.length - 1]; - if (last[0] === ';') { - this.semicolon = true; - tokens.pop(); - } - - node.source.end = this.getPosition( - last[3] || last[2] || findLastWithPosition(tokens) - ); - node.source.end.offset++; - - while (tokens[0][0] !== 'word') { - if (tokens.length === 1) this.unknownWord(tokens); - node.raws.before += tokens.shift()[1]; - } - node.source.start = this.getPosition(tokens[0][2]); - - node.prop = ''; - while (tokens.length) { - let type = tokens[0][0]; - if (type === ':' || type === 'space' || type === 'comment') { - break - } - node.prop += tokens.shift()[1]; - } - - node.raws.between = ''; - - let token; - while (tokens.length) { - token = tokens.shift(); - - if (token[0] === ':') { - node.raws.between += token[1]; - break - } else { - if (token[0] === 'word' && /\w/.test(token[1])) { - this.unknownWord([token]); - } - node.raws.between += token[1]; - } - } - - if (node.prop[0] === '_' || node.prop[0] === '*') { - node.raws.before += node.prop[0]; - node.prop = node.prop.slice(1); - } - - let firstSpaces = []; - let next; - while (tokens.length) { - next = tokens[0][0]; - if (next !== 'space' && next !== 'comment') break - firstSpaces.push(tokens.shift()); - } - - this.precheckMissedSemicolon(tokens); - - for (let i = tokens.length - 1; i >= 0; i--) { - token = tokens[i]; - if (token[1].toLowerCase() === '!important') { - node.important = true; - let string = this.stringFrom(tokens, i); - string = this.spacesFromEnd(tokens) + string; - if (string !== ' !important') node.raws.important = string; - break - } else if (token[1].toLowerCase() === 'important') { - let cache = tokens.slice(0); - let str = ''; - for (let j = i; j > 0; j--) { - let type = cache[j][0]; - if (str.trim().indexOf('!') === 0 && type !== 'space') { - break - } - str = cache.pop()[1] + str; - } - if (str.trim().indexOf('!') === 0) { - node.important = true; - node.raws.important = str; - tokens = cache; - } - } - - if (token[0] !== 'space' && token[0] !== 'comment') { - break - } - } - - let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment'); - - if (hasWord) { - node.raws.between += firstSpaces.map(i => i[1]).join(''); - firstSpaces = []; - } - this.raw(node, 'value', firstSpaces.concat(tokens), customProperty); - - if (node.value.includes(':') && !customProperty) { - this.checkMissedSemicolon(tokens); - } - } - - doubleColon(token) { - throw this.input.error( - 'Double colon', - { offset: token[2] }, - { offset: token[2] + token[1].length } - ) - } - - emptyRule(token) { - let node = new Rule$2(); - this.init(node, token[2]); - node.selector = ''; - node.raws.between = ''; - this.current = node; - } - - end(token) { - if (this.current.nodes && this.current.nodes.length) { - this.current.raws.semicolon = this.semicolon; - } - this.semicolon = false; - - this.current.raws.after = (this.current.raws.after || '') + this.spaces; - this.spaces = ''; - - if (this.current.parent) { - this.current.source.end = this.getPosition(token[2]); - this.current.source.end.offset++; - this.current = this.current.parent; - } else { - this.unexpectedClose(token); - } - } - - endFile() { - if (this.current.parent) this.unclosedBlock(); - if (this.current.nodes && this.current.nodes.length) { - this.current.raws.semicolon = this.semicolon; - } - this.current.raws.after = (this.current.raws.after || '') + this.spaces; - this.root.source.end = this.getPosition(this.tokenizer.position()); - } - - freeSemicolon(token) { - this.spaces += token[1]; - if (this.current.nodes) { - let prev = this.current.nodes[this.current.nodes.length - 1]; - if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { - prev.raws.ownSemicolon = this.spaces; - this.spaces = ''; - } - } - } - - // Helpers - - getPosition(offset) { - let pos = this.input.fromOffset(offset); - return { - column: pos.col, - line: pos.line, - offset - } - } - - init(node, offset) { - this.current.push(node); - node.source = { - input: this.input, - start: this.getPosition(offset) - }; - node.raws.before = this.spaces; - this.spaces = ''; - if (node.type !== 'comment') this.semicolon = false; - } - - other(start) { - let end = false; - let type = null; - let colon = false; - let bracket = null; - let brackets = []; - let customProperty = start[1].startsWith('--'); - - let tokens = []; - let token = start; - while (token) { - type = token[0]; - tokens.push(token); - - if (type === '(' || type === '[') { - if (!bracket) bracket = token; - brackets.push(type === '(' ? ')' : ']'); - } else if (customProperty && colon && type === '{') { - if (!bracket) bracket = token; - brackets.push('}'); - } else if (brackets.length === 0) { - if (type === ';') { - if (colon) { - this.decl(tokens, customProperty); - return - } else { - break - } - } else if (type === '{') { - this.rule(tokens); - return - } else if (type === '}') { - this.tokenizer.back(tokens.pop()); - end = true; - break - } else if (type === ':') { - colon = true; - } - } else if (type === brackets[brackets.length - 1]) { - brackets.pop(); - if (brackets.length === 0) bracket = null; - } - - token = this.tokenizer.nextToken(); - } - - if (this.tokenizer.endOfFile()) end = true; - if (brackets.length > 0) this.unclosedBracket(bracket); - - if (end && colon) { - if (!customProperty) { - while (tokens.length) { - token = tokens[tokens.length - 1][0]; - if (token !== 'space' && token !== 'comment') break - this.tokenizer.back(tokens.pop()); - } - } - this.decl(tokens, customProperty); - } else { - this.unknownWord(tokens); - } - } - - parse() { - let token; - while (!this.tokenizer.endOfFile()) { - token = this.tokenizer.nextToken(); - - switch (token[0]) { - case 'space': - this.spaces += token[1]; - break - - case ';': - this.freeSemicolon(token); - break - - case '}': - this.end(token); - break - - case 'comment': - this.comment(token); - break - - case 'at-word': - this.atrule(token); - break - - case '{': - this.emptyRule(token); - break - - default: - this.other(token); - break - } - } - this.endFile(); - } - - precheckMissedSemicolon(/* tokens */) { - // Hook for Safe Parser - } - - raw(node, prop, tokens, customProperty) { - let token, type; - let length = tokens.length; - let value = ''; - let clean = true; - let next, prev; - - for (let i = 0; i < length; i += 1) { - token = tokens[i]; - type = token[0]; - if (type === 'space' && i === length - 1 && !customProperty) { - clean = false; - } else if (type === 'comment') { - prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty'; - next = tokens[i + 1] ? tokens[i + 1][0] : 'empty'; - if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) { - if (value.slice(-1) === ',') { - clean = false; - } else { - value += token[1]; - } - } else { - clean = false; - } - } else { - value += token[1]; - } - } - if (!clean) { - let raw = tokens.reduce((all, i) => all + i[1], ''); - node.raws[prop] = { raw, value }; - } - node[prop] = value; - } - - rule(tokens) { - tokens.pop(); - - let node = new Rule$2(); - this.init(node, tokens[0][2]); - - node.raws.between = this.spacesAndCommentsFromEnd(tokens); - this.raw(node, 'selector', tokens); - this.current = node; - } - - spacesAndCommentsFromEnd(tokens) { - let lastTokenType; - let spaces = ''; - while (tokens.length) { - lastTokenType = tokens[tokens.length - 1][0]; - if (lastTokenType !== 'space' && lastTokenType !== 'comment') break - spaces = tokens.pop()[1] + spaces; - } - return spaces - } - - // Errors - - spacesAndCommentsFromStart(tokens) { - let next; - let spaces = ''; - while (tokens.length) { - next = tokens[0][0]; - if (next !== 'space' && next !== 'comment') break - spaces += tokens.shift()[1]; - } - return spaces - } - - spacesFromEnd(tokens) { - let lastTokenType; - let spaces = ''; - while (tokens.length) { - lastTokenType = tokens[tokens.length - 1][0]; - if (lastTokenType !== 'space') break - spaces = tokens.pop()[1] + spaces; - } - return spaces - } - - stringFrom(tokens, from) { - let result = ''; - for (let i = from; i < tokens.length; i++) { - result += tokens[i][1]; - } - tokens.splice(from, tokens.length - from); - return result - } - - unclosedBlock() { - let pos = this.current.source.start; - throw this.input.error('Unclosed block', pos.line, pos.column) - } - - unclosedBracket(bracket) { - throw this.input.error( - 'Unclosed bracket', - { offset: bracket[2] }, - { offset: bracket[2] + 1 } - ) - } - - unexpectedClose(token) { - throw this.input.error( - 'Unexpected }', - { offset: token[2] }, - { offset: token[2] + 1 } - ) - } - - unknownWord(tokens) { - throw this.input.error( - 'Unknown word', - { offset: tokens[0][2] }, - { offset: tokens[0][2] + tokens[0][1].length } - ) - } - - unnamedAtrule(node, token) { - throw this.input.error( - 'At-rule without name', - { offset: token[2] }, - { offset: token[2] + token[1].length } - ) - } - }; - - var parser$1 = Parser$1; - - let Container$2 = container$1; - let Parser = parser$1; - let Input$2 = input; - - function parse$3(css, opts) { - let input = new Input$2(css, opts); - let parser = new Parser(input); - try { - parser.parse(); - } catch (e) { - if (browser$1.env.NODE_ENV !== 'production') { - if (e.name === 'CssSyntaxError' && opts && opts.from) { - if (/\.scss$/i.test(opts.from)) { - e.message += - '\nYou tried to parse SCSS with ' + - 'the standard CSS parser; ' + - 'try again with the postcss-scss parser'; - } else if (/\.sass/i.test(opts.from)) { - e.message += - '\nYou tried to parse Sass with ' + - 'the standard CSS parser; ' + - 'try again with the postcss-sass parser'; - } else if (/\.less$/i.test(opts.from)) { - e.message += - '\nYou tried to parse Less with ' + - 'the standard CSS parser; ' + - 'try again with the postcss-less parser'; - } - } - } - throw e - } - - return parser.root - } - - var parse_1 = parse$3; - parse$3.default = parse$3; - - Container$2.registerParse(parse$3); - - let { isClean, my } = symbols; - let MapGenerator$1 = mapGenerator; - let stringify$2 = stringify_1; - let Container$1 = container$1; - let Document$2 = document; - let warnOnce$1 = warnOnce$2; - let Result$2 = result; - let parse$2 = parse_1; - let Root$3 = root$2; - - const TYPE_TO_CLASS_NAME = { - atrule: 'AtRule', - comment: 'Comment', - decl: 'Declaration', - document: 'Document', - root: 'Root', - rule: 'Rule' - }; - - const PLUGIN_PROPS = { - AtRule: true, - AtRuleExit: true, - Comment: true, - CommentExit: true, - Declaration: true, - DeclarationExit: true, - Document: true, - DocumentExit: true, - Once: true, - OnceExit: true, - postcssPlugin: true, - prepare: true, - Root: true, - RootExit: true, - Rule: true, - RuleExit: true - }; - - const NOT_VISITORS = { - Once: true, - postcssPlugin: true, - prepare: true - }; - - const CHILDREN = 0; - - function isPromise(obj) { - return typeof obj === 'object' && typeof obj.then === 'function' - } - - function getEvents(node) { - let key = false; - let type = TYPE_TO_CLASS_NAME[node.type]; - if (node.type === 'decl') { - key = node.prop.toLowerCase(); - } else if (node.type === 'atrule') { - key = node.name.toLowerCase(); - } - - if (key && node.append) { - return [ - type, - type + '-' + key, - CHILDREN, - type + 'Exit', - type + 'Exit-' + key - ] - } else if (key) { - return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] - } else if (node.append) { - return [type, CHILDREN, type + 'Exit'] - } else { - return [type, type + 'Exit'] - } - } - - function toStack(node) { - let events; - if (node.type === 'document') { - events = ['Document', CHILDREN, 'DocumentExit']; - } else if (node.type === 'root') { - events = ['Root', CHILDREN, 'RootExit']; - } else { - events = getEvents(node); - } - - return { - eventIndex: 0, - events, - iterator: 0, - node, - visitorIndex: 0, - visitors: [] - } - } - - function cleanMarks(node) { - node[isClean] = false; - if (node.nodes) node.nodes.forEach(i => cleanMarks(i)); - return node - } - - let postcss$2 = {}; - - let LazyResult$2 = class LazyResult { - constructor(processor, css, opts) { - this.stringified = false; - this.processed = false; - - let root; - if ( - typeof css === 'object' && - css !== null && - (css.type === 'root' || css.type === 'document') - ) { - root = cleanMarks(css); - } else if (css instanceof LazyResult || css instanceof Result$2) { - root = cleanMarks(css.root); - if (css.map) { - if (typeof opts.map === 'undefined') opts.map = {}; - if (!opts.map.inline) opts.map.inline = false; - opts.map.prev = css.map; - } - } else { - let parser = parse$2; - if (opts.syntax) parser = opts.syntax.parse; - if (opts.parser) parser = opts.parser; - if (parser.parse) parser = parser.parse; - - try { - root = parser(css, opts); - } catch (error) { - this.processed = true; - this.error = error; - } - - if (root && !root[my]) { - /* c8 ignore next 2 */ - Container$1.rebuild(root); - } - } - - this.result = new Result$2(processor, root, opts); - this.helpers = { ...postcss$2, postcss: postcss$2, result: this.result }; - this.plugins = this.processor.plugins.map(plugin => { - if (typeof plugin === 'object' && plugin.prepare) { - return { ...plugin, ...plugin.prepare(this.result) } - } else { - return plugin - } - }); - } - - async() { - if (this.error) return Promise.reject(this.error) - if (this.processed) return Promise.resolve(this.result) - if (!this.processing) { - this.processing = this.runAsync(); - } - return this.processing - } - - catch(onRejected) { - return this.async().catch(onRejected) - } - - finally(onFinally) { - return this.async().then(onFinally, onFinally) - } - - getAsyncError() { - throw new Error('Use process(css).then(cb) to work with async plugins') - } - - handleError(error, node) { - let plugin = this.result.lastPlugin; - try { - if (node) node.addToError(error); - this.error = error; - if (error.name === 'CssSyntaxError' && !error.plugin) { - error.plugin = plugin.postcssPlugin; - error.setMessage(); - } else if (plugin.postcssVersion) { - if (browser$1.env.NODE_ENV !== 'production') { - let pluginName = plugin.postcssPlugin; - let pluginVer = plugin.postcssVersion; - let runtimeVer = this.result.processor.version; - let a = pluginVer.split('.'); - let b = runtimeVer.split('.'); - - if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { - // eslint-disable-next-line no-console - console.error( - 'Unknown error from PostCSS plugin. Your current PostCSS ' + - 'version is ' + - runtimeVer + - ', but ' + - pluginName + - ' uses ' + - pluginVer + - '. Perhaps this is the source of the error below.' - ); - } - } - } - } catch (err) { - /* c8 ignore next 3 */ - // eslint-disable-next-line no-console - if (console && console.error) console.error(err); - } - return error - } - - prepareVisitors() { - this.listeners = {}; - let add = (plugin, type, cb) => { - if (!this.listeners[type]) this.listeners[type] = []; - this.listeners[type].push([plugin, cb]); - }; - for (let plugin of this.plugins) { - if (typeof plugin === 'object') { - for (let event in plugin) { - if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { - throw new Error( - `Unknown event ${event} in ${plugin.postcssPlugin}. ` + - `Try to update PostCSS (${this.processor.version} now).` - ) - } - if (!NOT_VISITORS[event]) { - if (typeof plugin[event] === 'object') { - for (let filter in plugin[event]) { - if (filter === '*') { - add(plugin, event, plugin[event][filter]); - } else { - add( - plugin, - event + '-' + filter.toLowerCase(), - plugin[event][filter] - ); - } - } - } else if (typeof plugin[event] === 'function') { - add(plugin, event, plugin[event]); - } - } - } - } - } - this.hasListener = Object.keys(this.listeners).length > 0; - } - - async runAsync() { - this.plugin = 0; - for (let i = 0; i < this.plugins.length; i++) { - let plugin = this.plugins[i]; - let promise = this.runOnRoot(plugin); - if (isPromise(promise)) { - try { - await promise; - } catch (error) { - throw this.handleError(error) - } - } - } - - this.prepareVisitors(); - if (this.hasListener) { - let root = this.result.root; - while (!root[isClean]) { - root[isClean] = true; - let stack = [toStack(root)]; - while (stack.length > 0) { - let promise = this.visitTick(stack); - if (isPromise(promise)) { - try { - await promise; - } catch (e) { - let node = stack[stack.length - 1].node; - throw this.handleError(e, node) - } - } - } - } - - if (this.listeners.OnceExit) { - for (let [plugin, visitor] of this.listeners.OnceExit) { - this.result.lastPlugin = plugin; - try { - if (root.type === 'document') { - let roots = root.nodes.map(subRoot => - visitor(subRoot, this.helpers) - ); - - await Promise.all(roots); - } else { - await visitor(root, this.helpers); - } - } catch (e) { - throw this.handleError(e) - } - } - } - } - - this.processed = true; - return this.stringify() - } - - runOnRoot(plugin) { - this.result.lastPlugin = plugin; - try { - if (typeof plugin === 'object' && plugin.Once) { - if (this.result.root.type === 'document') { - let roots = this.result.root.nodes.map(root => - plugin.Once(root, this.helpers) - ); - - if (isPromise(roots[0])) { - return Promise.all(roots) - } - - return roots - } - - return plugin.Once(this.result.root, this.helpers) - } else if (typeof plugin === 'function') { - return plugin(this.result.root, this.result) - } - } catch (error) { - throw this.handleError(error) - } - } - - stringify() { - if (this.error) throw this.error - if (this.stringified) return this.result - this.stringified = true; - - this.sync(); - - let opts = this.result.opts; - let str = stringify$2; - if (opts.syntax) str = opts.syntax.stringify; - if (opts.stringifier) str = opts.stringifier; - if (str.stringify) str = str.stringify; - - let map = new MapGenerator$1(str, this.result.root, this.result.opts); - let data = map.generate(); - this.result.css = data[0]; - this.result.map = data[1]; - - return this.result - } - - sync() { - if (this.error) throw this.error - if (this.processed) return this.result - this.processed = true; - - if (this.processing) { - throw this.getAsyncError() - } - - for (let plugin of this.plugins) { - let promise = this.runOnRoot(plugin); - if (isPromise(promise)) { - throw this.getAsyncError() - } - } - - this.prepareVisitors(); - if (this.hasListener) { - let root = this.result.root; - while (!root[isClean]) { - root[isClean] = true; - this.walkSync(root); - } - if (this.listeners.OnceExit) { - if (root.type === 'document') { - for (let subRoot of root.nodes) { - this.visitSync(this.listeners.OnceExit, subRoot); - } - } else { - this.visitSync(this.listeners.OnceExit, root); - } - } - } - - return this.result - } - - then(onFulfilled, onRejected) { - if (browser$1.env.NODE_ENV !== 'production') { - if (!('from' in this.opts)) { - warnOnce$1( - 'Without `from` option PostCSS could generate wrong source map ' + - 'and will not find Browserslist config. Set it to CSS file path ' + - 'or to `undefined` to prevent this warning.' - ); - } - } - return this.async().then(onFulfilled, onRejected) - } - - toString() { - return this.css - } - - visitSync(visitors, node) { - for (let [plugin, visitor] of visitors) { - this.result.lastPlugin = plugin; - let promise; - try { - promise = visitor(node, this.helpers); - } catch (e) { - throw this.handleError(e, node.proxyOf) - } - if (node.type !== 'root' && node.type !== 'document' && !node.parent) { - return true - } - if (isPromise(promise)) { - throw this.getAsyncError() - } - } - } - - visitTick(stack) { - let visit = stack[stack.length - 1]; - let { node, visitors } = visit; - - if (node.type !== 'root' && node.type !== 'document' && !node.parent) { - stack.pop(); - return - } - - if (visitors.length > 0 && visit.visitorIndex < visitors.length) { - let [plugin, visitor] = visitors[visit.visitorIndex]; - visit.visitorIndex += 1; - if (visit.visitorIndex === visitors.length) { - visit.visitors = []; - visit.visitorIndex = 0; - } - this.result.lastPlugin = plugin; - try { - return visitor(node.toProxy(), this.helpers) - } catch (e) { - throw this.handleError(e, node) - } - } - - if (visit.iterator !== 0) { - let iterator = visit.iterator; - let child; - while ((child = node.nodes[node.indexes[iterator]])) { - node.indexes[iterator] += 1; - if (!child[isClean]) { - child[isClean] = true; - stack.push(toStack(child)); - return - } - } - visit.iterator = 0; - delete node.indexes[iterator]; - } - - let events = visit.events; - while (visit.eventIndex < events.length) { - let event = events[visit.eventIndex]; - visit.eventIndex += 1; - if (event === CHILDREN) { - if (node.nodes && node.nodes.length) { - node[isClean] = true; - visit.iterator = node.getIterator(); - } - return - } else if (this.listeners[event]) { - visit.visitors = this.listeners[event]; - return - } - } - stack.pop(); - } - - walkSync(node) { - node[isClean] = true; - let events = getEvents(node); - for (let event of events) { - if (event === CHILDREN) { - if (node.nodes) { - node.each(child => { - if (!child[isClean]) this.walkSync(child); - }); - } - } else { - let visitors = this.listeners[event]; - if (visitors) { - if (this.visitSync(visitors, node.toProxy())) return - } - } - } - } - - warnings() { - return this.sync().warnings() - } - - get content() { - return this.stringify().content - } - - get css() { - return this.stringify().css - } - - get map() { - return this.stringify().map - } - - get messages() { - return this.sync().messages - } - - get opts() { - return this.result.opts - } - - get processor() { - return this.result.processor - } - - get root() { - return this.sync().root - } - - get [Symbol.toStringTag]() { - return 'LazyResult' - } - }; - - LazyResult$2.registerPostcss = dependant => { - postcss$2 = dependant; - }; - - var lazyResult = LazyResult$2; - LazyResult$2.default = LazyResult$2; - - Root$3.registerLazyResult(LazyResult$2); - Document$2.registerLazyResult(LazyResult$2); - - let MapGenerator = mapGenerator; - let stringify$1 = stringify_1; - let warnOnce = warnOnce$2; - let parse$1 = parse_1; - const Result$1 = result; - - let NoWorkResult$1 = class NoWorkResult { - constructor(processor, css, opts) { - css = css.toString(); - this.stringified = false; - - this._processor = processor; - this._css = css; - this._opts = opts; - this._map = undefined; - let root; - - let str = stringify$1; - this.result = new Result$1(this._processor, root, this._opts); - this.result.css = css; - - let self = this; - Object.defineProperty(this.result, 'root', { - get() { - return self.root - } - }); - - let map = new MapGenerator(str, root, this._opts, css); - if (map.isMap()) { - let [generatedCSS, generatedMap] = map.generate(); - if (generatedCSS) { - this.result.css = generatedCSS; - } - if (generatedMap) { - this.result.map = generatedMap; - } - } else { - map.clearAnnotation(); - this.result.css = map.css; - } - } - - async() { - if (this.error) return Promise.reject(this.error) - return Promise.resolve(this.result) - } - - catch(onRejected) { - return this.async().catch(onRejected) - } - - finally(onFinally) { - return this.async().then(onFinally, onFinally) - } - - sync() { - if (this.error) throw this.error - return this.result - } - - then(onFulfilled, onRejected) { - if (browser$1.env.NODE_ENV !== 'production') { - if (!('from' in this._opts)) { - warnOnce( - 'Without `from` option PostCSS could generate wrong source map ' + - 'and will not find Browserslist config. Set it to CSS file path ' + - 'or to `undefined` to prevent this warning.' - ); - } - } - - return this.async().then(onFulfilled, onRejected) - } - - toString() { - return this._css - } - - warnings() { - return [] - } - - get content() { - return this.result.css - } - - get css() { - return this.result.css - } - - get map() { - return this.result.map - } - - get messages() { - return [] - } - - get opts() { - return this.result.opts - } - - get processor() { - return this.result.processor - } - - get root() { - if (this._root) { - return this._root - } - - let root; - let parser = parse$1; - - try { - root = parser(this._css, this._opts); - } catch (error) { - this.error = error; - } - - if (this.error) { - throw this.error - } else { - this._root = root; - return root - } - } - - get [Symbol.toStringTag]() { - return 'NoWorkResult' - } - }; - - var noWorkResult = NoWorkResult$1; - NoWorkResult$1.default = NoWorkResult$1; - - let NoWorkResult = noWorkResult; - let LazyResult$1 = lazyResult; - let Document$1 = document; - let Root$2 = root$2; - - let Processor$1 = class Processor { - constructor(plugins = []) { - this.version = '8.4.35'; - this.plugins = this.normalize(plugins); - } - - normalize(plugins) { - let normalized = []; - for (let i of plugins) { - if (i.postcss === true) { - i = i(); - } else if (i.postcss) { - i = i.postcss; - } - - if (typeof i === 'object' && Array.isArray(i.plugins)) { - normalized = normalized.concat(i.plugins); - } else if (typeof i === 'object' && i.postcssPlugin) { - normalized.push(i); - } else if (typeof i === 'function') { - normalized.push(i); - } else if (typeof i === 'object' && (i.parse || i.stringify)) { - if (browser$1.env.NODE_ENV !== 'production') { - throw new Error( - 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' + - 'one of the syntax/parser/stringifier options as outlined ' + - 'in your PostCSS runner documentation.' - ) - } - } else { - throw new Error(i + ' is not a PostCSS plugin') - } - } - return normalized - } - - process(css, opts = {}) { - if ( - !this.plugins.length && - !opts.parser && - !opts.stringifier && - !opts.syntax - ) { - return new NoWorkResult(this, css, opts) - } else { - return new LazyResult$1(this, css, opts) - } - } - - use(plugin) { - this.plugins = this.plugins.concat(this.normalize([plugin])); - return this - } - }; - - var processor$1 = Processor$1; - Processor$1.default = Processor$1; - - Root$2.registerProcessor(Processor$1); - Document$1.registerProcessor(Processor$1); - - let Declaration$1 = declaration; - let PreviousMap = previousMap; - let Comment$1 = comment$3; - let AtRule$1 = atRule; - let Input$1 = input; - let Root$1 = root$2; - let Rule$1 = rule; - - function fromJSON$1(json, inputs) { - if (Array.isArray(json)) return json.map(n => fromJSON$1(n)) - - let { inputs: ownInputs, ...defaults } = json; - if (ownInputs) { - inputs = []; - for (let input of ownInputs) { - let inputHydrated = { ...input, __proto__: Input$1.prototype }; - if (inputHydrated.map) { - inputHydrated.map = { - ...inputHydrated.map, - __proto__: PreviousMap.prototype - }; - } - inputs.push(inputHydrated); - } - } - if (defaults.nodes) { - defaults.nodes = json.nodes.map(n => fromJSON$1(n, inputs)); - } - if (defaults.source) { - let { inputId, ...source } = defaults.source; - defaults.source = source; - if (inputId != null) { - defaults.source.input = inputs[inputId]; - } - } - if (defaults.type === 'root') { - return new Root$1(defaults) - } else if (defaults.type === 'decl') { - return new Declaration$1(defaults) - } else if (defaults.type === 'rule') { - return new Rule$1(defaults) - } else if (defaults.type === 'comment') { - return new Comment$1(defaults) - } else if (defaults.type === 'atrule') { - return new AtRule$1(defaults) - } else { - throw new Error('Unknown node type: ' + json.type) - } - } - - var fromJSON_1 = fromJSON$1; - fromJSON$1.default = fromJSON$1; - - let CssSyntaxError = cssSyntaxError; - let Declaration = declaration; - let LazyResult = lazyResult; - let Container = container$1; - let Processor = processor$1; - let stringify = stringify_1; - let fromJSON = fromJSON_1; - let Document = document; - let Warning = warning; - let Comment = comment$3; - let AtRule = atRule; - let Result = result; - let Input = input; - let parse = parse_1; - let list = list_1; - let Rule = rule; - let Root = root$2; - let Node = node$2; - - function postcss(...plugins) { - if (plugins.length === 1 && Array.isArray(plugins[0])) { - plugins = plugins[0]; - } - return new Processor(plugins) - } - - postcss.plugin = function plugin(name, initializer) { - let warningPrinted = false; - function creator(...args) { - // eslint-disable-next-line no-console - if (console && console.warn && !warningPrinted) { - warningPrinted = true; - // eslint-disable-next-line no-console - console.warn( - name + - ': postcss.plugin was deprecated. Migration guide:\n' + - 'https://evilmartians.com/chronicles/postcss-8-plugin-migration' - ); - if (browser$1.env.LANG && browser$1.env.LANG.startsWith('cn')) { - /* c8 ignore next 7 */ - // eslint-disable-next-line no-console - console.warn( - name + - ': 里面 postcss.plugin 被弃用. 迁移指南:\n' + - 'https://www.w3ctech.com/topic/2226' - ); - } - } - let transformer = initializer(...args); - transformer.postcssPlugin = name; - transformer.postcssVersion = new Processor().version; - return transformer - } - - let cache; - Object.defineProperty(creator, 'postcss', { - get() { - if (!cache) cache = creator(); - return cache - } - }); - - creator.process = function (css, processOpts, pluginOpts) { - return postcss([creator(pluginOpts)]).process(css, processOpts) - }; - - return creator - }; - - postcss.stringify = stringify; - postcss.parse = parse; - postcss.fromJSON = fromJSON; - postcss.list = list; - - postcss.comment = defaults => new Comment(defaults); - postcss.atRule = defaults => new AtRule(defaults); - postcss.decl = defaults => new Declaration(defaults); - postcss.rule = defaults => new Rule(defaults); - postcss.root = defaults => new Root(defaults); - postcss.document = defaults => new Document(defaults); - - postcss.CssSyntaxError = CssSyntaxError; - postcss.Declaration = Declaration; - postcss.Container = Container; - postcss.Processor = Processor; - postcss.Document = Document; - postcss.Comment = Comment; - postcss.Warning = Warning; - postcss.AtRule = AtRule; - postcss.Result = Result; - postcss.Input = Input; - postcss.Rule = Rule; - postcss.Root = Root; - postcss.Node = Node; - - LazyResult.registerPostcss(postcss); - - var postcss_1 = postcss; - postcss.default = postcss; - - var postcss$1 = /*@__PURE__*/getDefaultExportFromCjs(postcss_1); - - postcss$1.stringify; - postcss$1.fromJSON; - postcss$1.plugin; - postcss$1.parse; - postcss$1.list; - - postcss$1.document; - postcss$1.comment; - postcss$1.atRule; - postcss$1.rule; - postcss$1.decl; - postcss$1.root; - - postcss$1.CssSyntaxError; - postcss$1.Declaration; - postcss$1.Container; - postcss$1.Processor; - postcss$1.Document; - postcss$1.Comment; - postcss$1.Warning; - postcss$1.AtRule; - postcss$1.Result; - postcss$1.Input; - postcss$1.Rule; - postcss$1.Root; - postcss$1.Node; - - const trimPlugin = () => { - return { - postcssPlugin: "vue-sfc-trim", - Once(root) { - root.walk(({ type, raws }) => { - if (type === "rule" || type === "atrule") { - if (raws.before) - raws.before = "\n"; - if ("after" in raws && raws.after) - raws.after = "\n"; - } - }); - } - }; - }; - trimPlugin.postcss = true; - - var dist = { exports: {} }; - - var processor = { exports: {} }; - - var parser = { exports: {} }; - - var root$1 = { exports: {} }; - - var container = { exports: {} }; - - var node$1 = { exports: {} }; - - var util$6 = {}; - - var unesc = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = unesc; - // Many thanks for this post which made this migration much easier. - // https://mathiasbynens.be/notes/css-escapes - - /** - * - * @param {string} str - * @returns {[string, number]|undefined} - */ - function gobbleHex(str) { - var lower = str.toLowerCase(); - var hex = ''; - var spaceTerminated = false; - for (var i = 0; i < 6 && lower[i] !== undefined; i++) { - var code = lower.charCodeAt(i); - // check to see if we are dealing with a valid hex char [a-f|0-9] - var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; - // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point - spaceTerminated = code === 32; - if (!valid) { - break; - } - hex += lower[i]; - } - if (hex.length === 0) { - return undefined; - } - var codePoint = parseInt(hex, 16); - var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; - // Add special case for - // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point" - // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point - if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) { - return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)]; - } - return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)]; - } - var CONTAINS_ESCAPE = /\\/; - function unesc(str) { - var needToProcess = CONTAINS_ESCAPE.test(str); - if (!needToProcess) { - return str; - } - var ret = ""; - for (var i = 0; i < str.length; i++) { - if (str[i] === "\\") { - var gobbled = gobbleHex(str.slice(i + 1, i + 7)); - if (gobbled !== undefined) { - ret += gobbled[0]; - i += gobbled[1]; - continue; - } - - // Retain a pair of \\ if double escaped `\\\\` - // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e - if (str[i + 1] === "\\") { - ret += "\\"; - i++; - continue; - } - - // if \\ is at the end of the string retain it - // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb - if (str.length === i + 1) { - ret += str[i]; - } - continue; - } - ret += str[i]; - } - return ret; - } - module.exports = exports.default; - }(unesc, unesc.exports)); - - var unescExports = unesc.exports; - - var getProp = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = getProp; - function getProp(obj) { - for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - props[_key - 1] = arguments[_key]; - } - while (props.length > 0) { - var prop = props.shift(); - if (!obj[prop]) { - return undefined; - } - obj = obj[prop]; - } - return obj; - } - module.exports = exports.default; - }(getProp, getProp.exports)); - - var getPropExports = getProp.exports; - - var ensureObject = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = ensureObject; - function ensureObject(obj) { - for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - props[_key - 1] = arguments[_key]; - } - while (props.length > 0) { - var prop = props.shift(); - if (!obj[prop]) { - obj[prop] = {}; - } - obj = obj[prop]; - } - } - module.exports = exports.default; - }(ensureObject, ensureObject.exports)); - - var ensureObjectExports = ensureObject.exports; - - var stripComments = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = stripComments; - function stripComments(str) { - var s = ""; - var commentStart = str.indexOf("/*"); - var lastEnd = 0; - while (commentStart >= 0) { - s = s + str.slice(lastEnd, commentStart); - var commentEnd = str.indexOf("*/", commentStart + 2); - if (commentEnd < 0) { - return s; - } - lastEnd = commentEnd + 2; - commentStart = str.indexOf("/*", lastEnd); - } - s = s + str.slice(lastEnd); - return s; - } - module.exports = exports.default; - }(stripComments, stripComments.exports)); - - var stripCommentsExports = stripComments.exports; - - util$6.__esModule = true; - util$6.unesc = util$6.stripComments = util$6.getProp = util$6.ensureObject = void 0; - var _unesc = _interopRequireDefault$1(unescExports); - util$6.unesc = _unesc["default"]; - var _getProp = _interopRequireDefault$1(getPropExports); - util$6.getProp = _getProp["default"]; - var _ensureObject = _interopRequireDefault$1(ensureObjectExports); - util$6.ensureObject = _ensureObject["default"]; - var _stripComments = _interopRequireDefault$1(stripCommentsExports); - util$6.stripComments = _stripComments["default"]; - function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _util = util$6; - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - var cloneNode = function cloneNode(obj, parent) { - if (typeof obj !== 'object' || obj === null) { - return obj; - } - var cloned = new obj.constructor(); - for (var i in obj) { - if (!obj.hasOwnProperty(i)) { - continue; - } - var value = obj[i]; - var type = typeof value; - if (i === 'parent' && type === 'object') { - if (parent) { - cloned[i] = parent; - } - } else if (value instanceof Array) { - cloned[i] = value.map(function (j) { - return cloneNode(j, cloned); - }); - } else { - cloned[i] = cloneNode(value, cloned); - } - } - return cloned; - }; - var Node = /*#__PURE__*/function () { - function Node(opts) { - if (opts === void 0) { - opts = {}; - } - Object.assign(this, opts); - this.spaces = this.spaces || {}; - this.spaces.before = this.spaces.before || ''; - this.spaces.after = this.spaces.after || ''; - } - var _proto = Node.prototype; - _proto.remove = function remove() { - if (this.parent) { - this.parent.removeChild(this); - } - this.parent = undefined; - return this; - }; - _proto.replaceWith = function replaceWith() { - if (this.parent) { - for (var index in arguments) { - this.parent.insertBefore(this, arguments[index]); - } - this.remove(); - } - return this; - }; - _proto.next = function next() { - return this.parent.at(this.parent.index(this) + 1); - }; - _proto.prev = function prev() { - return this.parent.at(this.parent.index(this) - 1); - }; - _proto.clone = function clone(overrides) { - if (overrides === void 0) { - overrides = {}; - } - var cloned = cloneNode(this); - for (var name in overrides) { - cloned[name] = overrides[name]; - } - return cloned; - } - - /** - * Some non-standard syntax doesn't follow normal escaping rules for css. - * This allows non standard syntax to be appended to an existing property - * by specifying the escaped value. By specifying the escaped value, - * illegal characters are allowed to be directly inserted into css output. - * @param {string} name the property to set - * @param {any} value the unescaped value of the property - * @param {string} valueEscaped optional. the escaped value of the property. - */; - _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) { - if (!this.raws) { - this.raws = {}; - } - var originalValue = this[name]; - var originalEscaped = this.raws[name]; - this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first. - if (originalEscaped || valueEscaped !== value) { - this.raws[name] = (originalEscaped || originalValue) + valueEscaped; - } else { - delete this.raws[name]; // delete any escaped value that was created by the setter. - } - } - - /** - * Some non-standard syntax doesn't follow normal escaping rules for css. - * This allows the escaped value to be specified directly, allowing illegal - * characters to be directly inserted into css output. - * @param {string} name the property to set - * @param {any} value the unescaped value of the property - * @param {string} valueEscaped the escaped value of the property. - */; - _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) { - if (!this.raws) { - this.raws = {}; - } - this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. - this.raws[name] = valueEscaped; - } - - /** - * When you want a value to passed through to CSS directly. This method - * deletes the corresponding raw value causing the stringifier to fallback - * to the unescaped value. - * @param {string} name the property to set. - * @param {any} value The value that is both escaped and unescaped. - */; - _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) { - this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. - if (this.raws) { - delete this.raws[name]; - } - } - - /** - * - * @param {number} line The number (starting with 1) - * @param {number} column The column number (starting with 1) - */; - _proto.isAtPosition = function isAtPosition(line, column) { - if (this.source && this.source.start && this.source.end) { - if (this.source.start.line > line) { - return false; - } - if (this.source.end.line < line) { - return false; - } - if (this.source.start.line === line && this.source.start.column > column) { - return false; - } - if (this.source.end.line === line && this.source.end.column < column) { - return false; - } - return true; - } - return undefined; - }; - _proto.stringifyProperty = function stringifyProperty(name) { - return this.raws && this.raws[name] || this[name]; - }; - _proto.valueToString = function valueToString() { - return String(this.stringifyProperty("value")); - }; - _proto.toString = function toString() { - return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join(''); - }; - _createClass(Node, [{ - key: "rawSpaceBefore", - get: function get() { - var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before; - if (rawSpace === undefined) { - rawSpace = this.spaces && this.spaces.before; - } - return rawSpace || ""; - }, - set: function set(raw) { - (0, _util.ensureObject)(this, "raws", "spaces"); - this.raws.spaces.before = raw; - } - }, { - key: "rawSpaceAfter", - get: function get() { - var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after; - if (rawSpace === undefined) { - rawSpace = this.spaces.after; - } - return rawSpace || ""; - }, - set: function set(raw) { - (0, _util.ensureObject)(this, "raws", "spaces"); - this.raws.spaces.after = raw; - } - }]); - return Node; - }(); - exports["default"] = Node; - module.exports = exports.default; - }(node$1, node$1.exports)); - - var nodeExports = node$1.exports; - - var types = {}; - - types.__esModule = true; - types.UNIVERSAL = types.TAG = types.STRING = types.SELECTOR = types.ROOT = types.PSEUDO = types.NESTING = types.ID = types.COMMENT = types.COMBINATOR = types.CLASS = types.ATTRIBUTE = void 0; - var TAG = 'tag'; - types.TAG = TAG; - var STRING = 'string'; - types.STRING = STRING; - var SELECTOR = 'selector'; - types.SELECTOR = SELECTOR; - var ROOT = 'root'; - types.ROOT = ROOT; - var PSEUDO = 'pseudo'; - types.PSEUDO = PSEUDO; - var NESTING = 'nesting'; - types.NESTING = NESTING; - var ID = 'id'; - types.ID = ID; - var COMMENT = 'comment'; - types.COMMENT = COMMENT; - var COMBINATOR = 'combinator'; - types.COMBINATOR = COMBINATOR; - var CLASS = 'class'; - types.CLASS = CLASS; - var ATTRIBUTE = 'attribute'; - types.ATTRIBUTE = ATTRIBUTE; - var UNIVERSAL = 'universal'; - types.UNIVERSAL = UNIVERSAL; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _node = _interopRequireDefault(nodeExports); - var types$1 = _interopRequireWildcard(types); - function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } - function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Container = /*#__PURE__*/function (_Node) { - _inheritsLoose(Container, _Node); - function Container(opts) { - var _this; - _this = _Node.call(this, opts) || this; - if (!_this.nodes) { - _this.nodes = []; - } - return _this; - } - var _proto = Container.prototype; - _proto.append = function append(selector) { - selector.parent = this; - this.nodes.push(selector); - return this; - }; - _proto.prepend = function prepend(selector) { - selector.parent = this; - this.nodes.unshift(selector); - return this; - }; - _proto.at = function at(index) { - return this.nodes[index]; - }; - _proto.index = function index(child) { - if (typeof child === 'number') { - return child; - } - return this.nodes.indexOf(child); - }; - _proto.removeChild = function removeChild(child) { - child = this.index(child); - this.at(child).parent = undefined; - this.nodes.splice(child, 1); - var index; - for (var id in this.indexes) { - index = this.indexes[id]; - if (index >= child) { - this.indexes[id] = index - 1; - } - } - return this; - }; - _proto.removeAll = function removeAll() { - for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) { - var node = _step.value; - node.parent = undefined; - } - this.nodes = []; - return this; - }; - _proto.empty = function empty() { - return this.removeAll(); - }; - _proto.insertAfter = function insertAfter(oldNode, newNode) { - newNode.parent = this; - var oldIndex = this.index(oldNode); - this.nodes.splice(oldIndex + 1, 0, newNode); - newNode.parent = this; - var index; - for (var id in this.indexes) { - index = this.indexes[id]; - if (oldIndex <= index) { - this.indexes[id] = index + 1; - } - } - return this; - }; - _proto.insertBefore = function insertBefore(oldNode, newNode) { - newNode.parent = this; - var oldIndex = this.index(oldNode); - this.nodes.splice(oldIndex, 0, newNode); - newNode.parent = this; - var index; - for (var id in this.indexes) { - index = this.indexes[id]; - if (index <= oldIndex) { - this.indexes[id] = index + 1; - } - } - return this; - }; - _proto._findChildAtPosition = function _findChildAtPosition(line, col) { - var found = undefined; - this.each(function (node) { - if (node.atPosition) { - var foundChild = node.atPosition(line, col); - if (foundChild) { - found = foundChild; - return false; - } - } else if (node.isAtPosition(line, col)) { - found = node; - return false; - } - }); - return found; - } - - /** - * Return the most specific node at the line and column number given. - * The source location is based on the original parsed location, locations aren't - * updated as selector nodes are mutated. - * - * Note that this location is relative to the location of the first character - * of the selector, and not the location of the selector in the overall document - * when used in conjunction with postcss. - * - * If not found, returns undefined. - * @param {number} line The line number of the node to find. (1-based index) - * @param {number} col The column number of the node to find. (1-based index) - */; - _proto.atPosition = function atPosition(line, col) { - if (this.isAtPosition(line, col)) { - return this._findChildAtPosition(line, col) || this; - } else { - return undefined; - } - }; - _proto._inferEndPosition = function _inferEndPosition() { - if (this.last && this.last.source && this.last.source.end) { - this.source = this.source || {}; - this.source.end = this.source.end || {}; - Object.assign(this.source.end, this.last.source.end); - } - }; - _proto.each = function each(callback) { - if (!this.lastEach) { - this.lastEach = 0; - } - if (!this.indexes) { - this.indexes = {}; - } - this.lastEach++; - var id = this.lastEach; - this.indexes[id] = 0; - if (!this.length) { - return undefined; - } - var index, result; - while (this.indexes[id] < this.length) { - index = this.indexes[id]; - result = callback(this.at(index), index); - if (result === false) { - break; - } - this.indexes[id] += 1; - } - delete this.indexes[id]; - if (result === false) { - return false; - } - }; - _proto.walk = function walk(callback) { - return this.each(function (node, i) { - var result = callback(node, i); - if (result !== false && node.length) { - result = node.walk(callback); - } - if (result === false) { - return false; - } - }); - }; - _proto.walkAttributes = function walkAttributes(callback) { - var _this2 = this; - return this.walk(function (selector) { - if (selector.type === types$1.ATTRIBUTE) { - return callback.call(_this2, selector); - } - }); - }; - _proto.walkClasses = function walkClasses(callback) { - var _this3 = this; - return this.walk(function (selector) { - if (selector.type === types$1.CLASS) { - return callback.call(_this3, selector); - } - }); - }; - _proto.walkCombinators = function walkCombinators(callback) { - var _this4 = this; - return this.walk(function (selector) { - if (selector.type === types$1.COMBINATOR) { - return callback.call(_this4, selector); - } - }); - }; - _proto.walkComments = function walkComments(callback) { - var _this5 = this; - return this.walk(function (selector) { - if (selector.type === types$1.COMMENT) { - return callback.call(_this5, selector); - } - }); - }; - _proto.walkIds = function walkIds(callback) { - var _this6 = this; - return this.walk(function (selector) { - if (selector.type === types$1.ID) { - return callback.call(_this6, selector); - } - }); - }; - _proto.walkNesting = function walkNesting(callback) { - var _this7 = this; - return this.walk(function (selector) { - if (selector.type === types$1.NESTING) { - return callback.call(_this7, selector); - } - }); - }; - _proto.walkPseudos = function walkPseudos(callback) { - var _this8 = this; - return this.walk(function (selector) { - if (selector.type === types$1.PSEUDO) { - return callback.call(_this8, selector); - } - }); - }; - _proto.walkTags = function walkTags(callback) { - var _this9 = this; - return this.walk(function (selector) { - if (selector.type === types$1.TAG) { - return callback.call(_this9, selector); - } - }); - }; - _proto.walkUniversals = function walkUniversals(callback) { - var _this10 = this; - return this.walk(function (selector) { - if (selector.type === types$1.UNIVERSAL) { - return callback.call(_this10, selector); - } - }); - }; - _proto.split = function split(callback) { - var _this11 = this; - var current = []; - return this.reduce(function (memo, node, index) { - var split = callback.call(_this11, node); - current.push(node); - if (split) { - memo.push(current); - current = []; - } else if (index === _this11.length - 1) { - memo.push(current); - } - return memo; - }, []); - }; - _proto.map = function map(callback) { - return this.nodes.map(callback); - }; - _proto.reduce = function reduce(callback, memo) { - return this.nodes.reduce(callback, memo); - }; - _proto.every = function every(callback) { - return this.nodes.every(callback); - }; - _proto.some = function some(callback) { - return this.nodes.some(callback); - }; - _proto.filter = function filter(callback) { - return this.nodes.filter(callback); - }; - _proto.sort = function sort(callback) { - return this.nodes.sort(callback); - }; - _proto.toString = function toString() { - return this.map(String).join(''); - }; - _createClass(Container, [{ - key: "first", - get: function get() { - return this.at(0); - } - }, { - key: "last", - get: function get() { - return this.at(this.length - 1); - } - }, { - key: "length", - get: function get() { - return this.nodes.length; - } - }]); - return Container; - }(_node["default"]); - exports["default"] = Container; - module.exports = exports.default; - }(container, container.exports)); - - var containerExports = container.exports; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _container = _interopRequireDefault(containerExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Root = /*#__PURE__*/function (_Container) { - _inheritsLoose(Root, _Container); - function Root(opts) { - var _this; - _this = _Container.call(this, opts) || this; - _this.type = _types.ROOT; - return _this; - } - var _proto = Root.prototype; - _proto.toString = function toString() { - var str = this.reduce(function (memo, selector) { - memo.push(String(selector)); - return memo; - }, []).join(','); - return this.trailingComma ? str + ',' : str; - }; - _proto.error = function error(message, options) { - if (this._error) { - return this._error(message, options); - } else { - return new Error(message); - } - }; - _createClass(Root, [{ - key: "errorGenerator", - set: function set(handler) { - this._error = handler; - } - }]); - return Root; - }(_container["default"]); - exports["default"] = Root; - module.exports = exports.default; - }(root$1, root$1.exports)); - - var rootExports = root$1.exports; - - var selector$1 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _container = _interopRequireDefault(containerExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Selector = /*#__PURE__*/function (_Container) { - _inheritsLoose(Selector, _Container); - function Selector(opts) { - var _this; - _this = _Container.call(this, opts) || this; - _this.type = _types.SELECTOR; - return _this; - } - return Selector; - }(_container["default"]); - exports["default"] = Selector; - module.exports = exports.default; - }(selector$1, selector$1.exports)); - - var selectorExports = selector$1.exports; - - var className$1 = { exports: {} }; - - /*! https://mths.be/cssesc v3.0.0 by @mathias */ - - var object = {}; - var hasOwnProperty = object.hasOwnProperty; - var merge$2 = function merge(options, defaults) { - if (!options) { - return defaults; - } - var result = {}; - for (var key in defaults) { - // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since - // only recognized option names are used. - result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key]; - } - return result; - }; - - var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/; - var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/; - var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g; - - // https://mathiasbynens.be/notes/css-escapes#css - var cssesc = function cssesc(string, options) { - options = merge$2(options, cssesc.options); - if (options.quotes != 'single' && options.quotes != 'double') { - options.quotes = 'single'; - } - var quote = options.quotes == 'double' ? '"' : '\''; - var isIdentifier = options.isIdentifier; - - var firstChar = string.charAt(0); - var output = ''; - var counter = 0; - var length = string.length; - while (counter < length) { - var character = string.charAt(counter++); - var codePoint = character.charCodeAt(); - var value = void 0; - // If it’s not a printable ASCII character… - if (codePoint < 0x20 || codePoint > 0x7E) { - if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) { - // It’s a high surrogate, and there is a next character. - var extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // next character is low surrogate - codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000; - } else { - // It’s an unmatched surrogate; only append this code unit, in case - // the next code unit is the high surrogate of a surrogate pair. - counter--; - } - } - value = '\\' + codePoint.toString(16).toUpperCase() + ' '; - } else { - if (options.escapeEverything) { - if (regexAnySingleEscape.test(character)) { - value = '\\' + character; - } else { - value = '\\' + codePoint.toString(16).toUpperCase() + ' '; - } - } else if (/[\t\n\f\r\x0B]/.test(character)) { - value = '\\' + codePoint.toString(16).toUpperCase() + ' '; - } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) { - value = '\\' + character; - } else { - value = character; - } - } - output += value; - } - - if (isIdentifier) { - if (/^-[-\d]/.test(output)) { - output = '\\-' + output.slice(1); - } else if (/\d/.test(firstChar)) { - output = '\\3' + firstChar + ' ' + output.slice(1); - } - } - - // Remove spaces after `\HEX` escapes that are not followed by a hex digit, - // since they’re redundant. Note that this is only possible if the escape - // sequence isn’t preceded by an odd number of backslashes. - output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) { - if ($1 && $1.length % 2) { - // It’s not safe to remove the space, so don’t. - return $0; - } - // Strip the space. - return ($1 || '') + $2; - }); - - if (!isIdentifier && options.wrap) { - return quote + output + quote; - } - return output; - }; - - // Expose default options (so they can be overridden globally). - cssesc.options = { - 'escapeEverything': false, - 'isIdentifier': false, - 'quotes': 'single', - 'wrap': false - }; - - cssesc.version = '3.0.0'; - - var cssesc_1 = cssesc; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _cssesc = _interopRequireDefault(cssesc_1); - var _util = util$6; - var _node = _interopRequireDefault(nodeExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var ClassName = /*#__PURE__*/function (_Node) { - _inheritsLoose(ClassName, _Node); - function ClassName(opts) { - var _this; - _this = _Node.call(this, opts) || this; - _this.type = _types.CLASS; - _this._constructed = true; - return _this; - } - var _proto = ClassName.prototype; - _proto.valueToString = function valueToString() { - return '.' + _Node.prototype.valueToString.call(this); - }; - _createClass(ClassName, [{ - key: "value", - get: function get() { - return this._value; - }, - set: function set(v) { - if (this._constructed) { - var escaped = (0, _cssesc["default"])(v, { - isIdentifier: true - }); - if (escaped !== v) { - (0, _util.ensureObject)(this, "raws"); - this.raws.value = escaped; - } else if (this.raws) { - delete this.raws.value; - } - } - this._value = v; - } - }]); - return ClassName; - }(_node["default"]); - exports["default"] = ClassName; - module.exports = exports.default; - }(className$1, className$1.exports)); - - var classNameExports = className$1.exports; - - var comment$2 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _node = _interopRequireDefault(nodeExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Comment = /*#__PURE__*/function (_Node) { - _inheritsLoose(Comment, _Node); - function Comment(opts) { - var _this; - _this = _Node.call(this, opts) || this; - _this.type = _types.COMMENT; - return _this; - } - return Comment; - }(_node["default"]); - exports["default"] = Comment; - module.exports = exports.default; - }(comment$2, comment$2.exports)); - - var commentExports = comment$2.exports; - - var id$1 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _node = _interopRequireDefault(nodeExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var ID = /*#__PURE__*/function (_Node) { - _inheritsLoose(ID, _Node); - function ID(opts) { - var _this; - _this = _Node.call(this, opts) || this; - _this.type = _types.ID; - return _this; - } - var _proto = ID.prototype; - _proto.valueToString = function valueToString() { - return '#' + _Node.prototype.valueToString.call(this); - }; - return ID; - }(_node["default"]); - exports["default"] = ID; - module.exports = exports.default; - }(id$1, id$1.exports)); - - var idExports = id$1.exports; - - var tag$1 = { exports: {} }; - - var namespace = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _cssesc = _interopRequireDefault(cssesc_1); - var _util = util$6; - var _node = _interopRequireDefault(nodeExports); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Namespace = /*#__PURE__*/function (_Node) { - _inheritsLoose(Namespace, _Node); - function Namespace() { - return _Node.apply(this, arguments) || this; - } - var _proto = Namespace.prototype; - _proto.qualifiedName = function qualifiedName(value) { - if (this.namespace) { - return this.namespaceString + "|" + value; - } else { - return value; - } - }; - _proto.valueToString = function valueToString() { - return this.qualifiedName(_Node.prototype.valueToString.call(this)); - }; - _createClass(Namespace, [{ - key: "namespace", - get: function get() { - return this._namespace; - }, - set: function set(namespace) { - if (namespace === true || namespace === "*" || namespace === "&") { - this._namespace = namespace; - if (this.raws) { - delete this.raws.namespace; - } - return; - } - var escaped = (0, _cssesc["default"])(namespace, { - isIdentifier: true - }); - this._namespace = namespace; - if (escaped !== namespace) { - (0, _util.ensureObject)(this, "raws"); - this.raws.namespace = escaped; - } else if (this.raws) { - delete this.raws.namespace; - } - } - }, { - key: "ns", - get: function get() { - return this._namespace; - }, - set: function set(namespace) { - this.namespace = namespace; - } - }, { - key: "namespaceString", - get: function get() { - if (this.namespace) { - var ns = this.stringifyProperty("namespace"); - if (ns === true) { - return ''; - } else { - return ns; - } - } else { - return ''; - } - } - }]); - return Namespace; - }(_node["default"]); - exports["default"] = Namespace; - module.exports = exports.default; - }(namespace, namespace.exports)); - - var namespaceExports = namespace.exports; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _namespace = _interopRequireDefault(namespaceExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Tag = /*#__PURE__*/function (_Namespace) { - _inheritsLoose(Tag, _Namespace); - function Tag(opts) { - var _this; - _this = _Namespace.call(this, opts) || this; - _this.type = _types.TAG; - return _this; - } - return Tag; - }(_namespace["default"]); - exports["default"] = Tag; - module.exports = exports.default; - }(tag$1, tag$1.exports)); - - var tagExports = tag$1.exports; - - var string$1 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _node = _interopRequireDefault(nodeExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var String = /*#__PURE__*/function (_Node) { - _inheritsLoose(String, _Node); - function String(opts) { - var _this; - _this = _Node.call(this, opts) || this; - _this.type = _types.STRING; - return _this; - } - return String; - }(_node["default"]); - exports["default"] = String; - module.exports = exports.default; - }(string$1, string$1.exports)); - - var stringExports = string$1.exports; - - var pseudo$1 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _container = _interopRequireDefault(containerExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Pseudo = /*#__PURE__*/function (_Container) { - _inheritsLoose(Pseudo, _Container); - function Pseudo(opts) { - var _this; - _this = _Container.call(this, opts) || this; - _this.type = _types.PSEUDO; - return _this; - } - var _proto = Pseudo.prototype; - _proto.toString = function toString() { - var params = this.length ? '(' + this.map(String).join(',') + ')' : ''; - return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join(''); - }; - return Pseudo; - }(_container["default"]); - exports["default"] = Pseudo; - module.exports = exports.default; - }(pseudo$1, pseudo$1.exports)); - - var pseudoExports = pseudo$1.exports; - - var attribute$1 = {}; - - /** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - - var node = require$$0$1.deprecate; - - (function (exports) { - - exports.__esModule = true; - exports["default"] = void 0; - exports.unescapeValue = unescapeValue; - var _cssesc = _interopRequireDefault(cssesc_1); - var _unesc = _interopRequireDefault(unescExports); - var _namespace = _interopRequireDefault(namespaceExports); - var _types = types; - var _CSSESC_QUOTE_OPTIONS; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var deprecate = node; - var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/; - var warnOfDeprecatedValueAssignment = deprecate(function () { }, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead."); - var warnOfDeprecatedQuotedAssignment = deprecate(function () { }, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."); - var warnOfDeprecatedConstructor = deprecate(function () { }, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now."); - function unescapeValue(value) { - var deprecatedUsage = false; - var quoteMark = null; - var unescaped = value; - var m = unescaped.match(WRAPPED_IN_QUOTES); - if (m) { - quoteMark = m[1]; - unescaped = m[2]; - } - unescaped = (0, _unesc["default"])(unescaped); - if (unescaped !== value) { - deprecatedUsage = true; - } - return { - deprecatedUsage: deprecatedUsage, - unescaped: unescaped, - quoteMark: quoteMark - }; - } - function handleDeprecatedContructorOpts(opts) { - if (opts.quoteMark !== undefined) { - return opts; - } - if (opts.value === undefined) { - return opts; - } - warnOfDeprecatedConstructor(); - var _unescapeValue = unescapeValue(opts.value), - quoteMark = _unescapeValue.quoteMark, - unescaped = _unescapeValue.unescaped; - if (!opts.raws) { - opts.raws = {}; - } - if (opts.raws.value === undefined) { - opts.raws.value = opts.value; - } - opts.value = unescaped; - opts.quoteMark = quoteMark; - return opts; - } - var Attribute = /*#__PURE__*/function (_Namespace) { - _inheritsLoose(Attribute, _Namespace); - function Attribute(opts) { - var _this; - if (opts === void 0) { - opts = {}; - } - _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this; - _this.type = _types.ATTRIBUTE; - _this.raws = _this.raws || {}; - Object.defineProperty(_this.raws, 'unquoted', { - get: deprecate(function () { - return _this.value; - }, "attr.raws.unquoted is deprecated. Call attr.value instead."), - set: deprecate(function () { - return _this.value; - }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.") - }); - _this._constructed = true; - return _this; - } - - /** - * Returns the Attribute's value quoted such that it would be legal to use - * in the value of a css file. The original value's quotation setting - * used for stringification is left unchanged. See `setValue(value, options)` - * if you want to control the quote settings of a new value for the attribute. - * - * You can also change the quotation used for the current value by setting quoteMark. - * - * Options: - * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this - * option is not set, the original value for quoteMark will be used. If - * indeterminate, a double quote is used. The legal values are: - * * `null` - the value will be unquoted and characters will be escaped as necessary. - * * `'` - the value will be quoted with a single quote and single quotes are escaped. - * * `"` - the value will be quoted with a double quote and double quotes are escaped. - * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark - * over the quoteMark option value. - * * smart {boolean} - if true, will select a quote mark based on the value - * and the other options specified here. See the `smartQuoteMark()` - * method. - **/ - var _proto = Attribute.prototype; - _proto.getQuotedValue = function getQuotedValue(options) { - if (options === void 0) { - options = {}; - } - var quoteMark = this._determineQuoteMark(options); - var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark]; - var escaped = (0, _cssesc["default"])(this._value, cssescopts); - return escaped; - }; - _proto._determineQuoteMark = function _determineQuoteMark(options) { - return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options); - } - - /** - * Set the unescaped value with the specified quotation options. The value - * provided must not include any wrapping quote marks -- those quotes will - * be interpreted as part of the value and escaped accordingly. - */; - _proto.setValue = function setValue(value, options) { - if (options === void 0) { - options = {}; - } - this._value = value; - this._quoteMark = this._determineQuoteMark(options); - this._syncRawValue(); - } - - /** - * Intelligently select a quoteMark value based on the value's contents. If - * the value is a legal CSS ident, it will not be quoted. Otherwise a quote - * mark will be picked that minimizes the number of escapes. - * - * If there's no clear winner, the quote mark from these options is used, - * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is - * true). If the quoteMark is unspecified, a double quote is used. - * - * @param options This takes the quoteMark and preferCurrentQuoteMark options - * from the quoteValue method. - */; - _proto.smartQuoteMark = function smartQuoteMark(options) { - var v = this.value; - var numSingleQuotes = v.replace(/[^']/g, '').length; - var numDoubleQuotes = v.replace(/[^"]/g, '').length; - if (numSingleQuotes + numDoubleQuotes === 0) { - var escaped = (0, _cssesc["default"])(v, { - isIdentifier: true - }); - if (escaped === v) { - return Attribute.NO_QUOTE; - } else { - var pref = this.preferredQuoteMark(options); - if (pref === Attribute.NO_QUOTE) { - // pick a quote mark that isn't none and see if it's smaller - var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE; - var opts = CSSESC_QUOTE_OPTIONS[quote]; - var quoteValue = (0, _cssesc["default"])(v, opts); - if (quoteValue.length < escaped.length) { - return quote; - } - } - return pref; - } - } else if (numDoubleQuotes === numSingleQuotes) { - return this.preferredQuoteMark(options); - } else if (numDoubleQuotes < numSingleQuotes) { - return Attribute.DOUBLE_QUOTE; - } else { - return Attribute.SINGLE_QUOTE; - } - } - - /** - * Selects the preferred quote mark based on the options and the current quote mark value. - * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)` - * instead. - */; - _proto.preferredQuoteMark = function preferredQuoteMark(options) { - var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark; - if (quoteMark === undefined) { - quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark; - } - if (quoteMark === undefined) { - quoteMark = Attribute.DOUBLE_QUOTE; - } - return quoteMark; - }; - _proto._syncRawValue = function _syncRawValue() { - var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]); - if (rawValue === this._value) { - if (this.raws) { - delete this.raws.value; - } - } else { - this.raws.value = rawValue; - } - }; - _proto._handleEscapes = function _handleEscapes(prop, value) { - if (this._constructed) { - var escaped = (0, _cssesc["default"])(value, { - isIdentifier: true - }); - if (escaped !== value) { - this.raws[prop] = escaped; - } else { - delete this.raws[prop]; - } - } - }; - _proto._spacesFor = function _spacesFor(name) { - var attrSpaces = { - before: '', - after: '' - }; - var spaces = this.spaces[name] || {}; - var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {}; - return Object.assign(attrSpaces, spaces, rawSpaces); - }; - _proto._stringFor = function _stringFor(name, spaceName, concat) { - if (spaceName === void 0) { - spaceName = name; - } - if (concat === void 0) { - concat = defaultAttrConcat; - } - var attrSpaces = this._spacesFor(spaceName); - return concat(this.stringifyProperty(name), attrSpaces); - } - - /** - * returns the offset of the attribute part specified relative to the - * start of the node of the output string. - * - * * "ns" - alias for "namespace" - * * "namespace" - the namespace if it exists. - * * "attribute" - the attribute name - * * "attributeNS" - the start of the attribute or its namespace - * * "operator" - the match operator of the attribute - * * "value" - The value (string or identifier) - * * "insensitive" - the case insensitivity flag; - * @param part One of the possible values inside an attribute. - * @returns -1 if the name is invalid or the value doesn't exist in this attribute. - */; - _proto.offsetOf = function offsetOf(name) { - var count = 1; - var attributeSpaces = this._spacesFor("attribute"); - count += attributeSpaces.before.length; - if (name === "namespace" || name === "ns") { - return this.namespace ? count : -1; - } - if (name === "attributeNS") { - return count; - } - count += this.namespaceString.length; - if (this.namespace) { - count += 1; - } - if (name === "attribute") { - return count; - } - count += this.stringifyProperty("attribute").length; - count += attributeSpaces.after.length; - var operatorSpaces = this._spacesFor("operator"); - count += operatorSpaces.before.length; - var operator = this.stringifyProperty("operator"); - if (name === "operator") { - return operator ? count : -1; - } - count += operator.length; - count += operatorSpaces.after.length; - var valueSpaces = this._spacesFor("value"); - count += valueSpaces.before.length; - var value = this.stringifyProperty("value"); - if (name === "value") { - return value ? count : -1; - } - count += value.length; - count += valueSpaces.after.length; - var insensitiveSpaces = this._spacesFor("insensitive"); - count += insensitiveSpaces.before.length; - if (name === "insensitive") { - return this.insensitive ? count : -1; - } - return -1; - }; - _proto.toString = function toString() { - var _this2 = this; - var selector = [this.rawSpaceBefore, '[']; - selector.push(this._stringFor('qualifiedAttribute', 'attribute')); - if (this.operator && (this.value || this.value === '')) { - selector.push(this._stringFor('operator')); - selector.push(this._stringFor('value')); - selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) { - if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) { - attrSpaces.before = " "; - } - return defaultAttrConcat(attrValue, attrSpaces); - })); - } - selector.push(']'); - selector.push(this.rawSpaceAfter); - return selector.join(''); - }; - _createClass(Attribute, [{ - key: "quoted", - get: function get() { - var qm = this.quoteMark; - return qm === "'" || qm === '"'; - }, - set: function set(value) { - warnOfDeprecatedQuotedAssignment(); - } - - /** - * returns a single (`'`) or double (`"`) quote character if the value is quoted. - * returns `null` if the value is not quoted. - * returns `undefined` if the quotation state is unknown (this can happen when - * the attribute is constructed without specifying a quote mark.) - */ - }, { - key: "quoteMark", - get: function get() { - return this._quoteMark; - } - - /** - * Set the quote mark to be used by this attribute's value. - * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute - * value is updated accordingly. - * - * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted. - */, - set: function set(quoteMark) { - if (!this._constructed) { - this._quoteMark = quoteMark; - return; - } - if (this._quoteMark !== quoteMark) { - this._quoteMark = quoteMark; - this._syncRawValue(); - } - } - }, { - key: "qualifiedAttribute", - get: function get() { - return this.qualifiedName(this.raws.attribute || this.attribute); - } - }, { - key: "insensitiveFlag", - get: function get() { - return this.insensitive ? 'i' : ''; - } - }, { - key: "value", - get: function get() { - return this._value; - }, - set: - /** - * Before 3.0, the value had to be set to an escaped value including any wrapped - * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value - * is unescaped during parsing and any quote marks are removed. - * - * Because the ambiguity of this semantic change, if you set `attr.value = newValue`, - * a deprecation warning is raised when the new value contains any characters that would - * require escaping (including if it contains wrapped quotes). - * - * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe - * how the new value is quoted. - */ - function set(v) { - if (this._constructed) { - var _unescapeValue2 = unescapeValue(v), - deprecatedUsage = _unescapeValue2.deprecatedUsage, - unescaped = _unescapeValue2.unescaped, - quoteMark = _unescapeValue2.quoteMark; - if (deprecatedUsage) { - warnOfDeprecatedValueAssignment(); - } - if (unescaped === this._value && quoteMark === this._quoteMark) { - return; - } - this._value = unescaped; - this._quoteMark = quoteMark; - this._syncRawValue(); - } else { - this._value = v; - } - } - }, { - key: "insensitive", - get: function get() { - return this._insensitive; - } - - /** - * Set the case insensitive flag. - * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag` - * of the attribute is updated accordingly. - * - * @param {true | false} insensitive true if the attribute should match case-insensitively. - */, - set: function set(insensitive) { - if (!insensitive) { - this._insensitive = false; - - // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation. - // When setting `attr.insensitive = false` both should be erased to ensure correct serialization. - if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) { - this.raws.insensitiveFlag = undefined; - } - } - this._insensitive = insensitive; - } - }, { - key: "attribute", - get: function get() { - return this._attribute; - }, - set: function set(name) { - this._handleEscapes("attribute", name); - this._attribute = name; - } - }]); - return Attribute; - }(_namespace["default"]); - exports["default"] = Attribute; - Attribute.NO_QUOTE = null; - Attribute.SINGLE_QUOTE = "'"; - Attribute.DOUBLE_QUOTE = '"'; - var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = { - "'": { - quotes: 'single', - wrap: true - }, - '"': { - quotes: 'double', - wrap: true - } - }, _CSSESC_QUOTE_OPTIONS[null] = { - isIdentifier: true - }, _CSSESC_QUOTE_OPTIONS); - function defaultAttrConcat(attrValue, attrSpaces) { - return "" + attrSpaces.before + attrValue + attrSpaces.after; - } - }(attribute$1)); - - var universal$1 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _namespace = _interopRequireDefault(namespaceExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Universal = /*#__PURE__*/function (_Namespace) { - _inheritsLoose(Universal, _Namespace); - function Universal(opts) { - var _this; - _this = _Namespace.call(this, opts) || this; - _this.type = _types.UNIVERSAL; - _this.value = '*'; - return _this; - } - return Universal; - }(_namespace["default"]); - exports["default"] = Universal; - module.exports = exports.default; - }(universal$1, universal$1.exports)); - - var universalExports = universal$1.exports; - - var combinator$2 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _node = _interopRequireDefault(nodeExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Combinator = /*#__PURE__*/function (_Node) { - _inheritsLoose(Combinator, _Node); - function Combinator(opts) { - var _this; - _this = _Node.call(this, opts) || this; - _this.type = _types.COMBINATOR; - return _this; - } - return Combinator; - }(_node["default"]); - exports["default"] = Combinator; - module.exports = exports.default; - }(combinator$2, combinator$2.exports)); - - var combinatorExports = combinator$2.exports; - - var nesting$1 = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _node = _interopRequireDefault(nodeExports); - var _types = types; - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } - function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - var Nesting = /*#__PURE__*/function (_Node) { - _inheritsLoose(Nesting, _Node); - function Nesting(opts) { - var _this; - _this = _Node.call(this, opts) || this; - _this.type = _types.NESTING; - _this.value = '&'; - return _this; - } - return Nesting; - }(_node["default"]); - exports["default"] = Nesting; - module.exports = exports.default; - }(nesting$1, nesting$1.exports)); - - var nestingExports = nesting$1.exports; - - var sortAscending = { exports: {} }; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = sortAscending; - function sortAscending(list) { - return list.sort(function (a, b) { - return a - b; - }); - } - module.exports = exports.default; - }(sortAscending, sortAscending.exports)); - - var sortAscendingExports = sortAscending.exports; - - var tokenize = {}; - - var tokenTypes = {}; - - tokenTypes.__esModule = true; - tokenTypes.word = tokenTypes.tilde = tokenTypes.tab = tokenTypes.str = tokenTypes.space = tokenTypes.slash = tokenTypes.singleQuote = tokenTypes.semicolon = tokenTypes.plus = tokenTypes.pipe = tokenTypes.openSquare = tokenTypes.openParenthesis = tokenTypes.newline = tokenTypes.greaterThan = tokenTypes.feed = tokenTypes.equals = tokenTypes.doubleQuote = tokenTypes.dollar = tokenTypes.cr = tokenTypes.comment = tokenTypes.comma = tokenTypes.combinator = tokenTypes.colon = tokenTypes.closeSquare = tokenTypes.closeParenthesis = tokenTypes.caret = tokenTypes.bang = tokenTypes.backslash = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0; - var ampersand = 38; // `&`.charCodeAt(0); - tokenTypes.ampersand = ampersand; - var asterisk = 42; // `*`.charCodeAt(0); - tokenTypes.asterisk = asterisk; - var at = 64; // `@`.charCodeAt(0); - tokenTypes.at = at; - var comma$1 = 44; // `,`.charCodeAt(0); - tokenTypes.comma = comma$1; - var colon = 58; // `:`.charCodeAt(0); - tokenTypes.colon = colon; - var semicolon$1 = 59; // `;`.charCodeAt(0); - tokenTypes.semicolon = semicolon$1; - var openParenthesis = 40; // `(`.charCodeAt(0); - tokenTypes.openParenthesis = openParenthesis; - var closeParenthesis = 41; // `)`.charCodeAt(0); - tokenTypes.closeParenthesis = closeParenthesis; - var openSquare = 91; // `[`.charCodeAt(0); - tokenTypes.openSquare = openSquare; - var closeSquare = 93; // `]`.charCodeAt(0); - tokenTypes.closeSquare = closeSquare; - var dollar = 36; // `$`.charCodeAt(0); - tokenTypes.dollar = dollar; - var tilde = 126; // `~`.charCodeAt(0); - tokenTypes.tilde = tilde; - var caret = 94; // `^`.charCodeAt(0); - tokenTypes.caret = caret; - var plus = 43; // `+`.charCodeAt(0); - tokenTypes.plus = plus; - var equals = 61; // `=`.charCodeAt(0); - tokenTypes.equals = equals; - var pipe = 124; // `|`.charCodeAt(0); - tokenTypes.pipe = pipe; - var greaterThan = 62; // `>`.charCodeAt(0); - tokenTypes.greaterThan = greaterThan; - var space = 32; // ` `.charCodeAt(0); - tokenTypes.space = space; - var singleQuote = 39; // `'`.charCodeAt(0); - tokenTypes.singleQuote = singleQuote; - var doubleQuote = 34; // `"`.charCodeAt(0); - tokenTypes.doubleQuote = doubleQuote; - var slash = 47; // `/`.charCodeAt(0); - tokenTypes.slash = slash; - var bang = 33; // `!`.charCodeAt(0); - tokenTypes.bang = bang; - var backslash = 92; // '\\'.charCodeAt(0); - tokenTypes.backslash = backslash; - var cr = 13; // '\r'.charCodeAt(0); - tokenTypes.cr = cr; - var feed = 12; // '\f'.charCodeAt(0); - tokenTypes.feed = feed; - var newline = 10; // '\n'.charCodeAt(0); - tokenTypes.newline = newline; - var tab = 9; // '\t'.charCodeAt(0); - - // Expose aliases primarily for readability. - tokenTypes.tab = tab; - var str = singleQuote; - - // No good single character representation! - tokenTypes.str = str; - var comment$1 = -1; - tokenTypes.comment = comment$1; - var word = -2; - tokenTypes.word = word; - var combinator$1 = -3; - tokenTypes.combinator = combinator$1; - - (function (exports) { - - exports.__esModule = true; - exports.FIELDS = void 0; - exports["default"] = tokenize; - var t = _interopRequireWildcard(tokenTypes); - var _unescapable, _wordDelimiters; - function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } - function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable); - var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters); - var hex = {}; - var hexChars = "0123456789abcdefABCDEF"; - for (var i = 0; i < hexChars.length; i++) { - hex[hexChars.charCodeAt(i)] = true; - } - - /** - * Returns the last index of the bar css word - * @param {string} css The string in which the word begins - * @param {number} start The index into the string where word's first letter occurs - */ - function consumeWord(css, start) { - var next = start; - var code; - do { - code = css.charCodeAt(next); - if (wordDelimiters[code]) { - return next - 1; - } else if (code === t.backslash) { - next = consumeEscape(css, next) + 1; - } else { - // All other characters are part of the word - next++; - } - } while (next < css.length); - return next - 1; - } - - /** - * Returns the last index of the escape sequence - * @param {string} css The string in which the sequence begins - * @param {number} start The index into the string where escape character (`\`) occurs. - */ - function consumeEscape(css, start) { - var next = start; - var code = css.charCodeAt(next + 1); - if (unescapable[code]); else if (hex[code]) { - var hexDigits = 0; - // consume up to 6 hex chars - do { - next++; - hexDigits++; - code = css.charCodeAt(next + 1); - } while (hex[code] && hexDigits < 6); - // if fewer than 6 hex chars, a trailing space ends the escape - if (hexDigits < 6 && code === t.space) { - next++; - } - } else { - // the next char is part of the current word - next++; - } - return next; - } - var FIELDS = { - TYPE: 0, - START_LINE: 1, - START_COL: 2, - END_LINE: 3, - END_COL: 4, - START_POS: 5, - END_POS: 6 - }; - exports.FIELDS = FIELDS; - function tokenize(input) { - var tokens = []; - var css = input.css.valueOf(); - var _css = css, - length = _css.length; - var offset = -1; - var line = 1; - var start = 0; - var end = 0; - var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType; - function unclosed(what, fix) { - if (input.safe) { - // fyi: this is never set to true. - css += fix; - next = css.length - 1; - } else { - throw input.error('Unclosed ' + what, line, start - offset, start); - } - } - while (start < length) { - code = css.charCodeAt(start); - if (code === t.newline) { - offset = start; - line += 1; - } - switch (code) { - case t.space: - case t.tab: - case t.newline: - case t.cr: - case t.feed: - next = start; - do { - next += 1; - code = css.charCodeAt(next); - if (code === t.newline) { - offset = next; - line += 1; - } - } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed); - tokenType = t.space; - endLine = line; - endColumn = next - offset - 1; - end = next; - break; - case t.plus: - case t.greaterThan: - case t.tilde: - case t.pipe: - next = start; - do { - next += 1; - code = css.charCodeAt(next); - } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe); - tokenType = t.combinator; - endLine = line; - endColumn = start - offset; - end = next; - break; - - // Consume these characters as single tokens. - case t.asterisk: - case t.ampersand: - case t.bang: - case t.comma: - case t.equals: - case t.dollar: - case t.caret: - case t.openSquare: - case t.closeSquare: - case t.colon: - case t.semicolon: - case t.openParenthesis: - case t.closeParenthesis: - next = start; - tokenType = code; - endLine = line; - endColumn = start - offset; - end = next + 1; - break; - case t.singleQuote: - case t.doubleQuote: - quote = code === t.singleQuote ? "'" : '"'; - next = start; - do { - escaped = false; - next = css.indexOf(quote, next + 1); - if (next === -1) { - unclosed('quote', quote); - } - escapePos = next; - while (css.charCodeAt(escapePos - 1) === t.backslash) { - escapePos -= 1; - escaped = !escaped; - } - } while (escaped); - tokenType = t.str; - endLine = line; - endColumn = start - offset; - end = next + 1; - break; - default: - if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) { - next = css.indexOf('*/', start + 2) + 1; - if (next === 0) { - unclosed('comment', '*/'); - } - content = css.slice(start, next + 1); - lines = content.split('\n'); - last = lines.length - 1; - if (last > 0) { - nextLine = line + last; - nextOffset = next - lines[last].length; - } else { - nextLine = line; - nextOffset = offset; - } - tokenType = t.comment; - line = nextLine; - endLine = nextLine; - endColumn = next - nextOffset; - } else if (code === t.slash) { - next = start; - tokenType = code; - endLine = line; - endColumn = start - offset; - end = next + 1; - } else { - next = consumeWord(css, start); - tokenType = t.word; - endLine = line; - endColumn = next - offset; - } - end = next + 1; - break; - } - - // Ensure that the token structure remains consistent - tokens.push([tokenType, - // [0] Token type - line, - // [1] Starting line - start - offset, - // [2] Starting column - endLine, - // [3] Ending line - endColumn, - // [4] Ending column - start, - // [5] Start position / Source index - end // [6] End position - ]); - - // Reset offset for the next token - if (nextOffset) { - offset = nextOffset; - nextOffset = null; - } - start = end; - } - return tokens; - } - }(tokenize)); - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _root = _interopRequireDefault(rootExports); - var _selector = _interopRequireDefault(selectorExports); - var _className = _interopRequireDefault(classNameExports); - var _comment = _interopRequireDefault(commentExports); - var _id = _interopRequireDefault(idExports); - var _tag = _interopRequireDefault(tagExports); - var _string = _interopRequireDefault(stringExports); - var _pseudo = _interopRequireDefault(pseudoExports); - var _attribute = _interopRequireWildcard(attribute$1); - var _universal = _interopRequireDefault(universalExports); - var _combinator = _interopRequireDefault(combinatorExports); - var _nesting = _interopRequireDefault(nestingExports); - var _sortAscending = _interopRequireDefault(sortAscendingExports); - var _tokenize = _interopRequireWildcard(tokenize); - var tokens = _interopRequireWildcard(tokenTypes); - var types$1 = _interopRequireWildcard(types); - var _util = util$6; - var _WHITESPACE_TOKENS, _Object$assign; - function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } - function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } - var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS); - var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign)); - function tokenStart(token) { - return { - line: token[_tokenize.FIELDS.START_LINE], - column: token[_tokenize.FIELDS.START_COL] - }; - } - function tokenEnd(token) { - return { - line: token[_tokenize.FIELDS.END_LINE], - column: token[_tokenize.FIELDS.END_COL] - }; - } - function getSource(startLine, startColumn, endLine, endColumn) { - return { - start: { - line: startLine, - column: startColumn - }, - end: { - line: endLine, - column: endColumn - } - }; - } - function getTokenSource(token) { - return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]); - } - function getTokenSourceSpan(startToken, endToken) { - if (!startToken) { - return undefined; - } - return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]); - } - function unescapeProp(node, prop) { - var value = node[prop]; - if (typeof value !== "string") { - return; - } - if (value.indexOf("\\") !== -1) { - (0, _util.ensureObject)(node, 'raws'); - node[prop] = (0, _util.unesc)(value); - if (node.raws[prop] === undefined) { - node.raws[prop] = value; - } - } - return node; - } - function indexesOf(array, item) { - var i = -1; - var indexes = []; - while ((i = array.indexOf(item, i + 1)) !== -1) { - indexes.push(i); - } - return indexes; - } - function uniqs() { - var list = Array.prototype.concat.apply([], arguments); - return list.filter(function (item, i) { - return i === list.indexOf(item); - }); - } - var Parser = /*#__PURE__*/function () { - function Parser(rule, options) { - if (options === void 0) { - options = {}; - } - this.rule = rule; - this.options = Object.assign({ - lossy: false, - safe: false - }, options); - this.position = 0; - this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector; - this.tokens = (0, _tokenize["default"])({ - css: this.css, - error: this._errorGenerator(), - safe: this.options.safe - }); - var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]); - this.root = new _root["default"]({ - source: rootSource - }); - this.root.errorGenerator = this._errorGenerator(); - var selector = new _selector["default"]({ - source: { - start: { - line: 1, - column: 1 - } - } - }); - this.root.append(selector); - this.current = selector; - this.loop(); - } - var _proto = Parser.prototype; - _proto._errorGenerator = function _errorGenerator() { - var _this = this; - return function (message, errorOptions) { - if (typeof _this.rule === 'string') { - return new Error(message); - } - return _this.rule.error(message, errorOptions); - }; - }; - _proto.attribute = function attribute() { - var attr = []; - var startingToken = this.currToken; - this.position++; - while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { - attr.push(this.currToken); - this.position++; - } - if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { - return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]); - } - var len = attr.length; - var node = { - source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]), - sourceIndex: startingToken[_tokenize.FIELDS.START_POS] - }; - if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) { - return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]); - } - var pos = 0; - var spaceBefore = ''; - var commentBefore = ''; - var lastAdded = null; - var spaceAfterMeaningfulToken = false; - while (pos < len) { - var token = attr[pos]; - var content = this.content(token); - var next = attr[pos + 1]; - switch (token[_tokenize.FIELDS.TYPE]) { - case tokens.space: - // if ( - // len === 1 || - // pos === 0 && this.content(next) === '|' - // ) { - // return this.expected('attribute', token[TOKEN.START_POS], content); - // } - spaceAfterMeaningfulToken = true; - if (this.options.lossy) { - break; - } - if (lastAdded) { - (0, _util.ensureObject)(node, 'spaces', lastAdded); - var prevContent = node.spaces[lastAdded].after || ''; - node.spaces[lastAdded].after = prevContent + content; - var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null; - if (existingComment) { - node.raws.spaces[lastAdded].after = existingComment + content; - } - } else { - spaceBefore = spaceBefore + content; - commentBefore = commentBefore + content; - } - break; - case tokens.asterisk: - if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) { - if (spaceBefore) { - (0, _util.ensureObject)(node, 'spaces', 'attribute'); - node.spaces.attribute.before = spaceBefore; - spaceBefore = ''; - } - if (commentBefore) { - (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); - node.raws.spaces.attribute.before = spaceBefore; - commentBefore = ''; - } - node.namespace = (node.namespace || "") + content; - var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null; - if (rawValue) { - node.raws.namespace += content; - } - lastAdded = 'namespace'; - } - spaceAfterMeaningfulToken = false; - break; - case tokens.dollar: - if (lastAdded === "value") { - var oldRawValue = (0, _util.getProp)(node, 'raws', 'value'); - node.value += "$"; - if (oldRawValue) { - node.raws.value = oldRawValue + "$"; - } - break; - } - // Falls through - case tokens.caret: - if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } - spaceAfterMeaningfulToken = false; - break; - case tokens.combinator: - if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } - if (content !== '|') { - spaceAfterMeaningfulToken = false; - break; - } - if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } else if (!node.namespace && !node.attribute) { - node.namespace = true; - } - spaceAfterMeaningfulToken = false; - break; - case tokens.word: - if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && - // this look-ahead probably fails with comment nodes involved. - !node.operator && !node.namespace) { - node.namespace = content; - lastAdded = 'namespace'; - } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) { - if (spaceBefore) { - (0, _util.ensureObject)(node, 'spaces', 'attribute'); - node.spaces.attribute.before = spaceBefore; - spaceBefore = ''; - } - if (commentBefore) { - (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); - node.raws.spaces.attribute.before = commentBefore; - commentBefore = ''; - } - node.attribute = (node.attribute || "") + content; - var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null; - if (_rawValue) { - node.raws.attribute += content; - } - lastAdded = 'attribute'; - } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) { - var _unescaped = (0, _util.unesc)(content); - var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || ''; - var oldValue = node.value || ''; - node.value = oldValue + _unescaped; - node.quoteMark = null; - if (_unescaped !== content || _oldRawValue) { - (0, _util.ensureObject)(node, 'raws'); - node.raws.value = (_oldRawValue || oldValue) + content; - } - lastAdded = 'value'; - } else { - var insensitive = content === 'i' || content === "I"; - if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) { - node.insensitive = insensitive; - if (!insensitive || content === "I") { - (0, _util.ensureObject)(node, 'raws'); - node.raws.insensitiveFlag = content; - } - lastAdded = 'insensitive'; - if (spaceBefore) { - (0, _util.ensureObject)(node, 'spaces', 'insensitive'); - node.spaces.insensitive.before = spaceBefore; - spaceBefore = ''; - } - if (commentBefore) { - (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive'); - node.raws.spaces.insensitive.before = commentBefore; - commentBefore = ''; - } - } else if (node.value || node.value === '') { - lastAdded = 'value'; - node.value += content; - if (node.raws.value) { - node.raws.value += content; - } - } - } - spaceAfterMeaningfulToken = false; - break; - case tokens.str: - if (!node.attribute || !node.operator) { - return this.error("Expected an attribute followed by an operator preceding the string.", { - index: token[_tokenize.FIELDS.START_POS] - }); - } - var _unescapeValue = (0, _attribute.unescapeValue)(content), - unescaped = _unescapeValue.unescaped, - quoteMark = _unescapeValue.quoteMark; - node.value = unescaped; - node.quoteMark = quoteMark; - lastAdded = 'value'; - (0, _util.ensureObject)(node, 'raws'); - node.raws.value = content; - spaceAfterMeaningfulToken = false; - break; - case tokens.equals: - if (!node.attribute) { - return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content); - } - if (node.value) { - return this.error('Unexpected "=" found; an operator was already defined.', { - index: token[_tokenize.FIELDS.START_POS] - }); - } - node.operator = node.operator ? node.operator + content : content; - lastAdded = 'operator'; - spaceAfterMeaningfulToken = false; - break; - case tokens.comment: - if (lastAdded) { - if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') { - var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || ''; - var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment; - (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded); - node.raws.spaces[lastAdded].after = rawLastComment + content; - } else { - var lastValue = node[lastAdded] || ''; - var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue; - (0, _util.ensureObject)(node, 'raws'); - node.raws[lastAdded] = rawLastValue + content; - } - } else { - commentBefore = commentBefore + content; - } - break; - default: - return this.error("Unexpected \"" + content + "\" found.", { - index: token[_tokenize.FIELDS.START_POS] - }); - } - pos++; - } - unescapeProp(node, "attribute"); - unescapeProp(node, "namespace"); - this.newNode(new _attribute["default"](node)); - this.position++; - } - - /** - * return a node containing meaningless garbage up to (but not including) the specified token position. - * if the token position is negative, all remaining tokens are consumed. - * - * This returns an array containing a single string node if all whitespace, - * otherwise an array of comment nodes with space before and after. - * - * These tokens are not added to the current selector, the caller can add them or use them to amend - * a previous node's space metadata. - * - * In lossy mode, this returns only comments. - */; - _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) { - if (stopPosition < 0) { - stopPosition = this.tokens.length; - } - var startPosition = this.position; - var nodes = []; - var space = ""; - var lastComment = undefined; - do { - if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) { - if (!this.options.lossy) { - space += this.content(); - } - } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) { - var spaces = {}; - if (space) { - spaces.before = space; - space = ""; - } - lastComment = new _comment["default"]({ - value: this.content(), - source: getTokenSource(this.currToken), - sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], - spaces: spaces - }); - nodes.push(lastComment); - } - } while (++this.position < stopPosition); - if (space) { - if (lastComment) { - lastComment.spaces.after = space; - } else if (!this.options.lossy) { - var firstToken = this.tokens[startPosition]; - var lastToken = this.tokens[this.position - 1]; - nodes.push(new _string["default"]({ - value: '', - source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]), - sourceIndex: firstToken[_tokenize.FIELDS.START_POS], - spaces: { - before: space, - after: '' - } - })); - } - } - return nodes; - } - - /** - * - * @param {*} nodes - */; - _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) { - var _this2 = this; - if (requiredSpace === void 0) { - requiredSpace = false; - } - var space = ""; - var rawSpace = ""; - nodes.forEach(function (n) { - var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace); - var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace); - space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0); - rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0); - }); - if (rawSpace === space) { - rawSpace = undefined; - } - var result = { - space: space, - rawSpace: rawSpace - }; - return result; - }; - _proto.isNamedCombinator = function isNamedCombinator(position) { - if (position === void 0) { - position = this.position; - } - return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash; - }; - _proto.namedCombinator = function namedCombinator() { - if (this.isNamedCombinator()) { - var nameRaw = this.content(this.tokens[this.position + 1]); - var name = (0, _util.unesc)(nameRaw).toLowerCase(); - var raws = {}; - if (name !== nameRaw) { - raws.value = "/" + nameRaw + "/"; - } - var node = new _combinator["default"]({ - value: "/" + name + "/", - source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]), - sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], - raws: raws - }); - this.position = this.position + 3; - return node; - } else { - this.unexpected(); - } - }; - _proto.combinator = function combinator() { - var _this3 = this; - if (this.content() === '|') { - return this.namespace(); - } - // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector. - var nextSigTokenPos = this.locateNextMeaningfulToken(this.position); - if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) { - var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); - if (nodes.length > 0) { - var last = this.current.last; - if (last) { - var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes), - space = _this$convertWhitespa.space, - rawSpace = _this$convertWhitespa.rawSpace; - if (rawSpace !== undefined) { - last.rawSpaceAfter += rawSpace; - } - last.spaces.after += space; - } else { - nodes.forEach(function (n) { - return _this3.newNode(n); - }); - } - } - return; - } - var firstToken = this.currToken; - var spaceOrDescendantSelectorNodes = undefined; - if (nextSigTokenPos > this.position) { - spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); - } - var node; - if (this.isNamedCombinator()) { - node = this.namedCombinator(); - } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) { - node = new _combinator["default"]({ - value: this.content(), - source: getTokenSource(this.currToken), - sourceIndex: this.currToken[_tokenize.FIELDS.START_POS] - }); - this.position++; - } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]); else if (!spaceOrDescendantSelectorNodes) { - this.unexpected(); - } - if (node) { - if (spaceOrDescendantSelectorNodes) { - var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), - _space = _this$convertWhitespa2.space, - _rawSpace = _this$convertWhitespa2.rawSpace; - node.spaces.before = _space; - node.rawSpaceBefore = _rawSpace; - } - } else { - // descendant combinator - var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), - _space2 = _this$convertWhitespa3.space, - _rawSpace2 = _this$convertWhitespa3.rawSpace; - if (!_rawSpace2) { - _rawSpace2 = _space2; - } - var spaces = {}; - var raws = { - spaces: {} - }; - if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) { - spaces.before = _space2.slice(0, _space2.length - 1); - raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1); - } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) { - spaces.after = _space2.slice(1); - raws.spaces.after = _rawSpace2.slice(1); - } else { - raws.value = _rawSpace2; - } - node = new _combinator["default"]({ - value: ' ', - source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]), - sourceIndex: firstToken[_tokenize.FIELDS.START_POS], - spaces: spaces, - raws: raws - }); - } - if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) { - node.spaces.after = this.optionalSpace(this.content()); - this.position++; - } - return this.newNode(node); - }; - _proto.comma = function comma() { - if (this.position === this.tokens.length - 1) { - this.root.trailingComma = true; - this.position++; - return; - } - this.current._inferEndPosition(); - var selector = new _selector["default"]({ - source: { - start: tokenStart(this.tokens[this.position + 1]) - } - }); - this.current.parent.append(selector); - this.current = selector; - this.position++; - }; - _proto.comment = function comment() { - var current = this.currToken; - this.newNode(new _comment["default"]({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - })); - this.position++; - }; - _proto.error = function error(message, opts) { - throw this.root.error(message, opts); - }; - _proto.missingBackslash = function missingBackslash() { - return this.error('Expected a backslash preceding the semicolon.', { - index: this.currToken[_tokenize.FIELDS.START_POS] - }); - }; - _proto.missingParenthesis = function missingParenthesis() { - return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); - }; - _proto.missingSquareBracket = function missingSquareBracket() { - return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]); - }; - _proto.unexpected = function unexpected() { - return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]); - }; - _proto.unexpectedPipe = function unexpectedPipe() { - return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]); - }; - _proto.namespace = function namespace() { - var before = this.prevToken && this.content(this.prevToken) || true; - if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) { - this.position++; - return this.word(before); - } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) { - this.position++; - return this.universal(before); - } - this.unexpectedPipe(); - }; - _proto.nesting = function nesting() { - if (this.nextToken) { - var nextContent = this.content(this.nextToken); - if (nextContent === "|") { - this.position++; - return; - } - } - var current = this.currToken; - this.newNode(new _nesting["default"]({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - })); - this.position++; - }; - _proto.parentheses = function parentheses() { - var last = this.current.last; - var unbalanced = 1; - this.position++; - if (last && last.type === types$1.PSEUDO) { - var selector = new _selector["default"]({ - source: { - start: tokenStart(this.tokens[this.position - 1]) - } - }); - var cache = this.current; - last.append(selector); - this.current = selector; - while (this.position < this.tokens.length && unbalanced) { - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { - unbalanced++; - } - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { - unbalanced--; - } - if (unbalanced) { - this.parse(); - } else { - this.current.source.end = tokenEnd(this.currToken); - this.current.parent.source.end = tokenEnd(this.currToken); - this.position++; - } - } - this.current = cache; - } else { - // I think this case should be an error. It's used to implement a basic parse of media queries - // but I don't think it's a good idea. - var parenStart = this.currToken; - var parenValue = "("; - var parenEnd; - while (this.position < this.tokens.length && unbalanced) { - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { - unbalanced++; - } - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { - unbalanced--; - } - parenEnd = this.currToken; - parenValue += this.parseParenthesisToken(this.currToken); - this.position++; - } - if (last) { - last.appendToPropertyAndEscape("value", parenValue, parenValue); - } else { - this.newNode(new _string["default"]({ - value: parenValue, - source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]), - sourceIndex: parenStart[_tokenize.FIELDS.START_POS] - })); - } - } - if (unbalanced) { - return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); - } - }; - _proto.pseudo = function pseudo() { - var _this4 = this; - var pseudoStr = ''; - var startingToken = this.currToken; - while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) { - pseudoStr += this.content(); - this.position++; - } - if (!this.currToken) { - return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1); - } - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) { - this.splitWord(false, function (first, length) { - pseudoStr += first; - _this4.newNode(new _pseudo["default"]({ - value: pseudoStr, - source: getTokenSourceSpan(startingToken, _this4.currToken), - sourceIndex: startingToken[_tokenize.FIELDS.START_POS] - })); - if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { - _this4.error('Misplaced parenthesis.', { - index: _this4.nextToken[_tokenize.FIELDS.START_POS] - }); - } - }); - } else { - return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]); - } - }; - _proto.space = function space() { - var content = this.content(); - // Handle space before and after the selector - if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) { - return node.type === 'comment'; - })) { - this.spaces = this.optionalSpace(content); - this.position++; - } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { - this.current.last.spaces.after = this.optionalSpace(content); - this.position++; - } else { - this.combinator(); - } - }; - _proto.string = function string() { - var current = this.currToken; - this.newNode(new _string["default"]({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - })); - this.position++; - }; - _proto.universal = function universal(namespace) { - var nextToken = this.nextToken; - if (nextToken && this.content(nextToken) === '|') { - this.position++; - return this.namespace(); - } - var current = this.currToken; - this.newNode(new _universal["default"]({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - }), namespace); - this.position++; - }; - _proto.splitWord = function splitWord(namespace, firstCallback) { - var _this5 = this; - var nextToken = this.nextToken; - var word = this.content(); - while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) { - this.position++; - var current = this.content(); - word += current; - if (current.lastIndexOf('\\') === current.length - 1) { - var next = this.nextToken; - if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) { - word += this.requiredSpace(this.content(next)); - this.position++; - } - } - nextToken = this.nextToken; - } - var hasClass = indexesOf(word, '.').filter(function (i) { - // Allow escaped dot within class name - var escapedDot = word[i - 1] === '\\'; - // Allow decimal numbers percent in @keyframes - var isKeyframesPercent = /^\d+\.\d+%$/.test(word); - return !escapedDot && !isKeyframesPercent; - }); - var hasId = indexesOf(word, '#').filter(function (i) { - return word[i - 1] !== '\\'; - }); - // Eliminate Sass interpolations from the list of id indexes - var interpolations = indexesOf(word, '#{'); - if (interpolations.length) { - hasId = hasId.filter(function (hashIndex) { - return !~interpolations.indexOf(hashIndex); - }); - } - var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId))); - indices.forEach(function (ind, i) { - var index = indices[i + 1] || word.length; - var value = word.slice(ind, index); - if (i === 0 && firstCallback) { - return firstCallback.call(_this5, value, indices.length); - } - var node; - var current = _this5.currToken; - var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i]; - var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1)); - if (~hasClass.indexOf(ind)) { - var classNameOpts = { - value: value.slice(1), - source: source, - sourceIndex: sourceIndex - }; - node = new _className["default"](unescapeProp(classNameOpts, "value")); - } else if (~hasId.indexOf(ind)) { - var idOpts = { - value: value.slice(1), - source: source, - sourceIndex: sourceIndex - }; - node = new _id["default"](unescapeProp(idOpts, "value")); - } else { - var tagOpts = { - value: value, - source: source, - sourceIndex: sourceIndex - }; - unescapeProp(tagOpts, "value"); - node = new _tag["default"](tagOpts); - } - _this5.newNode(node, namespace); - // Ensure that the namespace is used only once - namespace = null; - }); - this.position++; - }; - _proto.word = function word(namespace) { - var nextToken = this.nextToken; - if (nextToken && this.content(nextToken) === '|') { - this.position++; - return this.namespace(); - } - return this.splitWord(namespace); - }; - _proto.loop = function loop() { - while (this.position < this.tokens.length) { - this.parse(true); - } - this.current._inferEndPosition(); - return this.root; - }; - _proto.parse = function parse(throwOnParenthesis) { - switch (this.currToken[_tokenize.FIELDS.TYPE]) { - case tokens.space: - this.space(); - break; - case tokens.comment: - this.comment(); - break; - case tokens.openParenthesis: - this.parentheses(); - break; - case tokens.closeParenthesis: - if (throwOnParenthesis) { - this.missingParenthesis(); - } - break; - case tokens.openSquare: - this.attribute(); - break; - case tokens.dollar: - case tokens.caret: - case tokens.equals: - case tokens.word: - this.word(); - break; - case tokens.colon: - this.pseudo(); - break; - case tokens.comma: - this.comma(); - break; - case tokens.asterisk: - this.universal(); - break; - case tokens.ampersand: - this.nesting(); - break; - case tokens.slash: - case tokens.combinator: - this.combinator(); - break; - case tokens.str: - this.string(); - break; - // These cases throw; no break needed. - case tokens.closeSquare: - this.missingSquareBracket(); - case tokens.semicolon: - this.missingBackslash(); - default: - this.unexpected(); - } - } - - /** - * Helpers - */; - _proto.expected = function expected(description, index, found) { - if (Array.isArray(description)) { - var last = description.pop(); - description = description.join(', ') + " or " + last; - } - var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a'; - if (!found) { - return this.error("Expected " + an + " " + description + ".", { - index: index - }); - } - return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", { - index: index - }); - }; - _proto.requiredSpace = function requiredSpace(space) { - return this.options.lossy ? ' ' : space; - }; - _proto.optionalSpace = function optionalSpace(space) { - return this.options.lossy ? '' : space; - }; - _proto.lossySpace = function lossySpace(space, required) { - if (this.options.lossy) { - return required ? ' ' : ''; - } else { - return space; - } - }; - _proto.parseParenthesisToken = function parseParenthesisToken(token) { - var content = this.content(token); - if (token[_tokenize.FIELDS.TYPE] === tokens.space) { - return this.requiredSpace(content); - } else { - return content; - } - }; - _proto.newNode = function newNode(node, namespace) { - if (namespace) { - if (/^ +$/.test(namespace)) { - if (!this.options.lossy) { - this.spaces = (this.spaces || '') + namespace; - } - namespace = true; - } - node.namespace = namespace; - unescapeProp(node, "namespace"); - } - if (this.spaces) { - node.spaces.before = this.spaces; - this.spaces = ''; - } - return this.current.append(node); - }; - _proto.content = function content(token) { - if (token === void 0) { - token = this.currToken; - } - return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]); - }; - /** - * returns the index of the next non-whitespace, non-comment token. - * returns -1 if no meaningful token is found. - */ - _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) { - if (startPosition === void 0) { - startPosition = this.position + 1; - } - var searchPosition = startPosition; - while (searchPosition < this.tokens.length) { - if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) { - searchPosition++; - continue; - } else { - return searchPosition; - } - } - return -1; - }; - _createClass(Parser, [{ - key: "currToken", - get: function get() { - return this.tokens[this.position]; - } - }, { - key: "nextToken", - get: function get() { - return this.tokens[this.position + 1]; - } - }, { - key: "prevToken", - get: function get() { - return this.tokens[this.position - 1]; - } - }]); - return Parser; - }(); - exports["default"] = Parser; - module.exports = exports.default; - }(parser, parser.exports)); - - var parserExports = parser.exports; - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _parser = _interopRequireDefault(parserExports); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - var Processor = /*#__PURE__*/function () { - function Processor(func, options) { - this.func = func || function noop() { }; - this.funcRes = null; - this.options = options; - } - var _proto = Processor.prototype; - _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) { - if (options === void 0) { - options = {}; - } - var merged = Object.assign({}, this.options, options); - if (merged.updateSelector === false) { - return false; - } else { - return typeof rule !== "string"; - } - }; - _proto._isLossy = function _isLossy(options) { - if (options === void 0) { - options = {}; - } - var merged = Object.assign({}, this.options, options); - if (merged.lossless === false) { - return true; - } else { - return false; - } - }; - _proto._root = function _root(rule, options) { - if (options === void 0) { - options = {}; - } - var parser = new _parser["default"](rule, this._parseOptions(options)); - return parser.root; - }; - _proto._parseOptions = function _parseOptions(options) { - return { - lossy: this._isLossy(options) - }; - }; - _proto._run = function _run(rule, options) { - var _this = this; - if (options === void 0) { - options = {}; - } - return new Promise(function (resolve, reject) { - try { - var root = _this._root(rule, options); - Promise.resolve(_this.func(root)).then(function (transform) { - var string = undefined; - if (_this._shouldUpdateSelector(rule, options)) { - string = root.toString(); - rule.selector = string; - } - return { - transform: transform, - root: root, - string: string - }; - }).then(resolve, reject); - } catch (e) { - reject(e); - return; - } - }); - }; - _proto._runSync = function _runSync(rule, options) { - if (options === void 0) { - options = {}; - } - var root = this._root(rule, options); - var transform = this.func(root); - if (transform && typeof transform.then === "function") { - throw new Error("Selector processor returned a promise to a synchronous call."); - } - var string = undefined; - if (options.updateSelector && typeof rule !== "string") { - string = root.toString(); - rule.selector = string; - } - return { - transform: transform, - root: root, - string: string - }; - } - - /** - * Process rule into a selector AST. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {Promise<parser.Root>} The AST of the selector after processing it. - */; - _proto.ast = function ast(rule, options) { - return this._run(rule, options).then(function (result) { - return result.root; - }); - } - - /** - * Process rule into a selector AST synchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {parser.Root} The AST of the selector after processing it. - */; - _proto.astSync = function astSync(rule, options) { - return this._runSync(rule, options).root; - } - - /** - * Process a selector into a transformed value asynchronously - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {Promise<any>} The value returned by the processor. - */; - _proto.transform = function transform(rule, options) { - return this._run(rule, options).then(function (result) { - return result.transform; - }); - } - - /** - * Process a selector into a transformed value synchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {any} The value returned by the processor. - */; - _proto.transformSync = function transformSync(rule, options) { - return this._runSync(rule, options).transform; - } - - /** - * Process a selector into a new selector string asynchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {string} the selector after processing. - */; - _proto.process = function process(rule, options) { - return this._run(rule, options).then(function (result) { - return result.string || result.root.toString(); - }); - } - - /** - * Process a selector into a new selector string synchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {string} the selector after processing. - */; - _proto.processSync = function processSync(rule, options) { - var result = this._runSync(rule, options); - return result.string || result.root.toString(); - }; - return Processor; - }(); - exports["default"] = Processor; - module.exports = exports.default; - }(processor, processor.exports)); - - var processorExports = processor.exports; - - var selectors = {}; - - var constructors = {}; - - constructors.__esModule = true; - constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0; - var _attribute = _interopRequireDefault(attribute$1); - var _className = _interopRequireDefault(classNameExports); - var _combinator = _interopRequireDefault(combinatorExports); - var _comment = _interopRequireDefault(commentExports); - var _id = _interopRequireDefault(idExports); - var _nesting = _interopRequireDefault(nestingExports); - var _pseudo = _interopRequireDefault(pseudoExports); - var _root = _interopRequireDefault(rootExports); - var _selector = _interopRequireDefault(selectorExports); - var _string = _interopRequireDefault(stringExports); - var _tag = _interopRequireDefault(tagExports); - var _universal = _interopRequireDefault(universalExports); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - var attribute = function attribute(opts) { - return new _attribute["default"](opts); - }; - constructors.attribute = attribute; - var className = function className(opts) { - return new _className["default"](opts); - }; - constructors.className = className; - var combinator = function combinator(opts) { - return new _combinator["default"](opts); - }; - constructors.combinator = combinator; - var comment = function comment(opts) { - return new _comment["default"](opts); - }; - constructors.comment = comment; - var id = function id(opts) { - return new _id["default"](opts); - }; - constructors.id = id; - var nesting = function nesting(opts) { - return new _nesting["default"](opts); - }; - constructors.nesting = nesting; - var pseudo = function pseudo(opts) { - return new _pseudo["default"](opts); - }; - constructors.pseudo = pseudo; - var root = function root(opts) { - return new _root["default"](opts); - }; - constructors.root = root; - var selector = function selector(opts) { - return new _selector["default"](opts); - }; - constructors.selector = selector; - var string = function string(opts) { - return new _string["default"](opts); - }; - constructors.string = string; - var tag = function tag(opts) { - return new _tag["default"](opts); - }; - constructors.tag = tag; - var universal = function universal(opts) { - return new _universal["default"](opts); - }; - constructors.universal = universal; - - var guards = {}; - - guards.__esModule = true; - guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0; - guards.isContainer = isContainer; - guards.isIdentifier = void 0; - guards.isNamespace = isNamespace; - guards.isNesting = void 0; - guards.isNode = isNode; - guards.isPseudo = void 0; - guards.isPseudoClass = isPseudoClass; - guards.isPseudoElement = isPseudoElement; - guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0; - var _types = types; - var _IS_TYPE; - var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE); - function isNode(node) { - return typeof node === "object" && IS_TYPE[node.type]; - } - function isNodeType(type, node) { - return isNode(node) && node.type === type; - } - var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE); - guards.isAttribute = isAttribute; - var isClassName = isNodeType.bind(null, _types.CLASS); - guards.isClassName = isClassName; - var isCombinator = isNodeType.bind(null, _types.COMBINATOR); - guards.isCombinator = isCombinator; - var isComment = isNodeType.bind(null, _types.COMMENT); - guards.isComment = isComment; - var isIdentifier = isNodeType.bind(null, _types.ID); - guards.isIdentifier = isIdentifier; - var isNesting = isNodeType.bind(null, _types.NESTING); - guards.isNesting = isNesting; - var isPseudo = isNodeType.bind(null, _types.PSEUDO); - guards.isPseudo = isPseudo; - var isRoot = isNodeType.bind(null, _types.ROOT); - guards.isRoot = isRoot; - var isSelector = isNodeType.bind(null, _types.SELECTOR); - guards.isSelector = isSelector; - var isString = isNodeType.bind(null, _types.STRING); - guards.isString = isString; - var isTag = isNodeType.bind(null, _types.TAG); - guards.isTag = isTag; - var isUniversal = isNodeType.bind(null, _types.UNIVERSAL); - guards.isUniversal = isUniversal; - function isPseudoElement(node) { - return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line"); - } - function isPseudoClass(node) { - return isPseudo(node) && !isPseudoElement(node); - } - function isContainer(node) { - return !!(isNode(node) && node.walk); - } - function isNamespace(node) { - return isAttribute(node) || isTag(node); - } - - (function (exports) { - - exports.__esModule = true; - var _types = types; - Object.keys(_types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _types[key]) return; - exports[key] = _types[key]; - }); - var _constructors = constructors; - Object.keys(_constructors).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _constructors[key]) return; - exports[key] = _constructors[key]; - }); - var _guards = guards; - Object.keys(_guards).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _guards[key]) return; - exports[key] = _guards[key]; - }); - }(selectors)); - - (function (module, exports) { - - exports.__esModule = true; - exports["default"] = void 0; - var _processor = _interopRequireDefault(processorExports); - var selectors$1 = _interopRequireWildcard(selectors); - function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } - function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } - var parser = function parser(processor) { - return new _processor["default"](processor); - }; - Object.assign(parser, selectors$1); - delete parser.__esModule; - var _default = parser; - exports["default"] = _default; - module.exports = exports.default; - }(dist, dist.exports)); - - var distExports = dist.exports; - var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports); - - const animationNameRE = /^(-\w+-)?animation-name$/; - const animationRE = /^(-\w+-)?animation$/; - const scopedPlugin = (id = "") => { - const keyframes = /* @__PURE__ */ Object.create(null); - const shortId = id.replace(/^data-v-/, ""); - return { - postcssPlugin: "vue-sfc-scoped", - Rule(rule) { - processRule(id, rule); - }, - AtRule(node) { - if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) { - keyframes[node.params] = node.params = node.params + "-" + shortId; - } - }, - OnceExit(root) { - if (Object.keys(keyframes).length) { - root.walkDecls((decl) => { - if (animationNameRE.test(decl.prop)) { - decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(","); - } - if (animationRE.test(decl.prop)) { - decl.value = decl.value.split(",").map((v) => { - const vals = v.trim().split(/\s+/); - const i = vals.findIndex((val) => keyframes[val]); - if (i !== -1) { - vals.splice(i, 1, keyframes[vals[i]]); - return vals.join(" "); - } else { - return v; - } - }).join(","); - } - }); - } - } - }; - }; - const processedRules = /* @__PURE__ */ new WeakSet(); - function processRule(id, rule) { - if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) { - return; - } - processedRules.add(rule); - rule.selector = selectorParser((selectorRoot) => { - selectorRoot.each((selector) => { - rewriteSelector(id, selector, selectorRoot); - }); - }).processSync(rule.selector); - } - function rewriteSelector(id, selector, selectorRoot, slotted = false) { - let node = null; - let shouldInject = true; - selector.each((n) => { - if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) { - n.value = " "; - n.spaces.before = n.spaces.after = ""; - warn( - `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.` - ); - return false; - } - if (n.type === "pseudo") { - const { value } = n; - if (value === ":deep" || value === "::v-deep") { - if (n.nodes.length) { - let last = n; - n.nodes[0].each((ss) => { - selector.insertAfter(last, ss); - last = ss; - }); - const prev = selector.at(selector.index(n) - 1); - if (!prev || !isSpaceCombinator(prev)) { - selector.insertAfter( - n, - selectorParser.combinator({ - value: " " - }) - ); - } - selector.removeChild(n); - } else { - warn( - `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.` - ); - const prev = selector.at(selector.index(n) - 1); - if (prev && isSpaceCombinator(prev)) { - selector.removeChild(prev); - } - selector.removeChild(n); - } - return false; - } - if (value === ":slotted" || value === "::v-slotted") { - rewriteSelector( - id, - n.nodes[0], - selectorRoot, - true - /* slotted */ - ); - let last = n; - n.nodes[0].each((ss) => { - selector.insertAfter(last, ss); - last = ss; - }); - selector.removeChild(n); - shouldInject = false; - return false; - } - if (value === ":global" || value === "::v-global") { - selectorRoot.insertAfter(selector, n.nodes[0]); - selectorRoot.removeChild(selector); - return false; - } - } - if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where")) { - node = n; - } - }); - if (node) { - const { type, value } = node; - if (type === "pseudo" && (value === ":is" || value === ":where")) { - node.nodes.forEach( - (value2) => rewriteSelector(id, value2, selectorRoot, slotted) - ); - shouldInject = false; - } - } - if (node) { - node.spaces.after = ""; - } else { - selector.first.spaces.before = ""; - } - if (shouldInject) { - const idToAdd = slotted ? id + "-s" : id; - selector.insertAfter( - // If node is null it means we need to inject [id] at the start - // insertAfter can handle `null` here - node, - selectorParser.attribute({ - attribute: idToAdd, - value: idToAdd, - raws: {}, - quoteMark: `"` - }) - ); - } - } - function isSpaceCombinator(node) { - return node.type === "combinator" && /^\s+$/.test(node.value); - } - scopedPlugin.postcss = true; - - var sourceMap$1 = {}; - - var sourceMapGenerator = {}; - - var base64Vlq = {}; - - var base64$1 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - - /** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ - base64$1.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); - }; - - /** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ - base64$1.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; - }; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - var base64 = base64$1; - - // A single base 64 digit can contain 6 bits of data. For the base 64 variable - // length quantities we use in the source map spec, the first bit is the sign, - // the next four bits are the actual value, and the 6th bit is the - // continuation bit. The continuation bit tells us whether there are more - // digits in this value following this digit. - // - // Continuation - // | Sign - // | | - // V V - // 101011 - - var VLQ_BASE_SHIFT = 5; - - // binary: 100000 - var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - - // binary: 011111 - var VLQ_BASE_MASK = VLQ_BASE - 1; - - // binary: 100000 - var VLQ_CONTINUATION_BIT = VLQ_BASE; - - /** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ - function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; - } - - /** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ - function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; - } - - /** - * Returns the base 64 VLQ encoded value. - */ - base64Vlq.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; - }; - - /** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ - base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; - }; - - var util$5 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - (function (exports) { - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - /** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ - function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } - } - exports.getArg = getArg; - - var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; - var dataUrlRegexp = /^data:.+\,.+$/; - - function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; - } - exports.urlParse = urlParse; - - function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port; - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; - } - exports.urlGenerate = urlGenerate; - - /** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '<dir>/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ - function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; - } - exports.normalize = normalize; - - /** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ - function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; - } - exports.join = join; - - exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || urlRegexp.test(aPath); - }; - - /** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ - function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); - } - exports.relative = relative; - - var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); - }()); - - function identity(s) { - return s; - } - - /** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ - function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; - } - exports.toSetString = supportsNullProto ? identity : toSetString; - - function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; - } - exports.fromSetString = supportsNullProto ? identity : fromSetString; - - function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; - } - - /** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ - function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByOriginalPositions = compareByOriginalPositions; - - /** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ - function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - - function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 === null) { - return 1; // aStr2 !== null - } - - if (aStr2 === null) { - return -1; // aStr1 !== null - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; - } - - /** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ - function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - - /** - * Strip any JSON XSSI avoidance prefix from the string (as documented - * in the source maps specification), and then parse the string as - * JSON. - */ - function parseSourceMapInput(str) { - return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); - } - exports.parseSourceMapInput = parseSourceMapInput; - - /** - * Compute the URL of a source given the the source root, the source's - * URL, and the source map's URL. - */ - function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { - sourceURL = sourceURL || ''; - - if (sourceRoot) { - // This follows what Chrome does. - if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { - sourceRoot += '/'; - } - // The spec says: - // Line 4: An optional source root, useful for relocating source - // files on a server or removing repeated values in the - // “sources” entry. This value is prepended to the individual - // entries in the “source” field. - sourceURL = sourceRoot + sourceURL; - } - - // Historically, SourceMapConsumer did not take the sourceMapURL as - // a parameter. This mode is still somewhat supported, which is why - // this code block is conditional. However, it's preferable to pass - // the source map URL to SourceMapConsumer, so that this function - // can implement the source URL resolution algorithm as outlined in - // the spec. This block is basically the equivalent of: - // new URL(sourceURL, sourceMapURL).toString() - // ... except it avoids using URL, which wasn't available in the - // older releases of node still supported by this library. - // - // The spec says: - // If the sources are not absolute URLs after prepending of the - // “sourceRoot”, the sources are resolved relative to the - // SourceMap (like resolving script src in a html document). - if (sourceMapURL) { - var parsed = urlParse(sourceMapURL); - if (!parsed) { - throw new Error("sourceMapURL could not be parsed"); - } - if (parsed.path) { - // Strip the last path component, but keep the "/". - var index = parsed.path.lastIndexOf('/'); - if (index >= 0) { - parsed.path = parsed.path.substring(0, index + 1); - } - } - sourceURL = join(urlGenerate(parsed), sourceURL); - } - - return normalize(sourceURL); - } - exports.computeSourceURL = computeSourceURL; - }(util$5)); - - var arraySet = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util$4 = util$5; - var has = Object.prototype.hasOwnProperty; - var hasNativeMap = typeof Map !== "undefined"; - - /** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ - function ArraySet$2() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); - } - - /** - * Static method for creating ArraySet instances from an existing array. - */ - ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet$2(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; - }; - - /** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ - ArraySet$2.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; - }; - - /** - * Add the given string to this set. - * - * @param String aStr - */ - ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; - } - } - }; - - /** - * Is the given string a member of this set? - * - * @param String aStr - */ - ArraySet$2.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util$4.toSetString(aStr); - return has.call(this._set, sStr); - } - }; - - /** - * What is the index of the given string in the array? - * - * @param String aStr - */ - ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util$4.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); - }; - - /** - * What is the element at the given index? - * - * @param Number aIdx - */ - ArraySet$2.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); - }; - - /** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ - ArraySet$2.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); - }; - - arraySet.ArraySet = ArraySet$2; - - var mappingList = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util$3 = util$5; - - /** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ - function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; - } - - /** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ - function MappingList$1() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = { generatedLine: -1, generatedColumn: 0 }; - } - - /** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ - MappingList$1.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - - /** - * Add the given source mapping. - * - * @param Object aMapping - */ - MappingList$1.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } - }; - - /** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ - MappingList$1.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util$3.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; - }; - - mappingList.MappingList = MappingList$1; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var base64VLQ$1 = base64Vlq; - var util$2 = util$5; - var ArraySet$1 = arraySet.ArraySet; - var MappingList = mappingList.MappingList; - - /** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ - function SourceMapGenerator$2(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util$2.getArg(aArgs, 'file', null); - this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet$1(); - this._names = new ArraySet$1(); - this._mappings = new MappingList(); - this._sourcesContents = null; - } - - SourceMapGenerator$2.prototype._version = 3; - - /** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ - SourceMapGenerator$2.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator$2({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util$2.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var sourceRelative = sourceFile; - if (sourceRoot !== null) { - sourceRelative = util$2.relative(sourceRoot, sourceFile); - } - - if (!generator._sources.has(sourceRelative)) { - generator._sources.add(sourceRelative); - } - - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - - /** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ - SourceMapGenerator$2.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util$2.getArg(aArgs, 'generated'); - var original = util$2.getArg(aArgs, 'original', null); - var source = util$2.getArg(aArgs, 'source', null); - var name = util$2.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - - /** - * Set the source content for a source file. - */ - SourceMapGenerator$2.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util$2.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util$2.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util$2.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - - /** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ - SourceMapGenerator$2.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util$2.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet$1(); - var newNames = new ArraySet$1(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util$2.join(aSourceMapPath, mapping.source); - } - if (sourceRoot != null) { - mapping.source = util$2.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util$2.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util$2.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - - /** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ - SourceMapGenerator$2.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - - /** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ - SourceMapGenerator$2.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = ''; - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ$1.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ$1.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ$1.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ$1.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ$1.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - - SourceMapGenerator$2.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util$2.relative(aSourceRoot, source); - } - var key = util$2.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - - /** - * Externalize the source map. - */ - SourceMapGenerator$2.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - - /** - * Render the source map being generated to a string. - */ - SourceMapGenerator$2.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - - sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$2; - - var sourceMapConsumer = {}; - - var binarySearch$1 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - (function (exports) { - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - exports.GREATEST_LOWER_BOUND = 1; - exports.LEAST_UPPER_BOUND = 2; - - /** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ - function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } - } - - /** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ - exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; - }; - }(binarySearch$1)); - - var quickSort$1 = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - // It turns out that some (most?) JavaScript engines don't self-host - // `Array.prototype.sort`. This makes sense because C++ will likely remain - // faster than JS when doing raw CPU-intensive sorting. However, when using a - // custom comparator function, calling back and forth between the VM's C++ and - // JIT'd JS is rather slow *and* loses JIT type information, resulting in - // worse generated code for the comparator function than would be optimal. In - // fact, when sorting with a comparator, these costs outweigh the benefits of - // sorting in C++. By using our own JS-implemented Quick Sort (below), we get - // a ~3500ms mean speed-up in `bench/bench.html`. - - /** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ - function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; - } - - /** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ - function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); - } - - /** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ - function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } - } - - /** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ - quickSort$1.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); - }; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util$1 = util$5; - var binarySearch = binarySearch$1; - var ArraySet = arraySet.ArraySet; - var base64VLQ = base64Vlq; - var quickSort = quickSort$1.quickSort; - - function SourceMapConsumer$1(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$1.parseSourceMapInput(aSourceMap); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) - : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); - } - - SourceMapConsumer$1.fromSourceMap = function (aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); - }; - - /** - * The version of the source mapping spec that we are consuming. - */ - SourceMapConsumer$1.prototype._version = 3; - - // `__generatedMappings` and `__originalMappings` are arrays that hold the - // parsed mapping coordinates from the source map's "mappings" attribute. They - // are lazily instantiated, accessed via the `_generatedMappings` and - // `_originalMappings` getters respectively, and we only parse the mappings - // and create these arrays once queried for a source location. We jump through - // these hoops because there can be many thousands of mappings, and parsing - // them is expensive, so we only want to do it if we must. - // - // Each object in the arrays is of the form: - // - // { - // generatedLine: The line number in the generated code, - // generatedColumn: The column number in the generated code, - // source: The path to the original source file that generated this - // chunk of code, - // originalLine: The line number in the original source that - // corresponds to this chunk of generated code, - // originalColumn: The column number in the original source that - // corresponds to this chunk of generated code, - // name: The name of the original symbol which generated this chunk of - // code. - // } - // - // All properties except for `generatedLine` and `generatedColumn` can be - // `null`. - // - // `_generatedMappings` is ordered by the generated positions. - // - // `_originalMappings` is ordered by the original positions. - - SourceMapConsumer$1.prototype.__generatedMappings = null; - Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } - }); - - SourceMapConsumer$1.prototype.__originalMappings = null; - Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } - }); - - SourceMapConsumer$1.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - SourceMapConsumer$1.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - - SourceMapConsumer$1.GENERATED_ORDER = 1; - SourceMapConsumer$1.ORIGINAL_ORDER = 2; - - SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1; - SourceMapConsumer$1.LEAST_UPPER_BOUND = 2; - - /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ - SourceMapConsumer$1.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer$1.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer$1.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL); - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - - /** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number is 1-based. - * - column: Optional. the column number in the original source. - * The column number is 0-based. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - SourceMapConsumer$1.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util$1.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util$1.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util$1.getArg(aArgs, 'column', 0) - }; - - needle.source = this._findSourceIndex(needle.source); - if (needle.source < 0) { - return []; - } - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util$1.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util$1.getArg(mapping, 'generatedLine', null), - column: util$1.getArg(mapping, 'generatedColumn', null), - lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util$1.getArg(mapping, 'generatedLine', null), - column: util$1.getArg(mapping, 'generatedColumn', null), - lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - - sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1; - - /** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The first parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ - function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$1.parseSourceMapInput(aSourceMap); - } - - var version = util$1.getArg(sourceMap, 'version'); - var sources = util$1.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util$1.getArg(sourceMap, 'names', []); - var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null); - var mappings = util$1.getArg(sourceMap, 'mappings'); - var file = util$1.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - if (sourceRoot) { - sourceRoot = util$1.normalize(sourceRoot); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util$1.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source) - ? util$1.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this._absoluteSources = this._sources.toArray().map(function (s) { - return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL); - }); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this._sourceMapURL = aSourceMapURL; - this.file = file; - } - - BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); - BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1; - - /** - * Utility function to find the index of a source. Returns -1 if not - * found. - */ - BasicSourceMapConsumer.prototype._findSourceIndex = function (aSource) { - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util$1.relative(this.sourceRoot, relativeSource); - } - - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - - // Maybe aSource is an absolute URL as returned by |sources|. In - // this case we can't simply undo the transform. - var i; - for (i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } - - return -1; - }; - - /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @param String aSourceMapURL - * The URL at which the source map can be found (optional) - * @returns BasicSourceMapConsumer - */ - BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - smc._sourceMapURL = aSourceMapURL; - smc._absoluteSources = smc._sources.toArray().map(function (s) { - return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); - }); - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util$1.compareByOriginalPositions); - - return smc; - }; - - /** - * The version of the source mapping spec that we are consuming. - */ - BasicSourceMapConsumer.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._absoluteSources.slice(); - } - }); - - /** - * Provide the JIT with a nice shape / hidden class. - */ - function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; - } - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util$1.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - - /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ - BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - - /** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ - BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ - BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util$1.getArg(aArgs, 'line'), - generatedColumn: util$1.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util$1.compareByGeneratedPositionsDeflated, - util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util$1.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - var name = util$1.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util$1.getArg(mapping, 'originalLine', null), - column: util$1.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - var index = this._findSourceIndex(aSource); - if (index >= 0) { - return this.sourcesContent[index]; - } - - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util$1.relative(this.sourceRoot, relativeSource); - } - - var url; - if (this.sourceRoot != null - && (url = util$1.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + relativeSource)) { - return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util$1.getArg(aArgs, 'source'); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - - var needle = { - source: source, - originalLine: util$1.getArg(aArgs, 'line'), - originalColumn: util$1.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util$1.compareByOriginalPositions, - util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util$1.getArg(mapping, 'generatedLine', null), - column: util$1.getArg(mapping, 'generatedColumn', null), - lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - - sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer; - - /** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The first parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ - function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util$1.parseSourceMapInput(aSourceMap); - } - - var version = util$1.getArg(sourceMap, 'version'); - var sections = util$1.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util$1.getArg(s, 'offset'); - var offsetLine = util$1.getArg(offset, 'line'); - var offsetColumn = util$1.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL) - } - }); - } - - IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); - IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1; - - /** - * The version of the source mapping spec that we are consuming. - */ - IndexedSourceMapConsumer.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } - }); - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ - IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util$1.getArg(aArgs, 'line'), - generatedColumn: util$1.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function (needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = null; - if (mapping.name) { - name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - } - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util$1.compareByOriginalPositions); - }; - - sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - - var sourceNode = {}; - - /* -*- Mode: js; js-indent-level: 2; -*- */ - - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator; - var util = util$5; - - // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other - // operating systems these days (capturing the result). - var REGEX_NEWLINE = /(\r?\n)/; - - // Newline character code for charCodeAt() comparisons - var NEWLINE_CODE = 10; - - // Private symbol for identifying `SourceNode`s when multiple versions of - // the source-map library are loaded. This MUST NOT CHANGE across - // versions! - var isSourceNode = "$$$isSourceNode$$$"; - - /** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ - function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); - } - - /** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ - SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function () { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex] || ''; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex] || ''; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - - /** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length - 1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { - source: this.source, - line: this.line, - column: this.column, - name: this.name - }); - } - } - } - }; - - /** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ - SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len - 1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; - }; - - /** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ - SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; - }; - - /** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ - SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - - /** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - - /** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ - SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; - }; - - /** - * Returns the string representation of this source node along with a source - * map. - */ - SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator$1(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if (lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; - }; - - sourceNode.SourceNode = SourceNode; - - /* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator; - sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer; - sourceMap$1.SourceNode = sourceNode.SourceNode; - - var sourceMap = sourceMap$1; - var SourceMapConsumer = sourceMap.SourceMapConsumer; - var SourceMapGenerator = sourceMap.SourceMapGenerator; - - var mergeSourceMap = merge; - - /** - * Merge old source map and new source map and return merged. - * If old or new source map value is falsy, return another one as it is. - * - * @param {object|string} [oldMap] old source map object - * @param {object|string} [newmap] new source map object - * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined - */ - function merge(oldMap, newMap) { - if (!oldMap) return newMap - if (!newMap) return oldMap - - var oldMapConsumer = new SourceMapConsumer(oldMap); - var newMapConsumer = new SourceMapConsumer(newMap); - var mergedMapGenerator = new SourceMapGenerator(); - - // iterate on new map and overwrite original position of new map with one of old map - newMapConsumer.eachMapping(function (m) { - // pass when `originalLine` is null. - // It occurs in case that the node does not have origin in original code. - if (m.originalLine == null) return - - var origPosInOldMap = oldMapConsumer.originalPositionFor({ - line: m.originalLine, - column: m.originalColumn - }); - - if (origPosInOldMap.source == null) return - - mergedMapGenerator.addMapping({ - original: { - line: origPosInOldMap.line, - column: origPosInOldMap.column - }, - generated: { - line: m.generatedLine, - column: m.generatedColumn - }, - source: origPosInOldMap.source, - name: origPosInOldMap.name - }); - }); - - var consumers = [oldMapConsumer, newMapConsumer]; - consumers.forEach(function (consumer) { - consumer.sources.forEach(function (sourceFile) { - mergedMapGenerator._sources.add(sourceFile); - var sourceContent = consumer.sourceContentFor(sourceFile); - if (sourceContent != null) { - mergedMapGenerator.setSourceContent(sourceFile, sourceContent); - } - }); - }); - - mergedMapGenerator._sourceRoot = oldMap.sourceRoot; - mergedMapGenerator._file = oldMap.file; - - return JSON.parse(mergedMapGenerator.toString()) - } - - var merge$1 = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMap); - - var __defProp$5 = Object.defineProperty; - var __defProps$4 = Object.defineProperties; - var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols; - var __hasOwnProp$5 = Object.prototype.hasOwnProperty; - var __propIsEnum$5 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$5 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$5.call(b, prop)) - __defNormalProp$5(a, prop, b[prop]); - if (__getOwnPropSymbols$5) - for (var prop of __getOwnPropSymbols$5(b)) { - if (__propIsEnum$5.call(b, prop)) - __defNormalProp$5(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b)); - const scss = (source, map, options, load = require) => { - const nodeSass = load("sass"); - const finalOptions = __spreadProps$4(__spreadValues$5({}, options), { - data: getSource(source, options.filename, options.additionalData), - file: options.filename, - outFile: options.filename, - sourceMap: !!map - }); - try { - const result = nodeSass.renderSync(finalOptions); - const dependencies = result.stats.includedFiles; - if (map) { - return { - code: result.css.toString(), - map: merge$1(map, JSON.parse(result.map.toString())), - errors: [], - dependencies - }; - } - return { code: result.css.toString(), errors: [], dependencies }; - } catch (e) { - return { code: "", errors: [e], dependencies: [] }; - } - }; - const sass = (source, map, options, load) => scss( - source, - map, - __spreadProps$4(__spreadValues$5({}, options), { - indentedSyntax: true - }), - load - ); - const less = (source, map, options, load = require) => { - const nodeLess = load("less"); - let result; - let error = null; - nodeLess.render( - getSource(source, options.filename, options.additionalData), - __spreadProps$4(__spreadValues$5({}, options), { syncImport: true }), - (err, output) => { - error = err; - result = output; - } - ); - if (error) - return { code: "", errors: [error], dependencies: [] }; - const dependencies = result.imports; - if (map) { - return { - code: result.css.toString(), - map: merge$1(map, result.map), - errors: [], - dependencies - }; - } - return { - code: result.css.toString(), - errors: [], - dependencies - }; - }; - const styl = (source, map, options, load = require) => { - const nodeStylus = load("stylus"); - try { - const ref = nodeStylus(source, options); - if (map) - ref.set("sourcemap", { inline: false, comment: false }); - const result = ref.render(); - const dependencies = ref.deps(); - if (map) { - return { - code: result, - map: merge$1(map, ref.sourcemap), - errors: [], - dependencies - }; - } - return { code: result, errors: [], dependencies }; - } catch (e) { - return { code: "", errors: [e], dependencies: [] }; - } - }; - function getSource(source, filename, additionalData) { - if (!additionalData) - return source; - if (isFunction$1(additionalData)) { - return additionalData(source, filename); - } - return additionalData + source; - } - const processors = { - less, - sass, - scss, - styl, - stylus: styl - }; - - var __defProp$4 = Object.defineProperty; - var __defProps$3 = Object.defineProperties; - var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; - var __hasOwnProp$4 = Object.prototype.hasOwnProperty; - var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$4 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$4.call(b, prop)) - __defNormalProp$4(a, prop, b[prop]); - if (__getOwnPropSymbols$4) - for (var prop of __getOwnPropSymbols$4(b)) { - if (__propIsEnum$4.call(b, prop)) - __defNormalProp$4(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); - function compileStyle(options) { - return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), { - isAsync: false - })); - } - function compileStyleAsync(options) { - return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), { - isAsync: true - })); - } - function doCompileStyle(options) { - const { - filename, - id, - scoped = false, - trim = true, - isProd = false, - modules = false, - modulesOptions = {}, - preprocessLang, - postcssOptions, - postcssPlugins - } = options; - const preprocessor = preprocessLang && processors[preprocessLang]; - const preProcessedSource = preprocessor && preprocess(options, preprocessor); - const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map; - const source = preProcessedSource ? preProcessedSource.code : options.source; - const shortId = id.replace(/^data-v-/, ""); - const longId = `data-v-${shortId}`; - const plugins = (postcssPlugins || []).slice(); - plugins.unshift(cssVarsPlugin({ id: shortId, isProd })); - if (trim) { - plugins.push(trimPlugin()); - } - if (scoped) { - plugins.push(scopedPlugin(longId)); - } - let cssModules; - if (modules) { - { - throw new Error( - "[@vue/compiler-sfc] `modules` option is not supported in the browser build." - ); - } - } - const postCSSOptions = __spreadProps$3(__spreadValues$4({}, postcssOptions), { - to: filename, - from: filename - }); - if (map) { - postCSSOptions.map = { - inline: false, - annotation: false, - prev: map - }; - } - let result; - let code; - let outMap; - const dependencies = new Set( - preProcessedSource ? preProcessedSource.dependencies : [] - ); - dependencies.delete(filename); - const errors = []; - if (preProcessedSource && preProcessedSource.errors.length) { - errors.push(...preProcessedSource.errors); - } - const recordPlainCssDependencies = (messages) => { - messages.forEach((msg) => { - if (msg.type === "dependency") { - dependencies.add(msg.file); - } - }); - return dependencies; - }; - try { - result = postcss$1(plugins).process(source, postCSSOptions); - if (options.isAsync) { - return result.then((result2) => ({ - code: result2.css || "", - map: result2.map && result2.map.toJSON(), - errors, - modules: cssModules, - rawResult: result2, - dependencies: recordPlainCssDependencies(result2.messages) - })).catch((error) => ({ - code: "", - map: void 0, - errors: [...errors, error], - rawResult: void 0, - dependencies - })); - } - recordPlainCssDependencies(result.messages); - code = result.css; - outMap = result.map; - } catch (e) { - errors.push(e); - } - return { - code: code || ``, - map: outMap && outMap.toJSON(), - errors, - rawResult: result, - dependencies - }; - } - function preprocess(options, preprocessor) { - if (!options.preprocessCustomRequire) { - throw new Error( - `[@vue/compiler-sfc] Style preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor.` - ); - } - return preprocessor( - options.source, - options.inMap || options.map, - __spreadValues$4({ - filename: options.filename - }, options.preprocessOptions), - options.preprocessCustomRequire - ); - } - - function analyzeScriptBindings(ast) { - for (const node of ast) { - if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") { - return analyzeBindingsFromOptions(node.declaration); - } - } - return {}; - } - function analyzeBindingsFromOptions(node) { - const bindings = {}; - Object.defineProperty(bindings, "__isScriptSetup", { - enumerable: false, - value: false - }); - for (const property of node.properties) { - if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") { - if (property.key.name === "props") { - for (const key of getObjectOrArrayExpressionKeys(property.value)) { - bindings[key] = "props"; - } - } else if (property.key.name === "inject") { - for (const key of getObjectOrArrayExpressionKeys(property.value)) { - bindings[key] = "options"; - } - } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) { - for (const key of getObjectExpressionKeys(property.value)) { - bindings[key] = "options"; - } - } - } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) { - for (const bodyItem of property.body.body) { - if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") { - for (const key of getObjectExpressionKeys(bodyItem.argument)) { - bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data"; - } - } - } - } - } - return bindings; - } - function getObjectExpressionKeys(node) { - const keys = []; - for (const prop of node.properties) { - if (prop.type === "SpreadElement") - continue; - const key = resolveObjectKey(prop.key, prop.computed); - if (key) - keys.push(String(key)); - } - return keys; - } - function getArrayExpressionKeys(node) { - const keys = []; - for (const element of node.elements) { - if (element && element.type === "StringLiteral") { - keys.push(element.value); - } - } - return keys; - } - function getObjectOrArrayExpressionKeys(value) { - if (value.type === "ArrayExpression") { - return getArrayExpressionKeys(value); - } - if (value.type === "ObjectExpression") { - return getObjectExpressionKeys(value); - } - return []; - } - - const comma = ','.charCodeAt(0); - const semicolon = ';'.charCodeAt(0); - const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - const intToChar = new Uint8Array(64); // 64 possible chars. - const charToInt = new Uint8Array(128); // z is 122 in ASCII - for (let i = 0; i < chars.length; i++) { - const c = chars.charCodeAt(i); - intToChar[i] = c; - charToInt[c] = i; - } - // Provide a fallback for older environments. - const td = typeof TextDecoder !== 'undefined' - ? /* #__PURE__ */ new TextDecoder() - : typeof Buffer !== 'undefined' - ? { - decode(buf) { - const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); - return out.toString(); - }, - } - : { - decode(buf) { - let out = ''; - for (let i = 0; i < buf.length; i++) { - out += String.fromCharCode(buf[i]); - } - return out; - }, - }; - function encode(decoded) { - const state = new Int32Array(5); - const bufLength = 1024 * 16; - const subLength = bufLength - 36; - const buf = new Uint8Array(bufLength); - const sub = buf.subarray(0, subLength); - let pos = 0; - let out = ''; - for (let i = 0; i < decoded.length; i++) { - const line = decoded[i]; - if (i > 0) { - if (pos === bufLength) { - out += td.decode(buf); - pos = 0; - } - buf[pos++] = semicolon; - } - if (line.length === 0) - continue; - state[0] = 0; - for (let j = 0; j < line.length; j++) { - const segment = line[j]; - // We can push up to 5 ints, each int can take at most 7 chars, and we - // may push a comma. - if (pos > subLength) { - out += td.decode(sub); - buf.copyWithin(0, subLength, pos); - pos -= subLength; - } - if (j > 0) - buf[pos++] = comma; - pos = encodeInteger(buf, pos, state, segment, 0); // genColumn - if (segment.length === 1) - continue; - pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex - pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine - pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn - if (segment.length === 4) - continue; - pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex - } - } - return out + td.decode(buf.subarray(0, pos)); - } - function encodeInteger(buf, pos, state, segment, j) { - const next = segment[j]; - let num = next - state[j]; - state[j] = next; - num = num < 0 ? (-num << 1) | 1 : num << 1; - do { - let clamped = num & 0b011111; - num >>>= 5; - if (num > 0) - clamped |= 0b100000; - buf[pos++] = intToChar[clamped]; - } while (num > 0); - return pos; - } - - class BitSet { - constructor(arg) { - this.bits = arg instanceof BitSet ? arg.bits.slice() : []; - } - - add(n) { - this.bits[n >> 5] |= 1 << (n & 31); - } - - has(n) { - return !!(this.bits[n >> 5] & (1 << (n & 31))); - } - } - - class Chunk { - constructor(start, end, content) { - this.start = start; - this.end = end; - this.original = content; - - this.intro = ''; - this.outro = ''; - - this.content = content; - this.storeName = false; - this.edited = false; - - { - this.previous = null; - this.next = null; - } - } - - appendLeft(content) { - this.outro += content; - } - - appendRight(content) { - this.intro = this.intro + content; - } - - clone() { - const chunk = new Chunk(this.start, this.end, this.original); - - chunk.intro = this.intro; - chunk.outro = this.outro; - chunk.content = this.content; - chunk.storeName = this.storeName; - chunk.edited = this.edited; - - return chunk; - } - - contains(index) { - return this.start < index && index < this.end; - } - - eachNext(fn) { - let chunk = this; - while (chunk) { - fn(chunk); - chunk = chunk.next; - } - } - - eachPrevious(fn) { - let chunk = this; - while (chunk) { - fn(chunk); - chunk = chunk.previous; - } - } - - edit(content, storeName, contentOnly) { - this.content = content; - if (!contentOnly) { - this.intro = ''; - this.outro = ''; - } - this.storeName = storeName; - - this.edited = true; - - return this; - } - - prependLeft(content) { - this.outro = content + this.outro; - } - - prependRight(content) { - this.intro = content + this.intro; - } - - reset() { - this.intro = ''; - this.outro = ''; - if (this.edited) { - this.content = this.original; - this.storeName = false; - this.edited = false; - } - } - - split(index) { - const sliceIndex = index - this.start; - - const originalBefore = this.original.slice(0, sliceIndex); - const originalAfter = this.original.slice(sliceIndex); - - this.original = originalBefore; - - const newChunk = new Chunk(index, this.end, originalAfter); - newChunk.outro = this.outro; - this.outro = ''; - - this.end = index; - - if (this.edited) { - // after split we should save the edit content record into the correct chunk - // to make sure sourcemap correct - // For example: - // ' test'.trim() - // split -> ' ' + 'test' - // ✔️ edit -> '' + 'test' - // ✖️ edit -> 'test' + '' - // TODO is this block necessary?... - newChunk.edit('', false); - this.content = ''; - } else { - this.content = originalBefore; - } - - newChunk.next = this.next; - if (newChunk.next) newChunk.next.previous = newChunk; - newChunk.previous = this; - this.next = newChunk; - - return newChunk; - } - - toString() { - return this.intro + this.content + this.outro; - } - - trimEnd(rx) { - this.outro = this.outro.replace(rx, ''); - if (this.outro.length) return true; - - const trimmed = this.content.replace(rx, ''); - - if (trimmed.length) { - if (trimmed !== this.content) { - this.split(this.start + trimmed.length).edit('', undefined, true); - if (this.edited) { - // save the change, if it has been edited - this.edit(trimmed, this.storeName, true); - } - } - return true; - } else { - this.edit('', undefined, true); - - this.intro = this.intro.replace(rx, ''); - if (this.intro.length) return true; - } - } - - trimStart(rx) { - this.intro = this.intro.replace(rx, ''); - if (this.intro.length) return true; - - const trimmed = this.content.replace(rx, ''); - - if (trimmed.length) { - if (trimmed !== this.content) { - const newChunk = this.split(this.end - trimmed.length); - if (this.edited) { - // save the change, if it has been edited - newChunk.edit(trimmed, this.storeName, true); - } - this.edit('', undefined, true); - } - return true; - } else { - this.edit('', undefined, true); - - this.outro = this.outro.replace(rx, ''); - if (this.outro.length) return true; - } - } - } - - function getBtoa() { - if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { - return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); - } else if (typeof Buffer === 'function') { - return (str) => Buffer.from(str, 'utf-8').toString('base64'); - } else { - return () => { - throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); - }; - } - } - - const btoa = /*#__PURE__*/ getBtoa(); - - class SourceMap { - constructor(properties) { - this.version = 3; - this.file = properties.file; - this.sources = properties.sources; - this.sourcesContent = properties.sourcesContent; - this.names = properties.names; - this.mappings = encode(properties.mappings); - if (typeof properties.x_google_ignoreList !== 'undefined') { - this.x_google_ignoreList = properties.x_google_ignoreList; - } - } - - toString() { - return JSON.stringify(this); - } - - toUrl() { - return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); - } - } - - function guessIndent(code) { - const lines = code.split('\n'); - - const tabbed = lines.filter((line) => /^\t+/.test(line)); - const spaced = lines.filter((line) => /^ {2,}/.test(line)); - - if (tabbed.length === 0 && spaced.length === 0) { - return null; - } - - // More lines tabbed than spaced? Assume tabs, and - // default to tabs in the case of a tie (or nothing - // to go on) - if (tabbed.length >= spaced.length) { - return '\t'; - } - - // Otherwise, we need to guess the multiple - const min = spaced.reduce((previous, current) => { - const numSpaces = /^ +/.exec(current)[0].length; - return Math.min(numSpaces, previous); - }, Infinity); - - return new Array(min + 1).join(' '); - } - - function getRelativePath(from, to) { - const fromParts = from.split(/[/\\]/); - const toParts = to.split(/[/\\]/); - - fromParts.pop(); // get dirname - - while (fromParts[0] === toParts[0]) { - fromParts.shift(); - toParts.shift(); - } - - if (fromParts.length) { - let i = fromParts.length; - while (i--) fromParts[i] = '..'; - } - - return fromParts.concat(toParts).join('/'); - } - - const toString = Object.prototype.toString; - - function isObject(thing) { - return toString.call(thing) === '[object Object]'; - } - - function getLocator(source) { - const originalLines = source.split('\n'); - const lineOffsets = []; - - for (let i = 0, pos = 0; i < originalLines.length; i++) { - lineOffsets.push(pos); - pos += originalLines[i].length + 1; - } - - return function locate(index) { - let i = 0; - let j = lineOffsets.length; - while (i < j) { - const m = (i + j) >> 1; - if (index < lineOffsets[m]) { - j = m; - } else { - i = m + 1; - } - } - const line = i - 1; - const column = index - lineOffsets[line]; - return { line, column }; - }; - } - - const wordRegex = /\w/; - - class Mappings { - constructor(hires) { - this.hires = hires; - this.generatedCodeLine = 0; - this.generatedCodeColumn = 0; - this.raw = []; - this.rawSegments = this.raw[this.generatedCodeLine] = []; - this.pending = null; - } - - addEdit(sourceIndex, content, loc, nameIndex) { - if (content.length) { - let contentLineEnd = content.indexOf('\n', 0); - let previousContentLineEnd = -1; - while (contentLineEnd >= 0) { - const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; - if (nameIndex >= 0) { - segment.push(nameIndex); - } - this.rawSegments.push(segment); - - this.generatedCodeLine += 1; - this.raw[this.generatedCodeLine] = this.rawSegments = []; - this.generatedCodeColumn = 0; - - previousContentLineEnd = contentLineEnd; - contentLineEnd = content.indexOf('\n', contentLineEnd + 1); - } - - const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; - if (nameIndex >= 0) { - segment.push(nameIndex); - } - this.rawSegments.push(segment); - - this.advance(content.slice(previousContentLineEnd + 1)); - } else if (this.pending) { - this.rawSegments.push(this.pending); - this.advance(content); - } - - this.pending = null; - } - - addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { - let originalCharIndex = chunk.start; - let first = true; - // when iterating each char, check if it's in a word boundary - let charInHiresBoundary = false; - - while (originalCharIndex < chunk.end) { - if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { - const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; - - if (this.hires === 'boundary') { - // in hires "boundary", group segments per word boundary than per char - if (wordRegex.test(original[originalCharIndex])) { - // for first char in the boundary found, start the boundary by pushing a segment - if (!charInHiresBoundary) { - this.rawSegments.push(segment); - charInHiresBoundary = true; - } - } else { - // for non-word char, end the boundary by pushing a segment - this.rawSegments.push(segment); - charInHiresBoundary = false; - } - } else { - this.rawSegments.push(segment); - } - } - - if (original[originalCharIndex] === '\n') { - loc.line += 1; - loc.column = 0; - this.generatedCodeLine += 1; - this.raw[this.generatedCodeLine] = this.rawSegments = []; - this.generatedCodeColumn = 0; - first = true; - } else { - loc.column += 1; - this.generatedCodeColumn += 1; - first = false; - } - - originalCharIndex += 1; - } - - this.pending = null; - } - - advance(str) { - if (!str) return; - - const lines = str.split('\n'); - - if (lines.length > 1) { - for (let i = 0; i < lines.length - 1; i++) { - this.generatedCodeLine++; - this.raw[this.generatedCodeLine] = this.rawSegments = []; - } - this.generatedCodeColumn = 0; - } - - this.generatedCodeColumn += lines[lines.length - 1].length; - } - } - - const n = '\n'; - - const warned = { - insertLeft: false, - insertRight: false, - storeName: false, - }; - - class MagicString { - constructor(string, options = {}) { - const chunk = new Chunk(0, string.length, string); - - Object.defineProperties(this, { - original: { writable: true, value: string }, - outro: { writable: true, value: '' }, - intro: { writable: true, value: '' }, - firstChunk: { writable: true, value: chunk }, - lastChunk: { writable: true, value: chunk }, - lastSearchedChunk: { writable: true, value: chunk }, - byStart: { writable: true, value: {} }, - byEnd: { writable: true, value: {} }, - filename: { writable: true, value: options.filename }, - indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, - sourcemapLocations: { writable: true, value: new BitSet() }, - storedNames: { writable: true, value: {} }, - indentStr: { writable: true, value: undefined }, - ignoreList: { writable: true, value: options.ignoreList }, - }); - - this.byStart[0] = chunk; - this.byEnd[string.length] = chunk; - } - - addSourcemapLocation(char) { - this.sourcemapLocations.add(char); - } - - append(content) { - if (typeof content !== 'string') throw new TypeError('outro content must be a string'); - - this.outro += content; - return this; - } - - appendLeft(index, content) { - if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); - - this._split(index); - - const chunk = this.byEnd[index]; - - if (chunk) { - chunk.appendLeft(content); - } else { - this.intro += content; - } - return this; - } - - appendRight(index, content) { - if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); - - this._split(index); - - const chunk = this.byStart[index]; - - if (chunk) { - chunk.appendRight(content); - } else { - this.outro += content; - } - return this; - } - - clone() { - const cloned = new MagicString(this.original, { filename: this.filename }); - - let originalChunk = this.firstChunk; - let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); - - while (originalChunk) { - cloned.byStart[clonedChunk.start] = clonedChunk; - cloned.byEnd[clonedChunk.end] = clonedChunk; - - const nextOriginalChunk = originalChunk.next; - const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); - - if (nextClonedChunk) { - clonedChunk.next = nextClonedChunk; - nextClonedChunk.previous = clonedChunk; - - clonedChunk = nextClonedChunk; - } - - originalChunk = nextOriginalChunk; - } - - cloned.lastChunk = clonedChunk; - - if (this.indentExclusionRanges) { - cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); - } - - cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); - - cloned.intro = this.intro; - cloned.outro = this.outro; - - return cloned; - } - - generateDecodedMap(options) { - options = options || {}; - - const sourceIndex = 0; - const names = Object.keys(this.storedNames); - const mappings = new Mappings(options.hires); - - const locate = getLocator(this.original); - - if (this.intro) { - mappings.advance(this.intro); - } - - this.firstChunk.eachNext((chunk) => { - const loc = locate(chunk.start); - - if (chunk.intro.length) mappings.advance(chunk.intro); - - if (chunk.edited) { - mappings.addEdit( - sourceIndex, - chunk.content, - loc, - chunk.storeName ? names.indexOf(chunk.original) : -1, - ); - } else { - mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); - } - - if (chunk.outro.length) mappings.advance(chunk.outro); - }); - - return { - file: options.file ? options.file.split(/[/\\]/).pop() : undefined, - sources: [ - options.source ? getRelativePath(options.file || '', options.source) : options.file || '', - ], - sourcesContent: options.includeContent ? [this.original] : undefined, - names, - mappings: mappings.raw, - x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, - }; - } - - generateMap(options) { - return new SourceMap(this.generateDecodedMap(options)); - } - - _ensureindentStr() { - if (this.indentStr === undefined) { - this.indentStr = guessIndent(this.original); - } - } - - _getRawIndentString() { - this._ensureindentStr(); - return this.indentStr; - } - - getIndentString() { - this._ensureindentStr(); - return this.indentStr === null ? '\t' : this.indentStr; - } - - indent(indentStr, options) { - const pattern = /^[^\r\n]/gm; - - if (isObject(indentStr)) { - options = indentStr; - indentStr = undefined; - } - - if (indentStr === undefined) { - this._ensureindentStr(); - indentStr = this.indentStr || '\t'; - } - - if (indentStr === '') return this; // noop - - options = options || {}; - - // Process exclusion ranges - const isExcluded = {}; - - if (options.exclude) { - const exclusions = - typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; - exclusions.forEach((exclusion) => { - for (let i = exclusion[0]; i < exclusion[1]; i += 1) { - isExcluded[i] = true; - } - }); - } - - let shouldIndentNextCharacter = options.indentStart !== false; - const replacer = (match) => { - if (shouldIndentNextCharacter) return `${indentStr}${match}`; - shouldIndentNextCharacter = true; - return match; - }; - - this.intro = this.intro.replace(pattern, replacer); - - let charIndex = 0; - let chunk = this.firstChunk; - - while (chunk) { - const end = chunk.end; - - if (chunk.edited) { - if (!isExcluded[charIndex]) { - chunk.content = chunk.content.replace(pattern, replacer); - - if (chunk.content.length) { - shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; - } - } - } else { - charIndex = chunk.start; - - while (charIndex < end) { - if (!isExcluded[charIndex]) { - const char = this.original[charIndex]; - - if (char === '\n') { - shouldIndentNextCharacter = true; - } else if (char !== '\r' && shouldIndentNextCharacter) { - shouldIndentNextCharacter = false; - - if (charIndex === chunk.start) { - chunk.prependRight(indentStr); - } else { - this._splitChunk(chunk, charIndex); - chunk = chunk.next; - chunk.prependRight(indentStr); - } - } - } - - charIndex += 1; - } - } - - charIndex = chunk.end; - chunk = chunk.next; - } - - this.outro = this.outro.replace(pattern, replacer); - - return this; - } - - insert() { - throw new Error( - 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', - ); - } - - insertLeft(index, content) { - if (!warned.insertLeft) { - console.warn( - 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', - ); // eslint-disable-line no-console - warned.insertLeft = true; - } - - return this.appendLeft(index, content); - } - - insertRight(index, content) { - if (!warned.insertRight) { - console.warn( - 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', - ); // eslint-disable-line no-console - warned.insertRight = true; - } - - return this.prependRight(index, content); - } - - move(start, end, index) { - if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); - - this._split(start); - this._split(end); - this._split(index); - - const first = this.byStart[start]; - const last = this.byEnd[end]; - - const oldLeft = first.previous; - const oldRight = last.next; - - const newRight = this.byStart[index]; - if (!newRight && last === this.lastChunk) return this; - const newLeft = newRight ? newRight.previous : this.lastChunk; - - if (oldLeft) oldLeft.next = oldRight; - if (oldRight) oldRight.previous = oldLeft; - - if (newLeft) newLeft.next = first; - if (newRight) newRight.previous = last; - - if (!first.previous) this.firstChunk = last.next; - if (!last.next) { - this.lastChunk = first.previous; - this.lastChunk.next = null; - } - - first.previous = newLeft; - last.next = newRight || null; - - if (!newLeft) this.firstChunk = first; - if (!newRight) this.lastChunk = last; - return this; - } - - overwrite(start, end, content, options) { - options = options || {}; - return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); - } - - update(start, end, content, options) { - if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); - - while (start < 0) start += this.original.length; - while (end < 0) end += this.original.length; - - if (end > this.original.length) throw new Error('end is out of bounds'); - if (start === end) - throw new Error( - 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', - ); - - this._split(start); - this._split(end); - - if (options === true) { - if (!warned.storeName) { - console.warn( - 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', - ); // eslint-disable-line no-console - warned.storeName = true; - } - - options = { storeName: true }; - } - const storeName = options !== undefined ? options.storeName : false; - const overwrite = options !== undefined ? options.overwrite : false; - - if (storeName) { - const original = this.original.slice(start, end); - Object.defineProperty(this.storedNames, original, { - writable: true, - value: true, - enumerable: true, - }); - } - - const first = this.byStart[start]; - const last = this.byEnd[end]; - - if (first) { - let chunk = first; - while (chunk !== last) { - if (chunk.next !== this.byStart[chunk.end]) { - throw new Error('Cannot overwrite across a split point'); - } - chunk = chunk.next; - chunk.edit('', false); - } - - first.edit(content, storeName, !overwrite); - } else { - // must be inserting at the end - const newChunk = new Chunk(start, end, '').edit(content, storeName); - - // TODO last chunk in the array may not be the last chunk, if it's moved... - last.next = newChunk; - newChunk.previous = last; - } - return this; - } - - prepend(content) { - if (typeof content !== 'string') throw new TypeError('outro content must be a string'); - - this.intro = content + this.intro; - return this; - } - - prependLeft(index, content) { - if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); - - this._split(index); - - const chunk = this.byEnd[index]; - - if (chunk) { - chunk.prependLeft(content); - } else { - this.intro = content + this.intro; - } - return this; - } - - prependRight(index, content) { - if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); - - this._split(index); - - const chunk = this.byStart[index]; - - if (chunk) { - chunk.prependRight(content); - } else { - this.outro = content + this.outro; - } - return this; - } - - remove(start, end) { - while (start < 0) start += this.original.length; - while (end < 0) end += this.original.length; - - if (start === end) return this; - - if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); - if (start > end) throw new Error('end must be greater than start'); - - this._split(start); - this._split(end); - - let chunk = this.byStart[start]; - - while (chunk) { - chunk.intro = ''; - chunk.outro = ''; - chunk.edit(''); - - chunk = end > chunk.end ? this.byStart[chunk.end] : null; - } - return this; - } - - reset(start, end) { - while (start < 0) start += this.original.length; - while (end < 0) end += this.original.length; - - if (start === end) return this; - - if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); - if (start > end) throw new Error('end must be greater than start'); - - this._split(start); - this._split(end); - - let chunk = this.byStart[start]; - - while (chunk) { - chunk.reset(); - - chunk = end > chunk.end ? this.byStart[chunk.end] : null; - } - return this; - } - - lastChar() { - if (this.outro.length) return this.outro[this.outro.length - 1]; - let chunk = this.lastChunk; - do { - if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; - if (chunk.content.length) return chunk.content[chunk.content.length - 1]; - if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; - } while ((chunk = chunk.previous)); - if (this.intro.length) return this.intro[this.intro.length - 1]; - return ''; - } - - lastLine() { - let lineIndex = this.outro.lastIndexOf(n); - if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); - let lineStr = this.outro; - let chunk = this.lastChunk; - do { - if (chunk.outro.length > 0) { - lineIndex = chunk.outro.lastIndexOf(n); - if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; - lineStr = chunk.outro + lineStr; - } - - if (chunk.content.length > 0) { - lineIndex = chunk.content.lastIndexOf(n); - if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; - lineStr = chunk.content + lineStr; - } - - if (chunk.intro.length > 0) { - lineIndex = chunk.intro.lastIndexOf(n); - if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; - lineStr = chunk.intro + lineStr; - } - } while ((chunk = chunk.previous)); - lineIndex = this.intro.lastIndexOf(n); - if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; - return this.intro + lineStr; - } - - slice(start = 0, end = this.original.length) { - while (start < 0) start += this.original.length; - while (end < 0) end += this.original.length; - - let result = ''; - - // find start chunk - let chunk = this.firstChunk; - while (chunk && (chunk.start > start || chunk.end <= start)) { - // found end chunk before start - if (chunk.start < end && chunk.end >= end) { - return result; - } - - chunk = chunk.next; - } - - if (chunk && chunk.edited && chunk.start !== start) - throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); - - const startChunk = chunk; - while (chunk) { - if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { - result += chunk.intro; - } - - const containsEnd = chunk.start < end && chunk.end >= end; - if (containsEnd && chunk.edited && chunk.end !== end) - throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); - - const sliceStart = startChunk === chunk ? start - chunk.start : 0; - const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; - - result += chunk.content.slice(sliceStart, sliceEnd); - - if (chunk.outro && (!containsEnd || chunk.end === end)) { - result += chunk.outro; - } - - if (containsEnd) { - break; - } - - chunk = chunk.next; - } - - return result; - } - - // TODO deprecate this? not really very useful - snip(start, end) { - const clone = this.clone(); - clone.remove(0, start); - clone.remove(end, clone.original.length); - - return clone; - } - - _split(index) { - if (this.byStart[index] || this.byEnd[index]) return; - - let chunk = this.lastSearchedChunk; - const searchForward = index > chunk.end; - - while (chunk) { - if (chunk.contains(index)) return this._splitChunk(chunk, index); - - chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; - } - } - - _splitChunk(chunk, index) { - if (chunk.edited && chunk.content.length) { - // zero-length edited chunks are a special case (overlapping replacements) - const loc = getLocator(this.original)(index); - throw new Error( - `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, - ); - } - - const newChunk = chunk.split(index); - - this.byEnd[index] = chunk; - this.byStart[index] = newChunk; - this.byEnd[newChunk.end] = newChunk; - - if (chunk === this.lastChunk) this.lastChunk = newChunk; - - this.lastSearchedChunk = chunk; - return true; - } - - toString() { - let str = this.intro; - - let chunk = this.firstChunk; - while (chunk) { - str += chunk.toString(); - chunk = chunk.next; - } - - return str + this.outro; - } - - isEmpty() { - let chunk = this.firstChunk; - do { - if ( - (chunk.intro.length && chunk.intro.trim()) || - (chunk.content.length && chunk.content.trim()) || - (chunk.outro.length && chunk.outro.trim()) - ) - return false; - } while ((chunk = chunk.next)); - return true; - } - - length() { - let chunk = this.firstChunk; - let length = 0; - do { - length += chunk.intro.length + chunk.content.length + chunk.outro.length; - } while ((chunk = chunk.next)); - return length; - } - - trimLines() { - return this.trim('[\\r\\n]'); - } - - trim(charType) { - return this.trimStart(charType).trimEnd(charType); - } - - trimEndAborted(charType) { - const rx = new RegExp((charType || '\\s') + '+$'); - - this.outro = this.outro.replace(rx, ''); - if (this.outro.length) return true; - - let chunk = this.lastChunk; - - do { - const end = chunk.end; - const aborted = chunk.trimEnd(rx); - - // if chunk was trimmed, we have a new lastChunk - if (chunk.end !== end) { - if (this.lastChunk === chunk) { - this.lastChunk = chunk.next; - } - - this.byEnd[chunk.end] = chunk; - this.byStart[chunk.next.start] = chunk.next; - this.byEnd[chunk.next.end] = chunk.next; - } - - if (aborted) return true; - chunk = chunk.previous; - } while (chunk); - - return false; - } - - trimEnd(charType) { - this.trimEndAborted(charType); - return this; - } - trimStartAborted(charType) { - const rx = new RegExp('^' + (charType || '\\s') + '+'); - - this.intro = this.intro.replace(rx, ''); - if (this.intro.length) return true; - - let chunk = this.firstChunk; - - do { - const end = chunk.end; - const aborted = chunk.trimStart(rx); - - if (chunk.end !== end) { - // special case... - if (chunk === this.lastChunk) this.lastChunk = chunk.next; - - this.byEnd[chunk.end] = chunk; - this.byStart[chunk.next.start] = chunk.next; - this.byEnd[chunk.next.end] = chunk.next; - } - - if (aborted) return true; - chunk = chunk.next; - } while (chunk); - - return false; - } - - trimStart(charType) { - this.trimStartAborted(charType); - return this; - } - - hasChanged() { - return this.original !== this.toString(); - } - - _replaceRegexp(searchValue, replacement) { - function getReplacement(match, str) { - if (typeof replacement === 'string') { - return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter - if (i === '$') return '$'; - if (i === '&') return match[0]; - const num = +i; - if (num < match.length) return match[+i]; - return `$${i}`; - }); - } else { - return replacement(...match, match.index, str, match.groups); - } - } - function matchAll(re, str) { - let match; - const matches = []; - while ((match = re.exec(str))) { - matches.push(match); - } - return matches; - } - if (searchValue.global) { - const matches = matchAll(searchValue, this.original); - matches.forEach((match) => { - if (match.index != null) - this.overwrite( - match.index, - match.index + match[0].length, - getReplacement(match, this.original), - ); - }); - } else { - const match = this.original.match(searchValue); - if (match && match.index != null) - this.overwrite( - match.index, - match.index + match[0].length, - getReplacement(match, this.original), - ); - } - return this; - } - - _replaceString(string, replacement) { - const { original } = this; - const index = original.indexOf(string); - - if (index !== -1) { - this.overwrite(index, index + string.length, replacement); - } - - return this; - } - - replace(searchValue, replacement) { - if (typeof searchValue === 'string') { - return this._replaceString(searchValue, replacement); - } - - return this._replaceRegexp(searchValue, replacement); - } - - _replaceAllString(string, replacement) { - const { original } = this; - const stringLength = string.length; - for ( - let index = original.indexOf(string); - index !== -1; - index = original.indexOf(string, index + stringLength) - ) { - this.overwrite(index, index + stringLength, replacement); - } - - return this; - } - - replaceAll(searchValue, replacement) { - if (typeof searchValue === 'string') { - return this._replaceAllString(searchValue, replacement); - } - - if (!searchValue.global) { - throw new TypeError( - 'MagicString.prototype.replaceAll called with a non-global RegExp argument', - ); - } - - return this._replaceRegexp(searchValue, replacement); - } - } - - var _a, _b; - class ScriptCompileContext { - constructor(descriptor, options) { - this.descriptor = descriptor; - this.options = options; - this.isCE = false; - this.source = this.descriptor.source; - this.filename = this.descriptor.filename; - this.s = new MagicString(this.source); - this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset; - this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset; - this.userImports = /* @__PURE__ */ Object.create(null); - // macros presence check - this.hasDefinePropsCall = false; - this.hasDefineEmitCall = false; - this.hasDefineExposeCall = false; - this.hasDefaultExportName = false; - this.hasDefaultExportRender = false; - this.hasDefineOptionsCall = false; - this.hasDefineSlotsCall = false; - this.hasDefineModelCall = false; - this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null); - // defineModel - this.modelDecls = /* @__PURE__ */ Object.create(null); - // codegen - this.bindingMetadata = {}; - this.helperImports = /* @__PURE__ */ new Set(); - const { script, scriptSetup } = descriptor; - const scriptLang = script && script.lang; - const scriptSetupLang = scriptSetup && scriptSetup.lang; - this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx"; - this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx"; - const customElement = options.customElement; - const filename = this.descriptor.filename; - if (customElement) { - this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename); - } - const plugins = resolveParserPlugins( - scriptLang || scriptSetupLang, - options.babelParserPlugins - ); - function parse(input, offset) { - try { - return parse_1$1(input, { - plugins, - sourceType: "module" - }).program; - } catch (e) { - e.message = `[vue/compiler-sfc] ${e.message} - -${descriptor.filename} -${generateCodeFrame( - descriptor.source, - e.pos + offset, - e.pos + offset + 1 - )}`; - throw e; - } - } - this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset); - this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset); - } - helper(key) { - this.helperImports.add(key); - return `_${key}`; - } - getString(node, scriptSetup = true) { - const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script; - return block.content.slice(node.start, node.end); - } - error(msg, node, scope) { - const offset = scope ? scope.offset : this.startOffset; - throw new Error( - `[@vue/compiler-sfc] ${msg} - -${(scope || this.descriptor).filename} -${generateCodeFrame( - (scope || this.descriptor).source, - node.start + offset, - node.end + offset - )}` - ); - } - } - function resolveParserPlugins(lang, userPlugins, dts = false) { - const plugins = []; - if (!userPlugins || !userPlugins.some( - (p) => p === "importAssertions" || p === "importAttributes" || isArray$3(p) && p[0] === "importAttributes" - )) { - plugins.push("importAttributes"); - } - if (lang === "jsx" || lang === "tsx") { - plugins.push("jsx"); - } else if (userPlugins) { - userPlugins = userPlugins.filter((p) => p !== "jsx"); - } - if (lang === "ts" || lang === "tsx") { - plugins.push(["typescript", { dts }], "explicitResourceManagement"); - if (!userPlugins || !userPlugins.includes("decorators")) { - plugins.push("decorators-legacy"); - } - } - if (userPlugins) { - plugins.push(...userPlugins); - } - return plugins; - } - - function rewriteDefault(input, as, parserPlugins) { - const ast = parse_1$1(input, { - sourceType: "module", - plugins: resolveParserPlugins("js", parserPlugins) - }).program.body; - const s = new MagicString(input); - rewriteDefaultAST(ast, s, as); - return s.toString(); - } - function rewriteDefaultAST(ast, s, as) { - if (!hasDefaultExport(ast)) { - s.append(` -const ${as} = {}`); - return; - } - ast.forEach((node) => { - if (node.type === "ExportDefaultDeclaration") { - if (node.declaration.type === "ClassDeclaration" && node.declaration.id) { - let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start; - s.overwrite(start, node.declaration.id.start, ` class `); - s.append(` -const ${as} = ${node.declaration.id.name}`); - } else { - s.overwrite(node.start, node.declaration.start, `const ${as} = `); - } - } else if (node.type === "ExportNamedDeclaration") { - for (const specifier of node.specifiers) { - if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") { - if (node.source) { - if (specifier.local.name === "default") { - s.prepend( - `import { default as __VUE_DEFAULT__ } from '${node.source.value}' -` - ); - const end2 = specifierEnd(s, specifier.local.end, node.end); - s.remove(specifier.start, end2); - s.append(` -const ${as} = __VUE_DEFAULT__`); - continue; - } else { - s.prepend( - `import { ${s.slice( - specifier.local.start, - specifier.local.end - )} as __VUE_DEFAULT__ } from '${node.source.value}' -` - ); - const end2 = specifierEnd(s, specifier.exported.end, node.end); - s.remove(specifier.start, end2); - s.append(` -const ${as} = __VUE_DEFAULT__`); - continue; - } - } - const end = specifierEnd(s, specifier.end, node.end); - s.remove(specifier.start, end); - s.append(` -const ${as} = ${specifier.local.name}`); - } - } - } - }); - } - function hasDefaultExport(ast) { - for (const stmt of ast) { - if (stmt.type === "ExportDefaultDeclaration") { - return true; - } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some( - (spec) => spec.exported.name === "default" - )) { - return true; - } - } - return false; - } - function specifierEnd(s, end, nodeEnd) { - let hasCommas = false; - let oldEnd = end; - while (end < nodeEnd) { - if (/\s/.test(s.slice(end, end + 1))) { - end++; - } else if (s.slice(end, end + 1) === ",") { - end++; - hasCommas = true; - break; - } else if (s.slice(end, end + 1) === "}") { - break; - } - } - return hasCommas ? end : oldEnd; - } - - var __defProp$3 = Object.defineProperty; - var __defProps$2 = Object.defineProperties; - var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; - var __hasOwnProp$3 = Object.prototype.hasOwnProperty; - var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$3 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$3.call(b, prop)) - __defNormalProp$3(a, prop, b[prop]); - if (__getOwnPropSymbols$3) - for (var prop of __getOwnPropSymbols$3(b)) { - if (__propIsEnum$3.call(b, prop)) - __defNormalProp$3(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); - const normalScriptDefaultVar = `__default__`; - function processNormalScript(ctx, scopeId) { - var _a; - const script = ctx.descriptor.script; - if (script.lang && !ctx.isJS && !ctx.isTS) { - return script; - } - try { - let content = script.content; - let map = script.map; - const scriptAst = ctx.scriptAst; - const bindings = analyzeScriptBindings(scriptAst.body); - const { cssVars } = ctx.descriptor; - const { genDefaultAs, isProd } = ctx.options; - if (cssVars.length || genDefaultAs) { - const defaultVar = genDefaultAs || normalScriptDefaultVar; - const s = new MagicString(content); - rewriteDefaultAST(scriptAst.body, s, defaultVar); - content = s.toString(); - if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) { - content += genNormalScriptCssVarsCode( - cssVars, - bindings, - scopeId, - !!isProd, - defaultVar - ); - } - if (!genDefaultAs) { - content += ` -export default ${defaultVar}`; - } - } - return __spreadProps$2(__spreadValues$3({}, script), { - content, - map, - bindings, - scriptAst: scriptAst.body - }); - } catch (e) { - return script; - } - } - - var __defProp$2 = Object.defineProperty; - var __defProps$1 = Object.defineProperties; - var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; - var __hasOwnProp$2 = Object.prototype.hasOwnProperty; - var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$2 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$2.call(b, prop)) - __defNormalProp$2(a, prop, b[prop]); - if (__getOwnPropSymbols$2) - for (var prop of __getOwnPropSymbols$2(b)) { - if (__propIsEnum$2.call(b, prop)) - __defNormalProp$2(a, prop, b[prop]); - } - return a; - }; - var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); - class TypeScope { - constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) { - this.filename = filename; - this.source = source; - this.offset = offset; - this.imports = imports; - this.types = types; - this.declares = declares; - this.isGenericScope = false; - this.resolvedImportSources = /* @__PURE__ */ Object.create(null); - this.exportedTypes = /* @__PURE__ */ Object.create(null); - this.exportedDeclares = /* @__PURE__ */ Object.create(null); - } - } - function resolveTypeElements(ctx, node, scope, typeParameters) { - const canCache = !typeParameters; - if (canCache && node._resolvedElements) { - return node._resolvedElements; - } - const resolved = innerResolveTypeElements( - ctx, - node, - node._ownerScope || scope || ctxToScope(ctx), - typeParameters - ); - return canCache ? node._resolvedElements = resolved : resolved; - } - function innerResolveTypeElements(ctx, node, scope, typeParameters) { - var _a, _b; - switch (node.type) { - case "TSTypeLiteral": - return typeElementsToMap(ctx, node.members, scope, typeParameters); - case "TSInterfaceDeclaration": - return resolveInterfaceMembers(ctx, node, scope, typeParameters); - case "TSTypeAliasDeclaration": - case "TSParenthesizedType": - return resolveTypeElements( - ctx, - node.typeAnnotation, - scope, - typeParameters - ); - case "TSFunctionType": { - return { props: {}, calls: [node] }; - } - case "TSUnionType": - case "TSIntersectionType": - return mergeElements( - node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)), - node.type - ); - case "TSMappedType": - return resolveMappedType(ctx, node, scope); - case "TSIndexedAccessType": { - const types = resolveIndexType(ctx, node, scope); - return mergeElements( - types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)), - "TSUnionType" - ); - } - case "TSExpressionWithTypeArguments": - case "TSTypeReference": { - const typeName = getReferenceName(node); - if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") { - return resolveExtractPropTypes( - resolveTypeElements( - ctx, - node.typeParameters.params[0], - scope, - typeParameters - ), - scope - ); - } - const resolved = resolveTypeReference(ctx, node, scope); - if (resolved) { - let typeParams; - if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) { - typeParams = /* @__PURE__ */ Object.create(null); - resolved.typeParameters.params.forEach((p, i) => { - let param = typeParameters && typeParameters[p.name]; - if (!param) - param = node.typeParameters.params[i]; - typeParams[p.name] = param; - }); - } - return resolveTypeElements( - ctx, - resolved, - resolved._ownerScope, - typeParams - ); - } else { - if (typeof typeName === "string") { - if (typeParameters && typeParameters[typeName]) { - return resolveTypeElements( - ctx, - typeParameters[typeName], - scope, - typeParameters - ); - } - if ( - // @ts-expect-error - SupportedBuiltinsSet.has(typeName) - ) { - return resolveBuiltin( - ctx, - node, - typeName, - scope, - typeParameters - ); - } else if (typeName === "ReturnType" && node.typeParameters) { - const ret = resolveReturnType( - ctx, - node.typeParameters.params[0], - scope - ); - if (ret) { - return resolveTypeElements(ctx, ret, scope); - } - } - } - return ctx.error( - `Unresolvable type reference or unsupported built-in utility type`, - node, - scope - ); - } - } - case "TSImportType": { - if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) { - return resolveExtractPropTypes( - resolveTypeElements(ctx, node.typeParameters.params[0], scope), - scope - ); - } - const sourceScope = importSourceToScope( - ctx, - node.argument, - scope, - node.argument.value - ); - const resolved = resolveTypeReference(ctx, node, sourceScope); - if (resolved) { - return resolveTypeElements(ctx, resolved, resolved._ownerScope); - } - break; - } - case "TSTypeQuery": - { - const resolved = resolveTypeReference(ctx, node, scope); - if (resolved) { - return resolveTypeElements(ctx, resolved, resolved._ownerScope); - } - } - break; - } - return ctx.error(`Unresolvable type: ${node.type}`, node, scope); - } - function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) { - const res = { props: {} }; - for (const e of elements) { - if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") { - if (typeParameters) { - scope = createChildScope(scope); - scope.isGenericScope = true; - Object.assign(scope.types, typeParameters); - } - e._ownerScope = scope; - const name = getId(e.key); - if (name && !e.computed) { - res.props[name] = e; - } else if (e.key.type === "TemplateLiteral") { - for (const key of resolveTemplateKeys(ctx, e.key, scope)) { - res.props[key] = e; - } - } else { - ctx.error( - `Unsupported computed key in type referenced by a macro`, - e.key, - scope - ); - } - } else if (e.type === "TSCallSignatureDeclaration") { - (res.calls || (res.calls = [])).push(e); - } - } - return res; - } - function mergeElements(maps, type) { - if (maps.length === 1) - return maps[0]; - const res = { props: {} }; - const { props: baseProps } = res; - for (const { props, calls } of maps) { - for (const key in props) { - if (!hasOwn(baseProps, key)) { - baseProps[key] = props[key]; - } else { - baseProps[key] = createProperty( - baseProps[key].key, - { - type, - // @ts-expect-error - types: [baseProps[key], props[key]] - }, - baseProps[key]._ownerScope, - baseProps[key].optional || props[key].optional - ); - } - } - if (calls) { - (res.calls || (res.calls = [])).push(...calls); - } - } - return res; - } - function createProperty(key, typeAnnotation, scope, optional) { - return { - type: "TSPropertySignature", - key, - kind: "get", - optional, - typeAnnotation: { - type: "TSTypeAnnotation", - typeAnnotation - }, - _ownerScope: scope - }; - } - function resolveInterfaceMembers(ctx, node, scope, typeParameters) { - const base = typeElementsToMap( - ctx, - node.body.body, - node._ownerScope, - typeParameters - ); - if (node.extends) { - for (const ext of node.extends) { - if (ext.leadingComments && ext.leadingComments.some((c) => c.value.includes("@vue-ignore"))) { - continue; - } - try { - const { props, calls } = resolveTypeElements(ctx, ext, scope); - for (const key in props) { - if (!hasOwn(base.props, key)) { - base.props[key] = props[key]; - } - } - if (calls) { - ; - (base.calls || (base.calls = [])).push(...calls); - } - } catch (e) { - ctx.error( - `Failed to resolve extends base type. -If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example: - -interface Props extends /* @vue-ignore */ Base {} - -Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`, - ext - ); - } - } - } - return base; - } - function resolveMappedType(ctx, node, scope) { - const res = { props: {} }; - const keys = resolveStringType(ctx, node.typeParameter.constraint, scope); - for (const key of keys) { - res.props[key] = createProperty( - { - type: "Identifier", - name: key - }, - node.typeAnnotation, - scope, - !!node.optional - ); - } - return res; - } - function resolveIndexType(ctx, node, scope) { - var _a, _b; - if (node.indexType.type === "TSNumberKeyword") { - return resolveArrayElementType(ctx, node.objectType, scope); - } - const { indexType, objectType } = node; - const types = []; - let keys; - let resolved; - if (indexType.type === "TSStringKeyword") { - resolved = resolveTypeElements(ctx, objectType, scope); - keys = Object.keys(resolved.props); - } else { - keys = resolveStringType(ctx, indexType, scope); - resolved = resolveTypeElements(ctx, objectType, scope); - } - for (const key of keys) { - const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation; - if (targetType) { - targetType._ownerScope = resolved.props[key]._ownerScope; - types.push(targetType); - } - } - return types; - } - function resolveArrayElementType(ctx, node, scope) { - if (node.type === "TSArrayType") { - return [node.elementType]; - } - if (node.type === "TSTupleType") { - return node.elementTypes.map( - (t) => t.type === "TSNamedTupleMember" ? t.elementType : t - ); - } - if (node.type === "TSTypeReference") { - if (getReferenceName(node) === "Array" && node.typeParameters) { - return node.typeParameters.params; - } else { - const resolved = resolveTypeReference(ctx, node, scope); - if (resolved) { - return resolveArrayElementType(ctx, resolved, scope); - } - } - } - return ctx.error( - "Failed to resolve element type from target type", - node, - scope - ); - } - function resolveStringType(ctx, node, scope) { - switch (node.type) { - case "StringLiteral": - return [node.value]; - case "TSLiteralType": - return resolveStringType(ctx, node.literal, scope); - case "TSUnionType": - return node.types.map((t) => resolveStringType(ctx, t, scope)).flat(); - case "TemplateLiteral": { - return resolveTemplateKeys(ctx, node, scope); - } - case "TSTypeReference": { - const resolved = resolveTypeReference(ctx, node, scope); - if (resolved) { - return resolveStringType(ctx, resolved, scope); - } - if (node.typeName.type === "Identifier") { - const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope); - switch (node.typeName.name) { - case "Extract": - return getParam(1); - case "Exclude": { - const excluded = getParam(1); - return getParam().filter((s) => !excluded.includes(s)); - } - case "Uppercase": - return getParam().map((s) => s.toUpperCase()); - case "Lowercase": - return getParam().map((s) => s.toLowerCase()); - case "Capitalize": - return getParam().map(capitalize$1); - case "Uncapitalize": - return getParam().map((s) => s[0].toLowerCase() + s.slice(1)); - default: - ctx.error( - "Unsupported type when resolving index type", - node.typeName, - scope - ); - } - } - } - } - return ctx.error("Failed to resolve index type into finite keys", node, scope); - } - function resolveTemplateKeys(ctx, node, scope) { - if (!node.expressions.length) { - return [node.quasis[0].value.raw]; - } - const res = []; - const e = node.expressions[0]; - const q = node.quasis[0]; - const leading = q ? q.value.raw : ``; - const resolved = resolveStringType(ctx, e, scope); - const restResolved = resolveTemplateKeys( - ctx, - __spreadProps$1(__spreadValues$2({}, node), { - expressions: node.expressions.slice(1), - quasis: q ? node.quasis.slice(1) : node.quasis - }), - scope - ); - for (const r of resolved) { - for (const rr of restResolved) { - res.push(leading + r + rr); - } - } - return res; - } - const SupportedBuiltinsSet = /* @__PURE__ */ new Set([ - "Partial", - "Required", - "Readonly", - "Pick", - "Omit" - ]); - function resolveBuiltin(ctx, node, name, scope, typeParameters) { - const t = resolveTypeElements( - ctx, - node.typeParameters.params[0], - scope, - typeParameters - ); - switch (name) { - case "Partial": { - const res2 = { props: {}, calls: t.calls }; - Object.keys(t.props).forEach((key) => { - res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: true }); - }); - return res2; - } - case "Required": { - const res2 = { props: {}, calls: t.calls }; - Object.keys(t.props).forEach((key) => { - res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: false }); - }); - return res2; - } - case "Readonly": - return t; - case "Pick": { - const picked = resolveStringType( - ctx, - node.typeParameters.params[1], - scope - ); - const res2 = { props: {}, calls: t.calls }; - for (const key of picked) { - res2.props[key] = t.props[key]; - } - return res2; - } - case "Omit": - const omitted = resolveStringType( - ctx, - node.typeParameters.params[1], - scope - ); - const res = { props: {}, calls: t.calls }; - for (const key in t.props) { - if (!omitted.includes(key)) { - res.props[key] = t.props[key]; - } - } - return res; - } - } - function resolveTypeReference(ctx, node, scope, name, onlyExported = false) { - const canCache = !(scope == null ? void 0 : scope.isGenericScope); - if (canCache && node._resolvedReference) { - return node._resolvedReference; - } - const resolved = innerResolveTypeReference( - ctx, - scope || ctxToScope(ctx), - name || getReferenceName(node), - node, - onlyExported - ); - return canCache ? node._resolvedReference = resolved : resolved; - } - function innerResolveTypeReference(ctx, scope, name, node, onlyExported) { - if (typeof name === "string") { - if (scope.imports[name]) { - return resolveTypeFromImport(ctx, node, name, scope); - } else { - const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types; - if (lookupSource[name]) { - return lookupSource[name]; - } else { - const globalScopes = resolveGlobalScope(ctx); - if (globalScopes) { - for (const s of globalScopes) { - const src = node.type === "TSTypeQuery" ? s.declares : s.types; - if (src[name]) { - (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename); - return src[name]; - } - } - } - } - } - } else { - let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported); - if (ns) { - if (ns.type !== "TSModuleDeclaration") { - ns = ns._ns; - } - if (ns) { - const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope); - return innerResolveTypeReference( - ctx, - childScope, - name.length > 2 ? name.slice(1) : name[name.length - 1], - node, - !ns.declare - ); - } - } - } - } - function getReferenceName(node) { - const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName; - if ((ref == null ? void 0 : ref.type) === "Identifier") { - return ref.name; - } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") { - return qualifiedNameToPath(ref); - } else { - return "default"; - } - } - function qualifiedNameToPath(node) { - if (node.type === "Identifier") { - return [node.name]; - } else { - return [...qualifiedNameToPath(node.left), node.right.name]; - } - } - function resolveGlobalScope(ctx) { - if (ctx.options.globalTypeFiles) { - const fs = resolveFS(ctx); - if (!fs) { - throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access."); - } - return ctx.options.globalTypeFiles.map( - (file) => fileToScope(ctx, normalizePath(file), true) - ); - } - } - let ts; - let loadTS; - function registerTS(_loadTS) { - loadTS = () => { - try { - return _loadTS(); - } catch (err) { - if (typeof err.message === "string" && err.message.includes("Cannot find module")) { - throw new Error( - 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.' - ); - } else { - throw new Error( - "Failed to load TypeScript for resolving imported types." - ); - } - } - }; - } - function resolveFS(ctx) { - if (ctx.fs) { - return ctx.fs; - } - if (!ts && loadTS) { - ts = loadTS(); - } - const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys); - if (!fs) { - return; - } - return ctx.fs = { - fileExists(file) { - if (file.endsWith(".vue.ts")) { - file = file.replace(/\.ts$/, ""); - } - return fs.fileExists(file); - }, - readFile(file) { - if (file.endsWith(".vue.ts")) { - file = file.replace(/\.ts$/, ""); - } - return fs.readFile(file); - }, - realpath: fs.realpath - }; - } - function resolveTypeFromImport(ctx, node, name, scope) { - const { source, imported } = scope.imports[name]; - const sourceScope = importSourceToScope(ctx, node, scope, source); - return resolveTypeReference(ctx, node, sourceScope, imported, true); - } - function importSourceToScope(ctx, node, scope, source) { - let fs; - try { - fs = resolveFS(ctx); - } catch (err) { - return ctx.error(err.message, node, scope); - } - if (!fs) { - return ctx.error( - `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`, - node, - scope - ); - } - let resolved = scope.resolvedImportSources[source]; - if (!resolved) { - if (source.startsWith("..")) { - const osSpecificJoinFn = joinPaths; - const filename = osSpecificJoinFn(dirname$2(scope.filename), source); - resolved = resolveExt(filename, fs); - } else if (source.startsWith(".")) { - const filename = joinPaths(dirname$2(scope.filename), source); - resolved = resolveExt(filename, fs); - } else { - { - return ctx.error( - `Type import from non-relative sources is not supported in the browser build.`, - node, - scope - ); - } - } - if (resolved) { - resolved = scope.resolvedImportSources[source] = normalizePath(resolved); - } - } - if (resolved) { - (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved); - return fileToScope(ctx, resolved); - } else { - return ctx.error( - `Failed to resolve import source ${JSON.stringify(source)}.`, - node, - scope - ); - } - } - function resolveExt(filename, fs) { - filename = filename.replace(/\.js$/, ""); - const tryResolve = (filename2) => { - if (fs.fileExists(filename2)) - return filename2; - }; - return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.d.ts`)); - } - const tsConfigCache = createCache(); - const tsConfigRefMap = /* @__PURE__ */ new Map(); - const fileToScopeCache = createCache(); - function invalidateTypeCache(filename) { - filename = normalizePath(filename); - fileToScopeCache.delete(filename); - tsConfigCache.delete(filename); - const affectedConfig = tsConfigRefMap.get(filename); - if (affectedConfig) - tsConfigCache.delete(affectedConfig); - } - function fileToScope(ctx, filename, asGlobal = false) { - const cached = fileToScopeCache.get(filename); - if (cached) { - return cached; - } - const fs = resolveFS(ctx); - const source = fs.readFile(filename) || ""; - const body = parseFile(filename, source, ctx.options.babelParserPlugins); - const scope = new TypeScope(filename, source, 0, recordImports(body)); - recordTypes(ctx, body, scope, asGlobal); - fileToScopeCache.set(filename, scope); - return scope; - } - function parseFile(filename, content, parserPlugins) { - const ext = extname(filename); - if (ext === ".ts" || ext === ".tsx") { - return parse_1$1(content, { - plugins: resolveParserPlugins( - ext.slice(1), - parserPlugins, - filename.endsWith(".d.ts") - ), - sourceType: "module" - }).program.body; - } else if (ext === ".vue") { - const { - descriptor: { script, scriptSetup } - } = parse$7(content); - if (!script && !scriptSetup) { - return []; - } - const scriptOffset = script ? script.loc.start.offset : Infinity; - const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity; - const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup; - const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script; - let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content; - if (secondBlock) { - scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content; - } - const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang); - return parse_1$1(scriptContent, { - plugins: resolveParserPlugins(lang, parserPlugins), - sourceType: "module" - }).program.body; - } - return []; - } - function ctxToScope(ctx) { - if (ctx.scope) { - return ctx.scope; - } - const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body; - const scope = new TypeScope( - ctx.filename, - ctx.source, - "startOffset" in ctx ? ctx.startOffset : 0, - "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body) - ); - recordTypes(ctx, body, scope); - return ctx.scope = scope; - } - function moduleDeclToScope(ctx, node, parentScope) { - if (node._resolvedChildScope) { - return node._resolvedChildScope; - } - const scope = createChildScope(parentScope); - if (node.body.type === "TSModuleDeclaration") { - const decl = node.body; - decl._ownerScope = scope; - const id = getId(decl.id); - scope.types[id] = scope.exportedTypes[id] = decl; - } else { - recordTypes(ctx, node.body.body, scope); - } - return node._resolvedChildScope = scope; - } - function createChildScope(parentScope) { - return new TypeScope( - parentScope.filename, - parentScope.source, - parentScope.offset, - Object.create(parentScope.imports), - Object.create(parentScope.types), - Object.create(parentScope.declares) - ); - } - const importExportRE = /^Import|^Export/; - function recordTypes(ctx, body, scope, asGlobal = false) { - const { types, declares, exportedTypes, exportedDeclares, imports } = scope; - const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false; - for (const stmt of body) { - if (asGlobal) { - if (isAmbient) { - if (stmt.declare) { - recordType(stmt, types, declares); - } - } else if (stmt.type === "TSModuleDeclaration" && stmt.global) { - for (const s of stmt.body.body) { - recordType(s, types, declares); - } - } - } else { - recordType(stmt, types, declares); - } - } - if (!asGlobal) { - for (const stmt of body) { - if (stmt.type === "ExportNamedDeclaration") { - if (stmt.declaration) { - recordType(stmt.declaration, types, declares); - recordType(stmt.declaration, exportedTypes, exportedDeclares); - } else { - for (const spec of stmt.specifiers) { - if (spec.type === "ExportSpecifier") { - const local = spec.local.name; - const exported = getId(spec.exported); - if (stmt.source) { - imports[exported] = { - source: stmt.source.value, - imported: local - }; - exportedTypes[exported] = { - type: "TSTypeReference", - typeName: { - type: "Identifier", - name: local - }, - _ownerScope: scope - }; - } else if (types[local]) { - exportedTypes[exported] = types[local]; - } - } - } - } - } else if (stmt.type === "ExportAllDeclaration") { - const sourceScope = importSourceToScope( - ctx, - stmt.source, - scope, - stmt.source.value - ); - Object.assign(scope.exportedTypes, sourceScope.exportedTypes); - } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) { - if (stmt.declaration.type !== "Identifier") { - recordType(stmt.declaration, types, declares, "default"); - recordType( - stmt.declaration, - exportedTypes, - exportedDeclares, - "default" - ); - } else if (types[stmt.declaration.name]) { - exportedTypes["default"] = types[stmt.declaration.name]; - } - } - } - } - for (const key of Object.keys(types)) { - const node = types[key]; - node._ownerScope = scope; - if (node._ns) - node._ns._ownerScope = scope; - } - for (const key of Object.keys(declares)) { - declares[key]._ownerScope = scope; - } - } - function recordType(node, types, declares, overwriteId) { - switch (node.type) { - case "TSInterfaceDeclaration": - case "TSEnumDeclaration": - case "TSModuleDeclaration": { - const id = overwriteId || getId(node.id); - let existing = types[id]; - if (existing) { - if (node.type === "TSModuleDeclaration") { - if (existing.type === "TSModuleDeclaration") { - mergeNamespaces(existing, node); - } else { - attachNamespace(existing, node); - } - break; - } - if (existing.type === "TSModuleDeclaration") { - types[id] = node; - attachNamespace(node, existing); - break; - } - if (existing.type !== node.type) { - break; - } - if (node.type === "TSInterfaceDeclaration") { - existing.body.body.push(...node.body.body); - } else { - existing.members.push(...node.members); - } - } else { - types[id] = node; - } - break; - } - case "ClassDeclaration": - if (overwriteId || node.id) - types[overwriteId || getId(node.id)] = node; - break; - case "TSTypeAliasDeclaration": - types[node.id.name] = node.typeParameters ? node : node.typeAnnotation; - break; - case "TSDeclareFunction": - if (node.id) - declares[node.id.name] = node; - break; - case "VariableDeclaration": { - if (node.declare) { - for (const decl of node.declarations) { - if (decl.id.type === "Identifier" && decl.id.typeAnnotation) { - declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation; - } - } - } - break; - } - } - } - function mergeNamespaces(to, from) { - const toBody = to.body; - const fromBody = from.body; - if (toBody.type === "TSModuleDeclaration") { - if (fromBody.type === "TSModuleDeclaration") { - mergeNamespaces(toBody, fromBody); - } else { - fromBody.body.push({ - type: "ExportNamedDeclaration", - declaration: toBody, - exportKind: "type", - specifiers: [] - }); - } - } else if (fromBody.type === "TSModuleDeclaration") { - toBody.body.push({ - type: "ExportNamedDeclaration", - declaration: fromBody, - exportKind: "type", - specifiers: [] - }); - } else { - toBody.body.push(...fromBody.body); - } - } - function attachNamespace(to, ns) { - if (!to._ns) { - to._ns = ns; - } else { - mergeNamespaces(to._ns, ns); - } - } - function recordImports(body) { - const imports = /* @__PURE__ */ Object.create(null); - for (const s of body) { - recordImport(s, imports); - } - return imports; - } - function recordImport(node, imports) { - if (node.type !== "ImportDeclaration") { - return; - } - for (const s of node.specifiers) { - imports[s.local.name] = { - imported: getImportedName(s), - source: node.source.value - }; - } - } - function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx)) { - try { - switch (node.type) { - case "TSStringKeyword": - return ["String"]; - case "TSNumberKeyword": - return ["Number"]; - case "TSBooleanKeyword": - return ["Boolean"]; - case "TSObjectKeyword": - return ["Object"]; - case "TSNullKeyword": - return ["null"]; - case "TSTypeLiteral": - case "TSInterfaceDeclaration": { - const types = /* @__PURE__ */ new Set(); - const members = node.type === "TSTypeLiteral" ? node.members : node.body.body; - for (const m of members) { - if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") { - types.add("Function"); - } else { - types.add("Object"); - } - } - return types.size ? Array.from(types) : ["Object"]; - } - case "TSPropertySignature": - if (node.typeAnnotation) { - return inferRuntimeType( - ctx, - node.typeAnnotation.typeAnnotation, - scope - ); - } - break; - case "TSMethodSignature": - case "TSFunctionType": - return ["Function"]; - case "TSArrayType": - case "TSTupleType": - return ["Array"]; - case "TSLiteralType": - switch (node.literal.type) { - case "StringLiteral": - return ["String"]; - case "BooleanLiteral": - return ["Boolean"]; - case "NumericLiteral": - case "BigIntLiteral": - return ["Number"]; - default: - return [UNKNOWN_TYPE]; - } - case "TSTypeReference": { - const resolved = resolveTypeReference(ctx, node, scope); - if (resolved) { - return inferRuntimeType(ctx, resolved, resolved._ownerScope); - } - if (node.typeName.type === "Identifier") { - switch (node.typeName.name) { - case "Array": - case "Function": - case "Object": - case "Set": - case "Map": - case "WeakSet": - case "WeakMap": - case "Date": - case "Promise": - case "Error": - return [node.typeName.name]; - case "Partial": - case "Required": - case "Readonly": - case "Record": - case "Pick": - case "Omit": - case "InstanceType": - return ["Object"]; - case "Uppercase": - case "Lowercase": - case "Capitalize": - case "Uncapitalize": - return ["String"]; - case "Parameters": - case "ConstructorParameters": - return ["Array"]; - case "NonNullable": - if (node.typeParameters && node.typeParameters.params[0]) { - return inferRuntimeType( - ctx, - node.typeParameters.params[0], - scope - ).filter((t) => t !== "null"); - } - break; - case "Extract": - if (node.typeParameters && node.typeParameters.params[1]) { - return inferRuntimeType( - ctx, - node.typeParameters.params[1], - scope - ); - } - break; - case "Exclude": - case "OmitThisParameter": - if (node.typeParameters && node.typeParameters.params[0]) { - return inferRuntimeType( - ctx, - node.typeParameters.params[0], - scope - ); - } - break; - } - } - break; - } - case "TSParenthesizedType": - return inferRuntimeType(ctx, node.typeAnnotation, scope); - case "TSUnionType": - return flattenTypes(ctx, node.types, scope); - case "TSIntersectionType": { - return flattenTypes(ctx, node.types, scope).filter( - (t) => t !== UNKNOWN_TYPE - ); - } - case "TSEnumDeclaration": - return inferEnumType(node); - case "TSSymbolKeyword": - return ["Symbol"]; - case "TSIndexedAccessType": { - const types = resolveIndexType(ctx, node, scope); - return flattenTypes(ctx, types, scope); - } - case "ClassDeclaration": - return ["Object"]; - case "TSImportType": { - const sourceScope = importSourceToScope( - ctx, - node.argument, - scope, - node.argument.value - ); - const resolved = resolveTypeReference(ctx, node, sourceScope); - if (resolved) { - return inferRuntimeType(ctx, resolved, resolved._ownerScope); - } - break; - } - case "TSTypeQuery": { - const id = node.exprName; - if (id.type === "Identifier") { - const matched = scope.declares[id.name]; - if (matched) { - return inferRuntimeType(ctx, matched, matched._ownerScope); - } - } - break; - } - } - } catch (e) { - } - return [UNKNOWN_TYPE]; - } - function flattenTypes(ctx, types, scope) { - if (types.length === 1) { - return inferRuntimeType(ctx, types[0], scope); - } - return [ - ...new Set( - [].concat( - ...types.map((t) => inferRuntimeType(ctx, t, scope)) - ) - ) - ]; - } - function inferEnumType(node) { - const types = /* @__PURE__ */ new Set(); - for (const m of node.members) { - if (m.initializer) { - switch (m.initializer.type) { - case "StringLiteral": - types.add("String"); - break; - case "NumericLiteral": - types.add("Number"); - break; - } - } - } - return types.size ? [...types] : ["Number"]; - } - function resolveExtractPropTypes({ props }, scope) { - const res = { props: {} }; - for (const key in props) { - const raw = props[key]; - res.props[key] = reverseInferType( - raw.key, - raw.typeAnnotation.typeAnnotation, - scope - ); - } - return res; - } - function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) { - if (checkObjectSyntax && node.type === "TSTypeLiteral") { - const typeType = findStaticPropertyType(node, "type"); - if (typeType) { - const requiredType = findStaticPropertyType(node, "required"); - const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true; - return reverseInferType(key, typeType, scope, optional2, false); - } - } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") { - if (node.typeName.name.endsWith("Constructor")) { - return createProperty( - key, - ctorToType(node.typeName.name), - scope, - optional - ); - } else if (node.typeName.name === "PropType" && node.typeParameters) { - return createProperty(key, node.typeParameters.params[0], scope, optional); - } - } - if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) { - for (const t of node.typeParameters.params) { - const inferred = reverseInferType(key, t, scope, optional); - if (inferred) - return inferred; - } - } - return createProperty(key, { type: `TSNullKeyword` }, scope, optional); - } - function ctorToType(ctorType) { - const ctor = ctorType.slice(0, -11); - switch (ctor) { - case "String": - case "Number": - case "Boolean": - return { type: `TS${ctor}Keyword` }; - case "Array": - case "Function": - case "Object": - case "Set": - case "Map": - case "WeakSet": - case "WeakMap": - case "Date": - case "Promise": - return { - type: "TSTypeReference", - typeName: { type: "Identifier", name: ctor } - }; - } - return { type: `TSNullKeyword` }; - } - function findStaticPropertyType(node, key) { - const prop = node.members.find( - (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation - ); - return prop && prop.typeAnnotation.typeAnnotation; - } - function resolveReturnType(ctx, arg, scope) { - var _a; - let resolved = arg; - if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") { - resolved = resolveTypeReference(ctx, arg, scope); - } - if (!resolved) - return; - if (resolved.type === "TSFunctionType") { - return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation; - } - if (resolved.type === "TSDeclareFunction") { - return resolved.returnType; - } - } - function resolveUnionType(ctx, node, scope) { - if (node.type === "TSTypeReference") { - const resolved = resolveTypeReference(ctx, node, scope); - if (resolved) - node = resolved; - } - let types; - if (node.type === "TSUnionType") { - types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope)); - } else { - types = [node]; - } - return types; - } - - const DEFINE_MODEL = "defineModel"; - function processDefineModel(ctx, node, declId) { - if (!isCallOf(node, DEFINE_MODEL)) { - return false; - } - ctx.hasDefineModelCall = true; - const type = node.typeParameters && node.typeParameters.params[0] || void 0; - let modelName; - let options; - const arg0 = node.arguments[0] && unwrapTSNode(node.arguments[0]); - const hasName = arg0 && arg0.type === "StringLiteral"; - if (hasName) { - modelName = arg0.value; - options = node.arguments[1]; - } else { - modelName = "modelValue"; - options = arg0; - } - if (ctx.modelDecls[modelName]) { - ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node); - } - let optionsString = options && ctx.getString(options); - let optionsRemoved = !options; - const runtimeOptionNodes = []; - if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) { - let removed = 0; - for (let i = options.properties.length - 1; i >= 0; i--) { - const p = options.properties[i]; - const next = options.properties[i + 1]; - const start = p.start; - const end = next ? next.start : options.end - 1; - if ((p.type === "ObjectProperty" || p.type === "ObjectMethod") && (p.key.type === "Identifier" && (p.key.name === "get" || p.key.name === "set") || p.key.type === "StringLiteral" && (p.key.value === "get" || p.key.value === "set"))) { - optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start); - } else { - removed++; - ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end); - runtimeOptionNodes.push(p); - } - } - if (removed === options.properties.length) { - optionsRemoved = true; - ctx.s.remove( - ctx.startOffset + (hasName ? arg0.end : options.start), - ctx.startOffset + options.end - ); - } - } - ctx.modelDecls[modelName] = { - type, - options: optionsString, - runtimeOptionNodes, - identifier: declId && declId.type === "Identifier" ? declId.name : void 0 - }; - ctx.bindingMetadata[modelName] = "props"; - ctx.s.overwrite( - ctx.startOffset + node.callee.start, - ctx.startOffset + node.callee.end, - ctx.helper("useModel") - ); - ctx.s.appendLeft( - ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1), - `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`) - ); - return true; - } - function genModelProps(ctx) { - if (!ctx.hasDefineModelCall) - return; - const isProd = !!ctx.options.isProd; - let modelPropsDecl = ""; - for (const [name, { type, options }] of Object.entries(ctx.modelDecls)) { - let skipCheck = false; - let runtimeTypes = type && inferRuntimeType(ctx, type); - if (runtimeTypes) { - const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE); - runtimeTypes = runtimeTypes.filter((el) => { - if (el === UNKNOWN_TYPE) - return false; - return isProd ? el === "Boolean" || el === "Function" && options : true; - }); - skipCheck = !isProd && hasUnknownType && runtimeTypes.length > 0; - } - let runtimeType = runtimeTypes && runtimeTypes.length > 0 && toRuntimeTypeString(runtimeTypes) || void 0; - const codegenOptions = concatStrings([ - runtimeType && `type: ${runtimeType}`, - skipCheck && "skipCheck: true" - ]); - let decl; - if (runtimeType && options) { - decl = ctx.isTS ? `{ ${codegenOptions}, ...${options} }` : `Object.assign({ ${codegenOptions} }, ${options})`; - } else { - decl = options || (runtimeType ? `{ ${codegenOptions} }` : "{}"); - } - modelPropsDecl += ` - ${JSON.stringify(name)}: ${decl},`; - const modifierPropName = JSON.stringify( - name === "modelValue" ? `modelModifiers` : `${name}Modifiers` - ); - modelPropsDecl += ` - ${modifierPropName}: {},`; - } - return `{${modelPropsDecl} - }`; - } - - const DEFINE_PROPS = "defineProps"; - const WITH_DEFAULTS = "withDefaults"; - function processDefineProps(ctx, node, declId) { - if (!isCallOf(node, DEFINE_PROPS)) { - return processWithDefaults(ctx, node, declId); - } - if (ctx.hasDefinePropsCall) { - ctx.error(`duplicate ${DEFINE_PROPS}() call`, node); - } - ctx.hasDefinePropsCall = true; - ctx.propsRuntimeDecl = node.arguments[0]; - if (ctx.propsRuntimeDecl) { - for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) { - if (!(key in ctx.bindingMetadata)) { - ctx.bindingMetadata[key] = "props"; - } - } - } - if (node.typeParameters) { - if (ctx.propsRuntimeDecl) { - ctx.error( - `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`, - node - ); - } - ctx.propsTypeDecl = node.typeParameters.params[0]; - } - if (declId && declId.type === "ObjectPattern") { - processPropsDestructure(ctx, declId); - } - ctx.propsCall = node; - ctx.propsDecl = declId; - return true; - } - function processWithDefaults(ctx, node, declId) { - if (!isCallOf(node, WITH_DEFAULTS)) { - return false; - } - if (!processDefineProps(ctx, node.arguments[0], declId)) { - ctx.error( - `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, - node.arguments[0] || node - ); - } - if (ctx.propsRuntimeDecl) { - ctx.error( - `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`, - node - ); - } - if (ctx.propsDestructureDecl) { - ctx.error( - `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}(). -Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`, - node.callee - ); - } - ctx.propsRuntimeDefaults = node.arguments[1]; - if (!ctx.propsRuntimeDefaults) { - ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node); - } - ctx.propsCall = node; - return true; - } - function genRuntimeProps(ctx) { - let propsDecls; - if (ctx.propsRuntimeDecl) { - propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim(); - if (ctx.propsDestructureDecl) { - const defaults = []; - for (const key in ctx.propsDestructuredBindings) { - const d = genDestructuredDefaultValue(ctx, key); - const finalKey = getEscapedPropName(key); - if (d) - defaults.push( - `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}` - ); - } - if (defaults.length) { - propsDecls = `/*#__PURE__*/${ctx.helper( - `mergeDefaults` - )}(${propsDecls}, { - ${defaults.join(",\n ")} -})`; - } - } - } else if (ctx.propsTypeDecl) { - propsDecls = extractRuntimeProps(ctx); - } - const modelsDecls = genModelProps(ctx); - if (propsDecls && modelsDecls) { - return `/*#__PURE__*/${ctx.helper( - "mergeModels" - )}(${propsDecls}, ${modelsDecls})`; - } else { - return modelsDecls || propsDecls; - } - } - function extractRuntimeProps(ctx) { - const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl); - if (!props.length) { - return; - } - const propStrings = []; - const hasStaticDefaults = hasStaticWithDefaults(ctx); - for (const prop of props) { - propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults)); - if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) { - ctx.bindingMetadata[prop.key] = "props"; - } - } - let propsDecls = `{ - ${propStrings.join(",\n ")} - }`; - if (ctx.propsRuntimeDefaults && !hasStaticDefaults) { - propsDecls = `/*#__PURE__*/${ctx.helper( - "mergeDefaults" - )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`; - } - return propsDecls; - } - function resolveRuntimePropsFromType(ctx, node) { - const props = []; - const elements = resolveTypeElements(ctx, node); - for (const key in elements.props) { - const e = elements.props[key]; - let type = inferRuntimeType(ctx, e); - let skipCheck = false; - if (type.includes(UNKNOWN_TYPE)) { - if (type.includes("Boolean") || type.includes("Function")) { - type = type.filter((t) => t !== UNKNOWN_TYPE); - skipCheck = true; - } else { - type = ["null"]; - } - } - props.push({ - key, - required: !e.optional, - type: type || [`null`], - skipCheck - }); - } - return props; - } - function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) { - let defaultString; - const destructured = genDestructuredDefaultValue(ctx, key, type); - if (destructured) { - defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`; - } else if (hasStaticDefaults) { - const prop = ctx.propsRuntimeDefaults.properties.find( - (node) => { - if (node.type === "SpreadElement") - return false; - return resolveObjectKey(node.key, node.computed) === key; - } - ); - if (prop) { - if (prop.type === "ObjectProperty") { - defaultString = `default: ${ctx.getString(prop.value)}`; - } else { - defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`; - } - } - } - const finalKey = getEscapedPropName(key); - if (!ctx.options.isProd) { - return `${finalKey}: { ${concatStrings([ - `type: ${toRuntimeTypeString(type)}`, - `required: ${required}`, - skipCheck && "skipCheck: true", - defaultString - ])} }`; - } else if (type.some( - (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function" - )) { - return `${finalKey}: { ${concatStrings([ - `type: ${toRuntimeTypeString(type)}`, - defaultString - ])} }`; - } else { - if (ctx.isCE) { - if (defaultString) { - return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString( - type - )} }`}`; - } else { - return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`; - } - } - return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`; - } - } - function hasStaticWithDefaults(ctx) { - return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every( - (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal")) - )); - } - function genDestructuredDefaultValue(ctx, key, inferredType) { - const destructured = ctx.propsDestructuredBindings[key]; - const defaultVal = destructured && destructured.default; - if (defaultVal) { - const value = ctx.getString(defaultVal); - const unwrapped = unwrapTSNode(defaultVal); - if (inferredType && inferredType.length && !inferredType.includes("null")) { - const valueType = inferValueType(unwrapped); - if (valueType && !inferredType.includes(valueType)) { - ctx.error( - `Default value of prop "${key}" does not match declared type.`, - unwrapped - ); - } - } - const needSkipFactory = !inferredType && (isFunctionType(unwrapped) || unwrapped.type === "Identifier"); - const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function")); - return { - valueString: needFactoryWrap ? `() => (${value})` : value, - needSkipFactory - }; - } - } - function inferValueType(node) { - switch (node.type) { - case "StringLiteral": - return "String"; - case "NumericLiteral": - return "Number"; - case "BooleanLiteral": - return "Boolean"; - case "ObjectExpression": - return "Object"; - case "ArrayExpression": - return "Array"; - case "FunctionExpression": - case "ArrowFunctionExpression": - return "Function"; - } - } - - function processPropsDestructure(ctx, declId) { - if (!ctx.options.propsDestructure) { - return; - } - warnOnce$3( - `This project is using reactive props destructure, which is an experimental feature. It may receive breaking changes or be removed in the future, so use at your own risk. -To stay updated, follow the RFC at https://github.com/vuejs/rfcs/discussions/502.` - ); - ctx.propsDestructureDecl = declId; - const registerBinding = (key, local, defaultValue) => { - ctx.propsDestructuredBindings[key] = { local, default: defaultValue }; - if (local !== key) { - ctx.bindingMetadata[local] = "props-aliased"; - (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key; - } - }; - for (const prop of declId.properties) { - if (prop.type === "ObjectProperty") { - const propKey = resolveObjectKey(prop.key, prop.computed); - if (!propKey) { - ctx.error( - `${DEFINE_PROPS}() destructure cannot use computed key.`, - prop.key - ); - } - if (prop.value.type === "AssignmentPattern") { - const { left, right } = prop.value; - if (left.type !== "Identifier") { - ctx.error( - `${DEFINE_PROPS}() destructure does not support nested patterns.`, - left - ); - } - registerBinding(propKey, left.name, right); - } else if (prop.value.type === "Identifier") { - registerBinding(propKey, prop.value.name); - } else { - ctx.error( - `${DEFINE_PROPS}() destructure does not support nested patterns.`, - prop.value - ); - } - } else { - ctx.propsDestructureRestId = prop.argument.name; - ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const"; - } - } - } - function transformDestructuredProps(ctx, vueImportAliases) { - if (!ctx.options.propsDestructure) { - return; - } - const rootScope = {}; - const scopeStack = [rootScope]; - let currentScope = rootScope; - const excludedIds = /* @__PURE__ */ new WeakSet(); - const parentStack = []; - const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null); - for (const key in ctx.propsDestructuredBindings) { - const { local } = ctx.propsDestructuredBindings[key]; - rootScope[local] = true; - propsLocalToPublicMap[local] = key; - } - function pushScope() { - scopeStack.push(currentScope = Object.create(currentScope)); - } - function popScope() { - scopeStack.pop(); - currentScope = scopeStack[scopeStack.length - 1] || null; - } - function registerLocalBinding(id) { - excludedIds.add(id); - if (currentScope) { - currentScope[id.name] = false; - } else { - ctx.error( - "registerBinding called without active scope, something is wrong.", - id - ); - } - } - function walkScope(node, isRoot = false) { - for (const stmt of node.body) { - if (stmt.type === "VariableDeclaration") { - walkVariableDeclaration(stmt, isRoot); - } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") { - if (stmt.declare || !stmt.id) - continue; - registerLocalBinding(stmt.id); - } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") { - walkVariableDeclaration(stmt.left); - } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") { - walkVariableDeclaration(stmt.declaration, isRoot); - } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") { - walkVariableDeclaration(stmt.body, isRoot); - } - } - } - function walkVariableDeclaration(stmt, isRoot = false) { - if (stmt.declare) { - return; - } - for (const decl of stmt.declarations) { - const isDefineProps = isRoot && decl.init && isCallOf(unwrapTSNode(decl.init), "defineProps"); - for (const id of extractIdentifiers$1(decl.id)) { - if (isDefineProps) { - excludedIds.add(id); - } else { - registerLocalBinding(id); - } - } - } - } - function rewriteId(id, parent, parentStack2) { - if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") { - ctx.error(`Cannot assign to destructured props as they are readonly.`, id); - } - if (isStaticProperty(parent) && parent.shorthand) { - if (!parent.inPattern || isInDestructureAssignment(parent, parentStack2)) { - ctx.s.appendLeft( - id.end + ctx.startOffset, - `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}` - ); - } - } else { - ctx.s.overwrite( - id.start + ctx.startOffset, - id.end + ctx.startOffset, - genPropsAccessExp(propsLocalToPublicMap[id.name]) - ); - } - } - function checkUsage(node, method, alias = method) { - if (isCallOf(node, alias)) { - const arg = unwrapTSNode(node.arguments[0]); - if (arg.type === "Identifier" && currentScope[arg.name]) { - ctx.error( - `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`, - arg - ); - } - } - } - const ast = ctx.scriptSetupAst; - walkScope(ast, true); - walk$2(ast, { - enter(node, parent) { - parent && parentStack.push(parent); - if (parent && parent.type.startsWith("TS") && parent.type !== "TSAsExpression" && parent.type !== "TSNonNullExpression" && parent.type !== "TSTypeAssertion") { - return this.skip(); - } - checkUsage(node, "watch", vueImportAliases.watch); - checkUsage(node, "toRef", vueImportAliases.toRef); - if (isFunctionType(node)) { - pushScope(); - walkFunctionParams(node, registerLocalBinding); - if (node.body.type === "BlockStatement") { - walkScope(node.body); - } - return; - } - if (node.type === "CatchClause") { - pushScope(); - if (node.param && node.param.type === "Identifier") { - registerLocalBinding(node.param); - } - walkScope(node.body); - return; - } - if (node.type === "BlockStatement" && !isFunctionType(parent)) { - pushScope(); - walkScope(node); - return; - } - if (node.type === "Identifier") { - if (isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) { - if (currentScope[node.name]) { - rewriteId(node, parent, parentStack); - } - } - } - }, - leave(node, parent) { - parent && parentStack.pop(); - if (node.type === "BlockStatement" && !isFunctionType(parent) || isFunctionType(node)) { - popScope(); - } - } - }); - } - - const DEFINE_EMITS = "defineEmits"; - function processDefineEmits(ctx, node, declId) { - if (!isCallOf(node, DEFINE_EMITS)) { - return false; - } - if (ctx.hasDefineEmitCall) { - ctx.error(`duplicate ${DEFINE_EMITS}() call`, node); - } - ctx.hasDefineEmitCall = true; - ctx.emitsRuntimeDecl = node.arguments[0]; - if (node.typeParameters) { - if (ctx.emitsRuntimeDecl) { - ctx.error( - `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`, - node - ); - } - ctx.emitsTypeDecl = node.typeParameters.params[0]; - } - ctx.emitDecl = declId; - return true; - } - function genRuntimeEmits(ctx) { - let emitsDecl = ""; - if (ctx.emitsRuntimeDecl) { - emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim(); - } else if (ctx.emitsTypeDecl) { - const typeDeclaredEmits = extractRuntimeEmits(ctx); - emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``; - } - if (ctx.hasDefineModelCall) { - let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`; - emitsDecl = emitsDecl ? `/*#__PURE__*/${ctx.helper( - "mergeModels" - )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl; - } - return emitsDecl; - } - function extractRuntimeEmits(ctx) { - const emits = /* @__PURE__ */ new Set(); - const node = ctx.emitsTypeDecl; - if (node.type === "TSFunctionType") { - extractEventNames(ctx, node.parameters[0], emits); - return emits; - } - const { props, calls } = resolveTypeElements(ctx, node); - let hasProperty = false; - for (const key in props) { - emits.add(key); - hasProperty = true; - } - if (calls) { - if (hasProperty) { - ctx.error( - `defineEmits() type cannot mixed call signature and property syntax.`, - node - ); - } - for (const call of calls) { - extractEventNames(ctx, call.parameters[0], emits); - } - } - return emits; - } - function extractEventNames(ctx, eventName, emits) { - if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") { - const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation); - for (const type of types) { - if (type.type === "TSLiteralType") { - if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") { - emits.add(String(type.literal.value)); - } - } - } - } - } - - const DEFINE_EXPOSE = "defineExpose"; - function processDefineExpose(ctx, node) { - if (isCallOf(node, DEFINE_EXPOSE)) { - if (ctx.hasDefineExposeCall) { - ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node); - } - ctx.hasDefineExposeCall = true; - return true; - } - return false; - } - - const DEFINE_SLOTS = "defineSlots"; - function processDefineSlots(ctx, node, declId) { - if (!isCallOf(node, DEFINE_SLOTS)) { - return false; - } - if (ctx.hasDefineSlotsCall) { - ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node); - } - ctx.hasDefineSlotsCall = true; - if (node.arguments.length > 0) { - ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node); - } - if (declId) { - ctx.s.overwrite( - ctx.startOffset + node.start, - ctx.startOffset + node.end, - `${ctx.helper("useSlots")}()` - ); - } - return true; - } - - const DEFINE_OPTIONS = "defineOptions"; - function processDefineOptions(ctx, node) { - if (!isCallOf(node, DEFINE_OPTIONS)) { - return false; - } - if (ctx.hasDefineOptionsCall) { - ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node); - } - if (node.typeParameters) { - ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node); - } - if (!node.arguments[0]) - return true; - ctx.hasDefineOptionsCall = true; - ctx.optionsRuntimeDecl = unwrapTSNode(node.arguments[0]); - let propsOption = void 0; - let emitsOption = void 0; - let exposeOption = void 0; - let slotsOption = void 0; - if (ctx.optionsRuntimeDecl.type === "ObjectExpression") { - for (const prop of ctx.optionsRuntimeDecl.properties) { - if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") { - if (prop.key.name === "props") - propsOption = prop; - if (prop.key.name === "emits") - emitsOption = prop; - if (prop.key.name === "expose") - exposeOption = prop; - if (prop.key.name === "slots") - slotsOption = prop; - } - } - } - if (propsOption) { - ctx.error( - `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`, - propsOption - ); - } - if (emitsOption) { - ctx.error( - `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`, - emitsOption - ); - } - if (exposeOption) { - ctx.error( - `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`, - exposeOption - ); - } - if (slotsOption) { - ctx.error( - `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`, - slotsOption - ); - } - return true; - } - - function processAwait(ctx, node, needSemi, isStatement) { - const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start; - const startOffset = ctx.startOffset; - const argumentStr = ctx.descriptor.source.slice( - argumentStart + startOffset, - node.argument.end + startOffset - ); - const containsNestedAwait = /\bawait\b/.test(argumentStr); - ctx.s.overwrite( - node.start + startOffset, - argumentStart + startOffset, - `${needSemi ? `;` : ``}( - ([__temp,__restore] = ${ctx.helper( - `withAsyncContext` - )}(${containsNestedAwait ? `async ` : ``}() => ` - ); - ctx.s.appendLeft( - node.end + startOffset, - `)), - ${isStatement ? `` : `__temp = `}await __temp, - __restore()${isStatement ? `` : `, - __temp`} -)` - ); - } - - var __defProp$1 = Object.defineProperty; - var __defProps = Object.defineProperties; - var __getOwnPropDescs = Object.getOwnPropertyDescriptors; - var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; - var __hasOwnProp$1 = Object.prototype.hasOwnProperty; - var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; - var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues$1 = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp$1.call(b, prop)) - __defNormalProp$1(a, prop, b[prop]); - if (__getOwnPropSymbols$1) - for (var prop of __getOwnPropSymbols$1(b)) { - if (__propIsEnum$1.call(b, prop)) - __defNormalProp$1(a, prop, b[prop]); - } - return a; - }; - var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); - function compileScript(sfc, options) { - var _a; - if (!options.id) { - warnOnce$3( - `compileScript now requires passing the \`id\` option. -Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.` - ); - } - const ctx = new ScriptCompileContext(sfc, options); - const { script, scriptSetup, source, filename } = sfc; - const hoistStatic = options.hoistStatic !== false && !script; - const scopeId = options.id ? options.id.replace(/^data-v-/, "") : ""; - const scriptLang = script && script.lang; - const scriptSetupLang = scriptSetup && scriptSetup.lang; - if (!scriptSetup) { - if (!script) { - throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`); - } - return processNormalScript(ctx, scopeId); - } - if (script && scriptLang !== scriptSetupLang) { - throw new Error( - `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.` - ); - } - if (scriptSetupLang && !ctx.isJS && !ctx.isTS) { - return scriptSetup; - } - const scriptBindings = /* @__PURE__ */ Object.create(null); - const setupBindings = /* @__PURE__ */ Object.create(null); - let defaultExport; - let hasAwait = false; - let hasInlinedSsrRenderFn = false; - const startOffset = ctx.startOffset; - const endOffset = ctx.endOffset; - const scriptStartOffset = script && script.loc.start.offset; - const scriptEndOffset = script && script.loc.end.offset; - function hoistNode(node) { - const start = node.start + startOffset; - let end = node.end + startOffset; - if (node.trailingComments && node.trailingComments.length > 0) { - const lastCommentNode = node.trailingComments[node.trailingComments.length - 1]; - end = lastCommentNode.end + startOffset; - } - while (end <= source.length) { - if (!/\s/.test(source.charAt(end))) { - break; - } - end++; - } - ctx.s.move(start, end, 0); - } - function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) { - let isUsedInTemplate = needTemplateUsageCheck; - if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) { - isUsedInTemplate = isImportUsed(local, sfc); - } - ctx.userImports[local] = { - isType, - imported, - local, - source: source2, - isFromSetup, - isUsedInTemplate - }; - } - function checkInvalidScopeReference(node, method) { - if (!node) - return; - walkIdentifiers(node, (id) => { - const binding = setupBindings[id.name]; - if (binding && binding !== "literal-const") { - ctx.error( - `\`${method}()\` in <script setup> cannot reference locally declared variables because it will be hoisted outside of the setup() function. If your component options require initialization in the module scope, use a separate normal <script> to export the options instead.`, - id - ); - } - }); - } - const scriptAst = ctx.scriptAst; - const scriptSetupAst = ctx.scriptSetupAst; - if (scriptAst) { - for (const node of scriptAst.body) { - if (node.type === "ImportDeclaration") { - for (const specifier of node.specifiers) { - const imported = getImportedName(specifier); - registerUserImport( - node.source.value, - specifier.local.name, - imported, - node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type", - false, - !options.inlineTemplate - ); - } - } - } - } - for (const node of scriptSetupAst.body) { - if (node.type === "ImportDeclaration") { - hoistNode(node); - let removed = 0; - const removeSpecifier = (i) => { - const removeLeft = i > removed; - removed++; - const current = node.specifiers[i]; - const next = node.specifiers[i + 1]; - ctx.s.remove( - removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset, - next && !removeLeft ? next.start + startOffset : current.end + startOffset - ); - }; - for (let i = 0; i < node.specifiers.length; i++) { - const specifier = node.specifiers[i]; - const local = specifier.local.name; - const imported = getImportedName(specifier); - const source2 = node.source.value; - const existing = ctx.userImports[local]; - if (source2 === "vue" && (imported === DEFINE_PROPS || imported === DEFINE_EMITS || imported === DEFINE_EXPOSE)) { - warnOnce$3( - `\`${imported}\` is a compiler macro and no longer needs to be imported.` - ); - removeSpecifier(i); - } else if (existing) { - if (existing.source === source2 && existing.imported === imported) { - removeSpecifier(i); - } else { - ctx.error( - `different imports aliased to same local name.`, - specifier - ); - } - } else { - registerUserImport( - source2, - local, - imported, - node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type", - true, - !options.inlineTemplate - ); - } - } - if (node.specifiers.length && removed === node.specifiers.length) { - ctx.s.remove(node.start + startOffset, node.end + startOffset); - } - } - } - const vueImportAliases = {}; - for (const key in ctx.userImports) { - const { source: source2, imported, local } = ctx.userImports[key]; - if (source2 === "vue") - vueImportAliases[imported] = local; - } - if (script && scriptAst) { - for (const node of scriptAst.body) { - if (node.type === "ExportDefaultDeclaration") { - defaultExport = node; - let optionProperties; - if (defaultExport.declaration.type === "ObjectExpression") { - optionProperties = defaultExport.declaration.properties; - } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") { - optionProperties = defaultExport.declaration.arguments[0].properties; - } - if (optionProperties) { - for (const p of optionProperties) { - if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") { - ctx.hasDefaultExportName = true; - } - if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") { - ctx.hasDefaultExportRender = true; - } - } - } - const start = node.start + scriptStartOffset; - const end = node.declaration.start + scriptStartOffset; - ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `); - } else if (node.type === "ExportNamedDeclaration") { - const defaultSpecifier = node.specifiers.find( - (s) => s.exported.type === "Identifier" && s.exported.name === "default" - ); - if (defaultSpecifier) { - defaultExport = node; - if (node.specifiers.length > 1) { - ctx.s.remove( - defaultSpecifier.start + scriptStartOffset, - defaultSpecifier.end + scriptStartOffset - ); - } else { - ctx.s.remove( - node.start + scriptStartOffset, - node.end + scriptStartOffset - ); - } - if (node.source) { - ctx.s.prepend( - `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}' -` - ); - } else { - ctx.s.appendLeft( - scriptEndOffset, - ` -const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name} -` - ); - } - } - if (node.declaration) { - walkDeclaration( - "script", - node.declaration, - scriptBindings, - vueImportAliases, - hoistStatic - ); - } - } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) { - walkDeclaration( - "script", - node, - scriptBindings, - vueImportAliases, - hoistStatic - ); - } - } - if (scriptStartOffset > startOffset) { - if (!/\n$/.test(script.content.trim())) { - ctx.s.appendLeft(scriptEndOffset, ` -`); - } - ctx.s.move(scriptStartOffset, scriptEndOffset, 0); - } - } - for (const node of scriptSetupAst.body) { - if (node.type === "ExpressionStatement") { - const expr = unwrapTSNode(node.expression); - if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) { - ctx.s.remove(node.start + startOffset, node.end + startOffset); - } else if (processDefineExpose(ctx, expr)) { - const callee = expr.callee; - ctx.s.overwrite( - callee.start + startOffset, - callee.end + startOffset, - "__expose" - ); - } else { - processDefineModel(ctx, expr); - } - } - if (node.type === "VariableDeclaration" && !node.declare) { - const total = node.declarations.length; - let left = total; - let lastNonRemoved; - for (let i = 0; i < total; i++) { - const decl = node.declarations[i]; - const init = decl.init && unwrapTSNode(decl.init); - if (init) { - if (processDefineOptions(ctx, init)) { - ctx.error( - `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`, - node - ); - } - const isDefineProps = processDefineProps(ctx, init, decl.id); - const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id); - !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id)); - if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) { - if (left === 1) { - ctx.s.remove(node.start + startOffset, node.end + startOffset); - } else { - let start = decl.start + startOffset; - let end = decl.end + startOffset; - if (i === total - 1) { - start = node.declarations[lastNonRemoved].end + startOffset; - } else { - end = node.declarations[i + 1].start + startOffset; - } - ctx.s.remove(start, end); - left--; - } - } else if (isDefineEmits) { - ctx.s.overwrite( - startOffset + init.start, - startOffset + init.end, - "__emit" - ); - } else { - lastNonRemoved = i; - } - } - } - } - let isAllLiteral = false; - if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) { - isAllLiteral = walkDeclaration( - "scriptSetup", - node, - setupBindings, - vueImportAliases, - hoistStatic - ); - } - if (hoistStatic && isAllLiteral) { - hoistNode(node); - } - if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) { - const scope = [scriptSetupAst.body]; - walk$2(node, { - enter(child, parent) { - if (isFunctionType(child)) { - this.skip(); - } - if (child.type === "BlockStatement") { - scope.push(child.body); - } - if (child.type === "AwaitExpression") { - hasAwait = true; - const currentScope = scope[scope.length - 1]; - const needsSemi = currentScope.some((n, i) => { - return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start; - }); - processAwait( - ctx, - child, - needsSemi, - parent.type === "ExpressionStatement" - ); - } - }, - exit(node2) { - if (node2.type === "BlockStatement") - scope.pop(); - } - }); - } - if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") { - ctx.error( - `<script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, - node - ); - } - if (ctx.isTS) { - if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) { - if (node.type !== "TSEnumDeclaration") { - hoistNode(node); - } - } - } - } - if (ctx.propsDestructureDecl) { - transformDestructuredProps(ctx, vueImportAliases); - } - checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS); - checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS); - checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS); - checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS); - checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS); - for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) { - for (const node of runtimeOptionNodes) { - checkInvalidScopeReference(node, DEFINE_MODEL); - } - } - if (script) { - if (startOffset < scriptStartOffset) { - ctx.s.remove(0, startOffset); - ctx.s.remove(endOffset, scriptStartOffset); - ctx.s.remove(scriptEndOffset, source.length); - } else { - ctx.s.remove(0, scriptStartOffset); - ctx.s.remove(scriptEndOffset, startOffset); - ctx.s.remove(endOffset, source.length); - } - } else { - ctx.s.remove(0, startOffset); - ctx.s.remove(endOffset, source.length); - } - if (scriptAst) { - Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body)); - } - for (const [key, { isType, imported, source: source2 }] of Object.entries( - ctx.userImports - )) { - if (isType) - continue; - ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref"; - } - for (const key in scriptBindings) { - ctx.bindingMetadata[key] = scriptBindings[key]; - } - for (const key in setupBindings) { - ctx.bindingMetadata[key] = setupBindings[key]; - } - if (sfc.cssVars.length && // no need to do this when targeting SSR - !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) { - ctx.helperImports.add(CSS_VARS_HELPER); - ctx.helperImports.add("unref"); - ctx.s.prependLeft( - startOffset, - ` -${genCssVarsCode( - sfc.cssVars, - ctx.bindingMetadata, - scopeId, - !!options.isProd - )} -` - ); - } - let args = `__props`; - if (ctx.propsTypeDecl) { - args += `: any`; - } - if (ctx.propsDecl) { - if (ctx.propsDestructureRestId) { - ctx.s.overwrite( - startOffset + ctx.propsCall.start, - startOffset + ctx.propsCall.end, - `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify( - Object.keys(ctx.propsDestructuredBindings) - )})` - ); - ctx.s.overwrite( - startOffset + ctx.propsDestructureDecl.start, - startOffset + ctx.propsDestructureDecl.end, - ctx.propsDestructureRestId - ); - } else if (!ctx.propsDestructureDecl) { - ctx.s.overwrite( - startOffset + ctx.propsCall.start, - startOffset + ctx.propsCall.end, - "__props" - ); - } - } - if (hasAwait) { - const any = ctx.isTS ? `: any` : ``; - ctx.s.prependLeft(startOffset, ` -let __temp${any}, __restore${any} -`); - } - const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : []; - if (ctx.emitDecl) { - destructureElements.push(`emit: __emit`); - } - if (destructureElements.length) { - args += `, { ${destructureElements.join(", ")} }`; - } - let returned; - if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) { - const allBindings = __spreadValues$1(__spreadValues$1({}, scriptBindings), setupBindings); - for (const key in ctx.userImports) { - if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) { - allBindings[key] = true; - } - } - returned = `{ `; - for (const key in allBindings) { - if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) { - returned += `get ${key}() { return ${key} }, `; - } else if (ctx.bindingMetadata[key] === "setup-let") { - const setArg = key === "v" ? `_v` : `v`; - returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `; - } else { - returned += `${key}, `; - } - } - returned = returned.replace(/, $/, "") + ` }`; - } else { - if (sfc.template && !sfc.template.src) { - if (options.templateOptions && options.templateOptions.ssr) { - hasInlinedSsrRenderFn = true; - } - const { code, ast, preamble, tips, errors } = compileTemplate(__spreadProps(__spreadValues$1({ - filename, - ast: sfc.template.ast, - source: sfc.template.content, - inMap: sfc.template.map - }, options.templateOptions), { - id: scopeId, - scoped: sfc.styles.some((s) => s.scoped), - isProd: options.isProd, - ssrCssVars: sfc.cssVars, - compilerOptions: __spreadProps(__spreadValues$1({}, options.templateOptions && options.templateOptions.compilerOptions), { - inline: true, - isTS: ctx.isTS, - bindingMetadata: ctx.bindingMetadata - }) - })); - if (tips.length) { - tips.forEach(warnOnce$3); - } - const err = errors[0]; - if (typeof err === "string") { - throw new Error(err); - } else if (err) { - if (err.loc) { - err.message += ` - -` + sfc.filename + "\n" + generateCodeFrame( - source, - err.loc.start.offset, - err.loc.end.offset - ) + ` -`; - } - throw err; - } - if (preamble) { - ctx.s.prepend(preamble); - } - if (ast && ast.helpers.has(UNREF)) { - ctx.helperImports.delete("unref"); - } - returned = code; - } else { - returned = `() => {}`; - } - } - if (!options.inlineTemplate && true) { - ctx.s.appendRight( - endOffset, - ` -const __returned__ = ${returned} -Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true }) -return __returned__ -} - -` - ); - } else { - ctx.s.appendRight(endOffset, ` -return ${returned} -} - -`); - } - const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`; - let runtimeOptions = ``; - if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) { - const match = filename.match(/([^/\\]+)\.\w+$/); - if (match) { - runtimeOptions += ` - __name: '${match[1]}',`; - } - } - if (hasInlinedSsrRenderFn) { - runtimeOptions += ` - __ssrInlineRender: true,`; - } - const propsDecl = genRuntimeProps(ctx); - if (propsDecl) - runtimeOptions += ` - props: ${propsDecl},`; - const emitsDecl = genRuntimeEmits(ctx); - if (emitsDecl) - runtimeOptions += ` - emits: ${emitsDecl},`; - let definedOptions = ""; - if (ctx.optionsRuntimeDecl) { - definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim(); - } - const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose(); -`; - if (ctx.isTS) { - const def = (defaultExport ? ` - ...${normalScriptDefaultVar},` : ``) + (definedOptions ? ` - ...${definedOptions},` : ""); - ctx.s.prependLeft( - startOffset, - ` -${genDefaultAs} /*#__PURE__*/${ctx.helper( - `defineComponent` - )}({${def}${runtimeOptions} - ${hasAwait ? `async ` : ``}setup(${args}) { -${exposeCall}` - ); - ctx.s.appendRight(endOffset, `})`); - } else { - if (defaultExport || definedOptions) { - ctx.s.prependLeft( - startOffset, - ` -${genDefaultAs} /*#__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions} - ${hasAwait ? `async ` : ``}setup(${args}) { -${exposeCall}` - ); - ctx.s.appendRight(endOffset, `})`); - } else { - ctx.s.prependLeft( - startOffset, - ` -${genDefaultAs} {${runtimeOptions} - ${hasAwait ? `async ` : ``}setup(${args}) { -${exposeCall}` - ); - ctx.s.appendRight(endOffset, `}`); - } - } - if (ctx.helperImports.size > 0) { - ctx.s.prepend( - `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from 'vue' -` - ); - } - return __spreadProps(__spreadValues$1({}, scriptSetup), { - bindings: ctx.bindingMetadata, - imports: ctx.userImports, - content: ctx.s.toString(), - map: options.sourceMap !== false ? ctx.s.generateMap({ - source: filename, - hires: true, - includeContent: true - }) : void 0, - scriptAst: scriptAst == null ? void 0 : scriptAst.body, - scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body, - deps: ctx.deps ? [...ctx.deps] : void 0 - }); - } - function registerBinding(bindings, node, type) { - bindings[node.name] = type; - } - function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic) { - let isAllLiteral = false; - if (node.type === "VariableDeclaration") { - const isConst = node.kind === "const"; - isAllLiteral = isConst && node.declarations.every( - (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init) - ); - for (const { id, init: _init } of node.declarations) { - const init = _init && unwrapTSNode(_init); - const isDefineCall = !!(isConst && isCallOf( - init, - (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS - )); - if (id.type === "Identifier") { - let bindingType; - const userReactiveBinding = userImportAliases["reactive"]; - if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) { - bindingType = "literal-const"; - } else if (isCallOf(init, userReactiveBinding)) { - bindingType = isConst ? "setup-reactive-const" : "setup-let"; - } else if ( - // if a declaration is a const literal, we can mark it so that - // the generated render fn code doesn't need to unref() it - isDefineCall || isConst && canNeverBeRef(init, userReactiveBinding) - ) { - bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const"; - } else if (isConst) { - if (isCallOf( - init, - (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL - )) { - bindingType = "setup-ref"; - } else { - bindingType = "setup-maybe-ref"; - } - } else { - bindingType = "setup-let"; - } - registerBinding(bindings, id, bindingType); - } else { - if (isCallOf(init, DEFINE_PROPS)) { - continue; - } - if (id.type === "ObjectPattern") { - walkObjectPattern(id, bindings, isConst, isDefineCall); - } else if (id.type === "ArrayPattern") { - walkArrayPattern(id, bindings, isConst, isDefineCall); - } - } - } - } else if (node.type === "TSEnumDeclaration") { - isAllLiteral = node.members.every( - (member) => !member.initializer || isStaticNode(member.initializer) - ); - bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const"; - } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") { - bindings[node.id.name] = "setup-const"; - } - return isAllLiteral; - } - function walkObjectPattern(node, bindings, isConst, isDefineCall = false) { - for (const p of node.properties) { - if (p.type === "ObjectProperty") { - if (p.key.type === "Identifier" && p.key === p.value) { - const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let"; - registerBinding(bindings, p.key, type); - } else { - walkPattern(p.value, bindings, isConst, isDefineCall); - } - } else { - const type = isConst ? "setup-const" : "setup-let"; - registerBinding(bindings, p.argument, type); - } - } - } - function walkArrayPattern(node, bindings, isConst, isDefineCall = false) { - for (const e of node.elements) { - e && walkPattern(e, bindings, isConst, isDefineCall); - } - } - function walkPattern(node, bindings, isConst, isDefineCall = false) { - if (node.type === "Identifier") { - const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let"; - registerBinding(bindings, node, type); - } else if (node.type === "RestElement") { - const type = isConst ? "setup-const" : "setup-let"; - registerBinding(bindings, node.argument, type); - } else if (node.type === "ObjectPattern") { - walkObjectPattern(node, bindings, isConst); - } else if (node.type === "ArrayPattern") { - walkArrayPattern(node, bindings, isConst); - } else if (node.type === "AssignmentPattern") { - if (node.left.type === "Identifier") { - const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let"; - registerBinding(bindings, node.left, type); - } else { - walkPattern(node.left, bindings, isConst); - } - } - } - function canNeverBeRef(node, userReactiveImport) { - if (isCallOf(node, userReactiveImport)) { - return true; - } - switch (node.type) { - case "UnaryExpression": - case "BinaryExpression": - case "ArrayExpression": - case "ObjectExpression": - case "FunctionExpression": - case "ArrowFunctionExpression": - case "UpdateExpression": - case "ClassExpression": - case "TaggedTemplateExpression": - return true; - case "SequenceExpression": - return canNeverBeRef( - node.expressions[node.expressions.length - 1], - userReactiveImport - ); - default: - if (isLiteralNode(node)) { - return true; - } - return false; - } - } - function isStaticNode(node) { - node = unwrapTSNode(node); - switch (node.type) { - case "UnaryExpression": - return isStaticNode(node.argument); - case "LogicalExpression": - case "BinaryExpression": - return isStaticNode(node.left) && isStaticNode(node.right); - case "ConditionalExpression": { - return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate); - } - case "SequenceExpression": - case "TemplateLiteral": - return node.expressions.every((expr) => isStaticNode(expr)); - case "ParenthesizedExpression": - return isStaticNode(node.expression); - case "StringLiteral": - case "NumericLiteral": - case "BooleanLiteral": - case "NullLiteral": - case "BigIntLiteral": - return true; - } - return false; - } - - var __defProp = Object.defineProperty; - var __getOwnPropSymbols = Object.getOwnPropertySymbols; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __propIsEnum = Object.prototype.propertyIsEnumerable; - var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __spreadValues = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp.call(b, prop)) - __defNormalProp(a, prop, b[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b)) { - if (__propIsEnum.call(b, prop)) - __defNormalProp(a, prop, b[prop]); - } - return a; - }; - const version = "3.4.21"; - const parseCache = parseCache$1; - const errorMessages = __spreadValues(__spreadValues({}, errorMessages$1), DOMErrorMessages); - const walk = walk$2; - const shouldTransformRef = () => false; - - return { MagicString, babelParse: parse_1$1, compileScript, compileStyle, compileStyleAsync, compileTemplate, errorMessages, extractIdentifiers: extractIdentifiers$1, extractRuntimeEmits, extractRuntimeProps, generateCodeFrame, inferRuntimeType, invalidateTypeCache, isInDestructureAssignment, isStaticProperty, parse: parse$7, parseCache, registerTS, resolveTypeElements, rewriteDefault, rewriteDefaultAST, shouldTransformRef, version, walk, walkIdentifiers }; -})(); \ No newline at end of file diff --git a/game/compiler-sfc.esm-browser.js b/game/compiler-sfc.esm-browser.js new file mode 100644 index 000000000..8ce77b30c --- /dev/null +++ b/game/compiler-sfc.esm-browser.js @@ -0,0 +1,48237 @@ +/** +* @vue/compiler-sfc v3.4.21 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/ +function makeMap(str, expectsLowerCase) { + const set = new Set(str.split(",")); + return expectsLowerCase ? (val) => set.has(val.toLowerCase()) : (val) => set.has(val); +} + +const EMPTY_OBJ = Object.freeze({}) ; +const NOOP = () => { +}; +const NO = () => false; +const isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter +(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); +const extend = Object.assign; +const hasOwnProperty$3 = Object.prototype.hasOwnProperty; +const hasOwn = (val, key) => hasOwnProperty$3.call(val, key); +const isArray$3 = Array.isArray; +const isMap = (val) => toTypeString(val) === "[object Map]"; +const isSet = (val) => toTypeString(val) === "[object Set]"; +const isFunction$1 = (val) => typeof val === "function"; +const isString$2 = (val) => typeof val === "string"; +const isSymbol$1 = (val) => typeof val === "symbol"; +const isObject$2 = (val) => val !== null && typeof val === "object"; +const objectToString$1 = Object.prototype.toString; +const toTypeString = (value) => objectToString$1.call(value); +const isPlainObject = (val) => toTypeString(val) === "[object Object]"; +const isReservedProp = /* @__PURE__ */ makeMap( + // the leading comma is intentional so empty string "" is also included + ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" +); +const isBuiltInDirective = /* @__PURE__ */ makeMap( + "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" +); +const cacheStringFunction = (fn) => { + const cache = /* @__PURE__ */ Object.create(null); + return (str) => { + const hit = cache[str]; + return hit || (cache[str] = fn(str)); + }; +}; +const camelizeRE = /-(\w)/g; +const camelize = cacheStringFunction((str) => { + return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); +}); +const hyphenateRE = /\B([A-Z])/g; +const hyphenate = cacheStringFunction( + (str) => str.replace(hyphenateRE, "-$1").toLowerCase() +); +const capitalize$1 = cacheStringFunction((str) => { + return str.charAt(0).toUpperCase() + str.slice(1); +}); +const toHandlerKey = cacheStringFunction((str) => { + const s = str ? `on${capitalize$1(str)}` : ``; + return s; +}); +const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/; +function genPropsAccessExp(name) { + return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`; +} + +const PatchFlagNames = { + [1]: `TEXT`, + [2]: `CLASS`, + [4]: `STYLE`, + [8]: `PROPS`, + [16]: `FULL_PROPS`, + [32]: `NEED_HYDRATION`, + [64]: `STABLE_FRAGMENT`, + [128]: `KEYED_FRAGMENT`, + [256]: `UNKEYED_FRAGMENT`, + [512]: `NEED_PATCH`, + [1024]: `DYNAMIC_SLOTS`, + [2048]: `DEV_ROOT_FRAGMENT`, + [-1]: `HOISTED`, + [-2]: `BAIL` +}; + +const slotFlagsText = { + [1]: "STABLE", + [2]: "DYNAMIC", + [3]: "FORWARDED" +}; + +const GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error"; +const isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED); + +const range = 2; +function generateCodeFrame(source, start = 0, end = source.length) { + let lines = source.split(/(\r?\n)/); + const newlineSequences = lines.filter((_, idx) => idx % 2 === 1); + lines = lines.filter((_, idx) => idx % 2 === 0); + let count = 0; + const res = []; + for (let i = 0; i < lines.length; i++) { + count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0); + if (count >= start) { + for (let j = i - range; j <= i + range || end > count; j++) { + if (j < 0 || j >= lines.length) + continue; + const line = j + 1; + res.push( + `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}` + ); + const lineLength = lines[j].length; + const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0; + if (j === i) { + const pad = start - (count - (lineLength + newLineSeqLength)); + const length = Math.max( + 1, + end > count ? lineLength - pad : end - start + ); + res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); + } else if (j > i) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1); + res.push(` | ` + "^".repeat(length)); + } + count += lineLength + newLineSeqLength; + } + } + break; + } + } + return res.join("\n"); +} + +function normalizeStyle(value) { + if (isArray$3(value)) { + const res = {}; + for (let i = 0; i < value.length; i++) { + const item = value[i]; + const normalized = isString$2(item) ? parseStringStyle(item) : normalizeStyle(item); + if (normalized) { + for (const key in normalized) { + res[key] = normalized[key]; + } + } + } + return res; + } else if (isString$2(value) || isObject$2(value)) { + return value; + } +} +const listDelimiterRE = /;(?![^(]*\))/g; +const propertyDelimiterRE = /:([^]+)/; +const styleCommentRE = /\/\*[^]*?\*\//g; +function parseStringStyle(cssText) { + const ret = {}; + cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => { + if (item) { + const tmp = item.split(propertyDelimiterRE); + tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); + } + }); + return ret; +} +function stringifyStyle(styles) { + let ret = ""; + if (!styles || isString$2(styles)) { + return ret; + } + for (const key in styles) { + const value = styles[key]; + const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); + if (isString$2(value) || typeof value === "number") { + ret += `${normalizedKey}:${value};`; + } + } + return ret; +} +function normalizeClass(value) { + let res = ""; + if (isString$2(value)) { + res = value; + } else if (isArray$3(value)) { + for (let i = 0; i < value.length; i++) { + const normalized = normalizeClass(value[i]); + if (normalized) { + res += normalized + " "; + } + } + } else if (isObject$2(value)) { + for (const name in value) { + if (value[name]) { + res += name + " "; + } + } + } + return res.trim(); +} + +const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; +const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; +const MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"; +const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; +const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); +const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); +const isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS); +const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); + +const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; +const isBooleanAttr = /* @__PURE__ */ makeMap( + specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` +); +const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; +const attrValidationCache = {}; +function isSSRSafeAttrName(name) { + if (attrValidationCache.hasOwnProperty(name)) { + return attrValidationCache[name]; + } + const isUnsafe = unsafeAttrCharRE.test(name); + if (isUnsafe) { + console.error(`unsafe attribute name: ${name}`); + } + return attrValidationCache[name] = !isUnsafe; +} +const propsToAttrMap = { + acceptCharset: "accept-charset", + className: "class", + htmlFor: "for", + httpEquiv: "http-equiv" +}; +const isKnownHtmlAttr = /* @__PURE__ */ makeMap( + `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap` +); +const isKnownSvgAttr = /* @__PURE__ */ makeMap( + `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan` +); + +const escapeRE = /["'&<>]/; +function escapeHtml(string) { + const str = "" + string; + const match = escapeRE.exec(str); + if (!match) { + return str; + } + let html = ""; + let escaped; + let index; + let lastIndex = 0; + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: + escaped = """; + break; + case 38: + escaped = "&"; + break; + case 39: + escaped = "'"; + break; + case 60: + escaped = "<"; + break; + case 62: + escaped = ">"; + break; + default: + continue; + } + if (lastIndex !== index) { + html += str.slice(lastIndex, index); + } + lastIndex = index + 1; + html += escaped; + } + return lastIndex !== index ? html + str.slice(lastIndex, index) : html; +} + +const toDisplayString = (val) => { + return isString$2(val) ? val : val == null ? "" : isArray$3(val) || isObject$2(val) && (val.toString === objectToString$1 || !isFunction$1(val.toString)) ? JSON.stringify(val, replacer, 2) : String(val); +}; +const replacer = (_key, val) => { + if (val && val.__v_isRef) { + return replacer(_key, val.value); + } else if (isMap(val)) { + return { + [`Map(${val.size})`]: [...val.entries()].reduce( + (entries, [key, val2], i) => { + entries[stringifySymbol(key, i) + " =>"] = val2; + return entries; + }, + {} + ) + }; + } else if (isSet(val)) { + return { + [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)) + }; + } else if (isSymbol$1(val)) { + return stringifySymbol(val); + } else if (isObject$2(val) && !isArray$3(val) && !isPlainObject(val)) { + return String(val); + } + return val; +}; +const stringifySymbol = (v, i = "") => { + var _a; + return isSymbol$1(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v; +}; + +const FRAGMENT = Symbol(`Fragment` ); +const TELEPORT = Symbol(`Teleport` ); +const SUSPENSE = Symbol(`Suspense` ); +const KEEP_ALIVE = Symbol(`KeepAlive` ); +const BASE_TRANSITION = Symbol(`BaseTransition` ); +const OPEN_BLOCK = Symbol(`openBlock` ); +const CREATE_BLOCK = Symbol(`createBlock` ); +const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` ); +const CREATE_VNODE = Symbol(`createVNode` ); +const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` ); +const CREATE_COMMENT = Symbol(`createCommentVNode` ); +const CREATE_TEXT = Symbol(`createTextVNode` ); +const CREATE_STATIC = Symbol(`createStaticVNode` ); +const RESOLVE_COMPONENT = Symbol(`resolveComponent` ); +const RESOLVE_DYNAMIC_COMPONENT = Symbol( + `resolveDynamicComponent` +); +const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` ); +const RESOLVE_FILTER = Symbol(`resolveFilter` ); +const WITH_DIRECTIVES = Symbol(`withDirectives` ); +const RENDER_LIST = Symbol(`renderList` ); +const RENDER_SLOT = Symbol(`renderSlot` ); +const CREATE_SLOTS = Symbol(`createSlots` ); +const TO_DISPLAY_STRING = Symbol(`toDisplayString` ); +const MERGE_PROPS = Symbol(`mergeProps` ); +const NORMALIZE_CLASS = Symbol(`normalizeClass` ); +const NORMALIZE_STYLE = Symbol(`normalizeStyle` ); +const NORMALIZE_PROPS = Symbol(`normalizeProps` ); +const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` ); +const TO_HANDLERS = Symbol(`toHandlers` ); +const CAMELIZE = Symbol(`camelize` ); +const CAPITALIZE = Symbol(`capitalize` ); +const TO_HANDLER_KEY = Symbol(`toHandlerKey` ); +const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` ); +const PUSH_SCOPE_ID = Symbol(`pushScopeId` ); +const POP_SCOPE_ID = Symbol(`popScopeId` ); +const WITH_CTX = Symbol(`withCtx` ); +const UNREF = Symbol(`unref` ); +const IS_REF = Symbol(`isRef` ); +const WITH_MEMO = Symbol(`withMemo` ); +const IS_MEMO_SAME = Symbol(`isMemoSame` ); +const helperNameMap = { + [FRAGMENT]: `Fragment`, + [TELEPORT]: `Teleport`, + [SUSPENSE]: `Suspense`, + [KEEP_ALIVE]: `KeepAlive`, + [BASE_TRANSITION]: `BaseTransition`, + [OPEN_BLOCK]: `openBlock`, + [CREATE_BLOCK]: `createBlock`, + [CREATE_ELEMENT_BLOCK]: `createElementBlock`, + [CREATE_VNODE]: `createVNode`, + [CREATE_ELEMENT_VNODE]: `createElementVNode`, + [CREATE_COMMENT]: `createCommentVNode`, + [CREATE_TEXT]: `createTextVNode`, + [CREATE_STATIC]: `createStaticVNode`, + [RESOLVE_COMPONENT]: `resolveComponent`, + [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`, + [RESOLVE_DIRECTIVE]: `resolveDirective`, + [RESOLVE_FILTER]: `resolveFilter`, + [WITH_DIRECTIVES]: `withDirectives`, + [RENDER_LIST]: `renderList`, + [RENDER_SLOT]: `renderSlot`, + [CREATE_SLOTS]: `createSlots`, + [TO_DISPLAY_STRING]: `toDisplayString`, + [MERGE_PROPS]: `mergeProps`, + [NORMALIZE_CLASS]: `normalizeClass`, + [NORMALIZE_STYLE]: `normalizeStyle`, + [NORMALIZE_PROPS]: `normalizeProps`, + [GUARD_REACTIVE_PROPS]: `guardReactiveProps`, + [TO_HANDLERS]: `toHandlers`, + [CAMELIZE]: `camelize`, + [CAPITALIZE]: `capitalize`, + [TO_HANDLER_KEY]: `toHandlerKey`, + [SET_BLOCK_TRACKING]: `setBlockTracking`, + [PUSH_SCOPE_ID]: `pushScopeId`, + [POP_SCOPE_ID]: `popScopeId`, + [WITH_CTX]: `withCtx`, + [UNREF]: `unref`, + [IS_REF]: `isRef`, + [WITH_MEMO]: `withMemo`, + [IS_MEMO_SAME]: `isMemoSame` +}; +function registerRuntimeHelpers(helpers) { + Object.getOwnPropertySymbols(helpers).forEach((s) => { + helperNameMap[s] = helpers[s]; + }); +} + +const Namespaces = { + "HTML": 0, + "0": "HTML", + "SVG": 1, + "1": "SVG", + "MATH_ML": 2, + "2": "MATH_ML" +}; +const NodeTypes = { + "ROOT": 0, + "0": "ROOT", + "ELEMENT": 1, + "1": "ELEMENT", + "TEXT": 2, + "2": "TEXT", + "COMMENT": 3, + "3": "COMMENT", + "SIMPLE_EXPRESSION": 4, + "4": "SIMPLE_EXPRESSION", + "INTERPOLATION": 5, + "5": "INTERPOLATION", + "ATTRIBUTE": 6, + "6": "ATTRIBUTE", + "DIRECTIVE": 7, + "7": "DIRECTIVE", + "COMPOUND_EXPRESSION": 8, + "8": "COMPOUND_EXPRESSION", + "IF": 9, + "9": "IF", + "IF_BRANCH": 10, + "10": "IF_BRANCH", + "FOR": 11, + "11": "FOR", + "TEXT_CALL": 12, + "12": "TEXT_CALL", + "VNODE_CALL": 13, + "13": "VNODE_CALL", + "JS_CALL_EXPRESSION": 14, + "14": "JS_CALL_EXPRESSION", + "JS_OBJECT_EXPRESSION": 15, + "15": "JS_OBJECT_EXPRESSION", + "JS_PROPERTY": 16, + "16": "JS_PROPERTY", + "JS_ARRAY_EXPRESSION": 17, + "17": "JS_ARRAY_EXPRESSION", + "JS_FUNCTION_EXPRESSION": 18, + "18": "JS_FUNCTION_EXPRESSION", + "JS_CONDITIONAL_EXPRESSION": 19, + "19": "JS_CONDITIONAL_EXPRESSION", + "JS_CACHE_EXPRESSION": 20, + "20": "JS_CACHE_EXPRESSION", + "JS_BLOCK_STATEMENT": 21, + "21": "JS_BLOCK_STATEMENT", + "JS_TEMPLATE_LITERAL": 22, + "22": "JS_TEMPLATE_LITERAL", + "JS_IF_STATEMENT": 23, + "23": "JS_IF_STATEMENT", + "JS_ASSIGNMENT_EXPRESSION": 24, + "24": "JS_ASSIGNMENT_EXPRESSION", + "JS_SEQUENCE_EXPRESSION": 25, + "25": "JS_SEQUENCE_EXPRESSION", + "JS_RETURN_STATEMENT": 26, + "26": "JS_RETURN_STATEMENT" +}; +const ElementTypes = { + "ELEMENT": 0, + "0": "ELEMENT", + "COMPONENT": 1, + "1": "COMPONENT", + "SLOT": 2, + "2": "SLOT", + "TEMPLATE": 3, + "3": "TEMPLATE" +}; +const ConstantTypes = { + "NOT_CONSTANT": 0, + "0": "NOT_CONSTANT", + "CAN_SKIP_PATCH": 1, + "1": "CAN_SKIP_PATCH", + "CAN_HOIST": 2, + "2": "CAN_HOIST", + "CAN_STRINGIFY": 3, + "3": "CAN_STRINGIFY" +}; +const locStub = { + start: { line: 1, column: 1, offset: 0 }, + end: { line: 1, column: 1, offset: 0 }, + source: "" +}; +function createRoot(children, source = "") { + return { + type: 0, + source, + children, + helpers: /* @__PURE__ */ new Set(), + components: [], + directives: [], + hoists: [], + imports: [], + cached: 0, + temps: 0, + codegenNode: void 0, + loc: locStub + }; +} +function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) { + if (context) { + if (isBlock) { + context.helper(OPEN_BLOCK); + context.helper(getVNodeBlockHelper(context.inSSR, isComponent)); + } else { + context.helper(getVNodeHelper(context.inSSR, isComponent)); + } + if (directives) { + context.helper(WITH_DIRECTIVES); + } + } + return { + type: 13, + tag, + props, + children, + patchFlag, + dynamicProps, + directives, + isBlock, + disableTracking, + isComponent, + loc + }; +} +function createArrayExpression(elements, loc = locStub) { + return { + type: 17, + loc, + elements + }; +} +function createObjectExpression(properties, loc = locStub) { + return { + type: 15, + loc, + properties + }; +} +function createObjectProperty(key, value) { + return { + type: 16, + loc: locStub, + key: isString$2(key) ? createSimpleExpression(key, true) : key, + value + }; +} +function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0) { + return { + type: 4, + loc, + content, + isStatic, + constType: isStatic ? 3 : constType + }; +} +function createInterpolation(content, loc) { + return { + type: 5, + loc, + content: isString$2(content) ? createSimpleExpression(content, false, loc) : content + }; +} +function createCompoundExpression(children, loc = locStub) { + return { + type: 8, + loc, + children + }; +} +function createCallExpression(callee, args = [], loc = locStub) { + return { + type: 14, + loc, + callee, + arguments: args + }; +} +function createFunctionExpression(params, returns = void 0, newline = false, isSlot = false, loc = locStub) { + return { + type: 18, + params, + returns, + newline, + isSlot, + loc + }; +} +function createConditionalExpression(test, consequent, alternate, newline = true) { + return { + type: 19, + test, + consequent, + alternate, + newline, + loc: locStub + }; +} +function createCacheExpression(index, value, isVNode = false) { + return { + type: 20, + index, + value, + isVNode, + loc: locStub + }; +} +function createBlockStatement(body) { + return { + type: 21, + body, + loc: locStub + }; +} +function createTemplateLiteral(elements) { + return { + type: 22, + elements, + loc: locStub + }; +} +function createIfStatement(test, consequent, alternate) { + return { + type: 23, + test, + consequent, + alternate, + loc: locStub + }; +} +function createAssignmentExpression(left, right) { + return { + type: 24, + left, + right, + loc: locStub + }; +} +function createSequenceExpression(expressions) { + return { + type: 25, + expressions, + loc: locStub + }; +} +function createReturnStatement(returns) { + return { + type: 26, + returns, + loc: locStub + }; +} +function getVNodeHelper(ssr, isComponent) { + return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE; +} +function getVNodeBlockHelper(ssr, isComponent) { + return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK; +} +function convertToBlock(node, { helper, removeHelper, inSSR }) { + if (!node.isBlock) { + node.isBlock = true; + removeHelper(getVNodeHelper(inSSR, node.isComponent)); + helper(OPEN_BLOCK); + helper(getVNodeBlockHelper(inSSR, node.isComponent)); + } +} + +// Generated using scripts/write-decode-map.ts +var htmlDecodeTree = new Uint16Array( +// prettier-ignore +"\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c" + .split("") + .map((c) => c.charCodeAt(0))); + +// Generated using scripts/write-decode-map.ts +var xmlDecodeTree = new Uint16Array( +// prettier-ignore +"\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022" + .split("") + .map((c) => c.charCodeAt(0))); + +// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 +var _a$1; +const decodeMap = new Map([ + [0, 65533], + // C1 Unicode control character reference replacements + [128, 8364], + [130, 8218], + [131, 402], + [132, 8222], + [133, 8230], + [134, 8224], + [135, 8225], + [136, 710], + [137, 8240], + [138, 352], + [139, 8249], + [140, 338], + [142, 381], + [145, 8216], + [146, 8217], + [147, 8220], + [148, 8221], + [149, 8226], + [150, 8211], + [151, 8212], + [152, 732], + [153, 8482], + [154, 353], + [155, 8250], + [156, 339], + [158, 382], + [159, 376], +]); +/** + * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. + */ +const fromCodePoint = +// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins +(_a$1 = String.fromCodePoint) !== null && _a$1 !== void 0 ? _a$1 : function (codePoint) { + let output = ""; + if (codePoint > 0xffff) { + codePoint -= 0x10000; + output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800); + codePoint = 0xdc00 | (codePoint & 0x3ff); + } + output += String.fromCharCode(codePoint); + return output; +}; +/** + * Replace the given code point with a replacement character if it is a + * surrogate or is outside the valid range. Otherwise return the code + * point unchanged. + */ +function replaceCodePoint(codePoint) { + var _a; + if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) { + return 0xfffd; + } + return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint; +} + +var CharCodes; +(function (CharCodes) { + CharCodes[CharCodes["NUM"] = 35] = "NUM"; + CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; + CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; + CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; + CharCodes[CharCodes["NINE"] = 57] = "NINE"; + CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; + CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; + CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; + CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; + CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; + CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; + CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; +})(CharCodes || (CharCodes = {})); +/** Bit that needs to be set to convert an upper case ASCII character to lower case */ +const TO_LOWER_BIT = 0b100000; +var BinTrieFlags; +(function (BinTrieFlags) { + BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; + BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; + BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; +})(BinTrieFlags || (BinTrieFlags = {})); +function isNumber$2(code) { + return code >= CharCodes.ZERO && code <= CharCodes.NINE; +} +function isHexadecimalCharacter(code) { + return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F)); +} +function isAsciiAlphaNumeric(code) { + return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) || + isNumber$2(code)); +} +/** + * Checks if the given character is a valid end character for an entity in an attribute. + * + * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. + * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state + */ +function isEntityInAttributeInvalidEnd(code) { + return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); +} +var EntityDecoderState; +(function (EntityDecoderState) { + EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; + EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; + EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; + EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; + EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; +})(EntityDecoderState || (EntityDecoderState = {})); +var DecodingMode; +(function (DecodingMode) { + /** Entities in text nodes that can end with any character. */ + DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; + /** Only allow entities terminated with a semicolon. */ + DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; + /** Entities in attributes have limitations on ending characters. */ + DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; +})(DecodingMode || (DecodingMode = {})); +/** + * Token decoder with support of writing partial entities. + */ +class EntityDecoder { + constructor( + /** The tree used to decode entities. */ + decodeTree, + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + emitCodePoint, + /** An object that is used to produce errors. */ + errors) { + this.decodeTree = decodeTree; + this.emitCodePoint = emitCodePoint; + this.errors = errors; + /** The current state of the decoder. */ + this.state = EntityDecoderState.EntityStart; + /** Characters that were consumed while parsing an entity. */ + this.consumed = 1; + /** + * The result of the entity. + * + * Either the result index of a numeric entity, or the codepoint of a + * numeric entity. + */ + this.result = 0; + /** The current index in the decode tree. */ + this.treeIndex = 0; + /** The number of characters that were consumed in excess. */ + this.excess = 1; + /** The mode in which the decoder is operating. */ + this.decodeMode = DecodingMode.Strict; + } + /** Resets the instance to make it reusable. */ + startEntity(decodeMode) { + this.decodeMode = decodeMode; + this.state = EntityDecoderState.EntityStart; + this.result = 0; + this.treeIndex = 0; + this.excess = 1; + this.consumed = 1; + } + /** + * Write an entity to the decoder. This can be called multiple times with partial entities. + * If the entity is incomplete, the decoder will return -1. + * + * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the + * entity is incomplete, and resume when the next string is written. + * + * @param string The string containing the entity (or a continuation of the entity). + * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + write(str, offset) { + switch (this.state) { + case EntityDecoderState.EntityStart: { + if (str.charCodeAt(offset) === CharCodes.NUM) { + this.state = EntityDecoderState.NumericStart; + this.consumed += 1; + return this.stateNumericStart(str, offset + 1); + } + this.state = EntityDecoderState.NamedEntity; + return this.stateNamedEntity(str, offset); + } + case EntityDecoderState.NumericStart: { + return this.stateNumericStart(str, offset); + } + case EntityDecoderState.NumericDecimal: { + return this.stateNumericDecimal(str, offset); + } + case EntityDecoderState.NumericHex: { + return this.stateNumericHex(str, offset); + } + case EntityDecoderState.NamedEntity: { + return this.stateNamedEntity(str, offset); + } + } + } + /** + * Switches between the numeric decimal and hexadecimal states. + * + * Equivalent to the `Numeric character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNumericStart(str, offset) { + if (offset >= str.length) { + return -1; + } + if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { + this.state = EntityDecoderState.NumericHex; + this.consumed += 1; + return this.stateNumericHex(str, offset + 1); + } + this.state = EntityDecoderState.NumericDecimal; + return this.stateNumericDecimal(str, offset); + } + addToNumericResult(str, start, end, base) { + if (start !== end) { + const digitCount = end - start; + this.result = + this.result * Math.pow(base, digitCount) + + parseInt(str.substr(start, digitCount), base); + this.consumed += digitCount; + } + } + /** + * Parses a hexadecimal numeric entity. + * + * Equivalent to the `Hexademical character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNumericHex(str, offset) { + const startIdx = offset; + while (offset < str.length) { + const char = str.charCodeAt(offset); + if (isNumber$2(char) || isHexadecimalCharacter(char)) { + offset += 1; + } + else { + this.addToNumericResult(str, startIdx, offset, 16); + return this.emitNumericEntity(char, 3); + } + } + this.addToNumericResult(str, startIdx, offset, 16); + return -1; + } + /** + * Parses a decimal numeric entity. + * + * Equivalent to the `Decimal character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNumericDecimal(str, offset) { + const startIdx = offset; + while (offset < str.length) { + const char = str.charCodeAt(offset); + if (isNumber$2(char)) { + offset += 1; + } + else { + this.addToNumericResult(str, startIdx, offset, 10); + return this.emitNumericEntity(char, 2); + } + } + this.addToNumericResult(str, startIdx, offset, 10); + return -1; + } + /** + * Validate and emit a numeric entity. + * + * Implements the logic from the `Hexademical character reference start + * state` and `Numeric character reference end state` in the HTML spec. + * + * @param lastCp The last code point of the entity. Used to see if the + * entity was terminated with a semicolon. + * @param expectedLength The minimum number of characters that should be + * consumed. Used to validate that at least one digit + * was consumed. + * @returns The number of characters that were consumed. + */ + emitNumericEntity(lastCp, expectedLength) { + var _a; + // Ensure we consumed at least one digit. + if (this.consumed <= expectedLength) { + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); + return 0; + } + // Figure out if this is a legit end of the entity + if (lastCp === CharCodes.SEMI) { + this.consumed += 1; + } + else if (this.decodeMode === DecodingMode.Strict) { + return 0; + } + this.emitCodePoint(replaceCodePoint(this.result), this.consumed); + if (this.errors) { + if (lastCp !== CharCodes.SEMI) { + this.errors.missingSemicolonAfterCharacterReference(); + } + this.errors.validateNumericCharacterReference(this.result); + } + return this.consumed; + } + /** + * Parses a named entity. + * + * Equivalent to the `Named character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNamedEntity(str, offset) { + const { decodeTree } = this; + let current = decodeTree[this.treeIndex]; + // The mask is the number of bytes of the value, including the current byte. + let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + for (; offset < str.length; offset++, this.excess++) { + const char = str.charCodeAt(offset); + this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); + if (this.treeIndex < 0) { + return this.result === 0 || + // If we are parsing an attribute + (this.decodeMode === DecodingMode.Attribute && + // We shouldn't have consumed any characters after the entity, + (valueLength === 0 || + // And there should be no invalid characters. + isEntityInAttributeInvalidEnd(char))) + ? 0 + : this.emitNotTerminatedNamedEntity(); + } + current = decodeTree[this.treeIndex]; + valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + // If the branch is a value, store it and continue + if (valueLength !== 0) { + // If the entity is terminated by a semicolon, we are done. + if (char === CharCodes.SEMI) { + return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); + } + // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. + if (this.decodeMode !== DecodingMode.Strict) { + this.result = this.treeIndex; + this.consumed += this.excess; + this.excess = 0; + } + } + } + return -1; + } + /** + * Emit a named entity that was not terminated with a semicolon. + * + * @returns The number of characters consumed. + */ + emitNotTerminatedNamedEntity() { + var _a; + const { result, decodeTree } = this; + const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; + this.emitNamedEntityData(result, valueLength, this.consumed); + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); + return this.consumed; + } + /** + * Emit a named entity. + * + * @param result The index of the entity in the decode tree. + * @param valueLength The number of bytes in the entity. + * @param consumed The number of characters consumed. + * + * @returns The number of characters consumed. + */ + emitNamedEntityData(result, valueLength, consumed) { + const { decodeTree } = this; + this.emitCodePoint(valueLength === 1 + ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH + : decodeTree[result + 1], consumed); + if (valueLength === 3) { + // For multi-byte values, we need to emit the second byte. + this.emitCodePoint(decodeTree[result + 2], consumed); + } + return consumed; + } + /** + * Signal to the parser that the end of the input was reached. + * + * Remaining data will be emitted and relevant errors will be produced. + * + * @returns The number of characters consumed. + */ + end() { + var _a; + switch (this.state) { + case EntityDecoderState.NamedEntity: { + // Emit a named entity if we have one. + return this.result !== 0 && + (this.decodeMode !== DecodingMode.Attribute || + this.result === this.treeIndex) + ? this.emitNotTerminatedNamedEntity() + : 0; + } + // Otherwise, emit a numeric entity if we have one. + case EntityDecoderState.NumericDecimal: { + return this.emitNumericEntity(0, 2); + } + case EntityDecoderState.NumericHex: { + return this.emitNumericEntity(0, 3); + } + case EntityDecoderState.NumericStart: { + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); + return 0; + } + case EntityDecoderState.EntityStart: { + // Return 0 if we have no entity. + return 0; + } + } + } +} +/** + * Creates a function that decodes entities in a string. + * + * @param decodeTree The decode tree. + * @returns A function that decodes entities in a string. + */ +function getDecoder(decodeTree) { + let ret = ""; + const decoder = new EntityDecoder(decodeTree, (str) => (ret += fromCodePoint(str))); + return function decodeWithTrie(str, decodeMode) { + let lastIndex = 0; + let offset = 0; + while ((offset = str.indexOf("&", offset)) >= 0) { + ret += str.slice(lastIndex, offset); + decoder.startEntity(decodeMode); + const len = decoder.write(str, + // Skip the "&" + offset + 1); + if (len < 0) { + lastIndex = offset + decoder.end(); + break; + } + lastIndex = offset + len; + // If `len` is 0, skip the current `&` and continue. + offset = len === 0 ? lastIndex + 1 : lastIndex; + } + const result = ret + str.slice(lastIndex); + // Make sure we don't keep a reference to the final string. + ret = ""; + return result; + }; +} +/** + * Determines the branch of the current node that is taken given the current + * character. This function is used to traverse the trie. + * + * @param decodeTree The trie. + * @param current The current node. + * @param nodeIdx The index right after the current node and its value. + * @param char The current character. + * @returns The index of the next node, or -1 if no branch is taken. + */ +function determineBranch(decodeTree, current, nodeIdx, char) { + const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; + const jumpOffset = current & BinTrieFlags.JUMP_TABLE; + // Case 1: Single branch encoded in jump offset + if (branchCount === 0) { + return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; + } + // Case 2: Multiple branches encoded in jump table + if (jumpOffset) { + const value = char - jumpOffset; + return value < 0 || value >= branchCount + ? -1 + : decodeTree[nodeIdx + value] - 1; + } + // Case 3: Multiple branches encoded in dictionary + // Binary search for the character. + let lo = nodeIdx; + let hi = lo + branchCount - 1; + while (lo <= hi) { + const mid = (lo + hi) >>> 1; + const midVal = decodeTree[mid]; + if (midVal < char) { + lo = mid + 1; + } + else if (midVal > char) { + hi = mid - 1; + } + else { + return decodeTree[mid + branchCount]; + } + } + return -1; +} +const htmlDecoder = getDecoder(htmlDecodeTree); +getDecoder(xmlDecodeTree); +/** + * Decodes an HTML string. + * + * @param str The string to decode. + * @param mode The decoding mode. + * @returns The decoded string. + */ +function decodeHTML(str, mode = DecodingMode.Legacy) { + return htmlDecoder(str, mode); +} + +const defaultDelimitersOpen = new Uint8Array([123, 123]); +const defaultDelimitersClose = new Uint8Array([125, 125]); +function isTagStartChar(c) { + return c >= 97 && c <= 122 || c >= 65 && c <= 90; +} +function isWhitespace$1(c) { + return c === 32 || c === 10 || c === 9 || c === 12 || c === 13; +} +function isEndOfTagSection(c) { + return c === 47 || c === 62 || isWhitespace$1(c); +} +function toCharCodes(str) { + const ret = new Uint8Array(str.length); + for (let i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i); + } + return ret; +} +const Sequences = { + Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]), + // CDATA[ + CdataEnd: new Uint8Array([93, 93, 62]), + // ]]> + CommentEnd: new Uint8Array([45, 45, 62]), + // `-->` + ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]), + // `<\/script` + StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]), + // `</style` + TitleEnd: new Uint8Array([60, 47, 116, 105, 116, 108, 101]), + // `</title` + TextareaEnd: new Uint8Array([ + 60, + 47, + 116, + 101, + 120, + 116, + 97, + 114, + 101, + 97 + ]) + // `</textarea +}; +let Tokenizer$1 = class Tokenizer { + constructor(stack, cbs) { + this.stack = stack; + this.cbs = cbs; + /** The current state the tokenizer is in. */ + this.state = 1; + /** The read buffer. */ + this.buffer = ""; + /** The beginning of the section that is currently being read. */ + this.sectionStart = 0; + /** The index within the buffer that we are currently looking at. */ + this.index = 0; + /** The start of the last entity. */ + this.entityStart = 0; + /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */ + this.baseState = 1; + /** For special parsing behavior inside of script and style tags. */ + this.inRCDATA = false; + /** For disabling RCDATA tags handling */ + this.inXML = false; + /** For disabling interpolation parsing in v-pre */ + this.inVPre = false; + /** Record newline positions for fast line / column calculation */ + this.newlines = []; + this.mode = 0; + this.delimiterOpen = defaultDelimitersOpen; + this.delimiterClose = defaultDelimitersClose; + this.delimiterIndex = -1; + this.currentSequence = void 0; + this.sequenceIndex = 0; + { + this.entityDecoder = new EntityDecoder( + htmlDecodeTree, + (cp, consumed) => this.emitCodePoint(cp, consumed) + ); + } + } + get inSFCRoot() { + return this.mode === 2 && this.stack.length === 0; + } + reset() { + this.state = 1; + this.mode = 0; + this.buffer = ""; + this.sectionStart = 0; + this.index = 0; + this.baseState = 1; + this.inRCDATA = false; + this.currentSequence = void 0; + this.newlines.length = 0; + this.delimiterOpen = defaultDelimitersOpen; + this.delimiterClose = defaultDelimitersClose; + } + /** + * Generate Position object with line / column information using recorded + * newline positions. We know the index is always going to be an already + * processed index, so all the newlines up to this index should have been + * recorded. + */ + getPos(index) { + let line = 1; + let column = index + 1; + for (let i = this.newlines.length - 1; i >= 0; i--) { + const newlineIndex = this.newlines[i]; + if (index > newlineIndex) { + line = i + 2; + column = index - newlineIndex; + break; + } + } + return { + column, + line, + offset: index + }; + } + peek() { + return this.buffer.charCodeAt(this.index + 1); + } + stateText(c) { + if (c === 60) { + if (this.index > this.sectionStart) { + this.cbs.ontext(this.sectionStart, this.index); + } + this.state = 5; + this.sectionStart = this.index; + } else if (c === 38) { + this.startEntity(); + } else if (!this.inVPre && c === this.delimiterOpen[0]) { + this.state = 2; + this.delimiterIndex = 0; + this.stateInterpolationOpen(c); + } + } + stateInterpolationOpen(c) { + if (c === this.delimiterOpen[this.delimiterIndex]) { + if (this.delimiterIndex === this.delimiterOpen.length - 1) { + const start = this.index + 1 - this.delimiterOpen.length; + if (start > this.sectionStart) { + this.cbs.ontext(this.sectionStart, start); + } + this.state = 3; + this.sectionStart = start; + } else { + this.delimiterIndex++; + } + } else if (this.inRCDATA) { + this.state = 32; + this.stateInRCDATA(c); + } else { + this.state = 1; + this.stateText(c); + } + } + stateInterpolation(c) { + if (c === this.delimiterClose[0]) { + this.state = 4; + this.delimiterIndex = 0; + this.stateInterpolationClose(c); + } + } + stateInterpolationClose(c) { + if (c === this.delimiterClose[this.delimiterIndex]) { + if (this.delimiterIndex === this.delimiterClose.length - 1) { + this.cbs.oninterpolation(this.sectionStart, this.index + 1); + if (this.inRCDATA) { + this.state = 32; + } else { + this.state = 1; + } + this.sectionStart = this.index + 1; + } else { + this.delimiterIndex++; + } + } else { + this.state = 3; + this.stateInterpolation(c); + } + } + stateSpecialStartSequence(c) { + const isEnd = this.sequenceIndex === this.currentSequence.length; + const isMatch = isEnd ? ( + // If we are at the end of the sequence, make sure the tag name has ended + isEndOfTagSection(c) + ) : ( + // Otherwise, do a case-insensitive comparison + (c | 32) === this.currentSequence[this.sequenceIndex] + ); + if (!isMatch) { + this.inRCDATA = false; + } else if (!isEnd) { + this.sequenceIndex++; + return; + } + this.sequenceIndex = 0; + this.state = 6; + this.stateInTagName(c); + } + /** Look for an end tag. For <title> and <textarea>, also decode entities. */ + stateInRCDATA(c) { + if (this.sequenceIndex === this.currentSequence.length) { + if (c === 62 || isWhitespace$1(c)) { + const endOfText = this.index - this.currentSequence.length; + if (this.sectionStart < endOfText) { + const actualIndex = this.index; + this.index = endOfText; + this.cbs.ontext(this.sectionStart, endOfText); + this.index = actualIndex; + } + this.sectionStart = endOfText + 2; + this.stateInClosingTagName(c); + this.inRCDATA = false; + return; + } + this.sequenceIndex = 0; + } + if ((c | 32) === this.currentSequence[this.sequenceIndex]) { + this.sequenceIndex += 1; + } else if (this.sequenceIndex === 0) { + if (this.currentSequence === Sequences.TitleEnd || this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot) { + if (c === 38) { + this.startEntity(); + } else if (c === this.delimiterOpen[0]) { + this.state = 2; + this.delimiterIndex = 0; + this.stateInterpolationOpen(c); + } + } else if (this.fastForwardTo(60)) { + this.sequenceIndex = 1; + } + } else { + this.sequenceIndex = Number(c === 60); + } + } + stateCDATASequence(c) { + if (c === Sequences.Cdata[this.sequenceIndex]) { + if (++this.sequenceIndex === Sequences.Cdata.length) { + this.state = 28; + this.currentSequence = Sequences.CdataEnd; + this.sequenceIndex = 0; + this.sectionStart = this.index + 1; + } + } else { + this.sequenceIndex = 0; + this.state = 23; + this.stateInDeclaration(c); + } + } + /** + * When we wait for one specific character, we can speed things up + * by skipping through the buffer until we find it. + * + * @returns Whether the character was found. + */ + fastForwardTo(c) { + while (++this.index < this.buffer.length) { + const cc = this.buffer.charCodeAt(this.index); + if (cc === 10) { + this.newlines.push(this.index); + } + if (cc === c) { + return true; + } + } + this.index = this.buffer.length - 1; + return false; + } + /** + * Comments and CDATA end with `-->` and `]]>`. + * + * Their common qualities are: + * - Their end sequences have a distinct character they start with. + * - That character is then repeated, so we have to check multiple repeats. + * - All characters but the start character of the sequence can be skipped. + */ + stateInCommentLike(c) { + if (c === this.currentSequence[this.sequenceIndex]) { + if (++this.sequenceIndex === this.currentSequence.length) { + if (this.currentSequence === Sequences.CdataEnd) { + this.cbs.oncdata(this.sectionStart, this.index - 2); + } else { + this.cbs.oncomment(this.sectionStart, this.index - 2); + } + this.sequenceIndex = 0; + this.sectionStart = this.index + 1; + this.state = 1; + } + } else if (this.sequenceIndex === 0) { + if (this.fastForwardTo(this.currentSequence[0])) { + this.sequenceIndex = 1; + } + } else if (c !== this.currentSequence[this.sequenceIndex - 1]) { + this.sequenceIndex = 0; + } + } + startSpecial(sequence, offset) { + this.enterRCDATA(sequence, offset); + this.state = 31; + } + enterRCDATA(sequence, offset) { + this.inRCDATA = true; + this.currentSequence = sequence; + this.sequenceIndex = offset; + } + stateBeforeTagName(c) { + if (c === 33) { + this.state = 22; + this.sectionStart = this.index + 1; + } else if (c === 63) { + this.state = 24; + this.sectionStart = this.index + 1; + } else if (isTagStartChar(c)) { + this.sectionStart = this.index; + if (this.mode === 0) { + this.state = 6; + } else if (this.inSFCRoot) { + this.state = 34; + } else if (!this.inXML) { + if (c === 116) { + this.state = 30; + } else { + this.state = c === 115 ? 29 : 6; + } + } else { + this.state = 6; + } + } else if (c === 47) { + this.state = 8; + } else { + this.state = 1; + this.stateText(c); + } + } + stateInTagName(c) { + if (isEndOfTagSection(c)) { + this.handleTagName(c); + } + } + stateInSFCRootTagName(c) { + if (isEndOfTagSection(c)) { + const tag = this.buffer.slice(this.sectionStart, this.index); + if (tag !== "template") { + this.enterRCDATA(toCharCodes(`</` + tag), 0); + } + this.handleTagName(c); + } + } + handleTagName(c) { + this.cbs.onopentagname(this.sectionStart, this.index); + this.sectionStart = -1; + this.state = 11; + this.stateBeforeAttrName(c); + } + stateBeforeClosingTagName(c) { + if (isWhitespace$1(c)) ; else if (c === 62) { + { + this.cbs.onerr(14, this.index); + } + this.state = 1; + this.sectionStart = this.index + 1; + } else { + this.state = isTagStartChar(c) ? 9 : 27; + this.sectionStart = this.index; + } + } + stateInClosingTagName(c) { + if (c === 62 || isWhitespace$1(c)) { + this.cbs.onclosetag(this.sectionStart, this.index); + this.sectionStart = -1; + this.state = 10; + this.stateAfterClosingTagName(c); + } + } + stateAfterClosingTagName(c) { + if (c === 62) { + this.state = 1; + this.sectionStart = this.index + 1; + } + } + stateBeforeAttrName(c) { + if (c === 62) { + this.cbs.onopentagend(this.index); + if (this.inRCDATA) { + this.state = 32; + } else { + this.state = 1; + } + this.sectionStart = this.index + 1; + } else if (c === 47) { + this.state = 7; + if (this.peek() !== 62) { + this.cbs.onerr(22, this.index); + } + } else if (c === 60 && this.peek() === 47) { + this.cbs.onopentagend(this.index); + this.state = 5; + this.sectionStart = this.index; + } else if (!isWhitespace$1(c)) { + if (c === 61) { + this.cbs.onerr( + 19, + this.index + ); + } + this.handleAttrStart(c); + } + } + handleAttrStart(c) { + if (c === 118 && this.peek() === 45) { + this.state = 13; + this.sectionStart = this.index; + } else if (c === 46 || c === 58 || c === 64 || c === 35) { + this.cbs.ondirname(this.index, this.index + 1); + this.state = 14; + this.sectionStart = this.index + 1; + } else { + this.state = 12; + this.sectionStart = this.index; + } + } + stateInSelfClosingTag(c) { + if (c === 62) { + this.cbs.onselfclosingtag(this.index); + this.state = 1; + this.sectionStart = this.index + 1; + this.inRCDATA = false; + } else if (!isWhitespace$1(c)) { + this.state = 11; + this.stateBeforeAttrName(c); + } + } + stateInAttrName(c) { + if (c === 61 || isEndOfTagSection(c)) { + this.cbs.onattribname(this.sectionStart, this.index); + this.handleAttrNameEnd(c); + } else if (c === 34 || c === 39 || c === 60) { + this.cbs.onerr( + 17, + this.index + ); + } + } + stateInDirName(c) { + if (c === 61 || isEndOfTagSection(c)) { + this.cbs.ondirname(this.sectionStart, this.index); + this.handleAttrNameEnd(c); + } else if (c === 58) { + this.cbs.ondirname(this.sectionStart, this.index); + this.state = 14; + this.sectionStart = this.index + 1; + } else if (c === 46) { + this.cbs.ondirname(this.sectionStart, this.index); + this.state = 16; + this.sectionStart = this.index + 1; + } + } + stateInDirArg(c) { + if (c === 61 || isEndOfTagSection(c)) { + this.cbs.ondirarg(this.sectionStart, this.index); + this.handleAttrNameEnd(c); + } else if (c === 91) { + this.state = 15; + } else if (c === 46) { + this.cbs.ondirarg(this.sectionStart, this.index); + this.state = 16; + this.sectionStart = this.index + 1; + } + } + stateInDynamicDirArg(c) { + if (c === 93) { + this.state = 14; + } else if (c === 61 || isEndOfTagSection(c)) { + this.cbs.ondirarg(this.sectionStart, this.index + 1); + this.handleAttrNameEnd(c); + { + this.cbs.onerr( + 27, + this.index + ); + } + } + } + stateInDirModifier(c) { + if (c === 61 || isEndOfTagSection(c)) { + this.cbs.ondirmodifier(this.sectionStart, this.index); + this.handleAttrNameEnd(c); + } else if (c === 46) { + this.cbs.ondirmodifier(this.sectionStart, this.index); + this.sectionStart = this.index + 1; + } + } + handleAttrNameEnd(c) { + this.sectionStart = this.index; + this.state = 17; + this.cbs.onattribnameend(this.index); + this.stateAfterAttrName(c); + } + stateAfterAttrName(c) { + if (c === 61) { + this.state = 18; + } else if (c === 47 || c === 62) { + this.cbs.onattribend(0, this.sectionStart); + this.sectionStart = -1; + this.state = 11; + this.stateBeforeAttrName(c); + } else if (!isWhitespace$1(c)) { + this.cbs.onattribend(0, this.sectionStart); + this.handleAttrStart(c); + } + } + stateBeforeAttrValue(c) { + if (c === 34) { + this.state = 19; + this.sectionStart = this.index + 1; + } else if (c === 39) { + this.state = 20; + this.sectionStart = this.index + 1; + } else if (!isWhitespace$1(c)) { + this.sectionStart = this.index; + this.state = 21; + this.stateInAttrValueNoQuotes(c); + } + } + handleInAttrValue(c, quote) { + if (c === quote || false) { + this.cbs.onattribdata(this.sectionStart, this.index); + this.sectionStart = -1; + this.cbs.onattribend( + quote === 34 ? 3 : 2, + this.index + 1 + ); + this.state = 11; + } else if (c === 38) { + this.startEntity(); + } + } + stateInAttrValueDoubleQuotes(c) { + this.handleInAttrValue(c, 34); + } + stateInAttrValueSingleQuotes(c) { + this.handleInAttrValue(c, 39); + } + stateInAttrValueNoQuotes(c) { + if (isWhitespace$1(c) || c === 62) { + this.cbs.onattribdata(this.sectionStart, this.index); + this.sectionStart = -1; + this.cbs.onattribend(1, this.index); + this.state = 11; + this.stateBeforeAttrName(c); + } else if (c === 34 || c === 39 || c === 60 || c === 61 || c === 96) { + this.cbs.onerr( + 18, + this.index + ); + } else if (c === 38) { + this.startEntity(); + } + } + stateBeforeDeclaration(c) { + if (c === 91) { + this.state = 26; + this.sequenceIndex = 0; + } else { + this.state = c === 45 ? 25 : 23; + } + } + stateInDeclaration(c) { + if (c === 62 || this.fastForwardTo(62)) { + this.state = 1; + this.sectionStart = this.index + 1; + } + } + stateInProcessingInstruction(c) { + if (c === 62 || this.fastForwardTo(62)) { + this.cbs.onprocessinginstruction(this.sectionStart, this.index); + this.state = 1; + this.sectionStart = this.index + 1; + } + } + stateBeforeComment(c) { + if (c === 45) { + this.state = 28; + this.currentSequence = Sequences.CommentEnd; + this.sequenceIndex = 2; + this.sectionStart = this.index + 1; + } else { + this.state = 23; + } + } + stateInSpecialComment(c) { + if (c === 62 || this.fastForwardTo(62)) { + this.cbs.oncomment(this.sectionStart, this.index); + this.state = 1; + this.sectionStart = this.index + 1; + } + } + stateBeforeSpecialS(c) { + if (c === Sequences.ScriptEnd[3]) { + this.startSpecial(Sequences.ScriptEnd, 4); + } else if (c === Sequences.StyleEnd[3]) { + this.startSpecial(Sequences.StyleEnd, 4); + } else { + this.state = 6; + this.stateInTagName(c); + } + } + stateBeforeSpecialT(c) { + if (c === Sequences.TitleEnd[3]) { + this.startSpecial(Sequences.TitleEnd, 4); + } else if (c === Sequences.TextareaEnd[3]) { + this.startSpecial(Sequences.TextareaEnd, 4); + } else { + this.state = 6; + this.stateInTagName(c); + } + } + startEntity() { + { + this.baseState = this.state; + this.state = 33; + this.entityStart = this.index; + this.entityDecoder.startEntity( + this.baseState === 1 || this.baseState === 32 ? DecodingMode.Legacy : DecodingMode.Attribute + ); + } + } + stateInEntity() { + { + const length = this.entityDecoder.write(this.buffer, this.index); + if (length >= 0) { + this.state = this.baseState; + if (length === 0) { + this.index = this.entityStart; + } + } else { + this.index = this.buffer.length - 1; + } + } + } + /** + * Iterates through the buffer, calling the function corresponding to the current state. + * + * States that are more likely to be hit are higher up, as a performance improvement. + */ + parse(input) { + this.buffer = input; + while (this.index < this.buffer.length) { + const c = this.buffer.charCodeAt(this.index); + if (c === 10) { + this.newlines.push(this.index); + } + switch (this.state) { + case 1: { + this.stateText(c); + break; + } + case 2: { + this.stateInterpolationOpen(c); + break; + } + case 3: { + this.stateInterpolation(c); + break; + } + case 4: { + this.stateInterpolationClose(c); + break; + } + case 31: { + this.stateSpecialStartSequence(c); + break; + } + case 32: { + this.stateInRCDATA(c); + break; + } + case 26: { + this.stateCDATASequence(c); + break; + } + case 19: { + this.stateInAttrValueDoubleQuotes(c); + break; + } + case 12: { + this.stateInAttrName(c); + break; + } + case 13: { + this.stateInDirName(c); + break; + } + case 14: { + this.stateInDirArg(c); + break; + } + case 15: { + this.stateInDynamicDirArg(c); + break; + } + case 16: { + this.stateInDirModifier(c); + break; + } + case 28: { + this.stateInCommentLike(c); + break; + } + case 27: { + this.stateInSpecialComment(c); + break; + } + case 11: { + this.stateBeforeAttrName(c); + break; + } + case 6: { + this.stateInTagName(c); + break; + } + case 34: { + this.stateInSFCRootTagName(c); + break; + } + case 9: { + this.stateInClosingTagName(c); + break; + } + case 5: { + this.stateBeforeTagName(c); + break; + } + case 17: { + this.stateAfterAttrName(c); + break; + } + case 20: { + this.stateInAttrValueSingleQuotes(c); + break; + } + case 18: { + this.stateBeforeAttrValue(c); + break; + } + case 8: { + this.stateBeforeClosingTagName(c); + break; + } + case 10: { + this.stateAfterClosingTagName(c); + break; + } + case 29: { + this.stateBeforeSpecialS(c); + break; + } + case 30: { + this.stateBeforeSpecialT(c); + break; + } + case 21: { + this.stateInAttrValueNoQuotes(c); + break; + } + case 7: { + this.stateInSelfClosingTag(c); + break; + } + case 23: { + this.stateInDeclaration(c); + break; + } + case 22: { + this.stateBeforeDeclaration(c); + break; + } + case 25: { + this.stateBeforeComment(c); + break; + } + case 24: { + this.stateInProcessingInstruction(c); + break; + } + case 33: { + this.stateInEntity(); + break; + } + } + this.index++; + } + this.cleanup(); + this.finish(); + } + /** + * Remove data that has already been consumed from the buffer. + */ + cleanup() { + if (this.sectionStart !== this.index) { + if (this.state === 1 || this.state === 32 && this.sequenceIndex === 0) { + this.cbs.ontext(this.sectionStart, this.index); + this.sectionStart = this.index; + } else if (this.state === 19 || this.state === 20 || this.state === 21) { + this.cbs.onattribdata(this.sectionStart, this.index); + this.sectionStart = this.index; + } + } + } + finish() { + if (this.state === 33) { + this.entityDecoder.end(); + this.state = this.baseState; + } + this.handleTrailingData(); + this.cbs.onend(); + } + /** Handle any trailing data. */ + handleTrailingData() { + const endIndex = this.buffer.length; + if (this.sectionStart >= endIndex) { + return; + } + if (this.state === 28) { + if (this.currentSequence === Sequences.CdataEnd) { + this.cbs.oncdata(this.sectionStart, endIndex); + } else { + this.cbs.oncomment(this.sectionStart, endIndex); + } + } else if (this.state === 6 || this.state === 11 || this.state === 18 || this.state === 17 || this.state === 12 || this.state === 13 || this.state === 14 || this.state === 15 || this.state === 16 || this.state === 20 || this.state === 19 || this.state === 21 || this.state === 9) ; else { + this.cbs.ontext(this.sectionStart, endIndex); + } + } + emitCodePoint(cp, consumed) { + { + if (this.baseState !== 1 && this.baseState !== 32) { + if (this.sectionStart < this.entityStart) { + this.cbs.onattribdata(this.sectionStart, this.entityStart); + } + this.sectionStart = this.entityStart + consumed; + this.index = this.sectionStart - 1; + this.cbs.onattribentity( + fromCodePoint(cp), + this.entityStart, + this.sectionStart + ); + } else { + if (this.sectionStart < this.entityStart) { + this.cbs.ontext(this.sectionStart, this.entityStart); + } + this.sectionStart = this.entityStart + consumed; + this.index = this.sectionStart - 1; + this.cbs.ontextentity( + fromCodePoint(cp), + this.entityStart, + this.sectionStart + ); + } + } + } +}; + +const CompilerDeprecationTypes = { + "COMPILER_IS_ON_ELEMENT": "COMPILER_IS_ON_ELEMENT", + "COMPILER_V_BIND_SYNC": "COMPILER_V_BIND_SYNC", + "COMPILER_V_BIND_OBJECT_ORDER": "COMPILER_V_BIND_OBJECT_ORDER", + "COMPILER_V_ON_NATIVE": "COMPILER_V_ON_NATIVE", + "COMPILER_V_IF_V_FOR_PRECEDENCE": "COMPILER_V_IF_V_FOR_PRECEDENCE", + "COMPILER_NATIVE_TEMPLATE": "COMPILER_NATIVE_TEMPLATE", + "COMPILER_INLINE_TEMPLATE": "COMPILER_INLINE_TEMPLATE", + "COMPILER_FILTERS": "COMPILER_FILTERS" +}; +const deprecationData = { + ["COMPILER_IS_ON_ELEMENT"]: { + message: `Platform-native elements with "is" prop will no longer be treated as components in Vue 3 unless the "is" value is explicitly prefixed with "vue:".`, + link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html` + }, + ["COMPILER_V_BIND_SYNC"]: { + message: (key) => `.sync modifier for v-bind has been removed. Use v-model with argument instead. \`v-bind:${key}.sync\` should be changed to \`v-model:${key}\`.`, + link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html` + }, + ["COMPILER_V_BIND_OBJECT_ORDER"]: { + message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript object spread: it will now overwrite an existing non-mergeable attribute that appears before v-bind in the case of conflict. To retain 2.x behavior, move v-bind to make it the first attribute. You can also suppress this warning if the usage is intended.`, + link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html` + }, + ["COMPILER_V_ON_NATIVE"]: { + message: `.native modifier for v-on has been removed as is no longer necessary.`, + link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html` + }, + ["COMPILER_V_IF_V_FOR_PRECEDENCE"]: { + message: `v-if / v-for precedence when used on the same element has changed in Vue 3: v-if now takes higher precedence and will no longer have access to v-for scope variables. It is best to avoid the ambiguity with <template> tags or use a computed property that filters v-for data source.`, + link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html` + }, + ["COMPILER_NATIVE_TEMPLATE"]: { + message: `<template> with no special directives will render as a native template element instead of its inner content in Vue 3.` + }, + ["COMPILER_INLINE_TEMPLATE"]: { + message: `"inline-template" has been removed in Vue 3.`, + link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html` + }, + ["COMPILER_FILTERS"]: { + message: `filters have been removed in Vue 3. The "|" symbol will be treated as native JavaScript bitwise OR operator. Use method calls or computed properties instead.`, + link: `https://v3-migration.vuejs.org/breaking-changes/filters.html` + } +}; +function getCompatValue(key, { compatConfig }) { + const value = compatConfig && compatConfig[key]; + if (key === "MODE") { + return value || 3; + } else { + return value; + } +} +function isCompatEnabled(key, context) { + const mode = getCompatValue("MODE", context); + const value = getCompatValue(key, context); + return mode === 3 ? value === true : value !== false; +} +function checkCompatEnabled(key, context, loc, ...args) { + const enabled = isCompatEnabled(key, context); + if (enabled) { + warnDeprecation(key, context, loc, ...args); + } + return enabled; +} +function warnDeprecation(key, context, loc, ...args) { + const val = getCompatValue(key, context); + if (val === "suppress-warning") { + return; + } + const { message, link } = deprecationData[key]; + const msg = `(deprecation ${key}) ${typeof message === "function" ? message(...args) : message}${link ? ` + Details: ${link}` : ``}`; + const err = new SyntaxError(msg); + err.code = key; + if (loc) + err.loc = loc; + context.onWarn(err); +} + +function defaultOnError(error) { + throw error; +} +function defaultOnWarn(msg) { + console.warn(`[Vue warn] ${msg.message}`); +} +function createCompilerError(code, loc, messages, additionalMessage) { + const msg = (messages || errorMessages$1)[code] + (additionalMessage || ``) ; + const error = new SyntaxError(String(msg)); + error.code = code; + error.loc = loc; + return error; +} +const ErrorCodes = { + "ABRUPT_CLOSING_OF_EMPTY_COMMENT": 0, + "0": "ABRUPT_CLOSING_OF_EMPTY_COMMENT", + "CDATA_IN_HTML_CONTENT": 1, + "1": "CDATA_IN_HTML_CONTENT", + "DUPLICATE_ATTRIBUTE": 2, + "2": "DUPLICATE_ATTRIBUTE", + "END_TAG_WITH_ATTRIBUTES": 3, + "3": "END_TAG_WITH_ATTRIBUTES", + "END_TAG_WITH_TRAILING_SOLIDUS": 4, + "4": "END_TAG_WITH_TRAILING_SOLIDUS", + "EOF_BEFORE_TAG_NAME": 5, + "5": "EOF_BEFORE_TAG_NAME", + "EOF_IN_CDATA": 6, + "6": "EOF_IN_CDATA", + "EOF_IN_COMMENT": 7, + "7": "EOF_IN_COMMENT", + "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT": 8, + "8": "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT", + "EOF_IN_TAG": 9, + "9": "EOF_IN_TAG", + "INCORRECTLY_CLOSED_COMMENT": 10, + "10": "INCORRECTLY_CLOSED_COMMENT", + "INCORRECTLY_OPENED_COMMENT": 11, + "11": "INCORRECTLY_OPENED_COMMENT", + "INVALID_FIRST_CHARACTER_OF_TAG_NAME": 12, + "12": "INVALID_FIRST_CHARACTER_OF_TAG_NAME", + "MISSING_ATTRIBUTE_VALUE": 13, + "13": "MISSING_ATTRIBUTE_VALUE", + "MISSING_END_TAG_NAME": 14, + "14": "MISSING_END_TAG_NAME", + "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES": 15, + "15": "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES", + "NESTED_COMMENT": 16, + "16": "NESTED_COMMENT", + "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME": 17, + "17": "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME", + "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE": 18, + "18": "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE", + "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME": 19, + "19": "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME", + "UNEXPECTED_NULL_CHARACTER": 20, + "20": "UNEXPECTED_NULL_CHARACTER", + "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME": 21, + "21": "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME", + "UNEXPECTED_SOLIDUS_IN_TAG": 22, + "22": "UNEXPECTED_SOLIDUS_IN_TAG", + "X_INVALID_END_TAG": 23, + "23": "X_INVALID_END_TAG", + "X_MISSING_END_TAG": 24, + "24": "X_MISSING_END_TAG", + "X_MISSING_INTERPOLATION_END": 25, + "25": "X_MISSING_INTERPOLATION_END", + "X_MISSING_DIRECTIVE_NAME": 26, + "26": "X_MISSING_DIRECTIVE_NAME", + "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END": 27, + "27": "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END", + "X_V_IF_NO_EXPRESSION": 28, + "28": "X_V_IF_NO_EXPRESSION", + "X_V_IF_SAME_KEY": 29, + "29": "X_V_IF_SAME_KEY", + "X_V_ELSE_NO_ADJACENT_IF": 30, + "30": "X_V_ELSE_NO_ADJACENT_IF", + "X_V_FOR_NO_EXPRESSION": 31, + "31": "X_V_FOR_NO_EXPRESSION", + "X_V_FOR_MALFORMED_EXPRESSION": 32, + "32": "X_V_FOR_MALFORMED_EXPRESSION", + "X_V_FOR_TEMPLATE_KEY_PLACEMENT": 33, + "33": "X_V_FOR_TEMPLATE_KEY_PLACEMENT", + "X_V_BIND_NO_EXPRESSION": 34, + "34": "X_V_BIND_NO_EXPRESSION", + "X_V_ON_NO_EXPRESSION": 35, + "35": "X_V_ON_NO_EXPRESSION", + "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET": 36, + "36": "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET", + "X_V_SLOT_MIXED_SLOT_USAGE": 37, + "37": "X_V_SLOT_MIXED_SLOT_USAGE", + "X_V_SLOT_DUPLICATE_SLOT_NAMES": 38, + "38": "X_V_SLOT_DUPLICATE_SLOT_NAMES", + "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN": 39, + "39": "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN", + "X_V_SLOT_MISPLACED": 40, + "40": "X_V_SLOT_MISPLACED", + "X_V_MODEL_NO_EXPRESSION": 41, + "41": "X_V_MODEL_NO_EXPRESSION", + "X_V_MODEL_MALFORMED_EXPRESSION": 42, + "42": "X_V_MODEL_MALFORMED_EXPRESSION", + "X_V_MODEL_ON_SCOPE_VARIABLE": 43, + "43": "X_V_MODEL_ON_SCOPE_VARIABLE", + "X_V_MODEL_ON_PROPS": 44, + "44": "X_V_MODEL_ON_PROPS", + "X_INVALID_EXPRESSION": 45, + "45": "X_INVALID_EXPRESSION", + "X_KEEP_ALIVE_INVALID_CHILDREN": 46, + "46": "X_KEEP_ALIVE_INVALID_CHILDREN", + "X_PREFIX_ID_NOT_SUPPORTED": 47, + "47": "X_PREFIX_ID_NOT_SUPPORTED", + "X_MODULE_MODE_NOT_SUPPORTED": 48, + "48": "X_MODULE_MODE_NOT_SUPPORTED", + "X_CACHE_HANDLER_NOT_SUPPORTED": 49, + "49": "X_CACHE_HANDLER_NOT_SUPPORTED", + "X_SCOPE_ID_NOT_SUPPORTED": 50, + "50": "X_SCOPE_ID_NOT_SUPPORTED", + "X_VNODE_HOOKS": 51, + "51": "X_VNODE_HOOKS", + "X_V_BIND_INVALID_SAME_NAME_ARGUMENT": 52, + "52": "X_V_BIND_INVALID_SAME_NAME_ARGUMENT", + "__EXTEND_POINT__": 53, + "53": "__EXTEND_POINT__" +}; +const errorMessages$1 = { + // parse errors + [0]: "Illegal comment.", + [1]: "CDATA section is allowed only in XML context.", + [2]: "Duplicate attribute.", + [3]: "End tag cannot have attributes.", + [4]: "Illegal '/' in tags.", + [5]: "Unexpected EOF in tag.", + [6]: "Unexpected EOF in CDATA section.", + [7]: "Unexpected EOF in comment.", + [8]: "Unexpected EOF in script.", + [9]: "Unexpected EOF in tag.", + [10]: "Incorrectly closed comment.", + [11]: "Incorrectly opened comment.", + [12]: "Illegal tag name. Use '<' to print '<'.", + [13]: "Attribute value was expected.", + [14]: "End tag name was expected.", + [15]: "Whitespace was expected.", + [16]: "Unexpected '<!--' in comment.", + [17]: `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<).`, + [18]: "Unquoted attribute value cannot contain U+0022 (\"), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).", + [19]: "Attribute name cannot start with '='.", + [21]: "'<?' is allowed only in XML context.", + [20]: `Unexpected null character.`, + [22]: "Illegal '/' in tags.", + // Vue-specific parse errors + [23]: "Invalid end tag.", + [24]: "Element is missing end tag.", + [25]: "Interpolation end sign was not found.", + [27]: "End bracket for dynamic directive argument was not found. Note that dynamic directive argument cannot contain spaces.", + [26]: "Legal directive name was expected.", + // transform errors + [28]: `v-if/v-else-if is missing expression.`, + [29]: `v-if/else branches must use unique keys.`, + [30]: `v-else/v-else-if has no adjacent v-if or v-else-if.`, + [31]: `v-for is missing expression.`, + [32]: `v-for has invalid expression.`, + [33]: `<template v-for> key should be placed on the <template> tag.`, + [34]: `v-bind is missing expression.`, + [52]: `v-bind with same-name shorthand only allows static argument.`, + [35]: `v-on is missing expression.`, + [36]: `Unexpected custom directive on <slot> outlet.`, + [37]: `Mixed v-slot usage on both the component and nested <template>. When there are multiple named slots, all slots should use <template> syntax to avoid scope ambiguity.`, + [38]: `Duplicate slot names found. `, + [39]: `Extraneous children found when component already has explicitly named default slot. These children will be ignored.`, + [40]: `v-slot can only be used on components or <template> tags.`, + [41]: `v-model is missing expression.`, + [42]: `v-model value must be a valid JavaScript member expression.`, + [43]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`, + [44]: `v-model cannot be used on a prop, because local prop bindings are not writable. +Use a v-bind binding combined with a v-on listener that emits update:x event instead.`, + [45]: `Error parsing JavaScript expression: `, + [46]: `<KeepAlive> expects exactly one child component.`, + [51]: `@vnode-* hooks in templates are no longer supported. Use the vue: prefix instead. For example, @vnode-mounted should be changed to @vue:mounted. @vnode-* hooks support has been removed in 3.4.`, + // generic errors + [47]: `"prefixIdentifiers" option is not supported in this build of compiler.`, + [48]: `ES module mode is not supported in this build of compiler.`, + [49]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`, + [50]: `"scopeId" option is only supported in module mode.`, + // just to fulfill types + [53]: `` +}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var lib = {}; + +Object.defineProperty(lib, '__esModule', { + value: true +}); +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + return target; +} +class Position { + constructor(line, col, index) { + this.line = void 0; + this.column = void 0; + this.index = void 0; + this.line = line; + this.column = col; + this.index = index; + } +} +class SourceLocation { + constructor(start, end) { + this.start = void 0; + this.end = void 0; + this.filename = void 0; + this.identifierName = void 0; + this.start = start; + this.end = end; + } +} +function createPositionWithColumnOffset(position, columnOffset) { + const { + line, + column, + index + } = position; + return new Position(line, column + columnOffset, index + columnOffset); +} +const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"; +var ModuleErrors = { + ImportMetaOutsideModule: { + message: `import.meta may appear only with 'sourceType: "module"'`, + code + }, + ImportOutsideModule: { + message: `'import' and 'export' may appear only with 'sourceType: "module"'`, + code + } +}; +const NodeDescriptions = { + ArrayPattern: "array destructuring pattern", + AssignmentExpression: "assignment expression", + AssignmentPattern: "assignment expression", + ArrowFunctionExpression: "arrow function expression", + ConditionalExpression: "conditional expression", + CatchClause: "catch clause", + ForOfStatement: "for-of statement", + ForInStatement: "for-in statement", + ForStatement: "for-loop", + FormalParameters: "function parameter list", + Identifier: "identifier", + ImportSpecifier: "import specifier", + ImportDefaultSpecifier: "import default specifier", + ImportNamespaceSpecifier: "import namespace specifier", + ObjectPattern: "object destructuring pattern", + ParenthesizedExpression: "parenthesized expression", + RestElement: "rest element", + UpdateExpression: { + true: "prefix operation", + false: "postfix operation" + }, + VariableDeclarator: "variable declaration", + YieldExpression: "yield expression" +}; +const toNodeDescription = ({ + type, + prefix +}) => type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[String(prefix)] : NodeDescriptions[type]; +var StandardErrors = { + AccessorIsGenerator: ({ + kind + }) => `A ${kind}ter cannot be a generator.`, + ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", + AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", + AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", + AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", + AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", + AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.", + AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", + AwaitNotInAsyncFunction: "'await' is only allowed within async functions.", + BadGetterArity: "A 'get' accessor must not have any formal parameters.", + BadSetterArity: "A 'set' accessor must have exactly one formal parameter.", + BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.", + ConstructorClassField: "Classes may not have a field named 'constructor'.", + ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", + ConstructorIsAccessor: "Class constructor may not be an accessor.", + ConstructorIsAsync: "Constructor can't be an async function.", + ConstructorIsGenerator: "Constructor can't be a generator.", + DeclarationMissingInitializer: ({ + kind + }) => `Missing initializer in ${kind} declaration.`, + DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.", + DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.", + DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.", + DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", + DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.", + DecoratorSemicolon: "Decorators must not be followed by a semicolon.", + DecoratorStaticBlock: "Decorators can't be used with a static block.", + DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.', + DeletePrivateField: "Deleting a private field is not allowed.", + DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", + DuplicateConstructor: "Duplicate constructor in the same class.", + DuplicateDefaultExport: "Only one default export allowed per module.", + DuplicateExport: ({ + exportName + }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`, + DuplicateProto: "Redefinition of __proto__ property.", + DuplicateRegExpFlags: "Duplicate regular expression flag.", + DynamicImportPhaseRequiresImportExpressions: ({ + phase + }) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`, + ElementAfterRest: "Rest element must be last element.", + EscapedCharNotAnIdentifier: "Invalid Unicode escape.", + ExportBindingIsString: ({ + localName, + exportName + }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`, + ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", + ForInOfLoopInitializer: ({ + type + }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`, + ForInUsing: "For-in loop may not start with 'using' declaration.", + ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", + ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", + GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", + IllegalBreakContinue: ({ + type + }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`, + IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", + IllegalReturn: "'return' outside of function.", + ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedAssertSyntax: true` option in the import attributes plugin to suppress this error.", + ImportBindingIsString: ({ + importName + }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`, + ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.", + ImportCallArity: ({ + maxArgumentCount + }) => `\`import()\` requires exactly ${maxArgumentCount === 1 ? "one argument" : "one or two arguments"}.`, + ImportCallNotNewExpression: "Cannot use new with import(...).", + ImportCallSpreadArgument: "`...` is not allowed in `import()`.", + ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.", + ImportReflectionHasAssertion: "`import module x` cannot have assertions.", + ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.', + IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.", + InvalidBigIntLiteral: "Invalid BigIntLiteral.", + InvalidCodePoint: "Code point out of bounds.", + InvalidCoverInitializedName: "Invalid shorthand property initializer.", + InvalidDecimal: "Invalid decimal.", + InvalidDigit: ({ + radix + }) => `Expected number in radix ${radix}.`, + InvalidEscapeSequence: "Bad character escape sequence.", + InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", + InvalidEscapedReservedWord: ({ + reservedWord + }) => `Escape sequence in keyword ${reservedWord}.`, + InvalidIdentifier: ({ + identifierName + }) => `Invalid identifier ${identifierName}.`, + InvalidLhs: ({ + ancestor + }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsBinding: ({ + ancestor + }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`, + InvalidLhsOptionalChaining: ({ + ancestor + }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`, + InvalidNumber: "Invalid number.", + InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", + InvalidOrUnexpectedToken: ({ + unexpected + }) => `Unexpected character '${unexpected}'.`, + InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", + InvalidPrivateFieldResolution: ({ + identifierName + }) => `Private name #${identifierName} is not defined.`, + InvalidPropertyBindingPattern: "Binding member expression.", + InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.", + InvalidRestAssignmentPattern: "Invalid rest operator's argument.", + LabelRedeclaration: ({ + labelName + }) => `Label '${labelName}' is already declared.`, + LetInLexicalBinding: "'let' is disallowed as a lexically bound name.", + LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", + MalformedRegExpFlags: "Invalid regular expression flag.", + MissingClassName: "A class name is required.", + MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", + MissingSemicolon: "Missing semicolon.", + MissingPlugin: ({ + missingPlugin + }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingOneOfPlugins: ({ + missingPlugin + }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`, + MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", + MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", + ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.", + ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", + ModuleAttributesWithDuplicateKeys: ({ + key + }) => `Duplicate key "${key}" is not allowed in module attributes.`, + ModuleExportNameHasLoneSurrogate: ({ + surrogateCharCode + }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`, + ModuleExportUndefined: ({ + localName + }) => `Export '${localName}' is not defined.`, + MultipleDefaultsInSwitch: "Multiple default clauses.", + NewlineAfterThrow: "Illegal newline after throw.", + NoCatchOrFinally: "Missing catch or finally clause.", + NumberIdentifier: "Identifier directly after number.", + NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", + ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", + OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", + OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", + OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", + ParamDupe: "Argument name clash.", + PatternHasAccessor: "Object pattern can't contain getter or setter.", + PatternHasMethod: "Object pattern can't contain methods.", + PrivateInExpectedIn: ({ + identifierName + }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`, + PrivateNameRedeclaration: ({ + identifierName + }) => `Duplicate private name #${identifierName}.`, + RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + RecordNoProto: "'__proto__' is not allowed in Record expressions.", + RestTrailingComma: "Unexpected trailing comma after rest element.", + SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.", + SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", + SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.', + StaticPrototype: "Classes may not have static property named prototype.", + SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", + SuperPrivateField: "Private fields can't be accessed on super.", + TrailingDecorator: "Decorators must be attached to a class element.", + TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", + TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", + UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", + UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.', + UnexpectedDigitAfterHash: "Unexpected digit after hash token.", + UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", + UnexpectedKeyword: ({ + keyword + }) => `Unexpected keyword '${keyword}'.`, + UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", + UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", + UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", + UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", + UnexpectedPrivateField: "Unexpected private name.", + UnexpectedReservedWord: ({ + reservedWord + }) => `Unexpected reserved word '${reservedWord}'.`, + UnexpectedSuper: "'super' is only allowed in object methods and classes.", + UnexpectedToken: ({ + expected, + unexpected + }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`, + UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", + UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.", + UnsupportedBind: "Binding should be performed on object property.", + UnsupportedDecoratorExport: "A decorated export must export a class declaration.", + UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", + UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", + UnsupportedMetaProperty: ({ + target, + onlyValidPropertyName + }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`, + UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", + UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", + UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", + UnterminatedComment: "Unterminated comment.", + UnterminatedRegExp: "Unterminated regular expression.", + UnterminatedString: "Unterminated string constant.", + UnterminatedTemplate: "Unterminated template.", + UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", + VarRedeclaration: ({ + identifierName + }) => `Identifier '${identifierName}' has already been declared.`, + YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", + YieldInParameter: "Yield expression is not allowed in formal parameters.", + ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." +}; +var StrictModeErrors = { + StrictDelete: "Deleting local variable in strict mode.", + StrictEvalArguments: ({ + referenceName + }) => `Assigning to '${referenceName}' in strict mode.`, + StrictEvalArgumentsBinding: ({ + bindingName + }) => `Binding '${bindingName}' in strict mode.`, + StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", + StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", + StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", + StrictWith: "'with' in strict mode." +}; +const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); +var PipelineOperatorErrors = { + PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.", + PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', + PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", + PipeTopicUnconfiguredToken: ({ + token + }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`, + PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", + PipeUnparenthesizedBody: ({ + type + }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({ + type + })}; please wrap it in parentheses.`, + PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.', + PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.", + PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.", + PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.", + PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.", + PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.' +}; +const _excluded = ["toMessage"], + _excluded2 = ["message"]; +function defineHidden(obj, key, value) { + Object.defineProperty(obj, key, { + enumerable: false, + configurable: true, + value + }); +} +function toParseErrorConstructor(_ref) { + let { + toMessage + } = _ref, + properties = _objectWithoutPropertiesLoose(_ref, _excluded); + return function constructor(loc, details) { + const error = new SyntaxError(); + Object.assign(error, properties, { + loc, + pos: loc.index + }); + if ("missingPlugin" in details) { + Object.assign(error, { + missingPlugin: details.missingPlugin + }); + } + defineHidden(error, "clone", function clone(overrides = {}) { + var _overrides$loc; + const { + line, + column, + index + } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc; + return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details)); + }); + defineHidden(error, "details", details); + Object.defineProperty(error, "message", { + configurable: true, + get() { + const message = `${toMessage(details)} (${loc.line}:${loc.column})`; + this.message = message; + return message; + }, + set(value) { + Object.defineProperty(this, "message", { + value, + writable: true + }); + } + }); + return error; + }; +} +function ParseErrorEnum(argument, syntaxPlugin) { + if (Array.isArray(argument)) { + return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]); + } + const ParseErrorConstructors = {}; + for (const reasonCode of Object.keys(argument)) { + const template = argument[reasonCode]; + const _ref2 = typeof template === "string" ? { + message: () => template + } : typeof template === "function" ? { + message: template + } : template, + { + message + } = _ref2, + rest = _objectWithoutPropertiesLoose(_ref2, _excluded2); + const toMessage = typeof message === "string" ? () => message : message; + ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({ + code: "BABEL_PARSER_SYNTAX_ERROR", + reasonCode, + toMessage + }, syntaxPlugin ? { + syntaxPlugin + } : {}, rest)); + } + return ParseErrorConstructors; +} +const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors)); +const { + defineProperty +} = Object; +const toUnenumerable = (object, key) => defineProperty(object, key, { + enumerable: false, + value: object[key] +}); +function toESTreeLocation(node) { + node.loc.start && toUnenumerable(node.loc.start, "index"); + node.loc.end && toUnenumerable(node.loc.end, "index"); + return node; +} +var estree = superClass => class ESTreeParserMixin extends superClass { + parse() { + const file = toESTreeLocation(super.parse()); + if (this.options.tokens) { + file.tokens = file.tokens.map(toESTreeLocation); + } + return file; + } + parseRegExpLiteral({ + pattern, + flags + }) { + let regex = null; + try { + regex = new RegExp(pattern, flags); + } catch (e) {} + const node = this.estreeParseLiteral(regex); + node.regex = { + pattern, + flags + }; + return node; + } + parseBigIntLiteral(value) { + let bigInt; + try { + bigInt = BigInt(value); + } catch (_unused) { + bigInt = null; + } + const node = this.estreeParseLiteral(bigInt); + node.bigint = String(node.value || value); + return node; + } + parseDecimalLiteral(value) { + const decimal = null; + const node = this.estreeParseLiteral(decimal); + node.decimal = String(node.value || value); + return node; + } + estreeParseLiteral(value) { + return this.parseLiteral(value, "Literal"); + } + parseStringLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNumericLiteral(value) { + return this.estreeParseLiteral(value); + } + parseNullLiteral() { + return this.estreeParseLiteral(null); + } + parseBooleanLiteral(value) { + return this.estreeParseLiteral(value); + } + directiveToStmt(directive) { + const expression = directive.value; + delete directive.value; + expression.type = "Literal"; + expression.raw = expression.extra.raw; + expression.value = expression.extra.expressionValue; + const stmt = directive; + stmt.type = "ExpressionStatement"; + stmt.expression = expression; + stmt.directive = expression.extra.rawValue; + delete expression.extra; + return stmt; + } + initFunction(node, isAsync) { + super.initFunction(node, isAsync); + node.expression = false; + } + checkDeclaration(node) { + if (node != null && this.isObjectProperty(node)) { + this.checkDeclaration(node.value); + } else { + super.checkDeclaration(node); + } + } + getObjectOrClassMethodParams(method) { + return method.value.params; + } + isValidDirective(stmt) { + var _stmt$expression$extr; + return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized); + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse); + const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); + node.body = directiveStatements.concat(node.body); + delete node.directives; + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true); + if (method.typeParameters) { + method.value.typeParameters = method.typeParameters; + delete method.typeParameters; + } + classBody.body.push(method); + } + parsePrivateName() { + const node = super.parsePrivateName(); + { + if (!this.getPluginOption("estree", "classFeatures")) { + return node; + } + } + return this.convertPrivateNameToPrivateIdentifier(node); + } + convertPrivateNameToPrivateIdentifier(node) { + const name = super.getPrivateNameSV(node); + node = node; + delete node.id; + node.name = name; + node.type = "PrivateIdentifier"; + return node; + } + isPrivateName(node) { + { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.isPrivateName(node); + } + } + return node.type === "PrivateIdentifier"; + } + getPrivateNameSV(node) { + { + if (!this.getPluginOption("estree", "classFeatures")) { + return super.getPrivateNameSV(node); + } + } + return node.name; + } + parseLiteral(value, type) { + const node = super.parseLiteral(value, type); + node.raw = node.extra.raw; + delete node.extra; + return node; + } + parseFunctionBody(node, allowExpression, isMethod = false) { + super.parseFunctionBody(node, allowExpression, isMethod); + node.expression = node.body.type !== "BlockStatement"; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + let funcNode = this.startNode(); + funcNode.kind = node.kind; + funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + funcNode.type = "FunctionExpression"; + delete funcNode.kind; + node.value = funcNode; + if (type === "ClassPrivateMethod") { + node.computed = false; + } + return this.finishNode(node, "MethodDefinition"); + } + parseClassProperty(...args) { + const propertyNode = super.parseClassProperty(...args); + { + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + } + propertyNode.type = "PropertyDefinition"; + return propertyNode; + } + parseClassPrivateProperty(...args) { + const propertyNode = super.parseClassPrivateProperty(...args); + { + if (!this.getPluginOption("estree", "classFeatures")) { + return propertyNode; + } + } + propertyNode.type = "PropertyDefinition"; + propertyNode.computed = false; + return propertyNode; + } + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor); + if (node) { + node.type = "Property"; + if (node.kind === "method") { + node.kind = "init"; + } + node.shorthand = false; + } + return node; + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (node) { + node.kind = "init"; + node.type = "Property"; + } + return node; + } + isValidLVal(type, isUnparenthesizedInAssign, binding) { + return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding); + } + isAssignable(node, isBinding) { + if (node != null && this.isObjectProperty(node)) { + return this.isAssignable(node.value, isBinding); + } + return super.isAssignable(node, isBinding); + } + toAssignable(node, isLHS = false) { + if (node != null && this.isObjectProperty(node)) { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + } else { + super.toAssignable(node, isLHS); + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.kind === "get" || prop.kind === "set") { + this.raise(Errors.PatternHasAccessor, prop.key); + } else if (prop.method) { + this.raise(Errors.PatternHasMethod, prop.key); + } else { + super.toAssignableObjectExpressionProp(prop, isLast, isLHS); + } + } + finishCallExpression(unfinished, optional) { + const node = super.finishCallExpression(unfinished, optional); + if (node.callee.type === "Import") { + node.type = "ImportExpression"; + node.source = node.arguments[0]; + if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { + var _node$arguments$, _node$arguments$2; + node.options = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null; + node.attributes = (_node$arguments$2 = node.arguments[1]) != null ? _node$arguments$2 : null; + } + delete node.arguments; + delete node.callee; + } + return node; + } + toReferencedArguments(node) { + if (node.type === "ImportExpression") { + return; + } + super.toReferencedArguments(node); + } + parseExport(unfinished, decorators) { + const exportStartLoc = this.state.lastTokStartLoc; + const node = super.parseExport(unfinished, decorators); + switch (node.type) { + case "ExportAllDeclaration": + node.exported = null; + break; + case "ExportNamedDeclaration": + if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { + node.type = "ExportAllDeclaration"; + node.exported = node.specifiers[0].exported; + delete node.specifiers; + } + case "ExportDefaultDeclaration": + { + var _declaration$decorato; + const { + declaration + } = node; + if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) { + this.resetStartLocation(node, exportStartLoc); + } + } + break; + } + return node; + } + parseSubscript(base, startLoc, noCalls, state) { + const node = super.parseSubscript(base, startLoc, noCalls, state); + if (state.optionalChainMember) { + if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") { + node.type = node.type.substring(8); + } + if (state.stop) { + const chain = this.startNodeAtNode(node); + chain.expression = node; + return this.finishNode(chain, "ChainExpression"); + } + } else if (node.type === "MemberExpression" || node.type === "CallExpression") { + node.optional = false; + } + return node; + } + isOptionalMemberExpression(node) { + if (node.type === "ChainExpression") { + return node.expression.type === "MemberExpression"; + } + return super.isOptionalMemberExpression(node); + } + hasPropertyAsPrivateName(node) { + if (node.type === "ChainExpression") { + node = node.expression; + } + return super.hasPropertyAsPrivateName(node); + } + isObjectProperty(node) { + return node.type === "Property" && node.kind === "init" && !node.method; + } + isObjectMethod(node) { + return node.method || node.kind === "get" || node.kind === "set"; + } + finishNodeAt(node, type, endLoc) { + return toESTreeLocation(super.finishNodeAt(node, type, endLoc)); + } + resetStartLocation(node, startLoc) { + super.resetStartLocation(node, startLoc); + toESTreeLocation(node); + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + super.resetEndLocation(node, endLoc); + toESTreeLocation(node); + } +}; +class TokContext { + constructor(token, preserveSpace) { + this.token = void 0; + this.preserveSpace = void 0; + this.token = token; + this.preserveSpace = !!preserveSpace; + } +} +const types$1 = { + brace: new TokContext("{"), + j_oTag: new TokContext("<tag"), + j_cTag: new TokContext("</tag"), + j_expr: new TokContext("<tag>...</tag>", true) +}; +{ + types$1.template = new TokContext("`", true); +} +const beforeExpr = true; +const startsExpr = true; +const isLoop = true; +const isAssign = true; +const prefix = true; +const postfix = true; +class ExportedTokenType { + constructor(label, conf = {}) { + this.label = void 0; + this.keyword = void 0; + this.beforeExpr = void 0; + this.startsExpr = void 0; + this.rightAssociative = void 0; + this.isLoop = void 0; + this.isAssign = void 0; + this.prefix = void 0; + this.postfix = void 0; + this.binop = void 0; + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.rightAssociative = !!conf.rightAssociative; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop != null ? conf.binop : null; + { + this.updateContext = null; + } + } +} +const keywords$1 = new Map(); +function createKeyword(name, options = {}) { + options.keyword = name; + const token = createToken(name, options); + keywords$1.set(name, token); + return token; +} +function createBinop(name, binop) { + return createToken(name, { + beforeExpr, + binop + }); +} +let tokenTypeCounter = -1; +const tokenTypes$1 = []; +const tokenLabels = []; +const tokenBinops = []; +const tokenBeforeExprs = []; +const tokenStartsExprs = []; +const tokenPrefixes = []; +function createToken(name, options = {}) { + var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix; + ++tokenTypeCounter; + tokenLabels.push(name); + tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1); + tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false); + tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false); + tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false); + tokenTypes$1.push(new ExportedTokenType(name, options)); + return tokenTypeCounter; +} +function createKeywordLike(name, options = {}) { + var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2; + ++tokenTypeCounter; + keywords$1.set(name, tokenTypeCounter); + tokenLabels.push(name); + tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1); + tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false); + tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false); + tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false); + tokenTypes$1.push(new ExportedTokenType("name", options)); + return tokenTypeCounter; +} +const tt = { + bracketL: createToken("[", { + beforeExpr, + startsExpr + }), + bracketHashL: createToken("#[", { + beforeExpr, + startsExpr + }), + bracketBarL: createToken("[|", { + beforeExpr, + startsExpr + }), + bracketR: createToken("]"), + bracketBarR: createToken("|]"), + braceL: createToken("{", { + beforeExpr, + startsExpr + }), + braceBarL: createToken("{|", { + beforeExpr, + startsExpr + }), + braceHashL: createToken("#{", { + beforeExpr, + startsExpr + }), + braceR: createToken("}"), + braceBarR: createToken("|}"), + parenL: createToken("(", { + beforeExpr, + startsExpr + }), + parenR: createToken(")"), + comma: createToken(",", { + beforeExpr + }), + semi: createToken(";", { + beforeExpr + }), + colon: createToken(":", { + beforeExpr + }), + doubleColon: createToken("::", { + beforeExpr + }), + dot: createToken("."), + question: createToken("?", { + beforeExpr + }), + questionDot: createToken("?."), + arrow: createToken("=>", { + beforeExpr + }), + template: createToken("template"), + ellipsis: createToken("...", { + beforeExpr + }), + backQuote: createToken("`", { + startsExpr + }), + dollarBraceL: createToken("${", { + beforeExpr, + startsExpr + }), + templateTail: createToken("...`", { + startsExpr + }), + templateNonTail: createToken("...${", { + beforeExpr, + startsExpr + }), + at: createToken("@"), + hash: createToken("#", { + startsExpr + }), + interpreterDirective: createToken("#!..."), + eq: createToken("=", { + beforeExpr, + isAssign + }), + assign: createToken("_=", { + beforeExpr, + isAssign + }), + slashAssign: createToken("_=", { + beforeExpr, + isAssign + }), + xorAssign: createToken("_=", { + beforeExpr, + isAssign + }), + moduloAssign: createToken("_=", { + beforeExpr, + isAssign + }), + incDec: createToken("++/--", { + prefix, + postfix, + startsExpr + }), + bang: createToken("!", { + beforeExpr, + prefix, + startsExpr + }), + tilde: createToken("~", { + beforeExpr, + prefix, + startsExpr + }), + doubleCaret: createToken("^^", { + startsExpr + }), + doubleAt: createToken("@@", { + startsExpr + }), + pipeline: createBinop("|>", 0), + nullishCoalescing: createBinop("??", 1), + logicalOR: createBinop("||", 1), + logicalAND: createBinop("&&", 2), + bitwiseOR: createBinop("|", 3), + bitwiseXOR: createBinop("^", 4), + bitwiseAND: createBinop("&", 5), + equality: createBinop("==/!=/===/!==", 6), + lt: createBinop("</>/<=/>=", 7), + gt: createBinop("</>/<=/>=", 7), + relational: createBinop("</>/<=/>=", 7), + bitShift: createBinop("<</>>/>>>", 8), + bitShiftL: createBinop("<</>>/>>>", 8), + bitShiftR: createBinop("<</>>/>>>", 8), + plusMin: createToken("+/-", { + beforeExpr, + binop: 9, + prefix, + startsExpr + }), + modulo: createToken("%", { + binop: 10, + startsExpr + }), + star: createToken("*", { + binop: 10 + }), + slash: createBinop("/", 10), + exponent: createToken("**", { + beforeExpr, + binop: 11, + rightAssociative: true + }), + _in: createKeyword("in", { + beforeExpr, + binop: 7 + }), + _instanceof: createKeyword("instanceof", { + beforeExpr, + binop: 7 + }), + _break: createKeyword("break"), + _case: createKeyword("case", { + beforeExpr + }), + _catch: createKeyword("catch"), + _continue: createKeyword("continue"), + _debugger: createKeyword("debugger"), + _default: createKeyword("default", { + beforeExpr + }), + _else: createKeyword("else", { + beforeExpr + }), + _finally: createKeyword("finally"), + _function: createKeyword("function", { + startsExpr + }), + _if: createKeyword("if"), + _return: createKeyword("return", { + beforeExpr + }), + _switch: createKeyword("switch"), + _throw: createKeyword("throw", { + beforeExpr, + prefix, + startsExpr + }), + _try: createKeyword("try"), + _var: createKeyword("var"), + _const: createKeyword("const"), + _with: createKeyword("with"), + _new: createKeyword("new", { + beforeExpr, + startsExpr + }), + _this: createKeyword("this", { + startsExpr + }), + _super: createKeyword("super", { + startsExpr + }), + _class: createKeyword("class", { + startsExpr + }), + _extends: createKeyword("extends", { + beforeExpr + }), + _export: createKeyword("export"), + _import: createKeyword("import", { + startsExpr + }), + _null: createKeyword("null", { + startsExpr + }), + _true: createKeyword("true", { + startsExpr + }), + _false: createKeyword("false", { + startsExpr + }), + _typeof: createKeyword("typeof", { + beforeExpr, + prefix, + startsExpr + }), + _void: createKeyword("void", { + beforeExpr, + prefix, + startsExpr + }), + _delete: createKeyword("delete", { + beforeExpr, + prefix, + startsExpr + }), + _do: createKeyword("do", { + isLoop, + beforeExpr + }), + _for: createKeyword("for", { + isLoop + }), + _while: createKeyword("while", { + isLoop + }), + _as: createKeywordLike("as", { + startsExpr + }), + _assert: createKeywordLike("assert", { + startsExpr + }), + _async: createKeywordLike("async", { + startsExpr + }), + _await: createKeywordLike("await", { + startsExpr + }), + _defer: createKeywordLike("defer", { + startsExpr + }), + _from: createKeywordLike("from", { + startsExpr + }), + _get: createKeywordLike("get", { + startsExpr + }), + _let: createKeywordLike("let", { + startsExpr + }), + _meta: createKeywordLike("meta", { + startsExpr + }), + _of: createKeywordLike("of", { + startsExpr + }), + _sent: createKeywordLike("sent", { + startsExpr + }), + _set: createKeywordLike("set", { + startsExpr + }), + _source: createKeywordLike("source", { + startsExpr + }), + _static: createKeywordLike("static", { + startsExpr + }), + _using: createKeywordLike("using", { + startsExpr + }), + _yield: createKeywordLike("yield", { + startsExpr + }), + _asserts: createKeywordLike("asserts", { + startsExpr + }), + _checks: createKeywordLike("checks", { + startsExpr + }), + _exports: createKeywordLike("exports", { + startsExpr + }), + _global: createKeywordLike("global", { + startsExpr + }), + _implements: createKeywordLike("implements", { + startsExpr + }), + _intrinsic: createKeywordLike("intrinsic", { + startsExpr + }), + _infer: createKeywordLike("infer", { + startsExpr + }), + _is: createKeywordLike("is", { + startsExpr + }), + _mixins: createKeywordLike("mixins", { + startsExpr + }), + _proto: createKeywordLike("proto", { + startsExpr + }), + _require: createKeywordLike("require", { + startsExpr + }), + _satisfies: createKeywordLike("satisfies", { + startsExpr + }), + _keyof: createKeywordLike("keyof", { + startsExpr + }), + _readonly: createKeywordLike("readonly", { + startsExpr + }), + _unique: createKeywordLike("unique", { + startsExpr + }), + _abstract: createKeywordLike("abstract", { + startsExpr + }), + _declare: createKeywordLike("declare", { + startsExpr + }), + _enum: createKeywordLike("enum", { + startsExpr + }), + _module: createKeywordLike("module", { + startsExpr + }), + _namespace: createKeywordLike("namespace", { + startsExpr + }), + _interface: createKeywordLike("interface", { + startsExpr + }), + _type: createKeywordLike("type", { + startsExpr + }), + _opaque: createKeywordLike("opaque", { + startsExpr + }), + name: createToken("name", { + startsExpr + }), + string: createToken("string", { + startsExpr + }), + num: createToken("num", { + startsExpr + }), + bigint: createToken("bigint", { + startsExpr + }), + decimal: createToken("decimal", { + startsExpr + }), + regexp: createToken("regexp", { + startsExpr + }), + privateName: createToken("#name", { + startsExpr + }), + eof: createToken("eof"), + jsxName: createToken("jsxName"), + jsxText: createToken("jsxText", { + beforeExpr: true + }), + jsxTagStart: createToken("jsxTagStart", { + startsExpr: true + }), + jsxTagEnd: createToken("jsxTagEnd"), + placeholder: createToken("%%", { + startsExpr: true + }) +}; +function tokenIsIdentifier(token) { + return token >= 93 && token <= 132; +} +function tokenKeywordOrIdentifierIsKeyword(token) { + return token <= 92; +} +function tokenIsKeywordOrIdentifier(token) { + return token >= 58 && token <= 132; +} +function tokenIsLiteralPropertyName(token) { + return token >= 58 && token <= 136; +} +function tokenComesBeforeExpression(token) { + return tokenBeforeExprs[token]; +} +function tokenCanStartExpression(token) { + return tokenStartsExprs[token]; +} +function tokenIsAssignment(token) { + return token >= 29 && token <= 33; +} +function tokenIsFlowInterfaceOrTypeOrOpaque(token) { + return token >= 129 && token <= 131; +} +function tokenIsLoop(token) { + return token >= 90 && token <= 92; +} +function tokenIsKeyword(token) { + return token >= 58 && token <= 92; +} +function tokenIsOperator(token) { + return token >= 39 && token <= 59; +} +function tokenIsPostfix(token) { + return token === 34; +} +function tokenIsPrefix(token) { + return tokenPrefixes[token]; +} +function tokenIsTSTypeOperator(token) { + return token >= 121 && token <= 123; +} +function tokenIsTSDeclarationStart(token) { + return token >= 124 && token <= 130; +} +function tokenLabelName(token) { + return tokenLabels[token]; +} +function tokenOperatorPrecedence(token) { + return tokenBinops[token]; +} +function tokenIsRightAssociative(token) { + return token === 57; +} +function tokenIsTemplate(token) { + return token >= 24 && token <= 25; +} +function getExportedToken(token) { + return tokenTypes$1[token]; +} +{ + tokenTypes$1[8].updateContext = context => { + context.pop(); + }; + tokenTypes$1[5].updateContext = tokenTypes$1[7].updateContext = tokenTypes$1[23].updateContext = context => { + context.push(types$1.brace); + }; + tokenTypes$1[22].updateContext = context => { + if (context[context.length - 1] === types$1.template) { + context.pop(); + } else { + context.push(types$1.template); + } + }; + tokenTypes$1[142].updateContext = context => { + context.push(types$1.j_expr, types$1.j_oTag); + }; +} +let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; +let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; +const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); +nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; +const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; +const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; +function isInAstralSet(code, set) { + let pos = 0x10000; + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + return false; +} +function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes); +} +function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); +} +const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] +}; +const keywords = new Set(reservedWords.keyword); +const reservedWordsStrictSet = new Set(reservedWords.strict); +const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); +function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; +} +function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); +} +function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); +} +function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); +} +function isKeyword(word) { + return keywords.has(word); +} +function isIteratorStart(current, next, next2) { + return current === 64 && next === 64 && isIdentifierStart(next2); +} +const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); +function canBeReservedWord(word) { + return reservedWordLikeSet.has(word); +} +class Scope { + constructor(flags) { + this.flags = 0; + this.names = new Map(); + this.firstLexicalName = ""; + this.flags = flags; + } +} +class ScopeHandler { + constructor(parser, inModule) { + this.parser = void 0; + this.scopeStack = []; + this.inModule = void 0; + this.undefinedExports = new Map(); + this.parser = parser; + this.inModule = inModule; + } + get inTopLevel() { + return (this.currentScope().flags & 1) > 0; + } + get inFunction() { + return (this.currentVarScopeFlags() & 2) > 0; + } + get allowSuper() { + return (this.currentThisScopeFlags() & 16) > 0; + } + get allowDirectSuper() { + return (this.currentThisScopeFlags() & 32) > 0; + } + get inClass() { + return (this.currentThisScopeFlags() & 64) > 0; + } + get inClassAndNotInNonArrowFunction() { + const flags = this.currentThisScopeFlags(); + return (flags & 64) > 0 && (flags & 2) === 0; + } + get inStaticBlock() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 128) { + return true; + } + if (flags & (387 | 64)) { + return false; + } + } + } + get inNonArrowFunction() { + return (this.currentThisScopeFlags() & 2) > 0; + } + get treatFunctionsAsVar() { + return this.treatFunctionsAsVarInScope(this.currentScope()); + } + createScope(flags) { + return new Scope(flags); + } + enter(flags) { + this.scopeStack.push(this.createScope(flags)); + } + exit() { + const scope = this.scopeStack.pop(); + return scope.flags; + } + treatFunctionsAsVarInScope(scope) { + return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1); + } + declareName(name, bindingType, loc) { + let scope = this.currentScope(); + if (bindingType & 8 || bindingType & 16) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + let type = scope.names.get(name) || 0; + if (bindingType & 16) { + type = type | 4; + } else { + if (!scope.firstLexicalName) { + scope.firstLexicalName = name; + } + type = type | 2; + } + scope.names.set(name, type); + if (bindingType & 8) { + this.maybeExportDefined(scope, name); + } + } else if (bindingType & 4) { + for (let i = this.scopeStack.length - 1; i >= 0; --i) { + scope = this.scopeStack[i]; + this.checkRedeclarationInScope(scope, name, bindingType, loc); + scope.names.set(name, (scope.names.get(name) || 0) | 1); + this.maybeExportDefined(scope, name); + if (scope.flags & 387) break; + } + } + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + maybeExportDefined(scope, name) { + if (this.parser.inModule && scope.flags & 1) { + this.undefinedExports.delete(name); + } + } + checkRedeclarationInScope(scope, name, bindingType, loc) { + if (this.isRedeclaredInScope(scope, name, bindingType)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + } + isRedeclaredInScope(scope, name, bindingType) { + if (!(bindingType & 1)) return false; + if (bindingType & 8) { + return scope.names.has(name); + } + const type = scope.names.get(name); + if (bindingType & 16) { + return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0; + } + return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0; + } + checkLocalExport(id) { + const { + name + } = id; + const topLevelScope = this.scopeStack[0]; + if (!topLevelScope.names.has(name)) { + this.undefinedExports.set(name, id.loc.start); + } + } + currentScope() { + return this.scopeStack[this.scopeStack.length - 1]; + } + currentVarScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & 387) { + return flags; + } + } + } + currentThisScopeFlags() { + for (let i = this.scopeStack.length - 1;; i--) { + const { + flags + } = this.scopeStack[i]; + if (flags & (387 | 64) && !(flags & 4)) { + return flags; + } + } + } +} +class FlowScope extends Scope { + constructor(...args) { + super(...args); + this.declareFunctions = new Set(); + } +} +class FlowScopeHandler extends ScopeHandler { + createScope(flags) { + return new FlowScope(flags); + } + declareName(name, bindingType, loc) { + const scope = this.currentScope(); + if (bindingType & 2048) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + scope.declareFunctions.add(name); + return; + } + super.declareName(name, bindingType, loc); + } + isRedeclaredInScope(scope, name, bindingType) { + if (super.isRedeclaredInScope(scope, name, bindingType)) return true; + if (bindingType & 2048 && !scope.declareFunctions.has(name)) { + const type = scope.names.get(name); + return (type & 4) > 0 || (type & 2) > 0; + } + return false; + } + checkLocalExport(id) { + if (!this.scopeStack[0].declareFunctions.has(id.name)) { + super.checkLocalExport(id); + } + } +} +class BaseParser { + constructor() { + this.sawUnambiguousESM = false; + this.ambiguousScriptDifferentAst = false; + } + hasPlugin(pluginConfig) { + if (typeof pluginConfig === "string") { + return this.plugins.has(pluginConfig); + } else { + const [pluginName, pluginOptions] = pluginConfig; + if (!this.hasPlugin(pluginName)) { + return false; + } + const actualOptions = this.plugins.get(pluginName); + for (const key of Object.keys(pluginOptions)) { + if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) { + return false; + } + } + return true; + } + } + getPluginOption(plugin, name) { + var _this$plugins$get; + return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name]; + } +} +function setTrailingComments(node, comments) { + if (node.trailingComments === undefined) { + node.trailingComments = comments; + } else { + node.trailingComments.unshift(...comments); + } +} +function setLeadingComments(node, comments) { + if (node.leadingComments === undefined) { + node.leadingComments = comments; + } else { + node.leadingComments.unshift(...comments); + } +} +function setInnerComments(node, comments) { + if (node.innerComments === undefined) { + node.innerComments = comments; + } else { + node.innerComments.unshift(...comments); + } +} +function adjustInnerComments(node, elements, commentWS) { + let lastElement = null; + let i = elements.length; + while (lastElement === null && i > 0) { + lastElement = elements[--i]; + } + if (lastElement === null || lastElement.start > commentWS.start) { + setInnerComments(node, commentWS.comments); + } else { + setTrailingComments(lastElement, commentWS.comments); + } +} +class CommentsParser extends BaseParser { + addComment(comment) { + if (this.filename) comment.loc.filename = this.filename; + const { + commentsLen + } = this.state; + if (this.comments.length != commentsLen) this.comments.length = commentsLen; + this.comments.push(comment); + this.state.commentsLen++; + } + processComment(node) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + const lastCommentWS = commentStack[i]; + if (lastCommentWS.start === node.end) { + lastCommentWS.leadingNode = node; + i--; + } + const { + start: nodeStart + } = node; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + if (commentEnd > nodeStart) { + commentWS.containingNode = node; + this.finalizeComment(commentWS); + commentStack.splice(i, 1); + } else { + if (commentEnd === nodeStart) { + commentWS.trailingNode = node; + } + break; + } + } + } + finalizeComment(commentWS) { + const { + comments + } = commentWS; + if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) { + if (commentWS.leadingNode !== null) { + setTrailingComments(commentWS.leadingNode, comments); + } + if (commentWS.trailingNode !== null) { + setLeadingComments(commentWS.trailingNode, comments); + } + } else { + const { + containingNode: node, + start: commentStart + } = commentWS; + if (this.input.charCodeAt(commentStart - 1) === 44) { + switch (node.type) { + case "ObjectExpression": + case "ObjectPattern": + case "RecordExpression": + adjustInnerComments(node, node.properties, commentWS); + break; + case "CallExpression": + case "OptionalCallExpression": + adjustInnerComments(node, node.arguments, commentWS); + break; + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "ObjectMethod": + case "ClassMethod": + case "ClassPrivateMethod": + adjustInnerComments(node, node.params, commentWS); + break; + case "ArrayExpression": + case "ArrayPattern": + case "TupleExpression": + adjustInnerComments(node, node.elements, commentWS); + break; + case "ExportNamedDeclaration": + case "ImportDeclaration": + adjustInnerComments(node, node.specifiers, commentWS); + break; + default: + { + setInnerComments(node, comments); + } + } + } else { + setInnerComments(node, comments); + } + } + } + finalizeRemainingComments() { + const { + commentStack + } = this.state; + for (let i = commentStack.length - 1; i >= 0; i--) { + this.finalizeComment(commentStack[i]); + } + this.state.commentStack = []; + } + resetPreviousNodeTrailingComments(node) { + const { + commentStack + } = this.state; + const { + length + } = commentStack; + if (length === 0) return; + const commentWS = commentStack[length - 1]; + if (commentWS.leadingNode === node) { + commentWS.leadingNode = null; + } + } + resetPreviousIdentifierLeadingComments(node) { + const { + commentStack + } = this.state; + const { + length + } = commentStack; + if (length === 0) return; + if (commentStack[length - 1].trailingNode === node) { + commentStack[length - 1].trailingNode = null; + } else if (length >= 2 && commentStack[length - 2].trailingNode === node) { + commentStack[length - 2].trailingNode = null; + } + } + takeSurroundingComments(node, start, end) { + const { + commentStack + } = this.state; + const commentStackLength = commentStack.length; + if (commentStackLength === 0) return; + let i = commentStackLength - 1; + for (; i >= 0; i--) { + const commentWS = commentStack[i]; + const commentEnd = commentWS.end; + const commentStart = commentWS.start; + if (commentStart === end) { + commentWS.leadingNode = node; + } else if (commentEnd === start) { + commentWS.trailingNode = node; + } else if (commentEnd < start) { + break; + } + } + } +} +const lineBreak = /\r\n?|[\n\u2028\u2029]/; +const lineBreakG = new RegExp(lineBreak.source, "g"); +function isNewLine(code) { + switch (code) { + case 10: + case 13: + case 8232: + case 8233: + return true; + default: + return false; + } +} +const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; +const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g; +const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y"); +function isWhitespace(code) { + switch (code) { + case 0x0009: + case 0x000b: + case 0x000c: + case 32: + case 160: + case 5760: + case 0x2000: + case 0x2001: + case 0x2002: + case 0x2003: + case 0x2004: + case 0x2005: + case 0x2006: + case 0x2007: + case 0x2008: + case 0x2009: + case 0x200a: + case 0x202f: + case 0x205f: + case 0x3000: + case 0xfeff: + return true; + default: + return false; + } +} +class State { + constructor() { + this.flags = 1024; + this.curLine = void 0; + this.lineStart = void 0; + this.startLoc = void 0; + this.endLoc = void 0; + this.errors = []; + this.potentialArrowAt = -1; + this.noArrowAt = []; + this.noArrowParamsConversionAt = []; + this.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + this.labels = []; + this.commentsLen = 0; + this.commentStack = []; + this.pos = 0; + this.type = 139; + this.value = null; + this.start = 0; + this.end = 0; + this.lastTokEndLoc = null; + this.lastTokStartLoc = null; + this.context = [types$1.brace]; + this.firstInvalidTemplateEscapePos = null; + this.strictErrors = new Map(); + this.tokensLength = 0; + } + get strict() { + return (this.flags & 1) > 0; + } + set strict(value) { + if (value) { + this.flags |= 1; + } else { + this.flags &= ~1; + } + } + init({ + strictMode, + sourceType, + startLine, + startColumn + }) { + this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; + this.curLine = startLine; + this.lineStart = -startColumn; + this.startLoc = this.endLoc = new Position(startLine, startColumn, 0); + } + get maybeInArrowParameters() { + return (this.flags & 2) > 0; + } + set maybeInArrowParameters(value) { + if (value) { + this.flags |= 2; + } else { + this.flags &= ~2; + } + } + get inType() { + return (this.flags & 4) > 0; + } + set inType(value) { + if (value) { + this.flags |= 4; + } else { + this.flags &= ~4; + } + } + get noAnonFunctionType() { + return (this.flags & 8) > 0; + } + set noAnonFunctionType(value) { + if (value) { + this.flags |= 8; + } else { + this.flags &= ~8; + } + } + get hasFlowComment() { + return (this.flags & 16) > 0; + } + set hasFlowComment(value) { + if (value) { + this.flags |= 16; + } else { + this.flags &= ~16; + } + } + get isAmbientContext() { + return (this.flags & 32) > 0; + } + set isAmbientContext(value) { + if (value) { + this.flags |= 32; + } else { + this.flags &= ~32; + } + } + get inAbstractClass() { + return (this.flags & 64) > 0; + } + set inAbstractClass(value) { + if (value) { + this.flags |= 64; + } else { + this.flags &= ~64; + } + } + get inDisallowConditionalTypesContext() { + return (this.flags & 128) > 0; + } + set inDisallowConditionalTypesContext(value) { + if (value) { + this.flags |= 128; + } else { + this.flags &= ~128; + } + } + get soloAwait() { + return (this.flags & 256) > 0; + } + set soloAwait(value) { + if (value) { + this.flags |= 256; + } else { + this.flags &= ~256; + } + } + get inFSharpPipelineDirectBody() { + return (this.flags & 512) > 0; + } + set inFSharpPipelineDirectBody(value) { + if (value) { + this.flags |= 512; + } else { + this.flags &= ~512; + } + } + get canStartJSXElement() { + return (this.flags & 1024) > 0; + } + set canStartJSXElement(value) { + if (value) { + this.flags |= 1024; + } else { + this.flags &= ~1024; + } + } + get containsEsc() { + return (this.flags & 2048) > 0; + } + set containsEsc(value) { + if (value) { + this.flags |= 2048; + } else { + this.flags &= ~2048; + } + } + curPosition() { + return new Position(this.curLine, this.pos - this.lineStart, this.pos); + } + clone() { + const state = new State(); + state.flags = this.flags; + state.curLine = this.curLine; + state.lineStart = this.lineStart; + state.startLoc = this.startLoc; + state.endLoc = this.endLoc; + state.errors = this.errors.slice(); + state.potentialArrowAt = this.potentialArrowAt; + state.noArrowAt = this.noArrowAt.slice(); + state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice(); + state.topicContext = this.topicContext; + state.labels = this.labels.slice(); + state.commentsLen = this.commentsLen; + state.commentStack = this.commentStack.slice(); + state.pos = this.pos; + state.type = this.type; + state.value = this.value; + state.start = this.start; + state.end = this.end; + state.lastTokEndLoc = this.lastTokEndLoc; + state.lastTokStartLoc = this.lastTokStartLoc; + state.context = this.context.slice(); + state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos; + state.strictErrors = this.strictErrors; + state.tokensLength = this.tokensLength; + return state; + } +} +var _isDigit = function isDigit(code) { + return code >= 48 && code <= 57; +}; +const forbiddenNumericSeparatorSiblings = { + decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]), + hex: new Set([46, 88, 95, 120]) +}; +const isAllowedNumericSeparatorSibling = { + bin: ch => ch === 48 || ch === 49, + oct: ch => ch >= 48 && ch <= 55, + dec: ch => ch >= 48 && ch <= 57, + hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 +}; +function readStringContents(type, input, pos, lineStart, curLine, errors) { + const initialPos = pos; + const initialLineStart = lineStart; + const initialCurLine = curLine; + let out = ""; + let firstInvalidLoc = null; + let chunkStart = pos; + const { + length + } = input; + for (;;) { + if (pos >= length) { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + out += input.slice(chunkStart, pos); + break; + } + const ch = input.charCodeAt(pos); + if (isStringEnd(type, ch, input, pos)) { + out += input.slice(chunkStart, pos); + break; + } + if (ch === 92) { + out += input.slice(chunkStart, pos); + const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors); + if (res.ch === null && !firstInvalidLoc) { + firstInvalidLoc = { + pos, + lineStart, + curLine + }; + } else { + out += res.ch; + } + ({ + pos, + lineStart, + curLine + } = res); + chunkStart = pos; + } else if (ch === 8232 || ch === 8233) { + ++pos; + ++curLine; + lineStart = pos; + } else if (ch === 10 || ch === 13) { + if (type === "template") { + out += input.slice(chunkStart, pos) + "\n"; + ++pos; + if (ch === 13 && input.charCodeAt(pos) === 10) { + ++pos; + } + ++curLine; + chunkStart = lineStart = pos; + } else { + errors.unterminated(initialPos, initialLineStart, initialCurLine); + } + } else { + ++pos; + } + } + return { + pos, + str: out, + firstInvalidLoc, + lineStart, + curLine, + containsInvalid: !!firstInvalidLoc + }; +} +function isStringEnd(type, ch, input, pos) { + if (type === "template") { + return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; + } + return ch === (type === "double" ? 34 : 39); +} +function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { + const throwOnInvalid = !inTemplate; + pos++; + const res = ch => ({ + pos, + ch, + lineStart, + curLine + }); + const ch = input.charCodeAt(pos++); + switch (ch) { + case 110: + return res("\n"); + case 114: + return res("\r"); + case 120: + { + let code; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCharCode(code)); + } + case 117: + { + let code; + ({ + code, + pos + } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); + return res(code === null ? null : String.fromCodePoint(code)); + } + case 116: + return res("\t"); + case 98: + return res("\b"); + case 118: + return res("\u000b"); + case 102: + return res("\f"); + case 13: + if (input.charCodeAt(pos) === 10) { + ++pos; + } + case 10: + lineStart = pos; + ++curLine; + case 8232: + case 8233: + return res(""); + case 56: + case 57: + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(pos - 1, lineStart, curLine); + } + default: + if (ch >= 48 && ch <= 55) { + const startPos = pos - 1; + const match = input.slice(startPos, pos + 2).match(/^[0-7]+/); + let octalStr = match[0]; + let octal = parseInt(octalStr, 8); + if (octal > 255) { + octalStr = octalStr.slice(0, -1); + octal = parseInt(octalStr, 8); + } + pos += octalStr.length - 1; + const next = input.charCodeAt(pos); + if (octalStr !== "0" || next === 56 || next === 57) { + if (inTemplate) { + return res(null); + } else { + errors.strictNumericEscape(startPos, lineStart, curLine); + } + } + return res(String.fromCharCode(octal)); + } + return res(String.fromCharCode(ch)); + } +} +function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { + const initialPos = pos; + let n; + ({ + n, + pos + } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); + if (n === null) { + if (throwOnInvalid) { + errors.invalidEscapeSequence(initialPos, lineStart, curLine); + } else { + pos = initialPos - 1; + } + } + return { + code: n, + pos + }; +} +function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { + const start = pos; + const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; + const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; + let invalid = false; + let total = 0; + for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { + const code = input.charCodeAt(pos); + let val; + if (code === 95 && allowNumSeparator !== "bail") { + const prev = input.charCodeAt(pos - 1); + const next = input.charCodeAt(pos + 1); + if (!allowNumSeparator) { + if (bailOnError) return { + n: null, + pos + }; + errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); + } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { + if (bailOnError) return { + n: null, + pos + }; + errors.unexpectedNumericSeparator(pos, lineStart, curLine); + } + ++pos; + continue; + } + if (code >= 97) { + val = code - 97 + 10; + } else if (code >= 65) { + val = code - 65 + 10; + } else if (_isDigit(code)) { + val = code - 48; + } else { + val = Infinity; + } + if (val >= radix) { + if (val <= 9 && bailOnError) { + return { + n: null, + pos + }; + } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { + val = 0; + } else if (forceLen) { + val = 0; + invalid = true; + } else { + break; + } + } + ++pos; + total = total * radix + val; + } + if (pos === start || len != null && pos - start !== len || invalid) { + return { + n: null, + pos + }; + } + return { + n: total, + pos + }; +} +function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { + const ch = input.charCodeAt(pos); + let code; + if (ch === 123) { + ++pos; + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); + ++pos; + if (code !== null && code > 0x10ffff) { + if (throwOnInvalid) { + errors.invalidCodePoint(pos, lineStart, curLine); + } else { + return { + code: null, + pos + }; + } + } + } else { + ({ + code, + pos + } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); + } + return { + code, + pos + }; +} +function buildPosition(pos, lineStart, curLine) { + return new Position(curLine, pos - lineStart, pos); +} +const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]); +class Token { + constructor(state) { + this.type = state.type; + this.value = state.value; + this.start = state.start; + this.end = state.end; + this.loc = new SourceLocation(state.startLoc, state.endLoc); + } +} +class Tokenizer extends CommentsParser { + constructor(options, input) { + super(); + this.isLookahead = void 0; + this.tokens = []; + this.errorHandlers_readInt = { + invalidDigit: (pos, lineStart, curLine, radix) => { + if (!this.options.errorRecovery) return false; + this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), { + radix + }); + return true; + }, + numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence), + unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator) + }; + this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, { + invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence), + invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint) + }); + this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: (pos, lineStart, curLine) => { + this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine)); + }, + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine)); + } + }); + this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, { + strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape), + unterminated: (pos, lineStart, curLine) => { + throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine)); + } + }); + this.state = new State(); + this.state.init(options); + this.input = input; + this.length = input.length; + this.comments = []; + this.isLookahead = false; + } + pushToken(token) { + this.tokens.length = this.state.tokensLength; + this.tokens.push(token); + ++this.state.tokensLength; + } + next() { + this.checkKeywordEscapes(); + if (this.options.tokens) { + this.pushToken(new Token(this.state)); + } + this.state.lastTokEndLoc = this.state.endLoc; + this.state.lastTokStartLoc = this.state.startLoc; + this.nextToken(); + } + eat(type) { + if (this.match(type)) { + this.next(); + return true; + } else { + return false; + } + } + match(type) { + return this.state.type === type; + } + createLookaheadState(state) { + return { + pos: state.pos, + value: null, + type: state.type, + start: state.start, + end: state.end, + context: [this.curContext()], + inType: state.inType, + startLoc: state.startLoc, + lastTokEndLoc: state.lastTokEndLoc, + curLine: state.curLine, + lineStart: state.lineStart, + curPosition: state.curPosition + }; + } + lookahead() { + const old = this.state; + this.state = this.createLookaheadState(old); + this.isLookahead = true; + this.nextToken(); + this.isLookahead = false; + const curr = this.state; + this.state = old; + return curr; + } + nextTokenStart() { + return this.nextTokenStartSince(this.state.pos); + } + nextTokenStartSince(pos) { + skipWhiteSpace.lastIndex = pos; + return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos; + } + lookaheadCharCode() { + return this.input.charCodeAt(this.nextTokenStart()); + } + nextTokenInLineStart() { + return this.nextTokenInLineStartSince(this.state.pos); + } + nextTokenInLineStartSince(pos) { + skipWhiteSpaceInLine.lastIndex = pos; + return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos; + } + lookaheadInLineCharCode() { + return this.input.charCodeAt(this.nextTokenInLineStart()); + } + codePointAtPos(pos) { + let cp = this.input.charCodeAt(pos); + if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) { + const trail = this.input.charCodeAt(pos); + if ((trail & 0xfc00) === 0xdc00) { + cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff); + } + } + return cp; + } + setStrict(strict) { + this.state.strict = strict; + if (strict) { + this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at)); + this.state.strictErrors.clear(); + } + } + curContext() { + return this.state.context[this.state.context.length - 1]; + } + nextToken() { + this.skipSpace(); + this.state.start = this.state.pos; + if (!this.isLookahead) this.state.startLoc = this.state.curPosition(); + if (this.state.pos >= this.length) { + this.finishToken(139); + return; + } + this.getTokenFromCode(this.codePointAtPos(this.state.pos)); + } + skipBlockComment(commentEnd) { + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + const start = this.state.pos; + const end = this.input.indexOf(commentEnd, start + 2); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + this.state.pos = end + commentEnd.length; + lineBreakG.lastIndex = start + 2; + while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) { + ++this.state.curLine; + this.state.lineStart = lineBreakG.lastIndex; + } + if (this.isLookahead) return; + const comment = { + type: "CommentBlock", + value: this.input.slice(start + 2, end), + start, + end: end + commentEnd.length, + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.options.tokens) this.pushToken(comment); + return comment; + } + skipLineComment(startSkip) { + const start = this.state.pos; + let startLoc; + if (!this.isLookahead) startLoc = this.state.curPosition(); + let ch = this.input.charCodeAt(this.state.pos += startSkip); + if (this.state.pos < this.length) { + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + } + if (this.isLookahead) return; + const end = this.state.pos; + const value = this.input.slice(start + startSkip, end); + const comment = { + type: "CommentLine", + value, + start, + end, + loc: new SourceLocation(startLoc, this.state.curPosition()) + }; + if (this.options.tokens) this.pushToken(comment); + return comment; + } + skipSpace() { + const spaceStart = this.state.pos; + const comments = []; + loop: while (this.state.pos < this.length) { + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 32: + case 160: + case 9: + ++this.state.pos; + break; + case 13: + if (this.input.charCodeAt(this.state.pos + 1) === 10) { + ++this.state.pos; + } + case 10: + case 8232: + case 8233: + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + break; + case 47: + switch (this.input.charCodeAt(this.state.pos + 1)) { + case 42: + { + const comment = this.skipBlockComment("*/"); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + break; + } + case 47: + { + const comment = this.skipLineComment(2); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + break; + } + default: + break loop; + } + break; + default: + if (isWhitespace(ch)) { + ++this.state.pos; + } else if (ch === 45 && !this.inModule && this.options.annexB) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) { + const comment = this.skipLineComment(3); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + } else { + break loop; + } + } else if (ch === 60 && !this.inModule && this.options.annexB) { + const pos = this.state.pos; + if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) { + const comment = this.skipLineComment(4); + if (comment !== undefined) { + this.addComment(comment); + if (this.options.attachComment) comments.push(comment); + } + } else { + break loop; + } + } else { + break loop; + } + } + } + if (comments.length > 0) { + const end = this.state.pos; + const commentWhitespace = { + start: spaceStart, + end, + comments, + leadingNode: null, + trailingNode: null, + containingNode: null + }; + this.state.commentStack.push(commentWhitespace); + } + } + finishToken(type, val) { + this.state.end = this.state.pos; + this.state.endLoc = this.state.curPosition(); + const prevType = this.state.type; + this.state.type = type; + this.state.value = val; + if (!this.isLookahead) { + this.updateContext(prevType); + } + } + replaceToken(type) { + this.state.type = type; + this.updateContext(); + } + readToken_numberSign() { + if (this.state.pos === 0 && this.readToken_interpreter()) { + return; + } + const nextPos = this.state.pos + 1; + const next = this.codePointAtPos(nextPos); + if (next >= 48 && next <= 57) { + throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition()); + } + if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { + this.expectPlugin("recordAndTuple"); + if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") { + throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + if (next === 123) { + this.finishToken(7); + } else { + this.finishToken(1); + } + } else if (isIdentifierStart(next)) { + ++this.state.pos; + this.finishToken(138, this.readWord1(next)); + } else if (next === 92) { + ++this.state.pos; + this.finishToken(138, this.readWord1()); + } else { + this.finishOp(27, 1); + } + } + readToken_dot() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next >= 48 && next <= 57) { + this.readNumber(true); + return; + } + if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { + this.state.pos += 3; + this.finishToken(21); + } else { + ++this.state.pos; + this.finishToken(16); + } + } + readToken_slash() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(31, 2); + } else { + this.finishOp(56, 1); + } + } + readToken_interpreter() { + if (this.state.pos !== 0 || this.length < 2) return false; + let ch = this.input.charCodeAt(this.state.pos + 1); + if (ch !== 33) return false; + const start = this.state.pos; + this.state.pos += 1; + while (!isNewLine(ch) && ++this.state.pos < this.length) { + ch = this.input.charCodeAt(this.state.pos); + } + const value = this.input.slice(start + 2, this.state.pos); + this.finishToken(28, value); + return true; + } + readToken_mult_modulo(code) { + let type = code === 42 ? 55 : 54; + let width = 1; + let next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 42) { + width++; + next = this.input.charCodeAt(this.state.pos + 2); + type = 57; + } + if (next === 61 && !this.state.inType) { + width++; + type = code === 37 ? 33 : 30; + } + this.finishOp(type, width); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + if (this.input.charCodeAt(this.state.pos + 2) === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(code === 124 ? 41 : 42, 2); + } + return; + } + if (code === 124) { + if (next === 62) { + this.finishOp(39, 2); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 125) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(9); + return; + } + if (this.hasPlugin("recordAndTuple") && next === 93) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(4); + return; + } + } + if (next === 61) { + this.finishOp(30, 2); + return; + } + this.finishOp(code === 124 ? 43 : 45, 1); + } + readToken_caret() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61 && !this.state.inType) { + this.finishOp(32, 2); + } else if (next === 94 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "^^" + }])) { + this.finishOp(37, 2); + const lookaheadCh = this.input.codePointAt(this.state.pos); + if (lookaheadCh === 94) { + this.unexpected(); + } + } else { + this.finishOp(44, 1); + } + } + readToken_atSign() { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 64 && this.hasPlugin(["pipelineOperator", { + proposal: "hack", + topicToken: "@@" + }])) { + this.finishOp(38, 2); + } else { + this.finishOp(26, 1); + } + } + readToken_plus_min(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) { + this.finishOp(34, 2); + return; + } + if (next === 61) { + this.finishOp(30, 2); + } else { + this.finishOp(53, 1); + } + } + readToken_lt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 60) { + if (this.input.charCodeAt(pos + 2) === 61) { + this.finishOp(30, 3); + return; + } + this.finishOp(51, 2); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(47, 1); + } + readToken_gt() { + const { + pos + } = this.state; + const next = this.input.charCodeAt(pos + 1); + if (next === 62) { + const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(pos + size) === 61) { + this.finishOp(30, size + 1); + return; + } + this.finishOp(52, size); + return; + } + if (next === 61) { + this.finishOp(49, 2); + return; + } + this.finishOp(48, 1); + } + readToken_eq_excl(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); + return; + } + if (code === 61 && next === 62) { + this.state.pos += 2; + this.finishToken(19); + return; + } + this.finishOp(code === 61 ? 29 : 35, 1); + } + readToken_question() { + const next = this.input.charCodeAt(this.state.pos + 1); + const next2 = this.input.charCodeAt(this.state.pos + 2); + if (next === 63) { + if (next2 === 61) { + this.finishOp(30, 3); + } else { + this.finishOp(40, 2); + } + } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { + this.state.pos += 2; + this.finishToken(18); + } else { + ++this.state.pos; + this.finishToken(17); + } + } + getTokenFromCode(code) { + switch (code) { + case 46: + this.readToken_dot(); + return; + case 40: + ++this.state.pos; + this.finishToken(10); + return; + case 41: + ++this.state.pos; + this.finishToken(11); + return; + case 59: + ++this.state.pos; + this.finishToken(13); + return; + case 44: + ++this.state.pos; + this.finishToken(12); + return; + case 91: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(2); + } else { + ++this.state.pos; + this.finishToken(0); + } + return; + case 93: + ++this.state.pos; + this.finishToken(3); + return; + case 123: + if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { + if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { + throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition()); + } + this.state.pos += 2; + this.finishToken(6); + } else { + ++this.state.pos; + this.finishToken(5); + } + return; + case 125: + ++this.state.pos; + this.finishToken(8); + return; + case 58: + if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { + this.finishOp(15, 2); + } else { + ++this.state.pos; + this.finishToken(14); + } + return; + case 63: + this.readToken_question(); + return; + case 96: + this.readTemplateToken(); + return; + case 48: + { + const next = this.input.charCodeAt(this.state.pos + 1); + if (next === 120 || next === 88) { + this.readRadixNumber(16); + return; + } + if (next === 111 || next === 79) { + this.readRadixNumber(8); + return; + } + if (next === 98 || next === 66) { + this.readRadixNumber(2); + return; + } + } + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + this.readNumber(false); + return; + case 34: + case 39: + this.readString(code); + return; + case 47: + this.readToken_slash(); + return; + case 37: + case 42: + this.readToken_mult_modulo(code); + return; + case 124: + case 38: + this.readToken_pipe_amp(code); + return; + case 94: + this.readToken_caret(); + return; + case 43: + case 45: + this.readToken_plus_min(code); + return; + case 60: + this.readToken_lt(); + return; + case 62: + this.readToken_gt(); + return; + case 61: + case 33: + this.readToken_eq_excl(code); + return; + case 126: + this.finishOp(36, 1); + return; + case 64: + this.readToken_atSign(); + return; + case 35: + this.readToken_numberSign(); + return; + case 92: + this.readWord(); + return; + default: + if (isIdentifierStart(code)) { + this.readWord(code); + return; + } + } + throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), { + unexpected: String.fromCodePoint(code) + }); + } + finishOp(type, size) { + const str = this.input.slice(this.state.pos, this.state.pos + size); + this.state.pos += size; + this.finishToken(type, str); + } + readRegexp() { + const startLoc = this.state.startLoc; + const start = this.state.start + 1; + let escaped, inClass; + let { + pos + } = this.state; + for (;; ++pos) { + if (pos >= this.length) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + const ch = this.input.charCodeAt(pos); + if (isNewLine(ch)) { + throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1)); + } + if (escaped) { + escaped = false; + } else { + if (ch === 91) { + inClass = true; + } else if (ch === 93 && inClass) { + inClass = false; + } else if (ch === 47 && !inClass) { + break; + } + escaped = ch === 92; + } + } + const content = this.input.slice(start, pos); + ++pos; + let mods = ""; + const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start); + while (pos < this.length) { + const cp = this.codePointAtPos(pos); + const char = String.fromCharCode(cp); + if (VALID_REGEX_FLAGS.has(cp)) { + if (cp === 118) { + if (mods.includes("u")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } else if (cp === 117) { + if (mods.includes("v")) { + this.raise(Errors.IncompatibleRegExpUVFlags, nextPos()); + } + } + if (mods.includes(char)) { + this.raise(Errors.DuplicateRegExpFlags, nextPos()); + } + } else if (isIdentifierChar(cp) || cp === 92) { + this.raise(Errors.MalformedRegExpFlags, nextPos()); + } else { + break; + } + ++pos; + mods += char; + } + this.state.pos = pos; + this.finishToken(137, { + pattern: content, + flags: mods + }); + } + readInt(radix, len, forceLen = false, allowNumSeparator = true) { + const { + n, + pos + } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false); + this.state.pos = pos; + return n; + } + readRadixNumber(radix) { + const startLoc = this.state.curPosition(); + let isBigInt = false; + this.state.pos += 2; + const val = this.readInt(radix); + if (val == null) { + this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), { + radix + }); + } + const next = this.input.charCodeAt(this.state.pos); + if (next === 110) { + ++this.state.pos; + isBigInt = true; + } else if (next === 109) { + throw this.raise(Errors.InvalidDecimal, startLoc); + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + if (isBigInt) { + const str = this.input.slice(startLoc.index, this.state.pos).replace(/[_n]/g, ""); + this.finishToken(135, str); + return; + } + this.finishToken(134, val); + } + readNumber(startsWithDot) { + const start = this.state.pos; + const startLoc = this.state.curPosition(); + let isFloat = false; + let isBigInt = false; + let isDecimal = false; + let hasExponent = false; + let isOctal = false; + if (!startsWithDot && this.readInt(10) === null) { + this.raise(Errors.InvalidNumber, this.state.curPosition()); + } + const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; + if (hasLeadingZero) { + const integer = this.input.slice(start, this.state.pos); + this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc); + if (!this.state.strict) { + const underscorePos = integer.indexOf("_"); + if (underscorePos > 0) { + this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos)); + } + } + isOctal = hasLeadingZero && !/[89]/.test(integer); + } + let next = this.input.charCodeAt(this.state.pos); + if (next === 46 && !isOctal) { + ++this.state.pos; + this.readInt(10); + isFloat = true; + next = this.input.charCodeAt(this.state.pos); + } + if ((next === 69 || next === 101) && !isOctal) { + next = this.input.charCodeAt(++this.state.pos); + if (next === 43 || next === 45) { + ++this.state.pos; + } + if (this.readInt(10) === null) { + this.raise(Errors.InvalidOrMissingExponent, startLoc); + } + isFloat = true; + hasExponent = true; + next = this.input.charCodeAt(this.state.pos); + } + if (next === 110) { + if (isFloat || hasLeadingZero) { + this.raise(Errors.InvalidBigIntLiteral, startLoc); + } + ++this.state.pos; + isBigInt = true; + } + if (next === 109) { + this.expectPlugin("decimal", this.state.curPosition()); + if (hasExponent || hasLeadingZero) { + this.raise(Errors.InvalidDecimal, startLoc); + } + ++this.state.pos; + isDecimal = true; + } + if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { + throw this.raise(Errors.NumberIdentifier, this.state.curPosition()); + } + const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); + if (isBigInt) { + this.finishToken(135, str); + return; + } + if (isDecimal) { + this.finishToken(136, str); + return; + } + const val = isOctal ? parseInt(str, 8) : parseFloat(str); + this.finishToken(134, val); + } + readCodePoint(throwOnInvalid) { + const { + code, + pos + } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint); + this.state.pos = pos; + return code; + } + readString(quote) { + const { + str, + pos, + curLine, + lineStart + } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + this.finishToken(133, str); + } + readTemplateContinuation() { + if (!this.match(8)) { + this.unexpected(null, 8); + } + this.state.pos--; + this.readTemplateToken(); + } + readTemplateToken() { + const opening = this.input[this.state.pos]; + const { + str, + firstInvalidLoc, + pos, + curLine, + lineStart + } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template); + this.state.pos = pos + 1; + this.state.lineStart = lineStart; + this.state.curLine = curLine; + if (firstInvalidLoc) { + this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, firstInvalidLoc.pos); + } + if (this.input.codePointAt(pos) === 96) { + this.finishToken(24, firstInvalidLoc ? null : opening + str + "`"); + } else { + this.state.pos++; + this.finishToken(25, firstInvalidLoc ? null : opening + str + "${"); + } + } + recordStrictModeErrors(toParseError, at) { + const index = at.index; + if (this.state.strict && !this.state.strictErrors.has(index)) { + this.raise(toParseError, at); + } else { + this.state.strictErrors.set(index, [toParseError, at]); + } + } + readWord1(firstCode) { + this.state.containsEsc = false; + let word = ""; + const start = this.state.pos; + let chunkStart = this.state.pos; + if (firstCode !== undefined) { + this.state.pos += firstCode <= 0xffff ? 1 : 2; + } + while (this.state.pos < this.length) { + const ch = this.codePointAtPos(this.state.pos); + if (isIdentifierChar(ch)) { + this.state.pos += ch <= 0xffff ? 1 : 2; + } else if (ch === 92) { + this.state.containsEsc = true; + word += this.input.slice(chunkStart, this.state.pos); + const escStart = this.state.curPosition(); + const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; + if (this.input.charCodeAt(++this.state.pos) !== 117) { + this.raise(Errors.MissingUnicodeEscape, this.state.curPosition()); + chunkStart = this.state.pos - 1; + continue; + } + ++this.state.pos; + const esc = this.readCodePoint(true); + if (esc !== null) { + if (!identifierCheck(esc)) { + this.raise(Errors.EscapedCharNotAnIdentifier, escStart); + } + word += String.fromCodePoint(esc); + } + chunkStart = this.state.pos; + } else { + break; + } + } + return word + this.input.slice(chunkStart, this.state.pos); + } + readWord(firstCode) { + const word = this.readWord1(firstCode); + const type = keywords$1.get(word); + if (type !== undefined) { + this.finishToken(type, tokenLabelName(type)); + } else { + this.finishToken(132, word); + } + } + checkKeywordEscapes() { + const { + type + } = this.state; + if (tokenIsKeyword(type) && this.state.containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, { + reservedWord: tokenLabelName(type) + }); + } + } + raise(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const error = toParseError(loc, details); + if (!this.options.errorRecovery) throw error; + if (!this.isLookahead) this.state.errors.push(error); + return error; + } + raiseOverwrite(toParseError, at, details = {}) { + const loc = at instanceof Position ? at : at.loc.start; + const pos = loc.index; + const errors = this.state.errors; + for (let i = errors.length - 1; i >= 0; i--) { + const error = errors[i]; + if (error.loc.index === pos) { + return errors[i] = toParseError(loc, details); + } + if (error.loc.index < pos) break; + } + return this.raise(toParseError, at, details); + } + updateContext(prevType) {} + unexpected(loc, type) { + throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, { + expected: type ? tokenLabelName(type) : null + }); + } + expectPlugin(pluginName, loc) { + if (this.hasPlugin(pluginName)) { + return true; + } + throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, { + missingPlugin: [pluginName] + }); + } + expectOnePlugin(pluginNames) { + if (!pluginNames.some(name => this.hasPlugin(name))) { + throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, { + missingPlugin: pluginNames + }); + } + } + errorBuilder(error) { + return (pos, lineStart, curLine) => { + this.raise(error, buildPosition(pos, lineStart, curLine)); + }; + } +} +class ClassScope { + constructor() { + this.privateNames = new Set(); + this.loneAccessors = new Map(); + this.undefinedPrivateNames = new Map(); + } +} +class ClassScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = []; + this.undefinedPrivateNames = new Map(); + this.parser = parser; + } + current() { + return this.stack[this.stack.length - 1]; + } + enter() { + this.stack.push(new ClassScope()); + } + exit() { + const oldClassScope = this.stack.pop(); + const current = this.current(); + for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) { + if (current) { + if (!current.undefinedPrivateNames.has(name)) { + current.undefinedPrivateNames.set(name, loc); + } + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } + } + declarePrivateName(name, elementType, loc) { + const { + privateNames, + loneAccessors, + undefinedPrivateNames + } = this.current(); + let redefined = privateNames.has(name); + if (elementType & 3) { + const accessor = redefined && loneAccessors.get(name); + if (accessor) { + const oldStatic = accessor & 4; + const newStatic = elementType & 4; + const oldKind = accessor & 3; + const newKind = elementType & 3; + redefined = oldKind === newKind || oldStatic !== newStatic; + if (!redefined) loneAccessors.delete(name); + } else if (!redefined) { + loneAccessors.set(name, elementType); + } + } + if (redefined) { + this.parser.raise(Errors.PrivateNameRedeclaration, loc, { + identifierName: name + }); + } + privateNames.add(name); + undefinedPrivateNames.delete(name); + } + usePrivateName(name, loc) { + let classScope; + for (classScope of this.stack) { + if (classScope.privateNames.has(name)) return; + } + if (classScope) { + classScope.undefinedPrivateNames.set(name, loc); + } else { + this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, { + identifierName: name + }); + } + } +} +class ExpressionScope { + constructor(type = 0) { + this.type = type; + } + canBeArrowParameterDeclaration() { + return this.type === 2 || this.type === 1; + } + isCertainlyParameterDeclaration() { + return this.type === 3; + } +} +class ArrowHeadParsingScope extends ExpressionScope { + constructor(type) { + super(type); + this.declarationErrors = new Map(); + } + recordDeclarationError(ParsingErrorClass, at) { + const index = at.index; + this.declarationErrors.set(index, [ParsingErrorClass, at]); + } + clearDeclarationError(index) { + this.declarationErrors.delete(index); + } + iterateErrors(iterator) { + this.declarationErrors.forEach(iterator); + } +} +class ExpressionScopeHandler { + constructor(parser) { + this.parser = void 0; + this.stack = [new ExpressionScope()]; + this.parser = parser; + } + enter(scope) { + this.stack.push(scope); + } + exit() { + this.stack.pop(); + } + recordParameterInitializerError(toParseError, node) { + const origin = node.loc.start; + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (!scope.isCertainlyParameterDeclaration()) { + if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(toParseError, origin); + } else { + return; + } + scope = stack[--i]; + } + this.parser.raise(toParseError, origin); + } + recordArrowParameterBindingError(error, node) { + const { + stack + } = this; + const scope = stack[stack.length - 1]; + const origin = node.loc.start; + if (scope.isCertainlyParameterDeclaration()) { + this.parser.raise(error, origin); + } else if (scope.canBeArrowParameterDeclaration()) { + scope.recordDeclarationError(error, origin); + } else { + return; + } + } + recordAsyncArrowParametersError(at) { + const { + stack + } = this; + let i = stack.length - 1; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + if (scope.type === 2) { + scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at); + } + scope = stack[--i]; + } + } + validateAsPattern() { + const { + stack + } = this; + const currentScope = stack[stack.length - 1]; + if (!currentScope.canBeArrowParameterDeclaration()) return; + currentScope.iterateErrors(([toParseError, loc]) => { + this.parser.raise(toParseError, loc); + let i = stack.length - 2; + let scope = stack[i]; + while (scope.canBeArrowParameterDeclaration()) { + scope.clearDeclarationError(loc.index); + scope = stack[--i]; + } + }); + } +} +function newParameterDeclarationScope() { + return new ExpressionScope(3); +} +function newArrowHeadScope() { + return new ArrowHeadParsingScope(1); +} +function newAsyncArrowScope() { + return new ArrowHeadParsingScope(2); +} +function newExpressionScope() { + return new ExpressionScope(); +} +class ProductionParameterHandler { + constructor() { + this.stacks = []; + } + enter(flags) { + this.stacks.push(flags); + } + exit() { + this.stacks.pop(); + } + currentFlags() { + return this.stacks[this.stacks.length - 1]; + } + get hasAwait() { + return (this.currentFlags() & 2) > 0; + } + get hasYield() { + return (this.currentFlags() & 1) > 0; + } + get hasReturn() { + return (this.currentFlags() & 4) > 0; + } + get hasIn() { + return (this.currentFlags() & 8) > 0; + } +} +function functionFlags(isAsync, isGenerator) { + return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0); +} +class UtilParser extends Tokenizer { + addExtra(node, key, value, enumerable = true) { + if (!node) return; + const extra = node.extra = node.extra || {}; + if (enumerable) { + extra[key] = value; + } else { + Object.defineProperty(extra, key, { + enumerable, + value + }); + } + } + isContextual(token) { + return this.state.type === token && !this.state.containsEsc; + } + isUnparsedContextual(nameStart, name) { + const nameEnd = nameStart + name.length; + if (this.input.slice(nameStart, nameEnd) === name) { + const nextCh = this.input.charCodeAt(nameEnd); + return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800); + } + return false; + } + isLookaheadContextual(name) { + const next = this.nextTokenStart(); + return this.isUnparsedContextual(next, name); + } + eatContextual(token) { + if (this.isContextual(token)) { + this.next(); + return true; + } + return false; + } + expectContextual(token, toParseError) { + if (!this.eatContextual(token)) { + if (toParseError != null) { + throw this.raise(toParseError, this.state.startLoc); + } + this.unexpected(null, token); + } + } + canInsertSemicolon() { + return this.match(139) || this.match(8) || this.hasPrecedingLineBreak(); + } + hasPrecedingLineBreak() { + return lineBreak.test(this.input.slice(this.state.lastTokEndLoc.index, this.state.start)); + } + hasFollowingLineBreak() { + skipWhiteSpaceToLineBreak.lastIndex = this.state.end; + return skipWhiteSpaceToLineBreak.test(this.input); + } + isLineTerminator() { + return this.eat(13) || this.canInsertSemicolon(); + } + semicolon(allowAsi = true) { + if (allowAsi ? this.isLineTerminator() : this.eat(13)) return; + this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc); + } + expect(type, loc) { + this.eat(type) || this.unexpected(loc, type); + } + tryParse(fn, oldState = this.state.clone()) { + const abortSignal = { + node: null + }; + try { + const node = fn((node = null) => { + abortSignal.node = node; + throw abortSignal; + }); + if (this.state.errors.length > oldState.errors.length) { + const failState = this.state; + this.state = oldState; + this.state.tokensLength = failState.tokensLength; + return { + node, + error: failState.errors[oldState.errors.length], + thrown: false, + aborted: false, + failState + }; + } + return { + node, + error: null, + thrown: false, + aborted: false, + failState: null + }; + } catch (error) { + const failState = this.state; + this.state = oldState; + if (error instanceof SyntaxError) { + return { + node: null, + error, + thrown: true, + aborted: false, + failState + }; + } + if (error === abortSignal) { + return { + node: abortSignal.node, + error: null, + thrown: false, + aborted: true, + failState + }; + } + throw error; + } + } + checkExpressionErrors(refExpressionErrors, andThrow) { + if (!refExpressionErrors) return false; + const { + shorthandAssignLoc, + doubleProtoLoc, + privateKeyLoc, + optionalParametersLoc + } = refExpressionErrors; + const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc; + if (!andThrow) { + return hasErrors; + } + if (shorthandAssignLoc != null) { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + if (doubleProtoLoc != null) { + this.raise(Errors.DuplicateProto, doubleProtoLoc); + } + if (privateKeyLoc != null) { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + if (optionalParametersLoc != null) { + this.unexpected(optionalParametersLoc); + } + } + isLiteralPropertyName() { + return tokenIsLiteralPropertyName(this.state.type); + } + isPrivateName(node) { + return node.type === "PrivateName"; + } + getPrivateNameSV(node) { + return node.id.name; + } + hasPropertyAsPrivateName(node) { + return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property); + } + isObjectProperty(node) { + return node.type === "ObjectProperty"; + } + isObjectMethod(node) { + return node.type === "ObjectMethod"; + } + initializeScopes(inModule = this.options.sourceType === "module") { + const oldLabels = this.state.labels; + this.state.labels = []; + const oldExportedIdentifiers = this.exportedIdentifiers; + this.exportedIdentifiers = new Set(); + const oldInModule = this.inModule; + this.inModule = inModule; + const oldScope = this.scope; + const ScopeHandler = this.getScopeHandler(); + this.scope = new ScopeHandler(this, inModule); + const oldProdParam = this.prodParam; + this.prodParam = new ProductionParameterHandler(); + const oldClassScope = this.classScope; + this.classScope = new ClassScopeHandler(this); + const oldExpressionScope = this.expressionScope; + this.expressionScope = new ExpressionScopeHandler(this); + return () => { + this.state.labels = oldLabels; + this.exportedIdentifiers = oldExportedIdentifiers; + this.inModule = oldInModule; + this.scope = oldScope; + this.prodParam = oldProdParam; + this.classScope = oldClassScope; + this.expressionScope = oldExpressionScope; + }; + } + enterInitialScopes() { + let paramFlags = 0; + if (this.inModule) { + paramFlags |= 2; + } + this.scope.enter(1); + this.prodParam.enter(paramFlags); + } + checkDestructuringPrivate(refExpressionErrors) { + const { + privateKeyLoc + } = refExpressionErrors; + if (privateKeyLoc !== null) { + this.expectPlugin("destructuringPrivate", privateKeyLoc); + } + } +} +class ExpressionErrors { + constructor() { + this.shorthandAssignLoc = null; + this.doubleProtoLoc = null; + this.privateKeyLoc = null; + this.optionalParametersLoc = null; + } +} +let Node$5 = class Node { + constructor(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new SourceLocation(loc); + if (parser != null && parser.options.ranges) this.range = [pos, 0]; + if (parser != null && parser.filename) this.loc.filename = parser.filename; + } +}; +const NodePrototype = Node$5.prototype; +{ + NodePrototype.__clone = function () { + const newNode = new Node$5(undefined, this.start, this.loc.start); + const keys = Object.keys(this); + for (let i = 0, length = keys.length; i < length; i++) { + const key = keys[i]; + if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { + newNode[key] = this[key]; + } + } + return newNode; + }; +} +function clonePlaceholder(node) { + return cloneIdentifier(node); +} +function cloneIdentifier(node) { + const { + type, + start, + end, + loc, + range, + extra, + name + } = node; + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + cloned.extra = extra; + cloned.name = name; + if (type === "Placeholder") { + cloned.expectedNode = node.expectedNode; + } + return cloned; +} +function cloneStringLiteral(node) { + const { + type, + start, + end, + loc, + range, + extra + } = node; + if (type === "Placeholder") { + return clonePlaceholder(node); + } + const cloned = Object.create(NodePrototype); + cloned.type = type; + cloned.start = start; + cloned.end = end; + cloned.loc = loc; + cloned.range = range; + if (node.raw !== undefined) { + cloned.raw = node.raw; + } else { + cloned.extra = extra; + } + cloned.value = node.value; + return cloned; +} +class NodeUtils extends UtilParser { + startNode() { + const loc = this.state.startLoc; + return new Node$5(this, loc.index, loc); + } + startNodeAt(loc) { + return new Node$5(this, loc.index, loc); + } + startNodeAtNode(type) { + return this.startNodeAt(type.loc.start); + } + finishNode(node, type) { + return this.finishNodeAt(node, type, this.state.lastTokEndLoc); + } + finishNodeAt(node, type, endLoc) { + node.type = type; + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = endLoc.index; + if (this.options.attachComment) this.processComment(node); + return node; + } + resetStartLocation(node, startLoc) { + node.start = startLoc.index; + node.loc.start = startLoc; + if (this.options.ranges) node.range[0] = startLoc.index; + } + resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { + node.end = endLoc.index; + node.loc.end = endLoc; + if (this.options.ranges) node.range[1] = endLoc.index; + } + resetStartLocationFromNode(node, locationNode) { + this.resetStartLocation(node, locationNode.loc.start); + } +} +const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); +const FlowErrors = ParseErrorEnum`flow`({ + AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", + AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.", + AssignReservedType: ({ + reservedType + }) => `Cannot overwrite reserved type ${reservedType}.`, + DeclareClassElement: "The `declare` modifier can only appear on class fields.", + DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", + DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.", + EnumBooleanMemberNotInitialized: ({ + memberName, + enumName + }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`, + EnumDuplicateMemberName: ({ + memberName, + enumName + }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`, + EnumInconsistentMemberValues: ({ + enumName + }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`, + EnumInvalidExplicitType: ({ + invalidEnumType, + enumName + }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidExplicitTypeUnknownSupplied: ({ + enumName + }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerPrimaryType: ({ + enumName, + memberName, + explicitType + }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`, + EnumInvalidMemberInitializerSymbolType: ({ + enumName, + memberName + }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`, + EnumInvalidMemberInitializerUnknownType: ({ + enumName, + memberName + }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`, + EnumInvalidMemberName: ({ + enumName, + memberName, + suggestion + }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`, + EnumNumberMemberNotInitialized: ({ + enumName, + memberName + }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`, + EnumStringMemberInconsistentlyInitialized: ({ + enumName + }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`, + GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.", + ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.", + InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.", + InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.", + InexactVariance: "Explicit inexact syntax cannot have variance.", + InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.", + MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", + NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.", + NestedFlowComment: "Cannot have a flow comment inside another flow comment.", + PatternIsOptional: Object.assign({ + message: "A binding pattern parameter cannot be optional in an implementation signature." + }, { + reasonCode: "OptionalBindingPattern" + }), + SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.", + SpreadVariance: "Spread properties cannot have variance.", + ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.", + ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.", + ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.", + ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.", + ThisParamNoDefault: "The `this` parameter may not have a default value.", + TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.", + UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.", + UnexpectedReservedType: ({ + reservedType + }) => `Unexpected reserved type ${reservedType}.`, + UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.", + UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", + UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.", + UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".', + UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.", + UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.", + UnsupportedDeclareExportKind: ({ + unsupportedExportKind, + suggestion + }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`, + UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.", + UnterminatedFlowComment: "Unterminated flow-comment." +}); +function isEsModuleType(bodyElement) { + return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); +} +function hasTypeImportKind(node) { + return node.importKind === "type" || node.importKind === "typeof"; +} +const exportSuggestions = { + const: "declare export var", + let: "declare export var", + type: "export type", + interface: "export interface" +}; +function partition(list, test) { + const list1 = []; + const list2 = []; + for (let i = 0; i < list.length; i++) { + (test(list[i], i, list) ? list1 : list2).push(list[i]); + } + return [list1, list2]; +} +const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; +var flow = superClass => class FlowParserMixin extends superClass { + constructor(...args) { + super(...args); + this.flowPragma = undefined; + } + getScopeHandler() { + return FlowScopeHandler; + } + shouldParseTypes() { + return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; + } + shouldParseEnums() { + return !!this.getPluginOption("flow", "enums"); + } + finishToken(type, val) { + if (type !== 133 && type !== 13 && type !== 28) { + if (this.flowPragma === undefined) { + this.flowPragma = null; + } + } + super.finishToken(type, val); + } + addComment(comment) { + if (this.flowPragma === undefined) { + const matches = FLOW_PRAGMA_REGEX.exec(comment.value); + if (!matches) ;else if (matches[1] === "flow") { + this.flowPragma = "flow"; + } else if (matches[1] === "noflow") { + this.flowPragma = "noflow"; + } else { + throw new Error("Unexpected flow pragma"); + } + } + super.addComment(comment); + } + flowParseTypeInitialiser(tok) { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(tok || 14); + const type = this.flowParseType(); + this.state.inType = oldInType; + return type; + } + flowParsePredicate() { + const node = this.startNode(); + const moduloLoc = this.state.startLoc; + this.next(); + this.expectContextual(110); + if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) { + this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc); + } + if (this.eat(10)) { + node.value = super.parseExpression(); + this.expect(11); + return this.finishNode(node, "DeclaredPredicate"); + } else { + return this.finishNode(node, "InferredPredicate"); + } + } + flowParseTypeAndPredicateInitialiser() { + const oldInType = this.state.inType; + this.state.inType = true; + this.expect(14); + let type = null; + let predicate = null; + if (this.match(54)) { + this.state.inType = oldInType; + predicate = this.flowParsePredicate(); + } else { + type = this.flowParseType(); + this.state.inType = oldInType; + if (this.match(54)) { + predicate = this.flowParsePredicate(); + } + } + return [type, predicate]; + } + flowParseDeclareClass(node) { + this.next(); + this.flowParseInterfaceish(node, true); + return this.finishNode(node, "DeclareClass"); + } + flowParseDeclareFunction(node) { + this.next(); + const id = node.id = this.parseIdentifier(); + const typeNode = this.startNode(); + const typeContainer = this.startNode(); + if (this.match(47)) { + typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + typeNode.typeParameters = null; + } + this.expect(10); + const tmp = this.flowParseFunctionTypeParams(); + typeNode.params = tmp.params; + typeNode.rest = tmp.rest; + typeNode.this = tmp._this; + this.expect(11); + [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); + id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); + this.resetEndLocation(id); + this.semicolon(); + this.scope.declareName(node.id.name, 2048, node.id.loc.start); + return this.finishNode(node, "DeclareFunction"); + } + flowParseDeclare(node, insideModule) { + if (this.match(80)) { + return this.flowParseDeclareClass(node); + } else if (this.match(68)) { + return this.flowParseDeclareFunction(node); + } else if (this.match(74)) { + return this.flowParseDeclareVariable(node); + } else if (this.eatContextual(127)) { + if (this.match(16)) { + return this.flowParseDeclareModuleExports(node); + } else { + if (insideModule) { + this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc); + } + return this.flowParseDeclareModule(node); + } + } else if (this.isContextual(130)) { + return this.flowParseDeclareTypeAlias(node); + } else if (this.isContextual(131)) { + return this.flowParseDeclareOpaqueType(node); + } else if (this.isContextual(129)) { + return this.flowParseDeclareInterface(node); + } else if (this.match(82)) { + return this.flowParseDeclareExportDeclaration(node, insideModule); + } else { + this.unexpected(); + } + } + flowParseDeclareVariable(node) { + this.next(); + node.id = this.flowParseTypeAnnotatableIdentifier(true); + this.scope.declareName(node.id.name, 5, node.id.loc.start); + this.semicolon(); + return this.finishNode(node, "DeclareVariable"); + } + flowParseDeclareModule(node) { + this.scope.enter(0); + if (this.match(133)) { + node.id = super.parseExprAtom(); + } else { + node.id = this.parseIdentifier(); + } + const bodyNode = node.body = this.startNode(); + const body = bodyNode.body = []; + this.expect(5); + while (!this.match(8)) { + let bodyNode = this.startNode(); + if (this.match(83)) { + this.next(); + if (!this.isContextual(130) && !this.match(87)) { + this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc); + } + super.parseImport(bodyNode); + } else { + this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule); + bodyNode = this.flowParseDeclare(bodyNode, true); + } + body.push(bodyNode); + } + this.scope.exit(); + this.expect(8); + this.finishNode(bodyNode, "BlockStatement"); + let kind = null; + let hasModuleExport = false; + body.forEach(bodyElement => { + if (isEsModuleType(bodyElement)) { + if (kind === "CommonJS") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "ES"; + } else if (bodyElement.type === "DeclareModuleExports") { + if (hasModuleExport) { + this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement); + } + if (kind === "ES") { + this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement); + } + kind = "CommonJS"; + hasModuleExport = true; + } + }); + node.kind = kind || "CommonJS"; + return this.finishNode(node, "DeclareModule"); + } + flowParseDeclareExportDeclaration(node, insideModule) { + this.expect(82); + if (this.eat(65)) { + if (this.match(68) || this.match(80)) { + node.declaration = this.flowParseDeclare(this.startNode()); + } else { + node.declaration = this.flowParseType(); + this.semicolon(); + } + node.default = true; + return this.finishNode(node, "DeclareExportDeclaration"); + } else { + if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) { + const label = this.state.value; + throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, { + unsupportedExportKind: label, + suggestion: exportSuggestions[label] + }); + } + if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) { + node.declaration = this.flowParseDeclare(this.startNode()); + node.default = false; + return this.finishNode(node, "DeclareExportDeclaration"); + } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) { + node = this.parseExport(node, null); + if (node.type === "ExportNamedDeclaration") { + node.type = "ExportDeclaration"; + node.default = false; + delete node.exportKind; + } + node.type = "Declare" + node.type; + return node; + } + } + this.unexpected(); + } + flowParseDeclareModuleExports(node) { + this.next(); + this.expectContextual(111); + node.typeAnnotation = this.flowParseTypeAnnotation(); + this.semicolon(); + return this.finishNode(node, "DeclareModuleExports"); + } + flowParseDeclareTypeAlias(node) { + this.next(); + const finished = this.flowParseTypeAlias(node); + finished.type = "DeclareTypeAlias"; + return finished; + } + flowParseDeclareOpaqueType(node) { + this.next(); + const finished = this.flowParseOpaqueType(node, true); + finished.type = "DeclareOpaqueType"; + return finished; + } + flowParseDeclareInterface(node) { + this.next(); + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "DeclareInterface"); + } + flowParseInterfaceish(node, isClass) { + node.id = this.flowParseRestrictedIdentifier(!isClass, true); + this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (!isClass && this.eat(12)); + } + if (isClass) { + node.implements = []; + node.mixins = []; + if (this.eatContextual(117)) { + do { + node.mixins.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + if (this.eatContextual(113)) { + do { + node.implements.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + } + node.body = this.flowParseObjectType({ + allowStatic: isClass, + allowExact: false, + allowSpread: false, + allowProto: isClass, + allowInexact: false + }); + } + flowParseInterfaceExtends() { + const node = this.startNode(); + node.id = this.flowParseQualifiedTypeIdentifier(); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + return this.finishNode(node, "InterfaceExtends"); + } + flowParseInterface(node) { + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "InterfaceDeclaration"); + } + checkNotUnderscore(word) { + if (word === "_") { + this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc); + } + } + checkReservedType(word, startLoc, declaration) { + if (!reservedTypes.has(word)) return; + this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, { + reservedType: word + }); + } + flowParseRestrictedIdentifier(liberal, declaration) { + this.checkReservedType(this.state.value, this.state.startLoc, declaration); + return this.parseIdentifier(liberal); + } + flowParseTypeAlias(node) { + node.id = this.flowParseRestrictedIdentifier(false, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.right = this.flowParseTypeInitialiser(29); + this.semicolon(); + return this.finishNode(node, "TypeAlias"); + } + flowParseOpaqueType(node, declare) { + this.expectContextual(130); + node.id = this.flowParseRestrictedIdentifier(true, true); + this.scope.declareName(node.id.name, 8201, node.id.loc.start); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + node.supertype = null; + if (this.match(14)) { + node.supertype = this.flowParseTypeInitialiser(14); + } + node.impltype = null; + if (!declare) { + node.impltype = this.flowParseTypeInitialiser(29); + } + this.semicolon(); + return this.finishNode(node, "OpaqueType"); + } + flowParseTypeParameter(requireDefault = false) { + const nodeStartLoc = this.state.startLoc; + const node = this.startNode(); + const variance = this.flowParseVariance(); + const ident = this.flowParseTypeAnnotatableIdentifier(); + node.name = ident.name; + node.variance = variance; + node.bound = ident.typeAnnotation; + if (this.match(29)) { + this.eat(29); + node.default = this.flowParseType(); + } else { + if (requireDefault) { + this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc); + } + } + return this.finishNode(node, "TypeParameter"); + } + flowParseTypeParameterDeclaration() { + const oldInType = this.state.inType; + const node = this.startNode(); + node.params = []; + this.state.inType = true; + if (this.match(47) || this.match(142)) { + this.next(); + } else { + this.unexpected(); + } + let defaultRequired = false; + do { + const typeParameter = this.flowParseTypeParameter(defaultRequired); + node.params.push(typeParameter); + if (typeParameter.default) { + defaultRequired = true; + } + if (!this.match(48)) { + this.expect(12); + } + } while (!this.match(48)); + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterDeclaration"); + } + flowParseTypeParameterInstantiation() { + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expect(47); + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = false; + while (!this.match(48)) { + node.params.push(this.flowParseType()); + if (!this.match(48)) { + this.expect(12); + } + } + this.state.noAnonFunctionType = oldNoAnonFunctionType; + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseTypeParameterInstantiationCallOrNew() { + const node = this.startNode(); + const oldInType = this.state.inType; + node.params = []; + this.state.inType = true; + this.expect(47); + while (!this.match(48)) { + node.params.push(this.flowParseTypeOrImplicitInstantiation()); + if (!this.match(48)) { + this.expect(12); + } + } + this.expect(48); + this.state.inType = oldInType; + return this.finishNode(node, "TypeParameterInstantiation"); + } + flowParseInterfaceType() { + const node = this.startNode(); + this.expectContextual(129); + node.extends = []; + if (this.eat(81)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (this.eat(12)); + } + node.body = this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: false, + allowProto: false, + allowInexact: false + }); + return this.finishNode(node, "InterfaceTypeAnnotation"); + } + flowParseObjectPropertyKey() { + return this.match(134) || this.match(133) ? super.parseExprAtom() : this.parseIdentifier(true); + } + flowParseObjectTypeIndexer(node, isStatic, variance) { + node.static = isStatic; + if (this.lookahead().type === 14) { + node.id = this.flowParseObjectPropertyKey(); + node.key = this.flowParseTypeInitialiser(); + } else { + node.id = null; + node.key = this.flowParseType(); + } + this.expect(3); + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + return this.finishNode(node, "ObjectTypeIndexer"); + } + flowParseObjectTypeInternalSlot(node, isStatic) { + node.static = isStatic; + node.id = this.flowParseObjectPropertyKey(); + this.expect(3); + this.expect(3); + if (this.match(47) || this.match(10)) { + node.method = true; + node.optional = false; + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + } else { + node.method = false; + if (this.eat(17)) { + node.optional = true; + } + node.value = this.flowParseTypeInitialiser(); + } + return this.finishNode(node, "ObjectTypeInternalSlot"); + } + flowParseObjectTypeMethodish(node) { + node.params = []; + node.rest = null; + node.typeParameters = null; + node.this = null; + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + this.expect(10); + if (this.match(78)) { + node.this = this.flowParseFunctionTypeParam(true); + node.this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + node.params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + node.rest = this.flowParseFunctionTypeParam(false); + } + this.expect(11); + node.returnType = this.flowParseTypeInitialiser(); + return this.finishNode(node, "FunctionTypeAnnotation"); + } + flowParseObjectTypeCallProperty(node, isStatic) { + const valueNode = this.startNode(); + node.static = isStatic; + node.value = this.flowParseObjectTypeMethodish(valueNode); + return this.finishNode(node, "ObjectTypeCallProperty"); + } + flowParseObjectType({ + allowStatic, + allowExact, + allowSpread, + allowProto, + allowInexact + }) { + const oldInType = this.state.inType; + this.state.inType = true; + const nodeStart = this.startNode(); + nodeStart.callProperties = []; + nodeStart.properties = []; + nodeStart.indexers = []; + nodeStart.internalSlots = []; + let endDelim; + let exact; + let inexact = false; + if (allowExact && this.match(6)) { + this.expect(6); + endDelim = 9; + exact = true; + } else { + this.expect(5); + endDelim = 8; + exact = false; + } + nodeStart.exact = exact; + while (!this.match(endDelim)) { + let isStatic = false; + let protoStartLoc = null; + let inexactStartLoc = null; + const node = this.startNode(); + if (allowProto && this.isContextual(118)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + protoStartLoc = this.state.startLoc; + allowStatic = false; + } + } + if (allowStatic && this.isContextual(106)) { + const lookahead = this.lookahead(); + if (lookahead.type !== 14 && lookahead.type !== 17) { + this.next(); + isStatic = true; + } + } + const variance = this.flowParseVariance(); + if (this.eat(0)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (this.eat(0)) { + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); + } else { + nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); + } + } else if (this.match(10) || this.match(47)) { + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); + } else { + let kind = "init"; + if (this.isContextual(99) || this.isContextual(104)) { + const lookahead = this.lookahead(); + if (tokenIsLiteralPropertyName(lookahead.type)) { + kind = this.state.value; + this.next(); + } + } + const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); + if (propOrInexact === null) { + inexact = true; + inexactStartLoc = this.state.lastTokStartLoc; + } else { + nodeStart.properties.push(propOrInexact); + } + } + this.flowObjectTypeSemicolon(); + if (inexactStartLoc && !this.match(8) && !this.match(9)) { + this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc); + } + } + this.expect(endDelim); + if (allowSpread) { + nodeStart.inexact = inexact; + } + const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); + this.state.inType = oldInType; + return out; + } + flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) { + if (this.eat(21)) { + const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9); + if (isInexactToken) { + if (!allowSpread) { + this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc); + } else if (!allowInexact) { + this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc); + } + if (variance) { + this.raise(FlowErrors.InexactVariance, variance); + } + return null; + } + if (!allowSpread) { + this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc); + } + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.raise(FlowErrors.SpreadVariance, variance); + } + node.argument = this.flowParseType(); + return this.finishNode(node, "ObjectTypeSpreadProperty"); + } else { + node.key = this.flowParseObjectPropertyKey(); + node.static = isStatic; + node.proto = protoStartLoc != null; + node.kind = kind; + let optional = false; + if (this.match(47) || this.match(10)) { + node.method = true; + if (protoStartLoc != null) { + this.unexpected(protoStartLoc); + } + if (variance) { + this.unexpected(variance.loc.start); + } + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start)); + if (kind === "get" || kind === "set") { + this.flowCheckGetterSetterParams(node); + } + if (!allowSpread && node.key.name === "constructor" && node.value.this) { + this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this); + } + } else { + if (kind !== "init") this.unexpected(); + node.method = false; + if (this.eat(17)) { + optional = true; + } + node.value = this.flowParseTypeInitialiser(); + node.variance = variance; + } + node.optional = optional; + return this.finishNode(node, "ObjectTypeProperty"); + } + } + flowCheckGetterSetterParams(property) { + const paramCount = property.kind === "get" ? 0 : 1; + const length = property.value.params.length + (property.value.rest ? 1 : 0); + if (property.value.this) { + this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this); + } + if (length !== paramCount) { + this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property); + } + if (property.kind === "set" && property.value.rest) { + this.raise(Errors.BadSetterRestParameter, property); + } + } + flowObjectTypeSemicolon() { + if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) { + this.unexpected(); + } + } + flowParseQualifiedTypeIdentifier(startLoc, id) { + var _startLoc; + (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; + let node = id || this.flowParseRestrictedIdentifier(true); + while (this.eat(16)) { + const node2 = this.startNodeAt(startLoc); + node2.qualification = node; + node2.id = this.flowParseRestrictedIdentifier(true); + node = this.finishNode(node2, "QualifiedTypeIdentifier"); + } + return node; + } + flowParseGenericType(startLoc, id) { + const node = this.startNodeAt(startLoc); + node.typeParameters = null; + node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } + return this.finishNode(node, "GenericTypeAnnotation"); + } + flowParseTypeofType() { + const node = this.startNode(); + this.expect(87); + node.argument = this.flowParsePrimaryType(); + return this.finishNode(node, "TypeofTypeAnnotation"); + } + flowParseTupleType() { + const node = this.startNode(); + node.types = []; + this.expect(0); + while (this.state.pos < this.length && !this.match(3)) { + node.types.push(this.flowParseType()); + if (this.match(3)) break; + this.expect(12); + } + this.expect(3); + return this.finishNode(node, "TupleTypeAnnotation"); + } + flowParseFunctionTypeParam(first) { + let name = null; + let optional = false; + let typeAnnotation = null; + const node = this.startNode(); + const lh = this.lookahead(); + const isThis = this.state.type === 78; + if (lh.type === 14 || lh.type === 17) { + if (isThis && !first) { + this.raise(FlowErrors.ThisParamMustBeFirst, node); + } + name = this.parseIdentifier(isThis); + if (this.eat(17)) { + optional = true; + if (isThis) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, node); + } + } + typeAnnotation = this.flowParseTypeInitialiser(); + } else { + typeAnnotation = this.flowParseType(); + } + node.name = name; + node.optional = optional; + node.typeAnnotation = typeAnnotation; + return this.finishNode(node, "FunctionTypeParam"); + } + reinterpretTypeAsFunctionTypeParam(type) { + const node = this.startNodeAt(type.loc.start); + node.name = null; + node.optional = false; + node.typeAnnotation = type; + return this.finishNode(node, "FunctionTypeParam"); + } + flowParseFunctionTypeParams(params = []) { + let rest = null; + let _this = null; + if (this.match(78)) { + _this = this.flowParseFunctionTypeParam(true); + _this.name = null; + if (!this.match(11)) { + this.expect(12); + } + } + while (!this.match(11) && !this.match(21)) { + params.push(this.flowParseFunctionTypeParam(false)); + if (!this.match(11)) { + this.expect(12); + } + } + if (this.eat(21)) { + rest = this.flowParseFunctionTypeParam(false); + } + return { + params, + rest, + _this + }; + } + flowIdentToTypeAnnotation(startLoc, node, id) { + switch (id.name) { + case "any": + return this.finishNode(node, "AnyTypeAnnotation"); + case "bool": + case "boolean": + return this.finishNode(node, "BooleanTypeAnnotation"); + case "mixed": + return this.finishNode(node, "MixedTypeAnnotation"); + case "empty": + return this.finishNode(node, "EmptyTypeAnnotation"); + case "number": + return this.finishNode(node, "NumberTypeAnnotation"); + case "string": + return this.finishNode(node, "StringTypeAnnotation"); + case "symbol": + return this.finishNode(node, "SymbolTypeAnnotation"); + default: + this.checkNotUnderscore(id.name); + return this.flowParseGenericType(startLoc, id); + } + } + flowParsePrimaryType() { + const startLoc = this.state.startLoc; + const node = this.startNode(); + let tmp; + let type; + let isGroupedType = false; + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + switch (this.state.type) { + case 5: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: false, + allowSpread: true, + allowProto: false, + allowInexact: true + }); + case 6: + return this.flowParseObjectType({ + allowStatic: false, + allowExact: true, + allowSpread: true, + allowProto: false, + allowInexact: false + }); + case 0: + this.state.noAnonFunctionType = false; + type = this.flowParseTupleType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + return type; + case 47: + node.typeParameters = this.flowParseTypeParameterDeclaration(); + this.expect(10); + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + return this.finishNode(node, "FunctionTypeAnnotation"); + case 10: + this.next(); + if (!this.match(11) && !this.match(21)) { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + const token = this.lookahead().type; + isGroupedType = token !== 17 && token !== 14; + } else { + isGroupedType = true; + } + } + if (isGroupedType) { + this.state.noAnonFunctionType = false; + type = this.flowParseType(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) { + this.expect(11); + return type; + } else { + this.eat(12); + } + } + if (type) { + tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); + } else { + tmp = this.flowParseFunctionTypeParams(); + } + node.params = tmp.params; + node.rest = tmp.rest; + node.this = tmp._this; + this.expect(11); + this.expect(19); + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + case 133: + return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); + case 85: + case 86: + node.value = this.match(85); + this.next(); + return this.finishNode(node, "BooleanLiteralTypeAnnotation"); + case 53: + if (this.state.value === "-") { + this.next(); + if (this.match(134)) { + return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node); + } + if (this.match(135)) { + return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); + } + throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc); + } + this.unexpected(); + return; + case 134: + return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); + case 135: + return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); + case 88: + this.next(); + return this.finishNode(node, "VoidTypeAnnotation"); + case 84: + this.next(); + return this.finishNode(node, "NullLiteralTypeAnnotation"); + case 78: + this.next(); + return this.finishNode(node, "ThisTypeAnnotation"); + case 55: + this.next(); + return this.finishNode(node, "ExistsTypeAnnotation"); + case 87: + return this.flowParseTypeofType(); + default: + if (tokenIsKeyword(this.state.type)) { + const label = tokenLabelName(this.state.type); + this.next(); + return super.createIdentifier(node, label); + } else if (tokenIsIdentifier(this.state.type)) { + if (this.isContextual(129)) { + return this.flowParseInterfaceType(); + } + return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier()); + } + } + this.unexpected(); + } + flowParsePostfixType() { + const startLoc = this.state.startLoc; + let type = this.flowParsePrimaryType(); + let seenOptionalIndexedAccess = false; + while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + const optional = this.eat(18); + seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional; + this.expect(0); + if (!optional && this.match(3)) { + node.elementType = type; + this.next(); + type = this.finishNode(node, "ArrayTypeAnnotation"); + } else { + node.objectType = type; + node.indexType = this.flowParseType(); + this.expect(3); + if (seenOptionalIndexedAccess) { + node.optional = optional; + type = this.finishNode(node, "OptionalIndexedAccessType"); + } else { + type = this.finishNode(node, "IndexedAccessType"); + } + } + } + return type; + } + flowParsePrefixType() { + const node = this.startNode(); + if (this.eat(17)) { + node.typeAnnotation = this.flowParsePrefixType(); + return this.finishNode(node, "NullableTypeAnnotation"); + } else { + return this.flowParsePostfixType(); + } + } + flowParseAnonFunctionWithoutParens() { + const param = this.flowParsePrefixType(); + if (!this.state.noAnonFunctionType && this.eat(19)) { + const node = this.startNodeAt(param.loc.start); + node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; + node.rest = null; + node.this = null; + node.returnType = this.flowParseType(); + node.typeParameters = null; + return this.finishNode(node, "FunctionTypeAnnotation"); + } + return param; + } + flowParseIntersectionType() { + const node = this.startNode(); + this.eat(45); + const type = this.flowParseAnonFunctionWithoutParens(); + node.types = [type]; + while (this.eat(45)) { + node.types.push(this.flowParseAnonFunctionWithoutParens()); + } + return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); + } + flowParseUnionType() { + const node = this.startNode(); + this.eat(43); + const type = this.flowParseIntersectionType(); + node.types = [type]; + while (this.eat(43)) { + node.types.push(this.flowParseIntersectionType()); + } + return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); + } + flowParseType() { + const oldInType = this.state.inType; + this.state.inType = true; + const type = this.flowParseUnionType(); + this.state.inType = oldInType; + return type; + } + flowParseTypeOrImplicitInstantiation() { + if (this.state.type === 132 && this.state.value === "_") { + const startLoc = this.state.startLoc; + const node = this.parseIdentifier(); + return this.flowParseGenericType(startLoc, node); + } else { + return this.flowParseType(); + } + } + flowParseTypeAnnotation() { + const node = this.startNode(); + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "TypeAnnotation"); + } + flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { + const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); + if (this.match(14)) { + ident.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(ident); + } + return ident; + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + flowParseVariance() { + let variance = null; + if (this.match(53)) { + variance = this.startNode(); + if (this.state.value === "+") { + variance.kind = "plus"; + } else { + variance.kind = "minus"; + } + this.next(); + return this.finishNode(variance, "Variance"); + } + return variance; + } + parseFunctionBody(node, allowExpressionBody, isMethod = false) { + if (allowExpressionBody) { + this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod)); + return; + } + super.parseFunctionBody(node, false, isMethod); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; + } + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + parseStatementLike(flags) { + if (this.state.strict && this.isContextual(129)) { + const lookahead = this.lookahead(); + if (tokenIsKeywordOrIdentifier(lookahead.type)) { + const node = this.startNode(); + this.next(); + return this.flowParseInterface(node); + } + } else if (this.shouldParseEnums() && this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + const stmt = super.parseStatementLike(flags); + if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { + this.flowPragma = null; + } + return stmt; + } + parseExpressionStatement(node, expr, decorators) { + if (expr.type === "Identifier") { + if (expr.name === "declare") { + if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) { + return this.flowParseDeclare(node); + } + } else if (tokenIsIdentifier(this.state.type)) { + if (expr.name === "interface") { + return this.flowParseInterface(node); + } else if (expr.name === "type") { + return this.flowParseTypeAlias(node); + } else if (expr.name === "opaque") { + return this.flowParseOpaqueType(node, false); + } + } + } + return super.parseExpressionStatement(node, expr, decorators); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) { + return !this.state.containsEsc; + } + return super.shouldParseExportDeclaration(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 126) { + return this.state.containsEsc; + } + return super.isExportDefaultSpecifier(); + } + parseExportDefaultExpression() { + if (this.shouldParseEnums() && this.isContextual(126)) { + const node = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(node); + } + return super.parseExportDefaultExpression(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.match(17)) return expr; + if (this.state.maybeInArrowParameters) { + const nextCh = this.lookaheadCharCode(); + if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { + this.setOptionalParametersError(refExpressionErrors); + return expr; + } + } + this.expect(17); + const state = this.state.clone(); + const originalNoArrowAt = this.state.noArrowAt; + const node = this.startNodeAt(startLoc); + let { + consequent, + failed + } = this.tryParseConditionalConsequent(); + let [valid, invalid] = this.getArrowLikeExpressions(consequent); + if (failed || invalid.length > 0) { + const noArrowAt = [...originalNoArrowAt]; + if (invalid.length > 0) { + this.state = state; + this.state.noArrowAt = noArrowAt; + for (let i = 0; i < invalid.length; i++) { + noArrowAt.push(invalid[i].start); + } + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + [valid, invalid] = this.getArrowLikeExpressions(consequent); + } + if (failed && valid.length > 1) { + this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc); + } + if (failed && valid.length === 1) { + this.state = state; + noArrowAt.push(valid[0].start); + this.state.noArrowAt = noArrowAt; + ({ + consequent, + failed + } = this.tryParseConditionalConsequent()); + } + } + this.getArrowLikeExpressions(consequent, true); + this.state.noArrowAt = originalNoArrowAt; + this.expect(14); + node.test = expr; + node.consequent = consequent; + node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined)); + return this.finishNode(node, "ConditionalExpression"); + } + tryParseConditionalConsequent() { + this.state.noArrowParamsConversionAt.push(this.state.start); + const consequent = this.parseMaybeAssignAllowIn(); + const failed = !this.match(14); + this.state.noArrowParamsConversionAt.pop(); + return { + consequent, + failed + }; + } + getArrowLikeExpressions(node, disallowInvalid) { + const stack = [node]; + const arrows = []; + while (stack.length !== 0) { + const node = stack.pop(); + if (node.type === "ArrowFunctionExpression") { + if (node.typeParameters || !node.returnType) { + this.finishArrowValidation(node); + } else { + arrows.push(node); + } + stack.push(node.body); + } else if (node.type === "ConditionalExpression") { + stack.push(node.consequent); + stack.push(node.alternate); + } + } + if (disallowInvalid) { + arrows.forEach(node => this.finishArrowValidation(node)); + return [arrows, []]; + } + return partition(arrows, node => node.params.every(param => this.isAssignable(param, true))); + } + finishArrowValidation(node) { + var _node$extra; + this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false); + this.scope.enter(2 | 4); + super.checkParams(node, false, true); + this.scope.exit(); + } + forwardNoArrowParamsConversionAt(node, parse) { + let result; + if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + this.state.noArrowParamsConversionAt.push(this.state.start); + result = parse(); + this.state.noArrowParamsConversionAt.pop(); + } else { + result = parse(); + } + return result; + } + parseParenItem(node, startLoc) { + node = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + node.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TypeCastExpression"); + } + return node; + } + assertModuleNodeAllowed(node) { + if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { + return; + } + super.assertModuleNodeAllowed(node); + } + parseExportDeclaration(node) { + if (this.isContextual(130)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + if (this.match(5)) { + node.specifiers = this.parseExportSpecifiers(true); + super.parseExportFrom(node); + return null; + } else { + return this.flowParseTypeAlias(declarationNode); + } + } else if (this.isContextual(131)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseOpaqueType(declarationNode, false); + } else if (this.isContextual(129)) { + node.exportKind = "type"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseInterface(declarationNode); + } else if (this.shouldParseEnums() && this.isContextual(126)) { + node.exportKind = "value"; + const declarationNode = this.startNode(); + this.next(); + return this.flowParseEnumDeclaration(declarationNode); + } else { + return super.parseExportDeclaration(node); + } + } + eatExportStar(node) { + if (super.eatExportStar(node)) return true; + if (this.isContextual(130) && this.lookahead().type === 55) { + node.exportKind = "type"; + this.next(); + this.next(); + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + const { + startLoc + } = this.state; + const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); + if (hasNamespace && node.exportKind === "type") { + this.unexpected(startLoc); + } + return hasNamespace; + } + parseClassId(node, isStatement, optionalId) { + super.parseClassId(node, isStatement, optionalId); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + } + parseClassMember(classBody, member, state) { + const { + startLoc + } = this.state; + if (this.isContextual(125)) { + if (super.parseClassMemberFromModifier(classBody, member)) { + return; + } + member.declare = true; + } + super.parseClassMember(classBody, member, state); + if (member.declare) { + if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { + this.raise(FlowErrors.DeclareClassElement, startLoc); + } else if (member.value) { + this.raise(FlowErrors.DeclareClassFieldInitializer, member.value); + } + } + } + isIterator(word) { + return word === "iterator" || word === "asyncIterator"; + } + readIterator() { + const word = super.readWord1(); + const fullWord = "@@" + word; + if (!this.isIterator(word) || !this.state.inType) { + this.raise(Errors.InvalidIdentifier, this.state.curPosition(), { + identifierName: fullWord + }); + } + this.finishToken(132, fullWord); + } + getTokenFromCode(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 123 && next === 124) { + this.finishOp(6, 2); + } else if (this.state.inType && (code === 62 || code === 60)) { + this.finishOp(code === 62 ? 48 : 47, 1); + } else if (this.state.inType && code === 63) { + if (next === 46) { + this.finishOp(18, 2); + } else { + this.finishOp(17, 1); + } + } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) { + this.state.pos += 2; + this.readIterator(); + } else { + super.getTokenFromCode(code); + } + } + isAssignable(node, isBinding) { + if (node.type === "TypeCastExpression") { + return this.isAssignable(node.expression, isBinding); + } else { + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + super.toAssignable(node, isLHS); + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + super.toAssignableList(exprList, trailingCommaLoc, isLHS); + } + toReferencedList(exprList, isParenthesizedExpr) { + for (let i = 0; i < exprList.length; i++) { + var _expr$extra; + const expr = exprList[i]; + if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { + this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation); + } + } + return exprList; + } + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); + if (canBePattern && !this.state.maybeInArrowParameters) { + this.toReferencedList(node.elements); + } + return node; + } + isValidLVal(type, isParenthesized, binding) { + return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding); + } + parseClassProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (this.match(14)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return super.parseClassPrivateProperty(node); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(14) || super.isClassProperty(); + } + isNonstaticConstructor(method) { + return !this.match(14) && super.isNonstaticConstructor(method); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + if (method.params && isConstructor) { + const params = method.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { + const params = method.value.params; + if (params.length > 0 && this.isThisParam(params[0])) { + this.raise(FlowErrors.ThisParamBannedInConstructor, method); + } + } + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + if (method.variance) { + this.unexpected(method.variance.loc.start); + } + delete method.variance; + if (this.match(47)) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass && this.match(47)) { + node.superTypeParameters = this.flowParseTypeParameterInstantiation(); + } + if (this.isContextual(113)) { + this.next(); + const implemented = node.implements = []; + do { + const node = this.startNode(); + node.id = this.flowParseRestrictedIdentifier(true); + if (this.match(47)) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + implemented.push(this.finishNode(node, "ClassImplements")); + } while (this.eat(12)); + } + } + checkGetterSetterParams(method) { + super.checkGetterSetterParams(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length > 0) { + const param = params[0]; + if (this.isThisParam(param) && method.kind === "get") { + this.raise(FlowErrors.GetterMayNotHaveThisParam, param); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.SetterMayNotHaveThisParam, param); + } + } + } + parsePropertyNamePrefixOperator(node) { + node.variance = this.flowParseVariance(); + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + if (prop.variance) { + this.unexpected(prop.variance.loc.start); + } + delete prop.variance; + let typeParameters; + if (this.match(47) && !isAccessor) { + typeParameters = this.flowParseTypeParameterDeclaration(); + if (!this.match(10)) this.unexpected(); + } + const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + if (typeParameters) { + (result.value || result).typeParameters = typeParameters; + } + return result; + } + parseAssignableListItemTypes(param) { + if (this.eat(17)) { + if (param.type !== "Identifier") { + this.raise(FlowErrors.PatternIsOptional, param); + } + if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamMayNotBeOptional, param); + } + param.optional = true; + } + if (this.match(14)) { + param.typeAnnotation = this.flowParseTypeAnnotation(); + } else if (this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamAnnotationRequired, param); + } + if (this.match(29) && this.isThisParam(param)) { + this.raise(FlowErrors.ThisParamNoDefault, param); + } + this.resetEndLocation(param); + return param; + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation); + } + return node; + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + if (!isExport) return true; + const ch = this.lookaheadCharCode(); + return ch === 123 || ch === 42; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + if (!phase && this.match(65)) { + return; + } + node.exportKind = phase === "type" ? phase : "value"; + } else { + if (phase === "type" && this.match(55)) this.unexpected(); + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + const firstIdent = specifier.imported; + let specifierTypeKind = null; + if (firstIdent.type === "Identifier") { + if (firstIdent.name === "type") { + specifierTypeKind = "type"; + } else if (firstIdent.name === "typeof") { + specifierTypeKind = "typeof"; + } + } + let isBinding = false; + if (this.isContextual(93) && !this.isLookaheadContextual("as")) { + const as_ident = this.parseIdentifier(true); + if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = as_ident; + specifier.importKind = specifierTypeKind; + specifier.local = cloneIdentifier(as_ident); + } else { + specifier.imported = firstIdent; + specifier.importKind = null; + specifier.local = this.parseIdentifier(); + } + } else { + if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) { + specifier.imported = this.parseIdentifier(true); + specifier.importKind = specifierTypeKind; + } else { + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: firstIdent.value + }); + } + specifier.imported = firstIdent; + specifier.importKind = null; + } + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + isBinding = true; + specifier.local = cloneIdentifier(specifier.imported); + } + } + const specifierIsTypeImport = hasTypeImportKind(specifier); + if (isInTypeOnlyImport && specifierIsTypeImport) { + this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier); + } + if (isInTypeOnlyImport || specifierIsTypeImport) { + this.checkReservedType(specifier.local.name, specifier.local.loc.start, true); + } + if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) { + this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true); + } + return this.finishImportSpecifier(specifier, "ImportSpecifier"); + } + parseBindingAtom() { + switch (this.state.type) { + case 78: + return this.parseIdentifier(true); + default: + return super.parseBindingAtom(); + } + } + parseFunctionParams(node, isConstructor) { + const kind = node.kind; + if (kind !== "get" && kind !== "set" && this.match(47)) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (this.match(14)) { + decl.id.typeAnnotation = this.flowParseTypeAnnotation(); + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + node.returnType = this.flowParseTypeAnnotation(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx; + let state = null; + let jsx; + if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types$1.j_oTag || currentContext === types$1.j_expr) { + context.pop(); + } + } + if ((_jsx = jsx) != null && _jsx.error || this.match(47)) { + var _jsx2, _jsx3; + state = state || this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _arrowExpression$extr; + typeParameters = this.flowParseTypeParameterDeclaration(); + const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => { + const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + this.resetStartLocationFromNode(result, typeParameters); + return result; + }); + if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort(); + const expr = this.maybeUnwrapTypeCastExpression(arrowExpression); + if (expr.type !== "ArrowFunctionExpression") abort(); + expr.typeParameters = typeParameters; + this.resetStartLocationFromNode(expr, typeParameters); + return arrowExpression; + }, state); + let arrowExpression = null; + if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { + if (!arrow.error && !arrow.aborted) { + if (arrow.node.async) { + this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters); + } + return arrow.node; + } + arrowExpression = arrow.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrowExpression) { + this.state = arrow.failState; + return arrowExpression; + } + if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error; + if (arrow.thrown) throw arrow.error; + throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters); + } + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(() => { + const oldNoAnonFunctionType = this.state.noAnonFunctionType; + this.state.noAnonFunctionType = true; + const typeNode = this.startNode(); + [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); + this.state.noAnonFunctionType = oldNoAnonFunctionType; + if (this.canInsertSemicolon()) this.unexpected(); + if (!this.match(19)) this.unexpected(); + return typeNode; + }); + if (result.thrown) return null; + if (result.error) this.state = result.failState; + node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; + } + return super.parseArrow(node); + } + shouldParseArrow(params) { + return this.match(14) || super.shouldParseArrow(params); + } + setArrowFunctionParameters(node, params) { + if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + node.params = params; + } else { + super.setArrowFunctionParameters(node, params); + } + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { + return; + } + for (let i = 0; i < node.params.length; i++) { + if (this.isThisParam(node.params[i]) && i > 0) { + this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]); + } + } + super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged); + } + parseParenAndDistinguishExpression(canBeArrow) { + return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1); + } + parseSubscripts(base, startLoc, noCalls) { + if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startLoc.index) !== -1) { + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = super.parseCallExpressionArguments(11, false); + base = this.finishNode(node, "CallExpression"); + } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) { + const state = this.state.clone(); + const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state); + if (!arrow.error && !arrow.aborted) return arrow.node; + const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state); + if (result.node && !result.error) return result.node; + if (arrow.node) { + this.state = arrow.failState; + return arrow.node; + } + if (result.node) { + this.state = result.failState; + return result.node; + } + throw arrow.error || result.error; + } + return super.parseSubscripts(base, startLoc, noCalls); + } + parseSubscript(base, startLoc, noCalls, subscriptState) { + if (this.match(18) && this.isLookaheadToken_lt()) { + subscriptState.optionalChainMember = true; + if (noCalls) { + subscriptState.stop = true; + return base; + } + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + node.typeArguments = this.flowParseTypeParameterInstantiation(); + this.expect(10); + node.arguments = this.parseCallExpressionArguments(11, false); + node.optional = true; + return this.finishCallExpression(node, true); + } else if (!noCalls && this.shouldParseTypes() && this.match(47)) { + const node = this.startNodeAt(startLoc); + node.callee = base; + const result = this.tryParse(() => { + node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); + this.expect(10); + node.arguments = super.parseCallExpressionArguments(11, false); + if (subscriptState.optionalChainMember) { + node.optional = false; + } + return this.finishCallExpression(node, subscriptState.optionalChainMember); + }); + if (result.node) { + if (result.error) this.state = result.failState; + return result.node; + } + } + return super.parseSubscript(base, startLoc, noCalls, subscriptState); + } + parseNewCallee(node) { + super.parseNewCallee(node); + let targs = null; + if (this.shouldParseTypes() && this.match(47)) { + targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; + } + node.typeArguments = targs; + } + parseAsyncArrowWithTypeParameters(startLoc) { + const node = this.startNodeAt(startLoc); + this.parseFunctionParams(node, false); + if (!this.parseArrow(node)) return; + return super.parseArrowExpression(node, undefined, true); + } + readToken_mult_modulo(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 42 && next === 47 && this.state.hasFlowComment) { + this.state.hasFlowComment = false; + this.state.pos += 2; + this.nextToken(); + return; + } + super.readToken_mult_modulo(code); + } + readToken_pipe_amp(code) { + const next = this.input.charCodeAt(this.state.pos + 1); + if (code === 124 && next === 125) { + this.finishOp(9, 2); + return; + } + super.readToken_pipe_amp(code); + } + parseTopLevel(file, program) { + const fileNode = super.parseTopLevel(file, program); + if (this.state.hasFlowComment) { + this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition()); + } + return fileNode; + } + skipBlockComment() { + if (this.hasPlugin("flowComments") && this.skipFlowComment()) { + if (this.state.hasFlowComment) { + throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc); + } + this.hasFlowCommentCompletion(); + const commentSkip = this.skipFlowComment(); + if (commentSkip) { + this.state.pos += commentSkip; + this.state.hasFlowComment = true; + } + return; + } + return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/"); + } + skipFlowComment() { + const { + pos + } = this.state; + let shiftToFirstNonWhiteSpace = 2; + while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { + shiftToFirstNonWhiteSpace++; + } + const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); + const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); + if (ch2 === 58 && ch3 === 58) { + return shiftToFirstNonWhiteSpace + 2; + } + if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { + return shiftToFirstNonWhiteSpace + 12; + } + if (ch2 === 58 && ch3 !== 58) { + return shiftToFirstNonWhiteSpace; + } + return false; + } + hasFlowCommentCompletion() { + const end = this.input.indexOf("*/", this.state.pos); + if (end === -1) { + throw this.raise(Errors.UnterminatedComment, this.state.curPosition()); + } + } + flowEnumErrorBooleanMemberNotInitialized(loc, { + enumName, + memberName + }) { + this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, { + memberName, + enumName + }); + } + flowEnumErrorInvalidMemberInitializer(loc, enumContext) { + return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext); + } + flowEnumErrorNumberMemberNotInitialized(loc, details) { + this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details); + } + flowEnumErrorStringMemberInconsistentlyInitialized(node, details) { + this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details); + } + flowEnumMemberInit() { + const startLoc = this.state.startLoc; + const endOfInit = () => this.match(12) || this.match(8); + switch (this.state.type) { + case 134: + { + const literal = this.parseNumericLiteral(this.state.value); + if (endOfInit()) { + return { + type: "number", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 133: + { + const literal = this.parseStringLiteral(this.state.value); + if (endOfInit()) { + return { + type: "string", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + case 85: + case 86: + { + const literal = this.parseBooleanLiteral(this.match(85)); + if (endOfInit()) { + return { + type: "boolean", + loc: literal.loc.start, + value: literal + }; + } + return { + type: "invalid", + loc: startLoc + }; + } + default: + return { + type: "invalid", + loc: startLoc + }; + } + } + flowEnumMemberRaw() { + const loc = this.state.startLoc; + const id = this.parseIdentifier(true); + const init = this.eat(29) ? this.flowEnumMemberInit() : { + type: "none", + loc + }; + return { + id, + init + }; + } + flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) { + const { + explicitType + } = context; + if (explicitType === null) { + return; + } + if (explicitType !== expectedType) { + this.flowEnumErrorInvalidMemberInitializer(loc, context); + } + } + flowEnumMembers({ + enumName, + explicitType + }) { + const seenNames = new Set(); + const members = { + booleanMembers: [], + numberMembers: [], + stringMembers: [], + defaultedMembers: [] + }; + let hasUnknownMembers = false; + while (!this.match(8)) { + if (this.eat(21)) { + hasUnknownMembers = true; + break; + } + const memberNode = this.startNode(); + const { + id, + init + } = this.flowEnumMemberRaw(); + const memberName = id.name; + if (memberName === "") { + continue; + } + if (/^[a-z]/.test(memberName)) { + this.raise(FlowErrors.EnumInvalidMemberName, id, { + memberName, + suggestion: memberName[0].toUpperCase() + memberName.slice(1), + enumName + }); + } + if (seenNames.has(memberName)) { + this.raise(FlowErrors.EnumDuplicateMemberName, id, { + memberName, + enumName + }); + } + seenNames.add(memberName); + const context = { + enumName, + explicitType, + memberName + }; + memberNode.id = id; + switch (init.type) { + case "boolean": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean"); + memberNode.init = init.value; + members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); + break; + } + case "number": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number"); + memberNode.init = init.value; + members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); + break; + } + case "string": + { + this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string"); + memberNode.init = init.value; + members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); + break; + } + case "invalid": + { + throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context); + } + case "none": + { + switch (explicitType) { + case "boolean": + this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context); + break; + case "number": + this.flowEnumErrorNumberMemberNotInitialized(init.loc, context); + break; + default: + members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); + } + } + } + if (!this.match(8)) { + this.expect(12); + } + } + return { + members, + hasUnknownMembers + }; + } + flowEnumStringMembers(initializedMembers, defaultedMembers, { + enumName + }) { + if (initializedMembers.length === 0) { + return defaultedMembers; + } else if (defaultedMembers.length === 0) { + return initializedMembers; + } else if (defaultedMembers.length > initializedMembers.length) { + for (const member of initializedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return defaultedMembers; + } else { + for (const member of defaultedMembers) { + this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { + enumName + }); + } + return initializedMembers; + } + } + flowEnumParseExplicitType({ + enumName + }) { + if (!this.eatContextual(102)) return null; + if (!tokenIsIdentifier(this.state.type)) { + throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, { + enumName + }); + } + const { + value + } = this.state; + this.next(); + if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { + this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, { + enumName, + invalidEnumType: value + }); + } + return value; + } + flowEnumBody(node, id) { + const enumName = id.name; + const nameLoc = id.loc.start; + const explicitType = this.flowEnumParseExplicitType({ + enumName + }); + this.expect(5); + const { + members, + hasUnknownMembers + } = this.flowEnumMembers({ + enumName, + explicitType + }); + node.hasUnknownMembers = hasUnknownMembers; + switch (explicitType) { + case "boolean": + node.explicitType = true; + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + case "number": + node.explicitType = true; + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + case "string": + node.explicitType = true; + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + case "symbol": + node.members = members.defaultedMembers; + this.expect(8); + return this.finishNode(node, "EnumSymbolBody"); + default: + { + const empty = () => { + node.members = []; + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + }; + node.explicitType = false; + const boolsLen = members.booleanMembers.length; + const numsLen = members.numberMembers.length; + const strsLen = members.stringMembers.length; + const defaultedLen = members.defaultedMembers.length; + if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { + return empty(); + } else if (!boolsLen && !numsLen) { + node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { + enumName + }); + this.expect(8); + return this.finishNode(node, "EnumStringBody"); + } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.booleanMembers; + this.expect(8); + return this.finishNode(node, "EnumBooleanBody"); + } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { + for (const member of members.defaultedMembers) { + this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, { + enumName, + memberName: member.id.name + }); + } + node.members = members.numberMembers; + this.expect(8); + return this.finishNode(node, "EnumNumberBody"); + } else { + this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, { + enumName + }); + return empty(); + } + } + } + } + flowParseEnumDeclaration(node) { + const id = this.parseIdentifier(); + node.id = id; + node.body = this.flowEnumBody(this.startNode(), id); + return this.finishNode(node, "EnumDeclaration"); + } + isLookaheadToken_lt() { + const next = this.nextTokenStart(); + if (this.input.charCodeAt(next) === 60) { + const afterNext = this.input.charCodeAt(next + 1); + return afterNext !== 60 && afterNext !== 61; + } + return false; + } + maybeUnwrapTypeCastExpression(node) { + return node.type === "TypeCastExpression" ? node.expression : node; + } +}; +const entities = { + __proto__: null, + quot: "\u0022", + amp: "&", + apos: "\u0027", + lt: "<", + gt: ">", + nbsp: "\u00A0", + iexcl: "\u00A1", + cent: "\u00A2", + pound: "\u00A3", + curren: "\u00A4", + yen: "\u00A5", + brvbar: "\u00A6", + sect: "\u00A7", + uml: "\u00A8", + copy: "\u00A9", + ordf: "\u00AA", + laquo: "\u00AB", + not: "\u00AC", + shy: "\u00AD", + reg: "\u00AE", + macr: "\u00AF", + deg: "\u00B0", + plusmn: "\u00B1", + sup2: "\u00B2", + sup3: "\u00B3", + acute: "\u00B4", + micro: "\u00B5", + para: "\u00B6", + middot: "\u00B7", + cedil: "\u00B8", + sup1: "\u00B9", + ordm: "\u00BA", + raquo: "\u00BB", + frac14: "\u00BC", + frac12: "\u00BD", + frac34: "\u00BE", + iquest: "\u00BF", + Agrave: "\u00C0", + Aacute: "\u00C1", + Acirc: "\u00C2", + Atilde: "\u00C3", + Auml: "\u00C4", + Aring: "\u00C5", + AElig: "\u00C6", + Ccedil: "\u00C7", + Egrave: "\u00C8", + Eacute: "\u00C9", + Ecirc: "\u00CA", + Euml: "\u00CB", + Igrave: "\u00CC", + Iacute: "\u00CD", + Icirc: "\u00CE", + Iuml: "\u00CF", + ETH: "\u00D0", + Ntilde: "\u00D1", + Ograve: "\u00D2", + Oacute: "\u00D3", + Ocirc: "\u00D4", + Otilde: "\u00D5", + Ouml: "\u00D6", + times: "\u00D7", + Oslash: "\u00D8", + Ugrave: "\u00D9", + Uacute: "\u00DA", + Ucirc: "\u00DB", + Uuml: "\u00DC", + Yacute: "\u00DD", + THORN: "\u00DE", + szlig: "\u00DF", + agrave: "\u00E0", + aacute: "\u00E1", + acirc: "\u00E2", + atilde: "\u00E3", + auml: "\u00E4", + aring: "\u00E5", + aelig: "\u00E6", + ccedil: "\u00E7", + egrave: "\u00E8", + eacute: "\u00E9", + ecirc: "\u00EA", + euml: "\u00EB", + igrave: "\u00EC", + iacute: "\u00ED", + icirc: "\u00EE", + iuml: "\u00EF", + eth: "\u00F0", + ntilde: "\u00F1", + ograve: "\u00F2", + oacute: "\u00F3", + ocirc: "\u00F4", + otilde: "\u00F5", + ouml: "\u00F6", + divide: "\u00F7", + oslash: "\u00F8", + ugrave: "\u00F9", + uacute: "\u00FA", + ucirc: "\u00FB", + uuml: "\u00FC", + yacute: "\u00FD", + thorn: "\u00FE", + yuml: "\u00FF", + OElig: "\u0152", + oelig: "\u0153", + Scaron: "\u0160", + scaron: "\u0161", + Yuml: "\u0178", + fnof: "\u0192", + circ: "\u02C6", + tilde: "\u02DC", + Alpha: "\u0391", + Beta: "\u0392", + Gamma: "\u0393", + Delta: "\u0394", + Epsilon: "\u0395", + Zeta: "\u0396", + Eta: "\u0397", + Theta: "\u0398", + Iota: "\u0399", + Kappa: "\u039A", + Lambda: "\u039B", + Mu: "\u039C", + Nu: "\u039D", + Xi: "\u039E", + Omicron: "\u039F", + Pi: "\u03A0", + Rho: "\u03A1", + Sigma: "\u03A3", + Tau: "\u03A4", + Upsilon: "\u03A5", + Phi: "\u03A6", + Chi: "\u03A7", + Psi: "\u03A8", + Omega: "\u03A9", + alpha: "\u03B1", + beta: "\u03B2", + gamma: "\u03B3", + delta: "\u03B4", + epsilon: "\u03B5", + zeta: "\u03B6", + eta: "\u03B7", + theta: "\u03B8", + iota: "\u03B9", + kappa: "\u03BA", + lambda: "\u03BB", + mu: "\u03BC", + nu: "\u03BD", + xi: "\u03BE", + omicron: "\u03BF", + pi: "\u03C0", + rho: "\u03C1", + sigmaf: "\u03C2", + sigma: "\u03C3", + tau: "\u03C4", + upsilon: "\u03C5", + phi: "\u03C6", + chi: "\u03C7", + psi: "\u03C8", + omega: "\u03C9", + thetasym: "\u03D1", + upsih: "\u03D2", + piv: "\u03D6", + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009", + zwnj: "\u200C", + zwj: "\u200D", + lrm: "\u200E", + rlm: "\u200F", + ndash: "\u2013", + mdash: "\u2014", + lsquo: "\u2018", + rsquo: "\u2019", + sbquo: "\u201A", + ldquo: "\u201C", + rdquo: "\u201D", + bdquo: "\u201E", + dagger: "\u2020", + Dagger: "\u2021", + bull: "\u2022", + hellip: "\u2026", + permil: "\u2030", + prime: "\u2032", + Prime: "\u2033", + lsaquo: "\u2039", + rsaquo: "\u203A", + oline: "\u203E", + frasl: "\u2044", + euro: "\u20AC", + image: "\u2111", + weierp: "\u2118", + real: "\u211C", + trade: "\u2122", + alefsym: "\u2135", + larr: "\u2190", + uarr: "\u2191", + rarr: "\u2192", + darr: "\u2193", + harr: "\u2194", + crarr: "\u21B5", + lArr: "\u21D0", + uArr: "\u21D1", + rArr: "\u21D2", + dArr: "\u21D3", + hArr: "\u21D4", + forall: "\u2200", + part: "\u2202", + exist: "\u2203", + empty: "\u2205", + nabla: "\u2207", + isin: "\u2208", + notin: "\u2209", + ni: "\u220B", + prod: "\u220F", + sum: "\u2211", + minus: "\u2212", + lowast: "\u2217", + radic: "\u221A", + prop: "\u221D", + infin: "\u221E", + ang: "\u2220", + and: "\u2227", + or: "\u2228", + cap: "\u2229", + cup: "\u222A", + int: "\u222B", + there4: "\u2234", + sim: "\u223C", + cong: "\u2245", + asymp: "\u2248", + ne: "\u2260", + equiv: "\u2261", + le: "\u2264", + ge: "\u2265", + sub: "\u2282", + sup: "\u2283", + nsub: "\u2284", + sube: "\u2286", + supe: "\u2287", + oplus: "\u2295", + otimes: "\u2297", + perp: "\u22A5", + sdot: "\u22C5", + lceil: "\u2308", + rceil: "\u2309", + lfloor: "\u230A", + rfloor: "\u230B", + lang: "\u2329", + rang: "\u232A", + loz: "\u25CA", + spades: "\u2660", + clubs: "\u2663", + hearts: "\u2665", + diams: "\u2666" +}; +const JsxErrors = ParseErrorEnum`jsx`({ + AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.", + MissingClosingTagElement: ({ + openingTagName + }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`, + MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.", + UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?", + UnexpectedToken: ({ + unexpected, + HTMLEntity + }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`, + UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.", + UnterminatedJsxContent: "Unterminated JSX contents.", + UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?" +}); +function isFragment(object) { + return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; +} +function getQualifiedJSXName(object) { + if (object.type === "JSXIdentifier") { + return object.name; + } + if (object.type === "JSXNamespacedName") { + return object.namespace.name + ":" + object.name.name; + } + if (object.type === "JSXMemberExpression") { + return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); + } + throw new Error("Node had unexpected type: " + object.type); +} +var jsx = superClass => class JSXParserMixin extends superClass { + jsxReadToken() { + let out = ""; + let chunkStart = this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 60: + case 123: + if (this.state.pos === this.state.start) { + if (ch === 60 && this.state.canStartJSXElement) { + ++this.state.pos; + this.finishToken(142); + } else { + super.getTokenFromCode(ch); + } + return; + } + out += this.input.slice(chunkStart, this.state.pos); + this.finishToken(141, out); + return; + case 38: + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + break; + case 62: + case 125: + default: + if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(true); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + } + } + jsxReadNewLine(normalizeCRLF) { + const ch = this.input.charCodeAt(this.state.pos); + let out; + ++this.state.pos; + if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } + ++this.state.curLine; + this.state.lineStart = this.state.pos; + return out; + } + jsxReadString(quote) { + let out = ""; + let chunkStart = ++this.state.pos; + for (;;) { + if (this.state.pos >= this.length) { + throw this.raise(Errors.UnterminatedString, this.state.startLoc); + } + const ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + if (ch === 38) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + } else if (isNewLine(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(false); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + out += this.input.slice(chunkStart, this.state.pos++); + this.finishToken(133, out); + } + jsxReadEntity() { + const startPos = ++this.state.pos; + if (this.codePointAtPos(this.state.pos) === 35) { + ++this.state.pos; + let radix = 10; + if (this.codePointAtPos(this.state.pos) === 120) { + radix = 16; + ++this.state.pos; + } + const codePoint = this.readInt(radix, undefined, false, "bail"); + if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) { + ++this.state.pos; + return String.fromCodePoint(codePoint); + } + } else { + let count = 0; + let semi = false; + while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) == 59)) { + ++this.state.pos; + } + if (semi) { + const desc = this.input.slice(startPos, this.state.pos); + const entity = entities[desc]; + ++this.state.pos; + if (entity) { + return entity; + } + } + } + this.state.pos = startPos; + return "&"; + } + jsxReadWord() { + let ch; + const start = this.state.pos; + do { + ch = this.input.charCodeAt(++this.state.pos); + } while (isIdentifierChar(ch) || ch === 45); + this.finishToken(140, this.input.slice(start, this.state.pos)); + } + jsxParseIdentifier() { + const node = this.startNode(); + if (this.match(140)) { + node.name = this.state.value; + } else if (tokenIsKeyword(this.state.type)) { + node.name = tokenLabelName(this.state.type); + } else { + this.unexpected(); + } + this.next(); + return this.finishNode(node, "JSXIdentifier"); + } + jsxParseNamespacedName() { + const startLoc = this.state.startLoc; + const name = this.jsxParseIdentifier(); + if (!this.eat(14)) return name; + const node = this.startNodeAt(startLoc); + node.namespace = name; + node.name = this.jsxParseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); + } + jsxParseElementName() { + const startLoc = this.state.startLoc; + let node = this.jsxParseNamespacedName(); + if (node.type === "JSXNamespacedName") { + return node; + } + while (this.eat(16)) { + const newNode = this.startNodeAt(startLoc); + newNode.object = node; + newNode.property = this.jsxParseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } + return node; + } + jsxParseAttributeValue() { + let node; + switch (this.state.type) { + case 5: + node = this.startNode(); + this.setContext(types$1.brace); + this.next(); + node = this.jsxParseExpressionContainer(node, types$1.j_oTag); + if (node.expression.type === "JSXEmptyExpression") { + this.raise(JsxErrors.AttributeIsEmpty, node); + } + return node; + case 142: + case 133: + return this.parseExprAtom(); + default: + throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc); + } + } + jsxParseEmptyExpression() { + const node = this.startNodeAt(this.state.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc); + } + jsxParseSpreadChild(node) { + this.next(); + node.expression = this.parseExpression(); + this.setContext(types$1.j_expr); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadChild"); + } + jsxParseExpressionContainer(node, previousContext) { + if (this.match(8)) { + node.expression = this.jsxParseEmptyExpression(); + } else { + const expression = this.parseExpression(); + node.expression = expression; + } + this.setContext(previousContext); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXExpressionContainer"); + } + jsxParseAttribute() { + const node = this.startNode(); + if (this.match(5)) { + this.setContext(types$1.brace); + this.next(); + this.expect(21); + node.argument = this.parseMaybeAssignAllowIn(); + this.setContext(types$1.j_oTag); + this.state.canStartJSXElement = true; + this.expect(8); + return this.finishNode(node, "JSXSpreadAttribute"); + } + node.name = this.jsxParseNamespacedName(); + node.value = this.eat(29) ? this.jsxParseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); + } + jsxParseOpeningElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(143)) { + return this.finishNode(node, "JSXOpeningFragment"); + } + node.name = this.jsxParseElementName(); + return this.jsxParseOpeningElementAfterName(node); + } + jsxParseOpeningElementAfterName(node) { + const attributes = []; + while (!this.match(56) && !this.match(143)) { + attributes.push(this.jsxParseAttribute()); + } + node.attributes = attributes; + node.selfClosing = this.eat(56); + this.expect(143); + return this.finishNode(node, "JSXOpeningElement"); + } + jsxParseClosingElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + if (this.eat(143)) { + return this.finishNode(node, "JSXClosingFragment"); + } + node.name = this.jsxParseElementName(); + this.expect(143); + return this.finishNode(node, "JSXClosingElement"); + } + jsxParseElementAt(startLoc) { + const node = this.startNodeAt(startLoc); + const children = []; + const openingElement = this.jsxParseOpeningElementAt(startLoc); + let closingElement = null; + if (!openingElement.selfClosing) { + contents: for (;;) { + switch (this.state.type) { + case 142: + startLoc = this.state.startLoc; + this.next(); + if (this.eat(56)) { + closingElement = this.jsxParseClosingElementAt(startLoc); + break contents; + } + children.push(this.jsxParseElementAt(startLoc)); + break; + case 141: + children.push(this.parseExprAtom()); + break; + case 5: + { + const node = this.startNode(); + this.setContext(types$1.brace); + this.next(); + if (this.match(21)) { + children.push(this.jsxParseSpreadChild(node)); + } else { + children.push(this.jsxParseExpressionContainer(node, types$1.j_expr)); + } + break; + } + default: + this.unexpected(); + } + } + if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) { + this.raise(JsxErrors.MissingClosingTagFragment, closingElement); + } else if (!isFragment(openingElement) && isFragment(closingElement)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } else if (!isFragment(openingElement) && !isFragment(closingElement)) { + if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { + this.raise(JsxErrors.MissingClosingTagElement, closingElement, { + openingTagName: getQualifiedJSXName(openingElement.name) + }); + } + } + } + if (isFragment(openingElement)) { + node.openingFragment = openingElement; + node.closingFragment = closingElement; + } else { + node.openingElement = openingElement; + node.closingElement = closingElement; + } + node.children = children; + if (this.match(47)) { + throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc); + } + return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); + } + jsxParseElement() { + const startLoc = this.state.startLoc; + this.next(); + return this.jsxParseElementAt(startLoc); + } + setContext(newContext) { + const { + context + } = this.state; + context[context.length - 1] = newContext; + } + parseExprAtom(refExpressionErrors) { + if (this.match(141)) { + return this.parseLiteral(this.state.value, "JSXText"); + } else if (this.match(142)) { + return this.jsxParseElement(); + } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) { + this.replaceToken(142); + return this.jsxParseElement(); + } else { + return super.parseExprAtom(refExpressionErrors); + } + } + skipSpace() { + const curContext = this.curContext(); + if (!curContext.preserveSpace) super.skipSpace(); + } + getTokenFromCode(code) { + const context = this.curContext(); + if (context === types$1.j_expr) { + this.jsxReadToken(); + return; + } + if (context === types$1.j_oTag || context === types$1.j_cTag) { + if (isIdentifierStart(code)) { + this.jsxReadWord(); + return; + } + if (code === 62) { + ++this.state.pos; + this.finishToken(143); + return; + } + if ((code === 34 || code === 39) && context === types$1.j_oTag) { + this.jsxReadString(code); + return; + } + } + if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) { + ++this.state.pos; + this.finishToken(142); + return; + } + super.getTokenFromCode(code); + } + updateContext(prevType) { + const { + context, + type + } = this.state; + if (type === 56 && prevType === 142) { + context.splice(-2, 2, types$1.j_cTag); + this.state.canStartJSXElement = false; + } else if (type === 142) { + context.push(types$1.j_oTag); + } else if (type === 143) { + const out = context[context.length - 1]; + if (out === types$1.j_oTag && prevType === 56 || out === types$1.j_cTag) { + context.pop(); + this.state.canStartJSXElement = context[context.length - 1] === types$1.j_expr; + } else { + this.setContext(types$1.j_expr); + this.state.canStartJSXElement = true; + } + } else { + this.state.canStartJSXElement = tokenComesBeforeExpression(type); + } + } +}; +class TypeScriptScope extends Scope { + constructor(...args) { + super(...args); + this.tsNames = new Map(); + } +} +class TypeScriptScopeHandler extends ScopeHandler { + constructor(...args) { + super(...args); + this.importsStack = []; + } + createScope(flags) { + this.importsStack.push(new Set()); + return new TypeScriptScope(flags); + } + enter(flags) { + if (flags == 256) { + this.importsStack.push(new Set()); + } + super.enter(flags); + } + exit() { + const flags = super.exit(); + if (flags == 256) { + this.importsStack.pop(); + } + return flags; + } + hasImport(name, allowShadow) { + const len = this.importsStack.length; + if (this.importsStack[len - 1].has(name)) { + return true; + } + if (!allowShadow && len > 1) { + for (let i = 0; i < len - 1; i++) { + if (this.importsStack[i].has(name)) return true; + } + } + return false; + } + declareName(name, bindingType, loc) { + if (bindingType & 4096) { + if (this.hasImport(name, true)) { + this.parser.raise(Errors.VarRedeclaration, loc, { + identifierName: name + }); + } + this.importsStack[this.importsStack.length - 1].add(name); + return; + } + const scope = this.currentScope(); + let type = scope.tsNames.get(name) || 0; + if (bindingType & 1024) { + this.maybeExportDefined(scope, name); + scope.tsNames.set(name, type | 16); + return; + } + super.declareName(name, bindingType, loc); + if (bindingType & 2) { + if (!(bindingType & 1)) { + this.checkRedeclarationInScope(scope, name, bindingType, loc); + this.maybeExportDefined(scope, name); + } + type = type | 1; + } + if (bindingType & 256) { + type = type | 2; + } + if (bindingType & 512) { + type = type | 4; + } + if (bindingType & 128) { + type = type | 8; + } + if (type) scope.tsNames.set(name, type); + } + isRedeclaredInScope(scope, name, bindingType) { + const type = scope.tsNames.get(name); + if ((type & 2) > 0) { + if (bindingType & 256) { + const isConst = !!(bindingType & 512); + const wasConst = (type & 4) > 0; + return isConst !== wasConst; + } + return true; + } + if (bindingType & 128 && (type & 8) > 0) { + if (scope.names.get(name) & 2) { + return !!(bindingType & 1); + } else { + return false; + } + } + if (bindingType & 2 && (type & 1) > 0) { + return true; + } + return super.isRedeclaredInScope(scope, name, bindingType); + } + checkLocalExport(id) { + const { + name + } = id; + if (this.hasImport(name)) return; + const len = this.scopeStack.length; + for (let i = len - 1; i >= 0; i--) { + const scope = this.scopeStack[i]; + const type = scope.tsNames.get(name); + if ((type & 1) > 0 || (type & 16) > 0) { + return; + } + } + super.checkLocalExport(id); + } +} +const getOwn$1 = (object, key) => Object.hasOwnProperty.call(object, key) && object[key]; +const unwrapParenthesizedExpression = node => { + return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; +}; +class LValParser extends NodeUtils { + toAssignable(node, isLHS = false) { + var _node$extra, _node$extra3; + let parenthesized = undefined; + if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) { + parenthesized = unwrapParenthesizedExpression(node); + if (isLHS) { + if (parenthesized.type === "Identifier") { + this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node); + } else if (parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } else { + this.raise(Errors.InvalidParenthesizedAssignment, node); + } + } + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break; + case "ObjectExpression": + node.type = "ObjectPattern"; + for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) { + var _node$extra2; + const prop = node.properties[i]; + const isLast = i === last; + this.toAssignableObjectExpressionProp(prop, isLast, isLHS); + if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc); + } + } + break; + case "ObjectProperty": + { + const { + key, + value + } = node; + if (this.isPrivateName(key)) { + this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); + } + this.toAssignable(value, isLHS); + break; + } + case "SpreadElement": + { + throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller."); + } + case "ArrayExpression": + node.type = "ArrayPattern"; + this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS); + break; + case "AssignmentExpression": + if (node.operator !== "=") { + this.raise(Errors.MissingEqInAssignment, node.left.loc.end); + } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isLHS); + break; + case "ParenthesizedExpression": + this.toAssignable(parenthesized, isLHS); + break; + } + } + toAssignableObjectExpressionProp(prop, isLast, isLHS) { + if (prop.type === "ObjectMethod") { + this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key); + } else if (prop.type === "SpreadElement") { + prop.type = "RestElement"; + const arg = prop.argument; + this.checkToRestConversion(arg, false); + this.toAssignable(arg, isLHS); + if (!isLast) { + this.raise(Errors.RestTrailingComma, prop); + } + } else { + this.toAssignable(prop, isLHS); + } + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + const end = exprList.length - 1; + for (let i = 0; i <= end; i++) { + const elt = exprList[i]; + if (!elt) continue; + if (elt.type === "SpreadElement") { + elt.type = "RestElement"; + const arg = elt.argument; + this.checkToRestConversion(arg, true); + this.toAssignable(arg, isLHS); + } else { + this.toAssignable(elt, isLHS); + } + if (elt.type === "RestElement") { + if (i < end) { + this.raise(Errors.RestTrailingComma, elt); + } else if (trailingCommaLoc) { + this.raise(Errors.RestTrailingComma, trailingCommaLoc); + } + } + } + } + isAssignable(node, isBinding) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + return true; + case "ObjectExpression": + { + const last = node.properties.length - 1; + return node.properties.every((prop, i) => { + return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop); + }); + } + case "ObjectProperty": + return this.isAssignable(node.value); + case "SpreadElement": + return this.isAssignable(node.argument); + case "ArrayExpression": + return node.elements.every(element => element === null || this.isAssignable(element)); + case "AssignmentExpression": + return node.operator === "="; + case "ParenthesizedExpression": + return this.isAssignable(node.expression); + case "MemberExpression": + case "OptionalMemberExpression": + return !isBinding; + default: + return false; + } + } + toReferencedList(exprList, isParenthesizedExpr) { + return exprList; + } + toReferencedListDeep(exprList, isParenthesizedExpr) { + this.toReferencedList(exprList, isParenthesizedExpr); + for (const expr of exprList) { + if ((expr == null ? void 0 : expr.type) === "ArrayExpression") { + this.toReferencedListDeep(expr.elements); + } + } + } + parseSpread(refExpressionErrors) { + const node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined); + return this.finishNode(node, "SpreadElement"); + } + parseRestBinding() { + const node = this.startNode(); + this.next(); + node.argument = this.parseBindingAtom(); + return this.finishNode(node, "RestElement"); + } + parseBindingAtom() { + switch (this.state.type) { + case 0: + { + const node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(3, 93, 1); + return this.finishNode(node, "ArrayPattern"); + } + case 5: + return this.parseObjectLike(8, true); + } + return this.parseIdentifier(); + } + parseBindingList(close, closeCharCode, flags) { + const allowEmpty = flags & 1; + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + } + if (allowEmpty && this.match(12)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(21)) { + elts.push(this.parseAssignableListItemTypes(this.parseRestBinding(), flags)); + if (!this.checkCommaAfterRest(closeCharCode)) { + this.expect(close); + break; + } + } else { + const decorators = []; + if (this.match(26) && this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + elts.push(this.parseAssignableListItem(flags, decorators)); + } + } + return elts; + } + parseBindingRestProperty(prop) { + this.next(); + prop.argument = this.parseIdentifier(); + this.checkCommaAfterRest(125); + return this.finishNode(prop, "RestElement"); + } + parseBindingProperty() { + const prop = this.startNode(); + const { + type, + startLoc + } = this.state; + if (type === 21) { + return this.parseBindingRestProperty(prop); + } else if (type === 138) { + this.expectPlugin("destructuringPrivate", startLoc); + this.classScope.usePrivateName(this.state.value, startLoc); + prop.key = this.parsePrivateName(); + } else { + this.parsePropertyName(prop); + } + prop.method = false; + return this.parseObjPropValue(prop, startLoc, false, false, true, false); + } + parseAssignableListItem(flags, decorators) { + const left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left, flags); + const elt = this.parseMaybeDefault(left.loc.start, left); + if (decorators.length) { + left.decorators = decorators; + } + return elt; + } + parseAssignableListItemTypes(param, flags) { + return param; + } + parseMaybeDefault(startLoc, left) { + var _startLoc, _left; + (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; + left = (_left = left) != null ? _left : this.parseBindingAtom(); + if (!this.eat(29)) return left; + const node = this.startNodeAt(startLoc); + node.left = left; + node.right = this.parseMaybeAssignAllowIn(); + return this.finishNode(node, "AssignmentPattern"); + } + isValidLVal(type, isUnparenthesizedInAssign, binding) { + return getOwn$1({ + AssignmentPattern: "left", + RestElement: "argument", + ObjectProperty: "value", + ParenthesizedExpression: "expression", + ArrayPattern: "elements", + ObjectPattern: "properties" + }, type); + } + isOptionalMemberExpression(expression) { + return expression.type === "OptionalMemberExpression"; + } + checkLVal(expression, { + in: ancestor, + binding = 64, + checkClashes = false, + strictModeChanged = false, + hasParenthesizedAncestor = false + }) { + var _expression$extra; + const type = expression.type; + if (this.isObjectMethod(expression)) return; + const isOptionalMemberExpression = this.isOptionalMemberExpression(expression); + if (isOptionalMemberExpression || type === "MemberExpression") { + if (isOptionalMemberExpression) { + this.expectPlugin("optionalChainingAssign", expression.loc.start); + if (ancestor.type !== "AssignmentExpression") { + this.raise(Errors.InvalidLhsOptionalChaining, expression, { + ancestor + }); + } + } + if (binding !== 64) { + this.raise(Errors.InvalidPropertyBindingPattern, expression); + } + return; + } + if (type === "Identifier") { + this.checkIdentifier(expression, binding, strictModeChanged); + const { + name + } = expression; + if (checkClashes) { + if (checkClashes.has(name)) { + this.raise(Errors.ParamDupe, expression); + } else { + checkClashes.add(name); + } + } + return; + } + const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding); + if (validity === true) return; + if (validity === false) { + const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding; + this.raise(ParseErrorClass, expression, { + ancestor + }); + return; + } + const [key, isParenthesizedExpression] = Array.isArray(validity) ? validity : [validity, type === "ParenthesizedExpression"]; + const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? { + type + } : ancestor; + for (const child of [].concat(expression[key])) { + if (child) { + this.checkLVal(child, { + in: nextAncestor, + binding, + checkClashes, + strictModeChanged, + hasParenthesizedAncestor: isParenthesizedExpression + }); + } + } + } + checkIdentifier(at, bindingType, strictModeChanged = false) { + if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) { + if (bindingType === 64) { + this.raise(Errors.StrictEvalArguments, at, { + referenceName: at.name + }); + } else { + this.raise(Errors.StrictEvalArgumentsBinding, at, { + bindingName: at.name + }); + } + } + if (bindingType & 8192 && at.name === "let") { + this.raise(Errors.LetInLexicalBinding, at); + } + if (!(bindingType & 64)) { + this.declareNameFromIdentifier(at, bindingType); + } + } + declareNameFromIdentifier(identifier, binding) { + this.scope.declareName(identifier.name, binding, identifier.loc.start); + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "ParenthesizedExpression": + this.checkToRestConversion(node.expression, allowPattern); + break; + case "Identifier": + case "MemberExpression": + break; + case "ArrayExpression": + case "ObjectExpression": + if (allowPattern) break; + default: + this.raise(Errors.InvalidRestAssignmentPattern, node); + } + } + checkCommaAfterRest(close) { + if (!this.match(12)) { + return false; + } + this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc); + return true; + } +} +const getOwn = (object, key) => Object.hasOwnProperty.call(object, key) && object[key]; +function nonNull(x) { + if (x == null) { + throw new Error(`Unexpected ${x} value.`); + } + return x; +} +function assert$1(x) { + if (!x) { + throw new Error("Assert fail"); + } +} +const TSErrors = ParseErrorEnum`typescript`({ + AbstractMethodHasImplementation: ({ + methodName + }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`, + AbstractPropertyHasInitializer: ({ + propertyName + }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`, + AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", + AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.", + AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.", + ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", + ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", + ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.", + ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", + DeclareAccessor: ({ + kind + }) => `'declare' is not allowed in ${kind}ters.`, + DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", + DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", + DuplicateAccessibilityModifier: ({ + modifier + }) => `Accessibility modifier already seen.`, + DuplicateModifier: ({ + modifier + }) => `Duplicate modifier: '${modifier}'.`, + EmptyHeritageClauseType: ({ + token + }) => `'${token}' list cannot be empty.`, + EmptyTypeArguments: "Type argument list cannot be empty.", + EmptyTypeParameters: "Type parameter list cannot be empty.", + ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", + ImportAliasHasImportType: "An import alias can not use 'import type'.", + ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier", + IncompatibleModifiers: ({ + modifiers + }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`, + IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", + IndexSignatureHasAccessibility: ({ + modifier + }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`, + IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", + IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", + IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", + InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.", + InvalidModifierOnTypeMember: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type member.`, + InvalidModifierOnTypeParameter: ({ + modifier + }) => `'${modifier}' modifier cannot appear on a type parameter.`, + InvalidModifierOnTypeParameterPositions: ({ + modifier + }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`, + InvalidModifiersOrder: ({ + orderedModifiers + }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`, + InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.", + InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", + MissingInterfaceName: "'interface' declarations must be followed by an identifier.", + NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", + NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.", + OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", + OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", + PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", + PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", + PrivateElementHasAccessibility: ({ + modifier + }) => `Private elements cannot have an accessibility modifier ('${modifier}').`, + ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", + ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.", + ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", + SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", + SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", + SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", + SingleTypeParameterWithoutTrailingComma: ({ + typeParameterName + }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`, + StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", + TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).", + TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", + TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", + TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.", + TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.", + UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", + UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", + UnexpectedTypeAnnotation: "Did not expect a type annotation here.", + UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", + UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", + UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", + UnsupportedSignatureParameterKind: ({ + type + }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.` +}); +function keywordTypeFromName(value) { + switch (value) { + case "any": + return "TSAnyKeyword"; + case "boolean": + return "TSBooleanKeyword"; + case "bigint": + return "TSBigIntKeyword"; + case "never": + return "TSNeverKeyword"; + case "number": + return "TSNumberKeyword"; + case "object": + return "TSObjectKeyword"; + case "string": + return "TSStringKeyword"; + case "symbol": + return "TSSymbolKeyword"; + case "undefined": + return "TSUndefinedKeyword"; + case "unknown": + return "TSUnknownKeyword"; + default: + return undefined; + } +} +function tsIsAccessModifier(modifier) { + return modifier === "private" || modifier === "public" || modifier === "protected"; +} +function tsIsVarianceAnnotations(modifier) { + return modifier === "in" || modifier === "out"; +} +var typescript = superClass => class TypeScriptParserMixin extends superClass { + constructor(...args) { + super(...args); + this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out"], + disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + this.tsParseConstModifier = this.tsParseModifiers.bind(this, { + allowedModifiers: ["const"], + disallowedModifiers: ["in", "out"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }); + this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, { + allowedModifiers: ["in", "out", "const"], + disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"], + errorTemplate: TSErrors.InvalidModifierOnTypeParameter + }); + } + getScopeHandler() { + return TypeScriptScopeHandler; + } + tsIsIdentifier() { + return tokenIsIdentifier(this.state.type); + } + tsTokenCanFollowModifier() { + return (this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(138) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak(); + } + tsNextTokenCanFollowModifier() { + this.next(); + return this.tsTokenCanFollowModifier(); + } + tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) { + if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) { + return undefined; + } + const modifier = this.state.value; + if (allowedModifiers.indexOf(modifier) !== -1) { + if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { + return undefined; + } + if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { + return modifier; + } + } + return undefined; + } + tsParseModifiers({ + allowedModifiers, + disallowedModifiers, + stopOnStartOfClassStaticBlock, + errorTemplate = TSErrors.InvalidModifierOnTypeMember + }, modified) { + const enforceOrder = (loc, modifier, before, after) => { + if (modifier === before && modified[after]) { + this.raise(TSErrors.InvalidModifiersOrder, loc, { + orderedModifiers: [before, after] + }); + } + }; + const incompatible = (loc, modifier, mod1, mod2) => { + if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { + this.raise(TSErrors.IncompatibleModifiers, loc, { + modifiers: [mod1, mod2] + }); + } + }; + for (;;) { + const { + startLoc + } = this.state; + const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock); + if (!modifier) break; + if (tsIsAccessModifier(modifier)) { + if (modified.accessibility) { + this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, modifier, "override"); + enforceOrder(startLoc, modifier, modifier, "static"); + enforceOrder(startLoc, modifier, modifier, "readonly"); + modified.accessibility = modifier; + } + } else if (tsIsVarianceAnnotations(modifier)) { + if (modified[modifier]) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } + modified[modifier] = true; + enforceOrder(startLoc, modifier, "in", "out"); + } else { + if (Object.hasOwnProperty.call(modified, modifier)) { + this.raise(TSErrors.DuplicateModifier, startLoc, { + modifier + }); + } else { + enforceOrder(startLoc, modifier, "static", "readonly"); + enforceOrder(startLoc, modifier, "static", "override"); + enforceOrder(startLoc, modifier, "override", "readonly"); + enforceOrder(startLoc, modifier, "abstract", "override"); + incompatible(startLoc, modifier, "declare", "override"); + incompatible(startLoc, modifier, "static", "abstract"); + } + modified[modifier] = true; + } + if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { + this.raise(errorTemplate, startLoc, { + modifier + }); + } + } + } + tsIsListTerminator(kind) { + switch (kind) { + case "EnumMembers": + case "TypeMembers": + return this.match(8); + case "HeritageClauseElement": + return this.match(5); + case "TupleElementTypes": + return this.match(3); + case "TypeParametersOrArguments": + return this.match(48); + } + } + tsParseList(kind, parseElement) { + const result = []; + while (!this.tsIsListTerminator(kind)) { + result.push(parseElement()); + } + return result; + } + tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) { + return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos)); + } + tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) { + const result = []; + let trailingCommaPos = -1; + for (;;) { + if (this.tsIsListTerminator(kind)) { + break; + } + trailingCommaPos = -1; + const element = parseElement(); + if (element == null) { + return undefined; + } + result.push(element); + if (this.eat(12)) { + trailingCommaPos = this.state.lastTokStartLoc.index; + continue; + } + if (this.tsIsListTerminator(kind)) { + break; + } + if (expectSuccess) { + this.expect(12); + } + return undefined; + } + if (refTrailingCommaPos) { + refTrailingCommaPos.value = trailingCommaPos; + } + return result; + } + tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) { + if (!skipFirstToken) { + if (bracket) { + this.expect(0); + } else { + this.expect(47); + } + } + const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos); + if (bracket) { + this.expect(3); + } else { + this.expect(48); + } + return result; + } + tsParseImportType() { + const node = this.startNode(); + this.expect(83); + this.expect(10); + if (!this.match(133)) { + this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc); + } + node.argument = super.parseExprAtom(); + this.expect(11); + if (this.eat(16)) { + node.qualifier = this.tsParseEntityName(); + } + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSImportType"); + } + tsParseEntityName(allowReservedWords = true) { + let entity = this.parseIdentifier(allowReservedWords); + while (this.eat(16)) { + const node = this.startNodeAtNode(entity); + node.left = entity; + node.right = this.parseIdentifier(allowReservedWords); + entity = this.finishNode(node, "TSQualifiedName"); + } + return entity; + } + tsParseTypeReference() { + const node = this.startNode(); + node.typeName = this.tsParseEntityName(); + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeReference"); + } + tsParseThisTypePredicate(lhs) { + this.next(); + const node = this.startNodeAtNode(lhs); + node.parameterName = lhs; + node.typeAnnotation = this.tsParseTypeAnnotation(false); + node.asserts = false; + return this.finishNode(node, "TSTypePredicate"); + } + tsParseThisTypeNode() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSThisType"); + } + tsParseTypeQuery() { + const node = this.startNode(); + this.expect(87); + if (this.match(83)) { + node.exprName = this.tsParseImportType(); + } else { + node.exprName = this.tsParseEntityName(); + } + if (!this.hasPrecedingLineBreak() && this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSTypeQuery"); + } + tsParseTypeParameter(parseModifiers) { + const node = this.startNode(); + parseModifiers(node); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsEatThenParseType(81); + node.default = this.tsEatThenParseType(29); + return this.finishNode(node, "TSTypeParameter"); + } + tsTryParseTypeParameters(parseModifiers) { + if (this.match(47)) { + return this.tsParseTypeParameters(parseModifiers); + } + } + tsParseTypeParameters(parseModifiers) { + const node = this.startNode(); + if (this.match(47) || this.match(142)) { + this.next(); + } else { + this.unexpected(); + } + const refTrailingCommaPos = { + value: -1 + }; + node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeParameters, node); + } + if (refTrailingCommaPos.value !== -1) { + this.addExtra(node, "trailingComma", refTrailingCommaPos.value); + } + return this.finishNode(node, "TSTypeParameterDeclaration"); + } + tsFillSignature(returnToken, signature) { + const returnTokenRequired = returnToken === 19; + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + this.expect(10); + signature[paramsKey] = this.tsParseBindingListForSignature(); + if (returnTokenRequired) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } else if (this.match(returnToken)) { + signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); + } + } + tsParseBindingListForSignature() { + const list = super.parseBindingList(11, 41, 2); + for (const pattern of list) { + const { + type + } = pattern; + if (type === "AssignmentPattern" || type === "TSParameterProperty") { + this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, { + type + }); + } + } + return list; + } + tsParseTypeMemberSemicolon() { + if (!this.eat(12) && !this.isLineTerminator()) { + this.expect(13); + } + } + tsParseSignatureMember(kind, node) { + this.tsFillSignature(14, node); + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, kind); + } + tsIsUnambiguouslyIndexSignature() { + this.next(); + if (tokenIsIdentifier(this.state.type)) { + this.next(); + return this.match(14); + } + return false; + } + tsTryParseIndexSignature(node) { + if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { + return; + } + this.expect(0); + const id = this.parseIdentifier(); + id.typeAnnotation = this.tsParseTypeAnnotation(); + this.resetEndLocation(id); + this.expect(3); + node.parameters = [id]; + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(node, "TSIndexSignature"); + } + tsParsePropertyOrMethodSignature(node, readonly) { + if (this.eat(17)) node.optional = true; + const nodeAny = node; + if (this.match(10) || this.match(47)) { + if (readonly) { + this.raise(TSErrors.ReadonlyForMethodSignature, node); + } + const method = nodeAny; + if (method.kind && this.match(47)) { + this.raise(TSErrors.AccesorCannotHaveTypeParameters, this.state.curPosition()); + } + this.tsFillSignature(14, method); + this.tsParseTypeMemberSemicolon(); + const paramsKey = "parameters"; + const returnTypeKey = "typeAnnotation"; + if (method.kind === "get") { + if (method[paramsKey].length > 0) { + this.raise(Errors.BadGetterArity, this.state.curPosition()); + if (this.isThisParam(method[paramsKey][0])) { + this.raise(TSErrors.AccesorCannotDeclareThisParameter, this.state.curPosition()); + } + } + } else if (method.kind === "set") { + if (method[paramsKey].length !== 1) { + this.raise(Errors.BadSetterArity, this.state.curPosition()); + } else { + const firstParameter = method[paramsKey][0]; + if (this.isThisParam(firstParameter)) { + this.raise(TSErrors.AccesorCannotDeclareThisParameter, this.state.curPosition()); + } + if (firstParameter.type === "Identifier" && firstParameter.optional) { + this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, this.state.curPosition()); + } + if (firstParameter.type === "RestElement") { + this.raise(TSErrors.SetAccesorCannotHaveRestParameter, this.state.curPosition()); + } + } + if (method[returnTypeKey]) { + this.raise(TSErrors.SetAccesorCannotHaveReturnType, method[returnTypeKey]); + } + } else { + method.kind = "method"; + } + return this.finishNode(method, "TSMethodSignature"); + } else { + const property = nodeAny; + if (readonly) property.readonly = true; + const type = this.tsTryParseTypeAnnotation(); + if (type) property.typeAnnotation = type; + this.tsParseTypeMemberSemicolon(); + return this.finishNode(property, "TSPropertySignature"); + } + } + tsParseTypeMember() { + const node = this.startNode(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); + } + if (this.match(77)) { + const id = this.startNode(); + this.next(); + if (this.match(10) || this.match(47)) { + return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); + } else { + node.key = this.createIdentifier(id, "new"); + return this.tsParsePropertyOrMethodSignature(node, false); + } + } + this.tsParseModifiers({ + allowedModifiers: ["readonly"], + disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"] + }, node); + const idx = this.tsTryParseIndexSignature(node); + if (idx) { + return idx; + } + super.parsePropertyName(node); + if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) { + node.kind = node.key.name; + super.parsePropertyName(node); + } + return this.tsParsePropertyOrMethodSignature(node, !!node.readonly); + } + tsParseTypeLiteral() { + const node = this.startNode(); + node.members = this.tsParseObjectTypeMembers(); + return this.finishNode(node, "TSTypeLiteral"); + } + tsParseObjectTypeMembers() { + this.expect(5); + const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); + this.expect(8); + return members; + } + tsIsStartOfMappedType() { + this.next(); + if (this.eat(53)) { + return this.isContextual(122); + } + if (this.isContextual(122)) { + this.next(); + } + if (!this.match(0)) { + return false; + } + this.next(); + if (!this.tsIsIdentifier()) { + return false; + } + this.next(); + return this.match(58); + } + tsParseMappedTypeParameter() { + const node = this.startNode(); + node.name = this.tsParseTypeParameterName(); + node.constraint = this.tsExpectThenParseType(58); + return this.finishNode(node, "TSTypeParameter"); + } + tsParseMappedType() { + const node = this.startNode(); + this.expect(5); + if (this.match(53)) { + node.readonly = this.state.value; + this.next(); + this.expectContextual(122); + } else if (this.eatContextual(122)) { + node.readonly = true; + } + this.expect(0); + node.typeParameter = this.tsParseMappedTypeParameter(); + node.nameType = this.eatContextual(93) ? this.tsParseType() : null; + this.expect(3); + if (this.match(53)) { + node.optional = this.state.value; + this.next(); + this.expect(17); + } else if (this.eat(17)) { + node.optional = true; + } + node.typeAnnotation = this.tsTryParseType(); + this.semicolon(); + this.expect(8); + return this.finishNode(node, "TSMappedType"); + } + tsParseTupleType() { + const node = this.startNode(); + node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); + let seenOptionalElement = false; + node.elementTypes.forEach(elementNode => { + const { + type + } = elementNode; + if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { + this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode); + } + seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"); + }); + return this.finishNode(node, "TSTupleType"); + } + tsParseTupleElementType() { + const { + startLoc + } = this.state; + const rest = this.eat(21); + let labeled; + let label; + let optional; + let type; + const isWord = tokenIsKeywordOrIdentifier(this.state.type); + const chAfterWord = isWord ? this.lookaheadCharCode() : null; + if (chAfterWord === 58) { + labeled = true; + optional = false; + label = this.parseIdentifier(true); + this.expect(14); + type = this.tsParseType(); + } else if (chAfterWord === 63) { + optional = true; + const startLoc = this.state.startLoc; + const wordName = this.state.value; + const typeOrLabel = this.tsParseNonArrayType(); + if (this.lookaheadCharCode() === 58) { + labeled = true; + label = this.createIdentifier(this.startNodeAt(startLoc), wordName); + this.expect(17); + this.expect(14); + type = this.tsParseType(); + } else { + labeled = false; + type = typeOrLabel; + this.expect(17); + } + } else { + type = this.tsParseType(); + optional = this.eat(17); + labeled = this.eat(14); + } + if (labeled) { + let labeledNode; + if (label) { + labeledNode = this.startNodeAtNode(label); + labeledNode.optional = optional; + labeledNode.label = label; + labeledNode.elementType = type; + if (this.eat(17)) { + labeledNode.optional = true; + this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc); + } + } else { + labeledNode = this.startNodeAtNode(type); + labeledNode.optional = optional; + this.raise(TSErrors.InvalidTupleMemberLabel, type); + labeledNode.label = type; + labeledNode.elementType = this.tsParseType(); + } + type = this.finishNode(labeledNode, "TSNamedTupleMember"); + } else if (optional) { + const optionalTypeNode = this.startNodeAtNode(type); + optionalTypeNode.typeAnnotation = type; + type = this.finishNode(optionalTypeNode, "TSOptionalType"); + } + if (rest) { + const restNode = this.startNodeAt(startLoc); + restNode.typeAnnotation = type; + type = this.finishNode(restNode, "TSRestType"); + } + return type; + } + tsParseParenthesizedType() { + const node = this.startNode(); + this.expect(10); + node.typeAnnotation = this.tsParseType(); + this.expect(11); + return this.finishNode(node, "TSParenthesizedType"); + } + tsParseFunctionOrConstructorType(type, abstract) { + const node = this.startNode(); + if (type === "TSConstructorType") { + node.abstract = !!abstract; + if (abstract) this.next(); + this.next(); + } + this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node)); + return this.finishNode(node, type); + } + tsParseLiteralTypeNode() { + const node = this.startNode(); + switch (this.state.type) { + case 134: + case 135: + case 133: + case 85: + case 86: + node.literal = super.parseExprAtom(); + break; + default: + this.unexpected(); + } + return this.finishNode(node, "TSLiteralType"); + } + tsParseTemplateLiteralType() { + const node = this.startNode(); + node.literal = super.parseTemplate(false); + return this.finishNode(node, "TSLiteralType"); + } + parseTemplateSubstitution() { + if (this.state.inType) return this.tsParseType(); + return super.parseTemplateSubstitution(); + } + tsParseThisTypeOrThisTypePredicate() { + const thisKeyword = this.tsParseThisTypeNode(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + return this.tsParseThisTypePredicate(thisKeyword); + } else { + return thisKeyword; + } + } + tsParseNonArrayType() { + switch (this.state.type) { + case 133: + case 134: + case 135: + case 85: + case 86: + return this.tsParseLiteralTypeNode(); + case 53: + if (this.state.value === "-") { + const node = this.startNode(); + const nextToken = this.lookahead(); + if (nextToken.type !== 134 && nextToken.type !== 135) { + this.unexpected(); + } + node.literal = this.parseMaybeUnary(); + return this.finishNode(node, "TSLiteralType"); + } + break; + case 78: + return this.tsParseThisTypeOrThisTypePredicate(); + case 87: + return this.tsParseTypeQuery(); + case 83: + return this.tsParseImportType(); + case 5: + return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); + case 0: + return this.tsParseTupleType(); + case 10: + return this.tsParseParenthesizedType(); + case 25: + case 24: + return this.tsParseTemplateLiteralType(); + default: + { + const { + type + } = this.state; + if (tokenIsIdentifier(type) || type === 88 || type === 84) { + const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value); + if (nodeType !== undefined && this.lookaheadCharCode() !== 46) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, nodeType); + } + return this.tsParseTypeReference(); + } + } + } + this.unexpected(); + } + tsParseArrayTypeOrHigher() { + let type = this.tsParseNonArrayType(); + while (!this.hasPrecedingLineBreak() && this.eat(0)) { + if (this.match(3)) { + const node = this.startNodeAtNode(type); + node.elementType = type; + this.expect(3); + type = this.finishNode(node, "TSArrayType"); + } else { + const node = this.startNodeAtNode(type); + node.objectType = type; + node.indexType = this.tsParseType(); + this.expect(3); + type = this.finishNode(node, "TSIndexedAccessType"); + } + } + return type; + } + tsParseTypeOperator() { + const node = this.startNode(); + const operator = this.state.value; + this.next(); + node.operator = operator; + node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); + if (operator === "readonly") { + this.tsCheckTypeAnnotationForReadOnly(node); + } + return this.finishNode(node, "TSTypeOperator"); + } + tsCheckTypeAnnotationForReadOnly(node) { + switch (node.typeAnnotation.type) { + case "TSTupleType": + case "TSArrayType": + return; + default: + this.raise(TSErrors.UnexpectedReadonly, node); + } + } + tsParseInferType() { + const node = this.startNode(); + this.expectContextual(115); + const typeParameter = this.startNode(); + typeParameter.name = this.tsParseTypeParameterName(); + typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType()); + node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); + return this.finishNode(node, "TSInferType"); + } + tsParseConstraintForInferType() { + if (this.eat(81)) { + const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType()); + if (this.state.inDisallowConditionalTypesContext || !this.match(17)) { + return constraint; + } + } + } + tsParseTypeOperatorOrHigher() { + const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc; + return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher()); + } + tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { + const node = this.startNode(); + const hasLeadingOperator = this.eat(operator); + const types = []; + do { + types.push(parseConstituentType()); + } while (this.eat(operator)); + if (types.length === 1 && !hasLeadingOperator) { + return types[0]; + } + node.types = types; + return this.finishNode(node, kind); + } + tsParseIntersectionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45); + } + tsParseUnionTypeOrHigher() { + return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43); + } + tsIsStartOfFunctionType() { + if (this.match(47)) { + return true; + } + return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); + } + tsSkipParameterStart() { + if (tokenIsIdentifier(this.state.type) || this.match(78)) { + this.next(); + return true; + } + if (this.match(5)) { + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + this.parseObjectLike(8, true); + return errors.length === previousErrorCount; + } catch (_unused) { + return false; + } + } + if (this.match(0)) { + this.next(); + const { + errors + } = this.state; + const previousErrorCount = errors.length; + try { + super.parseBindingList(3, 93, 1); + return errors.length === previousErrorCount; + } catch (_unused2) { + return false; + } + } + return false; + } + tsIsUnambiguouslyStartOfFunctionType() { + this.next(); + if (this.match(11) || this.match(21)) { + return true; + } + if (this.tsSkipParameterStart()) { + if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) { + return true; + } + if (this.match(11)) { + this.next(); + if (this.match(19)) { + return true; + } + } + } + return false; + } + tsParseTypeOrTypePredicateAnnotation(returnToken) { + return this.tsInType(() => { + const t = this.startNode(); + this.expect(returnToken); + const node = this.startNode(); + const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); + if (asserts && this.match(78)) { + let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); + if (thisTypePredicate.type === "TSThisType") { + node.parameterName = thisTypePredicate; + node.asserts = true; + node.typeAnnotation = null; + thisTypePredicate = this.finishNode(node, "TSTypePredicate"); + } else { + this.resetStartLocationFromNode(thisTypePredicate, node); + thisTypePredicate.asserts = true; + } + t.typeAnnotation = thisTypePredicate; + return this.finishNode(t, "TSTypeAnnotation"); + } + const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); + if (!typePredicateVariable) { + if (!asserts) { + return this.tsParseTypeAnnotation(false, t); + } + node.parameterName = this.parseIdentifier(); + node.asserts = asserts; + node.typeAnnotation = null; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + } + const type = this.tsParseTypeAnnotation(false); + node.parameterName = typePredicateVariable; + node.typeAnnotation = type; + node.asserts = asserts; + t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); + return this.finishNode(t, "TSTypeAnnotation"); + }); + } + tsTryParseTypeOrTypePredicateAnnotation() { + if (this.match(14)) { + return this.tsParseTypeOrTypePredicateAnnotation(14); + } + } + tsTryParseTypeAnnotation() { + if (this.match(14)) { + return this.tsParseTypeAnnotation(); + } + } + tsTryParseType() { + return this.tsEatThenParseType(14); + } + tsParseTypePredicatePrefix() { + const id = this.parseIdentifier(); + if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { + this.next(); + return id; + } + } + tsParseTypePredicateAsserts() { + if (this.state.type !== 109) { + return false; + } + const containsEsc = this.state.containsEsc; + this.next(); + if (!tokenIsIdentifier(this.state.type) && !this.match(78)) { + return false; + } + if (containsEsc) { + this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, { + reservedWord: "asserts" + }); + } + return true; + } + tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { + this.tsInType(() => { + if (eatColon) this.expect(14); + t.typeAnnotation = this.tsParseType(); + }); + return this.finishNode(t, "TSTypeAnnotation"); + } + tsParseType() { + assert$1(this.state.inType); + const type = this.tsParseNonConditionalType(); + if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) { + return type; + } + const node = this.startNodeAtNode(type); + node.checkType = type; + node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType()); + this.expect(17); + node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + this.expect(14); + node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); + return this.finishNode(node, "TSConditionalType"); + } + isAbstractConstructorSignature() { + return this.isContextual(124) && this.lookahead().type === 77; + } + tsParseNonConditionalType() { + if (this.tsIsStartOfFunctionType()) { + return this.tsParseFunctionOrConstructorType("TSFunctionType"); + } + if (this.match(77)) { + return this.tsParseFunctionOrConstructorType("TSConstructorType"); + } else if (this.isAbstractConstructorSignature()) { + return this.tsParseFunctionOrConstructorType("TSConstructorType", true); + } + return this.tsParseUnionTypeOrHigher(); + } + tsParseTypeAssertion() { + if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc); + } + const node = this.startNode(); + node.typeAnnotation = this.tsInType(() => { + this.next(); + return this.match(75) ? this.tsParseTypeReference() : this.tsParseType(); + }); + this.expect(48); + node.expression = this.parseMaybeUnary(); + return this.finishNode(node, "TSTypeAssertion"); + } + tsParseHeritageClause(token) { + const originalStartLoc = this.state.startLoc; + const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => { + const node = this.startNode(); + node.expression = this.tsParseEntityName(); + if (this.match(47)) { + node.typeParameters = this.tsParseTypeArguments(); + } + return this.finishNode(node, "TSExpressionWithTypeArguments"); + }); + if (!delimitedList.length) { + this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, { + token + }); + } + return delimitedList; + } + tsParseInterfaceDeclaration(node, properties = {}) { + if (this.hasFollowingLineBreak()) return null; + this.expectContextual(129); + if (properties.declare) node.declare = true; + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 130); + } else { + node.id = null; + this.raise(TSErrors.MissingInterfaceName, this.state.startLoc); + } + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (this.eat(81)) { + node.extends = this.tsParseHeritageClause("extends"); + } + const body = this.startNode(); + body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); + node.body = this.finishNode(body, "TSInterfaceBody"); + return this.finishNode(node, "TSInterfaceDeclaration"); + } + tsParseTypeAliasDeclaration(node) { + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, 2); + node.typeAnnotation = this.tsInType(() => { + node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers); + this.expect(29); + if (this.isContextual(114) && this.lookahead().type !== 16) { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "TSIntrinsicKeyword"); + } + return this.tsParseType(); + }); + this.semicolon(); + return this.finishNode(node, "TSTypeAliasDeclaration"); + } + tsInNoContext(cb) { + const oldContext = this.state.context; + this.state.context = [oldContext[0]]; + try { + return cb(); + } finally { + this.state.context = oldContext; + } + } + tsInType(cb) { + const oldInType = this.state.inType; + this.state.inType = true; + try { + return cb(); + } finally { + this.state.inType = oldInType; + } + } + tsInDisallowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = true; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsInAllowConditionalTypesContext(cb) { + const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; + this.state.inDisallowConditionalTypesContext = false; + try { + return cb(); + } finally { + this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; + } + } + tsEatThenParseType(token) { + if (this.match(token)) { + return this.tsNextThenParseType(); + } + } + tsExpectThenParseType(token) { + return this.tsInType(() => { + this.expect(token); + return this.tsParseType(); + }); + } + tsNextThenParseType() { + return this.tsInType(() => { + this.next(); + return this.tsParseType(); + }); + } + tsParseEnumMember() { + const node = this.startNode(); + node.id = this.match(133) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true); + if (this.eat(29)) { + node.initializer = super.parseMaybeAssignAllowIn(); + } + return this.finishNode(node, "TSEnumMember"); + } + tsParseEnumDeclaration(node, properties = {}) { + if (properties.const) node.const = true; + if (properties.declare) node.declare = true; + this.expectContextual(126); + node.id = this.parseIdentifier(); + this.checkIdentifier(node.id, node.const ? 8971 : 8459); + this.expect(5); + node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); + this.expect(8); + return this.finishNode(node, "TSEnumDeclaration"); + } + tsParseModuleBlock() { + const node = this.startNode(); + this.scope.enter(0); + this.expect(5); + super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8); + this.scope.exit(); + return this.finishNode(node, "TSModuleBlock"); + } + tsParseModuleOrNamespaceDeclaration(node, nested = false) { + node.id = this.parseIdentifier(); + if (!nested) { + this.checkIdentifier(node.id, 1024); + } + if (this.eat(16)) { + const inner = this.startNode(); + this.tsParseModuleOrNamespaceDeclaration(inner, true); + node.body = inner; + } else { + this.scope.enter(256); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseAmbientExternalModuleDeclaration(node) { + if (this.isContextual(112)) { + node.global = true; + node.id = this.parseIdentifier(); + } else if (this.match(133)) { + node.id = super.parseStringLiteral(this.state.value); + } else { + this.unexpected(); + } + if (this.match(5)) { + this.scope.enter(256); + this.prodParam.enter(0); + node.body = this.tsParseModuleBlock(); + this.prodParam.exit(); + this.scope.exit(); + } else { + this.semicolon(); + } + return this.finishNode(node, "TSModuleDeclaration"); + } + tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) { + node.isExport = isExport || false; + node.id = maybeDefaultIdentifier || this.parseIdentifier(); + this.checkIdentifier(node.id, 4096); + this.expect(29); + const moduleReference = this.tsParseModuleReference(); + if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { + this.raise(TSErrors.ImportAliasHasImportType, moduleReference); + } + node.moduleReference = moduleReference; + this.semicolon(); + return this.finishNode(node, "TSImportEqualsDeclaration"); + } + tsIsExternalModuleReference() { + return this.isContextual(119) && this.lookaheadCharCode() === 40; + } + tsParseModuleReference() { + return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false); + } + tsParseExternalModuleReference() { + const node = this.startNode(); + this.expectContextual(119); + this.expect(10); + if (!this.match(133)) { + this.unexpected(); + } + node.expression = super.parseExprAtom(); + this.expect(11); + this.sawUnambiguousESM = true; + return this.finishNode(node, "TSExternalModuleReference"); + } + tsLookAhead(f) { + const state = this.state.clone(); + const res = f(); + this.state = state; + return res; + } + tsTryParseAndCatch(f) { + const result = this.tryParse(abort => f() || abort()); + if (result.aborted || !result.node) return; + if (result.error) this.state = result.failState; + return result.node; + } + tsTryParse(f) { + const state = this.state.clone(); + const result = f(); + if (result !== undefined && result !== false) { + return result; + } + this.state = state; + } + tsTryParseDeclare(nany) { + if (this.isLineTerminator()) { + return; + } + let startType = this.state.type; + let kind; + if (this.isContextual(100)) { + startType = 74; + kind = "let"; + } + return this.tsInAmbientContext(() => { + switch (startType) { + case 68: + nany.declare = true; + return super.parseFunctionStatement(nany, false, false); + case 80: + nany.declare = true; + return this.parseClass(nany, true, false); + case 126: + return this.tsParseEnumDeclaration(nany, { + declare: true + }); + case 112: + return this.tsParseAmbientExternalModuleDeclaration(nany); + case 75: + case 74: + if (!this.match(75) || !this.isLookaheadContextual("enum")) { + nany.declare = true; + return this.parseVarStatement(nany, kind || this.state.value, true); + } + this.expect(75); + return this.tsParseEnumDeclaration(nany, { + const: true, + declare: true + }); + case 129: + { + const result = this.tsParseInterfaceDeclaration(nany, { + declare: true + }); + if (result) return result; + } + default: + if (tokenIsIdentifier(startType)) { + return this.tsParseDeclaration(nany, this.state.value, true, null); + } + } + }); + } + tsTryParseExportDeclaration() { + return this.tsParseDeclaration(this.startNode(), this.state.value, true, null); + } + tsParseExpressionStatement(node, expr, decorators) { + switch (expr.name) { + case "declare": + { + const declaration = this.tsTryParseDeclare(node); + if (declaration) { + declaration.declare = true; + } + return declaration; + } + case "global": + if (this.match(5)) { + this.scope.enter(256); + this.prodParam.enter(0); + const mod = node; + mod.global = true; + mod.id = expr; + mod.body = this.tsParseModuleBlock(); + this.scope.exit(); + this.prodParam.exit(); + return this.finishNode(mod, "TSModuleDeclaration"); + } + break; + default: + return this.tsParseDeclaration(node, expr.name, false, decorators); + } + } + tsParseDeclaration(node, value, next, decorators) { + switch (value) { + case "abstract": + if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) { + return this.tsParseAbstractDeclaration(node, decorators); + } + break; + case "module": + if (this.tsCheckLineTerminator(next)) { + if (this.match(133)) { + return this.tsParseAmbientExternalModuleDeclaration(node); + } else if (tokenIsIdentifier(this.state.type)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + } + break; + case "namespace": + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + return this.tsParseModuleOrNamespaceDeclaration(node); + } + break; + case "type": + if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { + return this.tsParseTypeAliasDeclaration(node); + } + break; + } + } + tsCheckLineTerminator(next) { + if (next) { + if (this.hasFollowingLineBreak()) return false; + this.next(); + return true; + } + return !this.isLineTerminator(); + } + tsTryParseGenericAsyncArrowFunction(startLoc) { + if (!this.match(47)) return; + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = true; + const res = this.tsTryParseAndCatch(() => { + const node = this.startNodeAt(startLoc); + node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + super.parseFunctionParams(node); + node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); + this.expect(19); + return node; + }); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + if (!res) return; + return super.parseArrowExpression(res, null, true); + } + tsParseTypeArgumentsInExpression() { + if (this.reScan_lt() !== 47) return; + return this.tsParseTypeArguments(); + } + tsParseTypeArguments() { + const node = this.startNode(); + node.params = this.tsInType(() => this.tsInNoContext(() => { + this.expect(47); + return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); + })); + if (node.params.length === 0) { + this.raise(TSErrors.EmptyTypeArguments, node); + } else if (!this.state.inType && this.curContext() === types$1.brace) { + this.reScan_lt_gt(); + } + this.expect(48); + return this.finishNode(node, "TSTypeParameterInstantiation"); + } + tsIsDeclarationStart() { + return tokenIsTSDeclarationStart(this.state.type); + } + isExportDefaultSpecifier() { + if (this.tsIsDeclarationStart()) return false; + return super.isExportDefaultSpecifier(); + } + parseAssignableListItem(flags, decorators) { + const startLoc = this.state.startLoc; + const modified = {}; + this.tsParseModifiers({ + allowedModifiers: ["public", "private", "protected", "override", "readonly"] + }, modified); + const accessibility = modified.accessibility; + const override = modified.override; + const readonly = modified.readonly; + if (!(flags & 4) && (accessibility || readonly || override)) { + this.raise(TSErrors.UnexpectedParameterModifier, startLoc); + } + const left = this.parseMaybeDefault(); + this.parseAssignableListItemTypes(left, flags); + const elt = this.parseMaybeDefault(left.loc.start, left); + if (accessibility || readonly || override) { + const pp = this.startNodeAt(startLoc); + if (decorators.length) { + pp.decorators = decorators; + } + if (accessibility) pp.accessibility = accessibility; + if (readonly) pp.readonly = readonly; + if (override) pp.override = override; + if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { + this.raise(TSErrors.UnsupportedParameterPropertyKind, pp); + } + pp.parameter = elt; + return this.finishNode(pp, "TSParameterProperty"); + } + if (decorators.length) { + left.decorators = decorators; + } + return elt; + } + isSimpleParameter(node) { + return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node); + } + tsDisallowOptionalPattern(node) { + for (const param of node.params) { + if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) { + this.raise(TSErrors.PatternIsOptional, param); + } + } + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + super.setArrowFunctionParameters(node, params, trailingCommaLoc); + this.tsDisallowOptionalPattern(node); + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + if (this.match(14)) { + node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + } + const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined; + if (bodilessType && !this.match(5) && this.isLineTerminator()) { + return this.finishNode(node, bodilessType); + } + if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { + this.raise(TSErrors.DeclareFunctionHasImplementation, node); + if (node.declare) { + return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); + } + } + this.tsDisallowOptionalPattern(node); + return super.parseFunctionBodyAndFinish(node, type, isMethod); + } + registerFunctionStatementId(node) { + if (!node.body && node.id) { + this.checkIdentifier(node.id, 1024); + } else { + super.registerFunctionStatementId(node); + } + } + tsCheckForInvalidTypeCasts(items) { + items.forEach(node => { + if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { + this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation); + } + }); + } + toReferencedList(exprList, isInParens) { + this.tsCheckForInvalidTypeCasts(exprList); + return exprList; + } + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); + if (node.type === "ArrayExpression") { + this.tsCheckForInvalidTypeCasts(node.elements); + } + return node; + } + parseSubscript(base, startLoc, noCalls, state) { + if (!this.hasPrecedingLineBreak() && this.match(35)) { + this.state.canStartJSXElement = false; + this.next(); + const nonNullExpression = this.startNodeAt(startLoc); + nonNullExpression.expression = base; + return this.finishNode(nonNullExpression, "TSNonNullExpression"); + } + let isOptionalCall = false; + if (this.match(18) && this.lookaheadCharCode() === 60) { + if (noCalls) { + state.stop = true; + return base; + } + state.optionalChainMember = isOptionalCall = true; + this.next(); + } + if (this.match(47) || this.match(51)) { + let missingParenErrorLoc; + const result = this.tsTryParseAndCatch(() => { + if (!noCalls && this.atPossibleAsyncArrow(base)) { + const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc); + if (asyncArrowFn) { + return asyncArrowFn; + } + } + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (!typeArguments) return; + if (isOptionalCall && !this.match(10)) { + missingParenErrorLoc = this.state.curPosition(); + return; + } + if (tokenIsTemplate(this.state.type)) { + const result = super.parseTaggedTemplateExpression(base, startLoc, state); + result.typeParameters = typeArguments; + return result; + } + if (!noCalls && this.eat(10)) { + const node = this.startNodeAt(startLoc); + node.callee = base; + node.arguments = this.parseCallExpressionArguments(11, false); + this.tsCheckForInvalidTypeCasts(node.arguments); + node.typeParameters = typeArguments; + if (state.optionalChainMember) { + node.optional = isOptionalCall; + } + return this.finishCallExpression(node, state.optionalChainMember); + } + const tokenType = this.state.type; + if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) { + return; + } + const node = this.startNodeAt(startLoc); + node.expression = base; + node.typeParameters = typeArguments; + return this.finishNode(node, "TSInstantiationExpression"); + }); + if (missingParenErrorLoc) { + this.unexpected(missingParenErrorLoc, 10); + } + if (result) { + if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) { + this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc); + } + return result; + } + } + return super.parseSubscript(base, startLoc, noCalls, state); + } + parseNewCallee(node) { + var _callee$extra; + super.parseNewCallee(node); + const { + callee + } = node; + if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) { + node.typeParameters = callee.typeParameters; + node.callee = callee.expression; + } + } + parseExprOp(left, leftStartLoc, minPrec) { + let isSatisfies; + if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) { + const node = this.startNodeAt(leftStartLoc); + node.expression = left; + node.typeAnnotation = this.tsInType(() => { + this.next(); + if (this.match(75)) { + if (isSatisfies) { + this.raise(Errors.UnexpectedKeyword, this.state.startLoc, { + keyword: "const" + }); + } + return this.tsParseTypeReference(); + } + return this.tsParseType(); + }); + this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression"); + this.reScan_lt_gt(); + return this.parseExprOp(node, leftStartLoc, minPrec); + } + return super.parseExprOp(left, leftStartLoc, minPrec); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (!this.state.isAmbientContext) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + checkImportReflection(node) { + super.checkImportReflection(node); + if (node.module && node.importKind !== "value") { + this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start); + } + } + checkDuplicateExports() {} + isPotentialImportPhase(isExport) { + if (super.isPotentialImportPhase(isExport)) return true; + if (this.isContextual(130)) { + const ch = this.lookaheadCharCode(); + return isExport ? ch === 123 || ch === 42 : ch !== 61; + } + return !isExport && this.isContextual(87); + } + applyImportPhase(node, isExport, phase, loc) { + super.applyImportPhase(node, isExport, phase, loc); + if (isExport) { + node.exportKind = phase === "type" ? "type" : "value"; + } else { + node.importKind = phase === "type" || phase === "typeof" ? phase : "value"; + } + } + parseImport(node) { + if (this.match(133)) { + node.importKind = "value"; + return super.parseImport(node); + } + let importNode; + if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) { + node.importKind = "value"; + return this.tsParseImportEqualsDeclaration(node); + } else if (this.isContextual(130)) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false); + if (this.lookaheadCharCode() === 61) { + return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier); + } else { + importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier); + } + } else { + importNode = super.parseImport(node); + } + if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { + this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode); + } + return importNode; + } + parseExport(node, decorators) { + if (this.match(83)) { + this.next(); + let maybeDefaultIdentifier = null; + if (this.isContextual(130) && this.isPotentialImportPhase(false)) { + maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false); + } else { + node.importKind = "value"; + } + return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, true); + } else if (this.eat(29)) { + const assign = node; + assign.expression = super.parseExpression(); + this.semicolon(); + this.sawUnambiguousESM = true; + return this.finishNode(assign, "TSExportAssignment"); + } else if (this.eatContextual(93)) { + const decl = node; + this.expectContextual(128); + decl.id = this.parseIdentifier(); + this.semicolon(); + return this.finishNode(decl, "TSNamespaceExportDeclaration"); + } else { + return super.parseExport(node, decorators); + } + } + isAbstractClass() { + return this.isContextual(124) && this.lookahead().type === 80; + } + parseExportDefaultExpression() { + if (this.isAbstractClass()) { + const cls = this.startNode(); + this.next(); + cls.abstract = true; + return this.parseClass(cls, true, true); + } + if (this.match(129)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseExportDefaultExpression(); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + const { + isAmbientContext + } = this.state; + const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext); + if (!isAmbientContext) return declaration; + for (const { + id, + init + } of declaration.declarations) { + if (!init) continue; + if (kind !== "const" || !!id.typeAnnotation) { + this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init); + } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) { + this.raise(TSErrors.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference, init); + } + } + return declaration; + } + parseStatementContent(flags, decorators) { + if (this.match(75) && this.isLookaheadContextual("enum")) { + const node = this.startNode(); + this.expect(75); + return this.tsParseEnumDeclaration(node, { + const: true + }); + } + if (this.isContextual(126)) { + return this.tsParseEnumDeclaration(this.startNode()); + } + if (this.isContextual(129)) { + const result = this.tsParseInterfaceDeclaration(this.startNode()); + if (result) return result; + } + return super.parseStatementContent(flags, decorators); + } + parseAccessModifier() { + return this.tsParseModifier(["public", "protected", "private"]); + } + tsHasSomeModifiers(member, modifiers) { + return modifiers.some(modifier => { + if (tsIsAccessModifier(modifier)) { + return member.accessibility === modifier; + } + return !!member[modifier]; + }); + } + tsIsStartOfStaticBlocks() { + return this.isContextual(106) && this.lookaheadCharCode() === 123; + } + parseClassMember(classBody, member, state) { + const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"]; + this.tsParseModifiers({ + allowedModifiers: modifiers, + disallowedModifiers: ["in", "out"], + stopOnStartOfClassStaticBlock: true, + errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions + }, member); + const callParseClassMemberWithIsStatic = () => { + if (this.tsIsStartOfStaticBlocks()) { + this.next(); + this.next(); + if (this.tsHasSomeModifiers(member, modifiers)) { + this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition()); + } + super.parseClassStaticBlock(classBody, member); + } else { + this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static); + } + }; + if (member.declare) { + this.tsInAmbientContext(callParseClassMemberWithIsStatic); + } else { + callParseClassMemberWithIsStatic(); + } + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const idx = this.tsTryParseIndexSignature(member); + if (idx) { + classBody.body.push(idx); + if (member.abstract) { + this.raise(TSErrors.IndexSignatureHasAbstract, member); + } + if (member.accessibility) { + this.raise(TSErrors.IndexSignatureHasAccessibility, member, { + modifier: member.accessibility + }); + } + if (member.declare) { + this.raise(TSErrors.IndexSignatureHasDeclare, member); + } + if (member.override) { + this.raise(TSErrors.IndexSignatureHasOverride, member); + } + return; + } + if (!this.state.inAbstractClass && member.abstract) { + this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member); + } + if (member.override) { + if (!state.hadSuperClass) { + this.raise(TSErrors.OverrideNotInSubClass, member); + } + } + super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parsePostMemberNameModifiers(methodOrProp) { + const optional = this.eat(17); + if (optional) methodOrProp.optional = true; + if (methodOrProp.readonly && this.match(10)) { + this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp); + } + if (methodOrProp.declare && this.match(10)) { + this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp); + } + } + parseExpressionStatement(node, expr, decorators) { + const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr, decorators) : undefined; + return decl || super.parseExpressionStatement(node, expr, decorators); + } + shouldParseExportDeclaration() { + if (this.tsIsDeclarationStart()) return true; + return super.shouldParseExportDeclaration(); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (!this.state.maybeInArrowParameters || !this.match(17)) { + return super.parseConditional(expr, startLoc, refExpressionErrors); + } + const result = this.tryParse(() => super.parseConditional(expr, startLoc)); + if (!result.node) { + if (result.error) { + super.setOptionalParametersError(refExpressionErrors, result.error); + } + return expr; + } + if (result.error) this.state = result.failState; + return result.node; + } + parseParenItem(node, startLoc) { + node = super.parseParenItem(node, startLoc); + if (this.eat(17)) { + node.optional = true; + this.resetEndLocation(node); + } + if (this.match(14)) { + const typeCastNode = this.startNodeAt(startLoc); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); + return this.finishNode(typeCastNode, "TSTypeCastExpression"); + } + return node; + } + parseExportDeclaration(node) { + if (!this.state.isAmbientContext && this.isContextual(125)) { + return this.tsInAmbientContext(() => this.parseExportDeclaration(node)); + } + const startLoc = this.state.startLoc; + const isDeclare = this.eatContextual(125); + if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) { + throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc); + } + const isIdentifier = tokenIsIdentifier(this.state.type); + const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node); + if (!declaration) return null; + if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) { + node.exportKind = "type"; + } + if (isDeclare) { + this.resetStartLocation(declaration, startLoc); + declaration.declare = true; + } + return declaration; + } + parseClassId(node, isStatement, optionalId, bindingType) { + if ((!isStatement || optionalId) && this.isContextual(113)) { + return; + } + super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331); + const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); + if (typeParameters) node.typeParameters = typeParameters; + } + parseClassPropertyAnnotation(node) { + if (!node.optional) { + if (this.eat(35)) { + node.definite = true; + } else if (this.eat(17)) { + node.optional = true; + } + } + const type = this.tsTryParseTypeAnnotation(); + if (type) node.typeAnnotation = type; + } + parseClassProperty(node) { + this.parseClassPropertyAnnotation(node); + if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) { + this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc); + } + if (node.abstract && this.match(29)) { + const { + key + } = node; + this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, { + propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` + }); + } + return super.parseClassProperty(node); + } + parseClassPrivateProperty(node) { + if (node.abstract) { + this.raise(TSErrors.PrivateElementHasAbstract, node); + } + if (node.accessibility) { + this.raise(TSErrors.PrivateElementHasAccessibility, node, { + modifier: node.accessibility + }); + } + this.parseClassPropertyAnnotation(node); + return super.parseClassPrivateProperty(node); + } + parseClassAccessorProperty(node) { + this.parseClassPropertyAnnotation(node); + if (node.optional) { + this.raise(TSErrors.AccessorCannotBeOptional, node); + } + return super.parseClassAccessorProperty(node); + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters && isConstructor) { + this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters); + } + const { + declare = false, + kind + } = method; + if (declare && (kind === "get" || kind === "set")) { + this.raise(TSErrors.DeclareAccessor, method, { + kind + }); + } + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) method.typeParameters = typeParameters; + super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); + } + declareClassPrivateMethodInScope(node, kind) { + if (node.type === "TSDeclareMethod") return; + if (node.type === "MethodDefinition" && !node.value.body) return; + super.declareClassPrivateMethodInScope(node, kind); + } + parseClassSuper(node) { + super.parseClassSuper(node); + if (node.superClass && (this.match(47) || this.match(51))) { + node.superTypeParameters = this.tsParseTypeArgumentsInExpression(); + } + if (this.eatContextual(113)) { + node.implements = this.tsParseHeritageClause("implements"); + } + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) prop.typeParameters = typeParameters; + return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); + } + parseFunctionParams(node, isConstructor) { + const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); + if (typeParameters) node.typeParameters = typeParameters; + super.parseFunctionParams(node, isConstructor); + } + parseVarId(decl, kind) { + super.parseVarId(decl, kind); + if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) { + decl.definite = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) { + decl.id.typeAnnotation = type; + this.resetEndLocation(decl.id); + } + } + parseAsyncArrowFromCallExpression(node, call) { + if (this.match(14)) { + node.returnType = this.tsParseTypeAnnotation(); + } + return super.parseAsyncArrowFromCallExpression(node, call); + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2; + let state; + let jsx; + let typeCast; + if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { + state = this.state.clone(); + jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!jsx.error) return jsx.node; + const { + context + } = this.state; + const currentContext = context[context.length - 1]; + if (currentContext === types$1.j_oTag || currentContext === types$1.j_expr) { + context.pop(); + } + } + if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) { + return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + } + if (!state || state === this.state) state = this.state.clone(); + let typeParameters; + const arrow = this.tryParse(abort => { + var _expr$extra, _typeParameters; + typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); + const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); + if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + abort(); + } + if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { + this.resetStartLocationFromNode(expr, typeParameters); + } + expr.typeParameters = typeParameters; + return expr; + }, state); + if (!arrow.error && !arrow.aborted) { + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if (!jsx) { + assert$1(!this.hasPlugin("jsx")); + typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); + if (!typeCast.error) return typeCast.node; + } + if ((_jsx2 = jsx) != null && _jsx2.node) { + this.state = jsx.failState; + return jsx.node; + } + if (arrow.node) { + this.state = arrow.failState; + if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); + return arrow.node; + } + if ((_typeCast = typeCast) != null && _typeCast.node) { + this.state = typeCast.failState; + return typeCast.node; + } + throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error); + } + reportReservedArrowTypeParam(node) { + var _node$extra; + if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { + this.raise(TSErrors.ReservedArrowTypeParam, node); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + if (!this.hasPlugin("jsx") && this.match(47)) { + return this.tsParseTypeAssertion(); + } + return super.parseMaybeUnary(refExpressionErrors, sawUnary); + } + parseArrow(node) { + if (this.match(14)) { + const result = this.tryParse(abort => { + const returnType = this.tsParseTypeOrTypePredicateAnnotation(14); + if (this.canInsertSemicolon() || !this.match(19)) abort(); + return returnType; + }); + if (result.aborted) return; + if (!result.thrown) { + if (result.error) this.state = result.failState; + node.returnType = result.node; + } + } + return super.parseArrow(node); + } + parseAssignableListItemTypes(param, flags) { + if (!(flags & 2)) return param; + if (this.eat(17)) { + param.optional = true; + } + const type = this.tsTryParseTypeAnnotation(); + if (type) param.typeAnnotation = type; + this.resetEndLocation(param); + return param; + } + isAssignable(node, isBinding) { + switch (node.type) { + case "TSTypeCastExpression": + return this.isAssignable(node.expression, isBinding); + case "TSParameterProperty": + return true; + default: + return super.isAssignable(node, isBinding); + } + } + toAssignable(node, isLHS = false) { + switch (node.type) { + case "ParenthesizedExpression": + this.toAssignableParenthesizedExpression(node, isLHS); + break; + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + if (isLHS) { + this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node); + } else { + this.raise(TSErrors.UnexpectedTypeCastInParameter, node); + } + this.toAssignable(node.expression, isLHS); + break; + case "AssignmentExpression": + if (!isLHS && node.left.type === "TSTypeCastExpression") { + node.left = this.typeCastToParameter(node.left); + } + default: + super.toAssignable(node, isLHS); + } + } + toAssignableParenthesizedExpression(node, isLHS) { + switch (node.expression.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSNonNullExpression": + case "TSTypeAssertion": + case "ParenthesizedExpression": + this.toAssignable(node.expression, isLHS); + break; + default: + super.toAssignable(node, isLHS); + } + } + checkToRestConversion(node, allowPattern) { + switch (node.type) { + case "TSAsExpression": + case "TSSatisfiesExpression": + case "TSTypeAssertion": + case "TSNonNullExpression": + this.checkToRestConversion(node.expression, false); + break; + default: + super.checkToRestConversion(node, allowPattern); + } + } + isValidLVal(type, isUnparenthesizedInAssign, binding) { + return getOwn({ + TSTypeCastExpression: true, + TSParameterProperty: "parameter", + TSNonNullExpression: "expression", + TSAsExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true], + TSSatisfiesExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true], + TSTypeAssertion: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true] + }, type) || super.isValidLVal(type, isUnparenthesizedInAssign, binding); + } + parseBindingAtom() { + if (this.state.type === 78) { + return this.parseIdentifier(true); + } + return super.parseBindingAtom(); + } + parseMaybeDecoratorArguments(expr) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsParseTypeArgumentsInExpression(); + if (this.match(10)) { + const call = super.parseMaybeDecoratorArguments(expr); + call.typeParameters = typeArguments; + return call; + } + this.unexpected(null, 10); + } + return super.parseMaybeDecoratorArguments(expr); + } + checkCommaAfterRest(close) { + if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) { + this.next(); + return false; + } + return super.checkCommaAfterRest(close); + } + isClassMethod() { + return this.match(47) || super.isClassMethod(); + } + isClassProperty() { + return this.match(35) || this.match(14) || super.isClassProperty(); + } + parseMaybeDefault(startLoc, left) { + const node = super.parseMaybeDefault(startLoc, left); + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation); + } + return node; + } + getTokenFromCode(code) { + if (this.state.inType) { + if (code === 62) { + this.finishOp(48, 1); + return; + } + if (code === 60) { + this.finishOp(47, 1); + return; + } + } + super.getTokenFromCode(code); + } + reScan_lt_gt() { + const { + type + } = this.state; + if (type === 47) { + this.state.pos -= 1; + this.readToken_lt(); + } else if (type === 48) { + this.state.pos -= 1; + this.readToken_gt(); + } + } + reScan_lt() { + const { + type + } = this.state; + if (type === 51) { + this.state.pos -= 2; + this.finishOp(47, 1); + return 47; + } + return type; + } + toAssignableList(exprList, trailingCommaLoc, isLHS) { + for (let i = 0; i < exprList.length; i++) { + const expr = exprList[i]; + if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + super.toAssignableList(exprList, trailingCommaLoc, isLHS); + } + typeCastToParameter(node) { + node.expression.typeAnnotation = node.typeAnnotation; + this.resetEndLocation(node.expression, node.typeAnnotation.loc.end); + return node.expression; + } + shouldParseArrow(params) { + if (this.match(14)) { + return params.every(expr => this.isAssignable(expr, true)); + } + return super.shouldParseArrow(params); + } + shouldParseAsyncArrow() { + return this.match(14) || super.shouldParseAsyncArrow(); + } + canHaveLeadingDecorator() { + return super.canHaveLeadingDecorator() || this.isAbstractClass(); + } + jsxParseOpeningElementAfterName(node) { + if (this.match(47) || this.match(51)) { + const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression()); + if (typeArguments) node.typeParameters = typeArguments; + } + return super.jsxParseOpeningElementAfterName(node); + } + getGetterSetterExpectedParamCount(method) { + const baseCount = super.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + const firstParam = params[0]; + const hasContextParam = firstParam && this.isThisParam(firstParam); + return hasContextParam ? baseCount + 1 : baseCount; + } + parseCatchClauseParam() { + const param = super.parseCatchClauseParam(); + const type = this.tsTryParseTypeAnnotation(); + if (type) { + param.typeAnnotation = type; + this.resetEndLocation(param); + } + return param; + } + tsInAmbientContext(cb) { + const oldIsAmbientContext = this.state.isAmbientContext; + this.state.isAmbientContext = true; + try { + return cb(); + } finally { + this.state.isAmbientContext = oldIsAmbientContext; + } + } + parseClass(node, isStatement, optionalId) { + const oldInAbstractClass = this.state.inAbstractClass; + this.state.inAbstractClass = !!node.abstract; + try { + return super.parseClass(node, isStatement, optionalId); + } finally { + this.state.inAbstractClass = oldInAbstractClass; + } + } + tsParseAbstractDeclaration(node, decorators) { + if (this.match(80)) { + node.abstract = true; + return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false)); + } else if (this.isContextual(129)) { + if (!this.hasFollowingLineBreak()) { + node.abstract = true; + this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, node); + return this.tsParseInterfaceDeclaration(node); + } + } else { + this.unexpected(null, 80); + } + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) { + const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); + if (method.abstract) { + const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body; + if (hasBody) { + const { + key + } = method; + this.raise(TSErrors.AbstractMethodHasImplementation, method, { + methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` + }); + } + } + return method; + } + tsParseTypeParameterName() { + const typeName = this.parseIdentifier(); + return typeName.name; + } + shouldParseAsAmbientContext() { + return !!this.getPluginOption("typescript", "dts"); + } + parse() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.parse(); + } + getExpression() { + if (this.shouldParseAsAmbientContext()) { + this.state.isAmbientContext = true; + } + return super.getExpression(); + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (!isString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport); + return this.finishNode(node, "ExportSpecifier"); + } + node.exportKind = "value"; + return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly); + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (!importedIsString && isMaybeTypeOnly) { + this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport); + return this.finishNode(specifier, "ImportSpecifier"); + } + specifier.importKind = "value"; + return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096); + } + parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) { + const leftOfAsKey = isImport ? "imported" : "local"; + const rightOfAsKey = isImport ? "local" : "exported"; + let leftOfAs = node[leftOfAsKey]; + let rightOfAs; + let hasTypeSpecifier = false; + let canParseAsKeyword = true; + const loc = leftOfAs.loc.start; + if (this.isContextual(93)) { + const firstAs = this.parseIdentifier(); + if (this.isContextual(93)) { + const secondAs = this.parseIdentifier(); + if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + leftOfAs = firstAs; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + canParseAsKeyword = false; + } else { + rightOfAs = secondAs; + canParseAsKeyword = false; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + canParseAsKeyword = false; + rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } else { + hasTypeSpecifier = true; + leftOfAs = firstAs; + } + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + hasTypeSpecifier = true; + if (isImport) { + leftOfAs = this.parseIdentifier(true); + if (!this.isContextual(93)) { + this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true); + } + } else { + leftOfAs = this.parseModuleExportName(); + } + } + if (hasTypeSpecifier && isInTypeOnlyImportExport) { + this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc); + } + node[leftOfAsKey] = leftOfAs; + node[rightOfAsKey] = rightOfAs; + const kindKey = isImport ? "importKind" : "exportKind"; + node[kindKey] = hasTypeSpecifier ? "type" : "value"; + if (canParseAsKeyword && this.eatContextual(93)) { + node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName(); + } + if (!node[rightOfAsKey]) { + node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]); + } + if (isImport) { + this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096); + } + } +}; +function isPossiblyLiteralEnum(expression) { + if (expression.type !== "MemberExpression") return false; + const { + computed, + property + } = expression; + if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +function isValidAmbientConstInitializer(expression, estree) { + var _expression$extra; + const { + type + } = expression; + if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) { + return false; + } + if (estree) { + if (type === "Literal") { + const { + value + } = expression; + if (typeof value === "string" || typeof value === "boolean") { + return true; + } + } + } else { + if (type === "StringLiteral" || type === "BooleanLiteral") { + return true; + } + } + if (isNumber$1(expression, estree) || isNegativeNumber(expression, estree)) { + return true; + } + if (type === "TemplateLiteral" && expression.expressions.length === 0) { + return true; + } + if (isPossiblyLiteralEnum(expression)) { + return true; + } + return false; +} +function isNumber$1(expression, estree) { + if (estree) { + return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression); + } + return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral"; +} +function isNegativeNumber(expression, estree) { + if (expression.type === "UnaryExpression") { + const { + operator, + argument + } = expression; + if (operator === "-" && isNumber$1(argument, estree)) { + return true; + } + } + return false; +} +function isUncomputedMemberExpressionChain(expression) { + if (expression.type === "Identifier") return true; + if (expression.type !== "MemberExpression" || expression.computed) { + return false; + } + return isUncomputedMemberExpressionChain(expression.object); +} +const PlaceholderErrors = ParseErrorEnum`placeholders`({ + ClassNameIsRequired: "A class name is required.", + UnexpectedSpace: "Unexpected space in placeholder." +}); +var placeholders = superClass => class PlaceholdersParserMixin extends superClass { + parsePlaceholder(expectedNode) { + if (this.match(144)) { + const node = this.startNode(); + this.next(); + this.assertNoSpace(); + node.name = super.parseIdentifier(true); + this.assertNoSpace(); + this.expect(144); + return this.finishPlaceholder(node, expectedNode); + } + } + finishPlaceholder(node, expectedNode) { + const isFinished = !!(node.expectedNode && node.type === "Placeholder"); + node.expectedNode = expectedNode; + return isFinished ? node : this.finishNode(node, "Placeholder"); + } + getTokenFromCode(code) { + if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { + this.finishOp(144, 2); + } else { + super.getTokenFromCode(code); + } + } + parseExprAtom(refExpressionErrors) { + return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors); + } + parseIdentifier(liberal) { + return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal); + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word !== undefined) { + super.checkReservedWord(word, startLoc, checkKeywords, isBinding); + } + } + parseBindingAtom() { + return this.parsePlaceholder("Pattern") || super.parseBindingAtom(); + } + isValidLVal(type, isParenthesized, binding) { + return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding); + } + toAssignable(node, isLHS) { + if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { + node.expectedNode = "Pattern"; + } else { + super.toAssignable(node, isLHS); + } + } + chStartsBindingIdentifier(ch, pos) { + if (super.chStartsBindingIdentifier(ch, pos)) { + return true; + } + const nextToken = this.lookahead(); + if (nextToken.type === 144) { + return true; + } + return false; + } + verifyBreakContinue(node, isBreak) { + if (node.label && node.label.type === "Placeholder") return; + super.verifyBreakContinue(node, isBreak); + } + parseExpressionStatement(node, expr) { + var _expr$extra; + if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { + return super.parseExpressionStatement(node, expr); + } + if (this.match(14)) { + const stmt = node; + stmt.label = this.finishPlaceholder(expr, "Identifier"); + this.next(); + stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration(); + return this.finishNode(stmt, "LabeledStatement"); + } + this.semicolon(); + node.name = expr.name; + return this.finishPlaceholder(node, "Statement"); + } + parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) { + return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse); + } + parseFunctionId(requireId) { + return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId); + } + parseClass(node, isStatement, optionalId) { + const type = isStatement ? "ClassDeclaration" : "ClassExpression"; + this.next(); + const oldStrict = this.state.strict; + const placeholder = this.parsePlaceholder("Identifier"); + if (placeholder) { + if (this.match(81) || this.match(144) || this.match(5)) { + node.id = placeholder; + } else if (optionalId || !isStatement) { + node.id = null; + node.body = this.finishPlaceholder(placeholder, "ClassBody"); + return this.finishNode(node, type); + } else { + throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc); + } + } else { + this.parseClassId(node, isStatement, optionalId); + } + super.parseClassSuper(node); + node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, type); + } + parseExport(node, decorators) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseExport(node, decorators); + if (!this.isContextual(98) && !this.match(12)) { + node.specifiers = []; + node.source = null; + node.declaration = this.finishPlaceholder(placeholder, "Declaration"); + return this.finishNode(node, "ExportNamedDeclaration"); + } + this.expectPlugin("exportDefaultFrom"); + const specifier = this.startNode(); + specifier.exported = placeholder; + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return super.parseExport(node, decorators); + } + isExportDefaultSpecifier() { + if (this.match(65)) { + const next = this.nextTokenStart(); + if (this.isUnparsedContextual(next, "from")) { + if (this.input.startsWith(tokenLabelName(144), this.nextTokenStartSince(next + 4))) { + return true; + } + } + } + return super.isExportDefaultSpecifier(); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + var _specifiers; + if ((_specifiers = node.specifiers) != null && _specifiers.length) { + return true; + } + return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + } + checkExport(node) { + const { + specifiers + } = node; + if (specifiers != null && specifiers.length) { + node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder"); + } + super.checkExport(node); + node.specifiers = specifiers; + } + parseImport(node) { + const placeholder = this.parsePlaceholder("Identifier"); + if (!placeholder) return super.parseImport(node); + node.specifiers = []; + if (!this.isContextual(98) && !this.match(12)) { + node.source = this.finishPlaceholder(placeholder, "StringLiteral"); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + const specifier = this.startNodeAtNode(placeholder); + specifier.local = placeholder; + node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier")); + if (this.eat(12)) { + const hasStarImport = this.maybeParseStarImportSpecifier(node); + if (!hasStarImport) this.parseNamedImportSpecifiers(node); + } + this.expectContextual(98); + node.source = this.parseImportSource(); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + return this.parsePlaceholder("StringLiteral") || super.parseImportSource(); + } + assertNoSpace() { + if (this.state.start > this.state.lastTokEndLoc.index) { + this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc); + } + } +}; +var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass { + parseV8Intrinsic() { + if (this.match(54)) { + const v8IntrinsicStartLoc = this.state.startLoc; + const node = this.startNode(); + this.next(); + if (tokenIsIdentifier(this.state.type)) { + const name = this.parseIdentifierName(); + const identifier = this.createIdentifier(node, name); + identifier.type = "V8IntrinsicIdentifier"; + if (this.match(10)) { + return identifier; + } + } + this.unexpected(v8IntrinsicStartLoc); + } + } + parseExprAtom(refExpressionErrors) { + return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors); + } +}; +function hasPlugin(plugins, expectedConfig) { + const [expectedName, expectedOptions] = typeof expectedConfig === "string" ? [expectedConfig, {}] : expectedConfig; + const expectedKeys = Object.keys(expectedOptions); + const expectedOptionsIsEmpty = expectedKeys.length === 0; + return plugins.some(p => { + if (typeof p === "string") { + return expectedOptionsIsEmpty && p === expectedName; + } else { + const [pluginName, pluginOptions] = p; + if (pluginName !== expectedName) { + return false; + } + for (const key of expectedKeys) { + if (pluginOptions[key] !== expectedOptions[key]) { + return false; + } + } + return true; + } + }); +} +function getPluginOption(plugins, name, option) { + const plugin = plugins.find(plugin => { + if (Array.isArray(plugin)) { + return plugin[0] === name; + } else { + return plugin === name; + } + }); + if (plugin && Array.isArray(plugin) && plugin.length > 1) { + return plugin[1][option]; + } + return null; +} +const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; +const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"]; +const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; +function validatePlugins(plugins) { + if (hasPlugin(plugins, "decorators")) { + if (hasPlugin(plugins, "decorators-legacy")) { + throw new Error("Cannot use the decorators and decorators-legacy plugin together"); + } + const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport"); + if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") { + throw new Error("'decoratorsBeforeExport' must be a boolean, if specified."); + } + const allowCallParenthesized = getPluginOption(plugins, "decorators", "allowCallParenthesized"); + if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") { + throw new Error("'allowCallParenthesized' must be a boolean."); + } + } + if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) { + throw new Error("Cannot combine flow and typescript plugins."); + } + if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) { + throw new Error("Cannot combine placeholders and v8intrinsic plugins."); + } + if (hasPlugin(plugins, "pipelineOperator")) { + const proposal = getPluginOption(plugins, "pipelineOperator", "proposal"); + if (!PIPELINE_PROPOSALS.includes(proposal)) { + const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", "); + throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`); + } + const tupleSyntaxIsHash = hasPlugin(plugins, ["recordAndTuple", { + syntaxType: "hash" + }]); + if (proposal === "hack") { + if (hasPlugin(plugins, "placeholders")) { + throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); + } + if (hasPlugin(plugins, "v8intrinsic")) { + throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); + } + const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken"); + if (!TOPIC_TOKENS.includes(topicToken)) { + const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", "); + throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`); + } + if (topicToken === "#" && tupleSyntaxIsHash) { + throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); + } + } else if (proposal === "smart" && tupleSyntaxIsHash) { + throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); + } + } + if (hasPlugin(plugins, "moduleAttributes")) { + { + if (hasPlugin(plugins, "importAssertions") || hasPlugin(plugins, "importAttributes")) { + throw new Error("Cannot combine importAssertions, importAttributes and moduleAttributes plugins."); + } + const moduleAttributesVersionPluginOption = getPluginOption(plugins, "moduleAttributes", "version"); + if (moduleAttributesVersionPluginOption !== "may-2020") { + throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'."); + } + } + } + if (hasPlugin(plugins, "importAssertions") && hasPlugin(plugins, "importAttributes")) { + throw new Error("Cannot combine importAssertions and importAttributes plugins."); + } + if (hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") != null && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) { + throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", ")); + } + if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) { + const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); + error.missingPlugins = "doExpressions"; + throw error; + } + if (hasPlugin(plugins, "optionalChainingAssign") && getPluginOption(plugins, "optionalChainingAssign", "version") !== "2023-07") { + throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'."); + } +} +const mixinPlugins = { + estree, + jsx, + flow, + typescript, + v8intrinsic, + placeholders +}; +const mixinPluginNames = Object.keys(mixinPlugins); +const defaultOptions = { + sourceType: "script", + sourceFilename: undefined, + startColumn: 0, + startLine: 1, + allowAwaitOutsideFunction: false, + allowReturnOutsideFunction: false, + allowNewTargetOutsideFunction: false, + allowImportExportEverywhere: false, + allowSuperOutsideMethod: false, + allowUndeclaredExports: false, + plugins: [], + strictMode: null, + ranges: false, + tokens: false, + createImportExpressions: false, + createParenthesizedExpressions: false, + errorRecovery: false, + attachComment: true, + annexB: true +}; +function getOptions(opts) { + if (opts == null) { + return Object.assign({}, defaultOptions); + } + if (opts.annexB != null && opts.annexB !== false) { + throw new Error("The `annexB` option can only be set to `false`."); + } + const options = {}; + for (const key of Object.keys(defaultOptions)) { + var _opts$key; + options[key] = (_opts$key = opts[key]) != null ? _opts$key : defaultOptions[key]; + } + return options; +} +class ExpressionParser extends LValParser { + checkProto(prop, isRecord, protoRef, refExpressionErrors) { + if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { + return; + } + const key = prop.key; + const name = key.type === "Identifier" ? key.name : key.value; + if (name === "__proto__") { + if (isRecord) { + this.raise(Errors.RecordNoProto, key); + return; + } + if (protoRef.used) { + if (refExpressionErrors) { + if (refExpressionErrors.doubleProtoLoc === null) { + refExpressionErrors.doubleProtoLoc = key.loc.start; + } + } else { + this.raise(Errors.DuplicateProto, key); + } + } + protoRef.used = true; + } + } + shouldExitDescending(expr, potentialArrowAt) { + return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt; + } + getExpression() { + this.enterInitialScopes(); + this.nextToken(); + const expr = this.parseExpression(); + if (!this.match(139)) { + this.unexpected(); + } + this.finalizeRemainingComments(); + expr.comments = this.comments; + expr.errors = this.state.errors; + if (this.options.tokens) { + expr.tokens = this.tokens; + } + return expr; + } + parseExpression(disallowIn, refExpressionErrors) { + if (disallowIn) { + return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); + } + parseExpressionBase(refExpressionErrors) { + const startLoc = this.state.startLoc; + const expr = this.parseMaybeAssign(refExpressionErrors); + if (this.match(12)) { + const node = this.startNodeAt(startLoc); + node.expressions = [expr]; + while (this.eat(12)) { + node.expressions.push(this.parseMaybeAssign(refExpressionErrors)); + } + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } + return expr; + } + parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) { + return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) { + return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); + } + setOptionalParametersError(refExpressionErrors, resultError) { + var _resultError$loc; + refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc; + } + parseMaybeAssign(refExpressionErrors, afterLeftParse) { + const startLoc = this.state.startLoc; + if (this.isContextual(108)) { + if (this.prodParam.hasYield) { + let left = this.parseYield(); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + return left; + } + } + let ownExpressionErrors; + if (refExpressionErrors) { + ownExpressionErrors = false; + } else { + refExpressionErrors = new ExpressionErrors(); + ownExpressionErrors = true; + } + const { + type + } = this.state; + if (type === 10 || tokenIsIdentifier(type)) { + this.state.potentialArrowAt = this.state.start; + } + let left = this.parseMaybeConditional(refExpressionErrors); + if (afterLeftParse) { + left = afterLeftParse.call(this, left, startLoc); + } + if (tokenIsAssignment(this.state.type)) { + const node = this.startNodeAt(startLoc); + const operator = this.state.value; + node.operator = operator; + if (this.match(29)) { + this.toAssignable(left, true); + node.left = left; + const startIndex = startLoc.index; + if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) { + refExpressionErrors.doubleProtoLoc = null; + } + if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) { + refExpressionErrors.shorthandAssignLoc = null; + } + if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) { + this.checkDestructuringPrivate(refExpressionErrors); + refExpressionErrors.privateKeyLoc = null; + } + } else { + node.left = left; + } + this.next(); + node.right = this.parseMaybeAssign(); + this.checkLVal(left, { + in: this.finishNode(node, "AssignmentExpression") + }); + return node; + } else if (ownExpressionErrors) { + this.checkExpressionErrors(refExpressionErrors, true); + } + return left; + } + parseMaybeConditional(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprOps(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseConditional(expr, startLoc, refExpressionErrors); + } + parseConditional(expr, startLoc, refExpressionErrors) { + if (this.eat(17)) { + const node = this.startNodeAt(startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssignAllowIn(); + this.expect(14); + node.alternate = this.parseMaybeAssign(); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; + } + parseMaybeUnaryOrPrivate(refExpressionErrors) { + return this.match(138) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors); + } + parseExprOps(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseExprOp(expr, startLoc, -1); + } + parseExprOp(left, leftStartLoc, minPrec) { + if (this.isPrivateName(left)) { + const value = this.getPrivateNameSV(left); + if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) { + this.raise(Errors.PrivateInExpectedIn, left, { + identifierName: value + }); + } + this.classScope.usePrivateName(value, left.loc.start); + } + const op = this.state.type; + if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) { + let prec = tokenOperatorPrecedence(op); + if (prec > minPrec) { + if (op === 39) { + this.expectPlugin("pipelineOperator"); + if (this.state.inFSharpPipelineDirectBody) { + return left; + } + this.checkPipelineAtInfixOperator(left, leftStartLoc); + } + const node = this.startNodeAt(leftStartLoc); + node.left = left; + node.operator = this.state.value; + const logical = op === 41 || op === 42; + const coalesce = op === 40; + if (coalesce) { + prec = tokenOperatorPrecedence(42); + } + this.next(); + if (op === 39 && this.hasPlugin(["pipelineOperator", { + proposal: "minimal" + }])) { + if (this.state.type === 96 && this.prodParam.hasAwait) { + throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc); + } + } + node.right = this.parseExprOpRightExpr(op, prec); + const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); + const nextOp = this.state.type; + if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) { + throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc); + } + return this.parseExprOp(finishedNode, leftStartLoc, minPrec); + } + } + return left; + } + parseExprOpRightExpr(op, prec) { + const startLoc = this.state.startLoc; + switch (op) { + case 39: + switch (this.getPluginOption("pipelineOperator", "proposal")) { + case "hack": + return this.withTopicBindingContext(() => { + return this.parseHackPipeBody(); + }); + case "smart": + return this.withTopicBindingContext(() => { + if (this.prodParam.hasYield && this.isContextual(108)) { + throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc); + } + return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc); + }); + case "fsharp": + return this.withSoloAwaitPermittingContext(() => { + return this.parseFSharpPipelineBody(prec); + }); + } + default: + return this.parseExprOpBaseRightExpr(op, prec); + } + } + parseExprOpBaseRightExpr(op, prec) { + const startLoc = this.state.startLoc; + return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec); + } + parseHackPipeBody() { + var _body$extra; + const { + startLoc + } = this.state; + const body = this.parseMaybeAssign(); + const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type); + if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) { + this.raise(Errors.PipeUnparenthesizedBody, startLoc, { + type: body.type + }); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipeTopicUnused, startLoc); + } + return body; + } + checkExponentialAfterUnary(node) { + if (this.match(57)) { + this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument); + } + } + parseMaybeUnary(refExpressionErrors, sawUnary) { + const startLoc = this.state.startLoc; + const isAwait = this.isContextual(96); + if (isAwait && this.isAwaitAllowed()) { + this.next(); + const expr = this.parseAwait(startLoc); + if (!sawUnary) this.checkExponentialAfterUnary(expr); + return expr; + } + const update = this.match(34); + const node = this.startNode(); + if (tokenIsPrefix(this.state.type)) { + node.operator = this.state.value; + node.prefix = true; + if (this.match(72)) { + this.expectPlugin("throwExpressions"); + } + const isDelete = this.match(89); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + this.checkExpressionErrors(refExpressionErrors, true); + if (this.state.strict && isDelete) { + const arg = node.argument; + if (arg.type === "Identifier") { + this.raise(Errors.StrictDelete, node); + } else if (this.hasPropertyAsPrivateName(arg)) { + this.raise(Errors.DeletePrivateField, node); + } + } + if (!update) { + if (!sawUnary) { + this.checkExponentialAfterUnary(node); + } + return this.finishNode(node, "UnaryExpression"); + } + } + const expr = this.parseUpdate(node, update, refExpressionErrors); + if (isAwait) { + const { + type + } = this.state; + const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); + if (startsExpr && !this.isAmbiguousAwait()) { + this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc); + return this.parseAwait(startLoc); + } + } + return expr; + } + parseUpdate(node, update, refExpressionErrors) { + if (update) { + const updateExpressionNode = node; + this.checkLVal(updateExpressionNode.argument, { + in: this.finishNode(updateExpressionNode, "UpdateExpression") + }); + return node; + } + const startLoc = this.state.startLoc; + let expr = this.parseExprSubscripts(refExpressionErrors); + if (this.checkExpressionErrors(refExpressionErrors, false)) return expr; + while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) { + const node = this.startNodeAt(startLoc); + node.operator = this.state.value; + node.prefix = false; + node.argument = expr; + this.next(); + this.checkLVal(expr, { + in: expr = this.finishNode(node, "UpdateExpression") + }); + } + return expr; + } + parseExprSubscripts(refExpressionErrors) { + const startLoc = this.state.startLoc; + const potentialArrowAt = this.state.potentialArrowAt; + const expr = this.parseExprAtom(refExpressionErrors); + if (this.shouldExitDescending(expr, potentialArrowAt)) { + return expr; + } + return this.parseSubscripts(expr, startLoc); + } + parseSubscripts(base, startLoc, noCalls) { + const state = { + optionalChainMember: false, + maybeAsyncArrow: this.atPossibleAsyncArrow(base), + stop: false + }; + do { + base = this.parseSubscript(base, startLoc, noCalls, state); + state.maybeAsyncArrow = false; + } while (!state.stop); + return base; + } + parseSubscript(base, startLoc, noCalls, state) { + const { + type + } = this.state; + if (!noCalls && type === 15) { + return this.parseBind(base, startLoc, noCalls, state); + } else if (tokenIsTemplate(type)) { + return this.parseTaggedTemplateExpression(base, startLoc, state); + } + let optional = false; + if (type === 18) { + if (noCalls) { + this.raise(Errors.OptionalChainingNoNew, this.state.startLoc); + if (this.lookaheadCharCode() === 40) { + state.stop = true; + return base; + } + } + state.optionalChainMember = optional = true; + this.next(); + } + if (!noCalls && this.match(10)) { + return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional); + } else { + const computed = this.eat(0); + if (computed || optional || this.eat(16)) { + return this.parseMember(base, startLoc, state, computed, optional); + } else { + state.stop = true; + return base; + } + } + } + parseMember(base, startLoc, state, computed, optional) { + const node = this.startNodeAt(startLoc); + node.object = base; + node.computed = computed; + if (computed) { + node.property = this.parseExpression(); + this.expect(3); + } else if (this.match(138)) { + if (base.type === "Super") { + this.raise(Errors.SuperPrivateField, startLoc); + } + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + if (state.optionalChainMember) { + node.optional = optional; + return this.finishNode(node, "OptionalMemberExpression"); + } else { + return this.finishNode(node, "MemberExpression"); + } + } + parseBind(base, startLoc, noCalls, state) { + const node = this.startNodeAt(startLoc); + node.object = base; + this.next(); + node.callee = this.parseNoCallExpr(); + state.stop = true; + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls); + } + parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) { + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + let refExpressionErrors = null; + this.state.maybeInArrowParameters = true; + this.next(); + const node = this.startNodeAt(startLoc); + node.callee = base; + const { + maybeAsyncArrow, + optionalChainMember + } = state; + if (maybeAsyncArrow) { + this.expressionScope.enter(newAsyncArrowScope()); + refExpressionErrors = new ExpressionErrors(); + } + if (optionalChainMember) { + node.optional = optional; + } + if (optional) { + node.arguments = this.parseCallExpressionArguments(11); + } else { + node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors); + } + let finishedNode = this.finishCallExpression(node, optionalChainMember); + if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { + state.stop = true; + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode); + } else { + if (maybeAsyncArrow) { + this.checkExpressionErrors(refExpressionErrors, true); + this.expressionScope.exit(); + } + this.toReferencedArguments(finishedNode); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return finishedNode; + } + toReferencedArguments(node, isParenthesizedExpr) { + this.toReferencedListDeep(node.arguments, isParenthesizedExpr); + } + parseTaggedTemplateExpression(base, startLoc, state) { + const node = this.startNodeAt(startLoc); + node.tag = base; + node.quasi = this.parseTemplate(true); + if (state.optionalChainMember) { + this.raise(Errors.OptionalChainingNoTemplate, startLoc); + } + return this.finishNode(node, "TaggedTemplateExpression"); + } + atPossibleAsyncArrow(base) { + return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; + } + expectImportAttributesPlugin() { + if (!this.hasPlugin("importAssertions")) { + this.expectPlugin("importAttributes"); + } + } + finishCallExpression(node, optional) { + if (node.callee.type === "Import") { + if (node.arguments.length === 2) { + { + if (!this.hasPlugin("moduleAttributes")) { + this.expectImportAttributesPlugin(); + } + } + } + if (node.arguments.length === 0 || node.arguments.length > 2) { + this.raise(Errors.ImportCallArity, node, { + maxArgumentCount: this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? 2 : 1 + }); + } else { + for (const arg of node.arguments) { + if (arg.type === "SpreadElement") { + this.raise(Errors.ImportCallSpreadArgument, arg); + } + } + } + } + return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); + } + parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) { + const elts = []; + let first = true; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + if (dynamicImport && !this.hasPlugin("importAttributes") && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) { + this.raise(Errors.ImportCallArgumentTrailingComma, this.state.lastTokStartLoc); + } + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder)); + } + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return elts; + } + shouldParseAsyncArrow() { + return this.match(19) && !this.canInsertSemicolon(); + } + parseAsyncArrowFromCallExpression(node, call) { + var _call$extra; + this.resetPreviousNodeTrailingComments(call); + this.expect(19); + this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc); + if (call.innerComments) { + setInnerComments(node, call.innerComments); + } + if (call.callee.trailingComments) { + setInnerComments(node, call.callee.trailingComments); + } + return node; + } + parseNoCallExpr() { + const startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startLoc, true); + } + parseExprAtom(refExpressionErrors) { + let node; + let decorators = null; + const { + type + } = this.state; + switch (type) { + case 79: + return this.parseSuper(); + case 83: + node = this.startNode(); + this.next(); + if (this.match(16)) { + return this.parseImportMetaProperty(node); + } + if (this.match(10)) { + if (this.options.createImportExpressions) { + return this.parseImportCall(node); + } else { + return this.finishNode(node, "Import"); + } + } else { + this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc); + return this.finishNode(node, "Import"); + } + case 78: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + case 90: + { + return this.parseDo(this.startNode(), false); + } + case 56: + case 31: + { + this.readRegexp(); + return this.parseRegExpLiteral(this.state.value); + } + case 134: + return this.parseNumericLiteral(this.state.value); + case 135: + return this.parseBigIntLiteral(this.state.value); + case 136: + return this.parseDecimalLiteral(this.state.value); + case 133: + return this.parseStringLiteral(this.state.value); + case 84: + return this.parseNullLiteral(); + case 85: + return this.parseBooleanLiteral(true); + case 86: + return this.parseBooleanLiteral(false); + case 10: + { + const canBeArrow = this.state.potentialArrowAt === this.state.start; + return this.parseParenAndDistinguishExpression(canBeArrow); + } + case 2: + case 1: + { + return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true); + } + case 0: + { + return this.parseArrayLike(3, true, false, refExpressionErrors); + } + case 6: + case 7: + { + return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true); + } + case 5: + { + return this.parseObjectLike(8, false, false, refExpressionErrors); + } + case 68: + return this.parseFunctionOrFunctionSent(); + case 26: + decorators = this.parseDecorators(); + case 80: + return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false); + case 77: + return this.parseNewOrNewTarget(); + case 25: + case 24: + return this.parseTemplate(false); + case 15: + { + node = this.startNode(); + this.next(); + node.object = null; + const callee = node.callee = this.parseNoCallExpr(); + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + throw this.raise(Errors.UnsupportedBind, callee); + } + } + case 138: + { + this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, { + identifierName: this.state.value + }); + return this.parsePrivateName(); + } + case 33: + { + return this.parseTopicReferenceThenEqualsSign(54, "%"); + } + case 32: + { + return this.parseTopicReferenceThenEqualsSign(44, "^"); + } + case 37: + case 38: + { + return this.parseTopicReference("hack"); + } + case 44: + case 54: + case 27: + { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + return this.parseTopicReference(pipeProposal); + } + this.unexpected(); + break; + } + case 47: + { + const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); + if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { + this.expectOnePlugin(["jsx", "flow", "typescript"]); + } else { + this.unexpected(); + } + break; + } + default: + if (tokenIsIdentifier(type)) { + if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) { + return this.parseModuleExpression(); + } + const canBeArrow = this.state.potentialArrowAt === this.state.start; + const containsEsc = this.state.containsEsc; + const id = this.parseIdentifier(); + if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { + const { + type + } = this.state; + if (type === 68) { + this.resetPreviousNodeTrailingComments(id); + this.next(); + return this.parseAsyncFunctionExpression(this.startNodeAtNode(id)); + } else if (tokenIsIdentifier(type)) { + if (this.lookaheadCharCode() === 61) { + return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); + } else { + return id; + } + } else if (type === 90) { + this.resetPreviousNodeTrailingComments(id); + return this.parseDo(this.startNodeAtNode(id), true); + } + } + if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) { + this.next(); + return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); + } + return id; + } else { + this.unexpected(); + } + } + } + parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) { + const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); + if (pipeProposal) { + this.state.type = topicTokenType; + this.state.value = topicTokenValue; + this.state.pos--; + this.state.end--; + this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1); + return this.parseTopicReference(pipeProposal); + } else { + this.unexpected(); + } + } + parseTopicReference(pipeProposal) { + const node = this.startNode(); + const startLoc = this.state.startLoc; + const tokenType = this.state.type; + this.next(); + return this.finishTopicReference(node, startLoc, pipeProposal, tokenType); + } + finishTopicReference(node, startLoc, pipeProposal, tokenType) { + if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) { + const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" : "TopicReference"; + if (!this.topicReferenceIsAllowedInCurrentContext()) { + this.raise(pipeProposal === "smart" ? Errors.PrimaryTopicNotAllowed : Errors.PipeTopicUnbound, startLoc); + } + this.registerTopicReference(); + return this.finishNode(node, nodeType); + } else { + throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, { + token: tokenLabelName(tokenType) + }); + } + } + testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) { + switch (pipeProposal) { + case "hack": + { + return this.hasPlugin(["pipelineOperator", { + topicToken: tokenLabelName(tokenType) + }]); + } + case "smart": + return tokenType === 27; + default: + throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc); + } + } + parseAsyncArrowUnaryFunction(node) { + this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); + const params = [this.parseIdentifier()]; + this.prodParam.exit(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition()); + } + this.expect(19); + return this.parseArrowExpression(node, params, true); + } + parseDo(node, isAsync) { + this.expectPlugin("doExpressions"); + if (isAsync) { + this.expectPlugin("asyncDoExpressions"); + } + node.async = isAsync; + this.next(); + const oldLabels = this.state.labels; + this.state.labels = []; + if (isAsync) { + this.prodParam.enter(2); + node.body = this.parseBlock(); + this.prodParam.exit(); + } else { + node.body = this.parseBlock(); + } + this.state.labels = oldLabels; + return this.finishNode(node, "DoExpression"); + } + parseSuper() { + const node = this.startNode(); + this.next(); + if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { + this.raise(Errors.SuperNotAllowed, node); + } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { + this.raise(Errors.UnexpectedSuper, node); + } + if (!this.match(10) && !this.match(0) && !this.match(16)) { + this.raise(Errors.UnsupportedSuper, node); + } + return this.finishNode(node, "Super"); + } + parsePrivateName() { + const node = this.startNode(); + const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1)); + const name = this.state.value; + this.next(); + node.id = this.createIdentifier(id, name); + return this.finishNode(node, "PrivateName"); + } + parseFunctionOrFunctionSent() { + const node = this.startNode(); + this.next(); + if (this.prodParam.hasYield && this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "function"); + this.next(); + if (this.match(103)) { + this.expectPlugin("functionSent"); + } else if (!this.hasPlugin("functionSent")) { + this.unexpected(); + } + return this.parseMetaProperty(node, meta, "sent"); + } + return this.parseFunction(node); + } + parseMetaProperty(node, meta, propertyName) { + node.meta = meta; + const containsEsc = this.state.containsEsc; + node.property = this.parseIdentifier(true); + if (node.property.name !== propertyName || containsEsc) { + this.raise(Errors.UnsupportedMetaProperty, node.property, { + target: meta.name, + onlyValidPropertyName: propertyName + }); + } + return this.finishNode(node, "MetaProperty"); + } + parseImportMetaProperty(node) { + const id = this.createIdentifier(this.startNodeAtNode(node), "import"); + this.next(); + if (this.isContextual(101)) { + if (!this.inModule) { + this.raise(Errors.ImportMetaOutsideModule, id); + } + this.sawUnambiguousESM = true; + } else if (this.isContextual(105) || this.isContextual(97)) { + const isSource = this.isContextual(105); + if (!isSource) this.unexpected(); + this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation"); + if (!this.options.createImportExpressions) { + throw this.raise(Errors.DynamicImportPhaseRequiresImportExpressions, this.state.startLoc, { + phase: this.state.value + }); + } + this.next(); + node.phase = isSource ? "source" : "defer"; + return this.parseImportCall(node); + } + return this.parseMetaProperty(node, id, "meta"); + } + parseLiteralAtNode(value, type, node) { + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(node.start, this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); + } + parseLiteral(value, type) { + const node = this.startNode(); + return this.parseLiteralAtNode(value, type, node); + } + parseStringLiteral(value) { + return this.parseLiteral(value, "StringLiteral"); + } + parseNumericLiteral(value) { + return this.parseLiteral(value, "NumericLiteral"); + } + parseBigIntLiteral(value) { + return this.parseLiteral(value, "BigIntLiteral"); + } + parseDecimalLiteral(value) { + return this.parseLiteral(value, "DecimalLiteral"); + } + parseRegExpLiteral(value) { + const node = this.parseLiteral(value.value, "RegExpLiteral"); + node.pattern = value.pattern; + node.flags = value.flags; + return node; + } + parseBooleanLiteral(value) { + const node = this.startNode(); + node.value = value; + this.next(); + return this.finishNode(node, "BooleanLiteral"); + } + parseNullLiteral() { + const node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); + } + parseParenAndDistinguishExpression(canBeArrow) { + const startLoc = this.state.startLoc; + let val; + this.next(); + this.expressionScope.enter(newArrowHeadScope()); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.maybeInArrowParameters = true; + this.state.inFSharpPipelineDirectBody = false; + const innerStartLoc = this.state.startLoc; + const exprList = []; + const refExpressionErrors = new ExpressionErrors(); + let first = true; + let spreadStartLoc; + let optionalCommaStartLoc; + while (!this.match(11)) { + if (first) { + first = false; + } else { + this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc); + if (this.match(11)) { + optionalCommaStartLoc = this.state.startLoc; + break; + } + } + if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + spreadStartLoc = this.state.startLoc; + exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc)); + if (!this.checkCommaAfterRest(41)) { + break; + } + } else { + exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem)); + } + } + const innerEndLoc = this.state.lastTokEndLoc; + this.expect(11); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let arrowNode = this.startNodeAt(startLoc); + if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) { + this.checkDestructuringPrivate(refExpressionErrors); + this.expressionScope.validateAsPattern(); + this.expressionScope.exit(); + this.parseArrowExpression(arrowNode, exprList, false); + return arrowNode; + } + this.expressionScope.exit(); + if (!exprList.length) { + this.unexpected(this.state.lastTokStartLoc); + } + if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc); + if (spreadStartLoc) this.unexpected(spreadStartLoc); + this.checkExpressionErrors(refExpressionErrors, true); + this.toReferencedListDeep(exprList, true); + if (exprList.length > 1) { + val = this.startNodeAt(innerStartLoc); + val.expressions = exprList; + this.finishNode(val, "SequenceExpression"); + this.resetEndLocation(val, innerEndLoc); + } else { + val = exprList[0]; + } + return this.wrapParenthesis(startLoc, val); + } + wrapParenthesis(startLoc, expression) { + if (!this.options.createParenthesizedExpressions) { + this.addExtra(expression, "parenthesized", true); + this.addExtra(expression, "parenStart", startLoc.index); + this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index); + return expression; + } + const parenExpression = this.startNodeAt(startLoc); + parenExpression.expression = expression; + return this.finishNode(parenExpression, "ParenthesizedExpression"); + } + shouldParseArrow(params) { + return !this.canInsertSemicolon(); + } + parseArrow(node) { + if (this.eat(19)) { + return node; + } + } + parseParenItem(node, startLoc) { + return node; + } + parseNewOrNewTarget() { + const node = this.startNode(); + this.next(); + if (this.match(16)) { + const meta = this.createIdentifier(this.startNodeAtNode(node), "new"); + this.next(); + const metaProp = this.parseMetaProperty(node, meta, "target"); + if (!this.scope.inNonArrowFunction && !this.scope.inClass && !this.options.allowNewTargetOutsideFunction) { + this.raise(Errors.UnexpectedNewTarget, metaProp); + } + return metaProp; + } + return this.parseNew(node); + } + parseNew(node) { + this.parseNewCallee(node); + if (this.eat(10)) { + const args = this.parseExprList(11); + this.toReferencedList(args); + node.arguments = args; + } else { + node.arguments = []; + } + return this.finishNode(node, "NewExpression"); + } + parseNewCallee(node) { + const isImport = this.match(83); + const callee = this.parseNoCallExpr(); + node.callee = callee; + if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) { + this.raise(Errors.ImportCallNotNewExpression, callee); + } + } + parseTemplateElement(isTagged) { + const { + start, + startLoc, + end, + value + } = this.state; + const elemStart = start + 1; + const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1)); + if (value === null) { + if (!isTagged) { + this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1)); + } + } + const isTail = this.match(24); + const endOffset = isTail ? -1 : -2; + const elemEnd = end + endOffset; + elem.value = { + raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"), + cooked: value === null ? null : value.slice(1, endOffset) + }; + elem.tail = isTail; + this.next(); + const finishedNode = this.finishNode(elem, "TemplateElement"); + this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); + return finishedNode; + } + parseTemplate(isTagged) { + const node = this.startNode(); + node.expressions = []; + let curElt = this.parseTemplateElement(isTagged); + node.quasis = [curElt]; + while (!curElt.tail) { + node.expressions.push(this.parseTemplateSubstitution()); + this.readTemplateContinuation(); + node.quasis.push(curElt = this.parseTemplateElement(isTagged)); + } + return this.finishNode(node, "TemplateLiteral"); + } + parseTemplateSubstitution() { + return this.parseExpression(); + } + parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { + if (isRecord) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const propHash = Object.create(null); + let first = true; + const node = this.startNode(); + node.properties = []; + this.next(); + while (!this.match(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + this.addTrailingCommaExtraToNode(node); + break; + } + } + let prop; + if (isPattern) { + prop = this.parseBindingProperty(); + } else { + prop = this.parsePropertyDefinition(refExpressionErrors); + this.checkProto(prop, isRecord, propHash, refExpressionErrors); + } + if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { + this.raise(Errors.InvalidRecordProperty, prop); + } + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } + node.properties.push(prop); + } + this.next(); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + let type = "ObjectExpression"; + if (isPattern) { + type = "ObjectPattern"; + } else if (isRecord) { + type = "RecordExpression"; + } + return this.finishNode(node, type); + } + addTrailingCommaExtraToNode(node) { + this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index); + this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false); + } + maybeAsyncOrAccessorProp(prop) { + return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55)); + } + parsePropertyDefinition(refExpressionErrors) { + let decorators = []; + if (this.match(26)) { + if (this.hasPlugin("decorators")) { + this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc); + } + while (this.match(26)) { + decorators.push(this.parseDecorator()); + } + } + const prop = this.startNode(); + let isAsync = false; + let isAccessor = false; + let startLoc; + if (this.match(21)) { + if (decorators.length) this.unexpected(); + return this.parseSpread(); + } + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } + prop.method = false; + if (refExpressionErrors) { + startLoc = this.state.startLoc; + } + let isGenerator = this.eat(55); + this.parsePropertyNamePrefixOperator(prop); + const containsEsc = this.state.containsEsc; + const key = this.parsePropertyName(prop, refExpressionErrors); + if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { + const keyName = key.name; + if (keyName === "async" && !this.hasPrecedingLineBreak()) { + isAsync = true; + this.resetPreviousNodeTrailingComments(key); + isGenerator = this.eat(55); + this.parsePropertyName(prop); + } + if (keyName === "get" || keyName === "set") { + isAccessor = true; + this.resetPreviousNodeTrailingComments(key); + prop.kind = keyName; + if (this.match(55)) { + isGenerator = true; + this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), { + kind: keyName + }); + this.next(); + } + this.parsePropertyName(prop); + } + } + return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors); + } + getGetterSetterExpectedParamCount(method) { + return method.kind === "get" ? 0 : 1; + } + getObjectOrClassMethodParams(method) { + return method.params; + } + checkGetterSetterParams(method) { + var _params; + const paramCount = this.getGetterSetterExpectedParamCount(method); + const params = this.getObjectOrClassMethodParams(method); + if (params.length !== paramCount) { + this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method); + } + if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { + this.raise(Errors.BadSetterRestParameter, method); + } + } + parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { + if (isAccessor) { + const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); + this.checkGetterSetterParams(finishedProp); + return finishedProp; + } + if (isAsync || isGenerator || this.match(10)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); + } + } + parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { + prop.shorthand = false; + if (this.eat(14)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors); + return this.finishNode(prop, "ObjectProperty"); + } + if (!prop.computed && prop.key.type === "Identifier") { + this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false); + if (isPattern) { + prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); + } else if (this.match(29)) { + const shorthandAssignLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.shorthandAssignLoc === null) { + refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc; + } + } else { + this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc); + } + prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); + } else { + prop.value = cloneIdentifier(prop.key); + } + prop.shorthand = true; + return this.finishNode(prop, "ObjectProperty"); + } + } + parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { + const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); + if (!node) this.unexpected(); + return node; + } + parsePropertyName(prop, refExpressionErrors) { + if (this.eat(0)) { + prop.computed = true; + prop.key = this.parseMaybeAssignAllowIn(); + this.expect(3); + } else { + const { + type, + value + } = this.state; + let key; + if (tokenIsKeywordOrIdentifier(type)) { + key = this.parseIdentifier(true); + } else { + switch (type) { + case 134: + key = this.parseNumericLiteral(value); + break; + case 133: + key = this.parseStringLiteral(value); + break; + case 135: + key = this.parseBigIntLiteral(value); + break; + case 136: + key = this.parseDecimalLiteral(value); + break; + case 138: + { + const privateKeyLoc = this.state.startLoc; + if (refExpressionErrors != null) { + if (refExpressionErrors.privateKeyLoc === null) { + refExpressionErrors.privateKeyLoc = privateKeyLoc; + } + } else { + this.raise(Errors.UnexpectedPrivateField, privateKeyLoc); + } + key = this.parsePrivateName(); + break; + } + default: + this.unexpected(); + } + } + prop.key = key; + if (type !== 138) { + prop.computed = false; + } + } + return prop.key; + } + initFunction(node, isAsync) { + node.id = null; + node.generator = false; + node.async = isAsync; + } + parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { + this.initFunction(node, isAsync); + node.generator = isGenerator; + this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0)); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + this.parseFunctionParams(node, isConstructor); + const finishedNode = this.parseFunctionBodyAndFinish(node, type, true); + this.prodParam.exit(); + this.scope.exit(); + return finishedNode; + } + parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { + if (isTuple) { + this.expectPlugin("recordAndTuple"); + } + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = false; + const node = this.startNode(); + this.next(); + node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); + } + parseArrowExpression(node, params, isAsync, trailingCommaLoc) { + this.scope.enter(2 | 4); + let flags = functionFlags(isAsync, false); + if (!this.match(5) && this.prodParam.hasIn) { + flags |= 8; + } + this.prodParam.enter(flags); + this.initFunction(node, isAsync); + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + if (params) { + this.state.maybeInArrowParameters = true; + this.setArrowFunctionParameters(node, params, trailingCommaLoc); + } + this.state.maybeInArrowParameters = false; + this.parseFunctionBody(node, true); + this.prodParam.exit(); + this.scope.exit(); + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return this.finishNode(node, "ArrowFunctionExpression"); + } + setArrowFunctionParameters(node, params, trailingCommaLoc) { + this.toAssignableList(params, trailingCommaLoc, false); + node.params = params; + } + parseFunctionBodyAndFinish(node, type, isMethod = false) { + this.parseFunctionBody(node, false, isMethod); + return this.finishNode(node, type); + } + parseFunctionBody(node, allowExpression, isMethod = false) { + const isExpression = allowExpression && !this.match(5); + this.expressionScope.enter(newExpressionScope()); + if (isExpression) { + node.body = this.parseMaybeAssign(); + this.checkParams(node, false, allowExpression, false); + } else { + const oldStrict = this.state.strict; + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(this.prodParam.currentFlags() | 4); + node.body = this.parseBlock(true, false, hasStrictModeDirective => { + const nonSimple = !this.isSimpleParamList(node.params); + if (hasStrictModeDirective && nonSimple) { + this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node); + } + const strictModeChanged = !oldStrict && this.state.strict; + this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); + if (this.state.strict && node.id) { + this.checkIdentifier(node.id, 65, strictModeChanged); + } + }); + this.prodParam.exit(); + this.state.labels = oldLabels; + } + this.expressionScope.exit(); + } + isSimpleParameter(node) { + return node.type === "Identifier"; + } + isSimpleParamList(params) { + for (let i = 0, len = params.length; i < len; i++) { + if (!this.isSimpleParameter(params[i])) return false; + } + return true; + } + checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { + const checkClashes = !allowDuplicates && new Set(); + const formalParameters = { + type: "FormalParameters" + }; + for (const param of node.params) { + this.checkLVal(param, { + in: formalParameters, + binding: 5, + checkClashes, + strictModeChanged + }); + } + } + parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { + const elts = []; + let first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.match(close)) { + if (nodeForExtra) { + this.addTrailingCommaExtraToNode(nodeForExtra); + } + this.next(); + break; + } + } + elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors)); + } + return elts; + } + parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) { + let elt; + if (this.match(12)) { + if (!allowEmpty) { + this.raise(Errors.UnexpectedToken, this.state.curPosition(), { + unexpected: "," + }); + } + elt = null; + } else if (this.match(21)) { + const spreadNodeStartLoc = this.state.startLoc; + elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc); + } else if (this.match(17)) { + this.expectPlugin("partialApplication"); + if (!allowPlaceholder) { + this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc); + } + const node = this.startNode(); + this.next(); + elt = this.finishNode(node, "ArgumentPlaceholder"); + } else { + elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem); + } + return elt; + } + parseIdentifier(liberal) { + const node = this.startNode(); + const name = this.parseIdentifierName(liberal); + return this.createIdentifier(node, name); + } + createIdentifier(node, name) { + node.name = name; + node.loc.identifierName = name; + return this.finishNode(node, "Identifier"); + } + parseIdentifierName(liberal) { + let name; + const { + startLoc, + type + } = this.state; + if (tokenIsKeywordOrIdentifier(type)) { + name = this.state.value; + } else { + this.unexpected(); + } + const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type); + if (liberal) { + if (tokenIsKeyword) { + this.replaceToken(132); + } + } else { + this.checkReservedWord(name, startLoc, tokenIsKeyword, false); + } + this.next(); + return name; + } + checkReservedWord(word, startLoc, checkKeywords, isBinding) { + if (word.length > 10) { + return; + } + if (!canBeReservedWord(word)) { + return; + } + if (checkKeywords && isKeyword(word)) { + this.raise(Errors.UnexpectedKeyword, startLoc, { + keyword: word + }); + return; + } + const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; + if (reservedTest(word, this.inModule)) { + this.raise(Errors.UnexpectedReservedWord, startLoc, { + reservedWord: word + }); + return; + } else if (word === "yield") { + if (this.prodParam.hasYield) { + this.raise(Errors.YieldBindingIdentifier, startLoc); + return; + } + } else if (word === "await") { + if (this.prodParam.hasAwait) { + this.raise(Errors.AwaitBindingIdentifier, startLoc); + return; + } + if (this.scope.inStaticBlock) { + this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc); + return; + } + this.expressionScope.recordAsyncArrowParametersError(startLoc); + } else if (word === "arguments") { + if (this.scope.inClassAndNotInNonArrowFunction) { + this.raise(Errors.ArgumentsInClass, startLoc); + return; + } + } + } + isAwaitAllowed() { + if (this.prodParam.hasAwait) return true; + if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) { + return true; + } + return false; + } + parseAwait(startLoc) { + const node = this.startNodeAt(startLoc); + this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node); + if (this.eat(55)) { + this.raise(Errors.ObsoleteAwaitStar, node); + } + if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { + if (this.isAmbiguousAwait()) { + this.ambiguousScriptDifferentAst = true; + } else { + this.sawUnambiguousESM = true; + } + } + if (!this.state.soloAwait) { + node.argument = this.parseMaybeUnary(null, true); + } + return this.finishNode(node, "AwaitExpression"); + } + isAmbiguousAwait() { + if (this.hasPrecedingLineBreak()) return true; + const { + type + } = this.state; + return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 137 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54; + } + parseYield() { + const node = this.startNode(); + this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node); + this.next(); + let delegating = false; + let argument = null; + if (!this.hasPrecedingLineBreak()) { + delegating = this.eat(55); + switch (this.state.type) { + case 13: + case 139: + case 8: + case 11: + case 3: + case 9: + case 14: + case 12: + if (!delegating) break; + default: + argument = this.parseMaybeAssign(); + } + } + node.delegate = delegating; + node.argument = argument; + return this.finishNode(node, "YieldExpression"); + } + parseImportCall(node) { + this.next(); + node.source = this.parseMaybeAssignAllowIn(); + if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { + node.options = null; + } + if (this.eat(12)) { + this.expectImportAttributesPlugin(); + if (!this.match(11)) { + node.options = this.parseMaybeAssignAllowIn(); + this.eat(12); + } + } + this.expect(11); + return this.finishNode(node, "ImportExpression"); + } + checkPipelineAtInfixOperator(left, leftStartLoc) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + if (left.type === "SequenceExpression") { + this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc); + } + } + } + parseSmartPipelineBodyInStyle(childExpr, startLoc) { + if (this.isSimpleReference(childExpr)) { + const bodyNode = this.startNodeAt(startLoc); + bodyNode.callee = childExpr; + return this.finishNode(bodyNode, "PipelineBareFunction"); + } else { + const bodyNode = this.startNodeAt(startLoc); + this.checkSmartPipeTopicBodyEarlyErrors(startLoc); + bodyNode.expression = childExpr; + return this.finishNode(bodyNode, "PipelineTopicExpression"); + } + } + isSimpleReference(expression) { + switch (expression.type) { + case "MemberExpression": + return !expression.computed && this.isSimpleReference(expression.object); + case "Identifier": + return true; + default: + return false; + } + } + checkSmartPipeTopicBodyEarlyErrors(startLoc) { + if (this.match(19)) { + throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc); + } + if (!this.topicReferenceWasUsedInCurrentContext()) { + this.raise(Errors.PipelineTopicUnused, startLoc); + } + } + withTopicBindingContext(callback) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 1, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } + withSmartMixTopicForbiddingContext(callback) { + if (this.hasPlugin(["pipelineOperator", { + proposal: "smart" + }])) { + const outerContextTopicState = this.state.topicContext; + this.state.topicContext = { + maxNumOfResolvableTopics: 0, + maxTopicIndex: null + }; + try { + return callback(); + } finally { + this.state.topicContext = outerContextTopicState; + } + } else { + return callback(); + } + } + withSoloAwaitPermittingContext(callback) { + const outerContextSoloAwaitState = this.state.soloAwait; + this.state.soloAwait = true; + try { + return callback(); + } finally { + this.state.soloAwait = outerContextSoloAwaitState; + } + } + allowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToSet = 8 & ~flags; + if (prodParamToSet) { + this.prodParam.enter(flags | 8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + disallowInAnd(callback) { + const flags = this.prodParam.currentFlags(); + const prodParamToClear = 8 & flags; + if (prodParamToClear) { + this.prodParam.enter(flags & ~8); + try { + return callback(); + } finally { + this.prodParam.exit(); + } + } + return callback(); + } + registerTopicReference() { + this.state.topicContext.maxTopicIndex = 0; + } + topicReferenceIsAllowedInCurrentContext() { + return this.state.topicContext.maxNumOfResolvableTopics >= 1; + } + topicReferenceWasUsedInCurrentContext() { + return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; + } + parseFSharpPipelineBody(prec) { + const startLoc = this.state.startLoc; + this.state.potentialArrowAt = this.state.start; + const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; + this.state.inFSharpPipelineDirectBody = true; + const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec); + this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; + return ret; + } + parseModuleExpression() { + this.expectPlugin("moduleBlocks"); + const node = this.startNode(); + this.next(); + if (!this.match(5)) { + this.unexpected(null, 5); + } + const program = this.startNodeAt(this.state.endLoc); + this.next(); + const revertScopes = this.initializeScopes(true); + this.enterInitialScopes(); + try { + node.body = this.parseProgram(program, 8, "module"); + } finally { + revertScopes(); + } + return this.finishNode(node, "ModuleExpression"); + } + parsePropertyNamePrefixOperator(prop) {} +} +const loopLabel = { + kind: 1 + }, + switchLabel = { + kind: 2 + }; +const loneSurrogate = /[\uD800-\uDFFF]/u; +const keywordRelationalOperator = /in(?:stanceof)?/y; +function babel7CompatTokens(tokens, input) { + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + const { + type + } = token; + if (typeof type === "number") { + { + if (type === 138) { + const { + loc, + start, + value, + end + } = token; + const hashEndPos = start + 1; + const hashEndLoc = createPositionWithColumnOffset(loc.start, 1); + tokens.splice(i, 1, new Token({ + type: getExportedToken(27), + value: "#", + start: start, + end: hashEndPos, + startLoc: loc.start, + endLoc: hashEndLoc + }), new Token({ + type: getExportedToken(132), + value: value, + start: hashEndPos, + end: end, + startLoc: hashEndLoc, + endLoc: loc.end + })); + i++; + continue; + } + if (tokenIsTemplate(type)) { + const { + loc, + start, + value, + end + } = token; + const backquoteEnd = start + 1; + const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1); + let startToken; + if (input.charCodeAt(start) === 96) { + startToken = new Token({ + type: getExportedToken(22), + value: "`", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } else { + startToken = new Token({ + type: getExportedToken(8), + value: "}", + start: start, + end: backquoteEnd, + startLoc: loc.start, + endLoc: backquoteEndLoc + }); + } + let templateValue, templateElementEnd, templateElementEndLoc, endToken; + if (type === 24) { + templateElementEnd = end - 1; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1); + templateValue = value === null ? null : value.slice(1, -1); + endToken = new Token({ + type: getExportedToken(22), + value: "`", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } else { + templateElementEnd = end - 2; + templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2); + templateValue = value === null ? null : value.slice(1, -2); + endToken = new Token({ + type: getExportedToken(23), + value: "${", + start: templateElementEnd, + end: end, + startLoc: templateElementEndLoc, + endLoc: loc.end + }); + } + tokens.splice(i, 1, startToken, new Token({ + type: getExportedToken(20), + value: templateValue, + start: backquoteEnd, + end: templateElementEnd, + startLoc: backquoteEndLoc, + endLoc: templateElementEndLoc + }), endToken); + i += 2; + continue; + } + } + token.type = getExportedToken(type); + } + } + return tokens; +} +class StatementParser extends ExpressionParser { + parseTopLevel(file, program) { + file.program = this.parseProgram(program); + file.comments = this.comments; + if (this.options.tokens) { + file.tokens = babel7CompatTokens(this.tokens, this.input); + } + return this.finishNode(file, "File"); + } + parseProgram(program, end = 139, sourceType = this.options.sourceType) { + program.sourceType = sourceType; + program.interpreter = this.parseInterpreterDirective(); + this.parseBlockBody(program, true, true, end); + if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) { + for (const [localName, at] of Array.from(this.scope.undefinedExports)) { + this.raise(Errors.ModuleExportUndefined, at, { + localName + }); + } + } + let finishedProgram; + if (end === 139) { + finishedProgram = this.finishNode(program, "Program"); + } else { + finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1)); + } + return finishedProgram; + } + stmtToDirective(stmt) { + const directive = stmt; + directive.type = "Directive"; + directive.value = directive.expression; + delete directive.expression; + const directiveLiteral = directive.value; + const expressionValue = directiveLiteral.value; + const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end); + const val = directiveLiteral.value = raw.slice(1, -1); + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + this.addExtra(directiveLiteral, "expressionValue", expressionValue); + directiveLiteral.type = "DirectiveLiteral"; + return directive; + } + parseInterpreterDirective() { + if (!this.match(28)) { + return null; + } + const node = this.startNode(); + node.value = this.state.value; + this.next(); + return this.finishNode(node, "InterpreterDirective"); + } + isLet() { + if (!this.isContextual(100)) { + return false; + } + return this.hasFollowingBindingAtom(); + } + chStartsBindingIdentifier(ch, pos) { + if (isIdentifierStart(ch)) { + keywordRelationalOperator.lastIndex = pos; + if (keywordRelationalOperator.test(this.input)) { + const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex); + if (!isIdentifierChar(endCh) && endCh !== 92) { + return false; + } + } + return true; + } else if (ch === 92) { + return true; + } else { + return false; + } + } + chStartsBindingPattern(ch) { + return ch === 91 || ch === 123; + } + hasFollowingBindingAtom() { + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next); + } + hasInLineFollowingBindingIdentifier() { + const next = this.nextTokenInLineStart(); + const nextCh = this.codePointAtPos(next); + return this.chStartsBindingIdentifier(nextCh, next); + } + startsUsingForOf() { + const { + type, + containsEsc + } = this.lookahead(); + if (type === 102 && !containsEsc) { + return false; + } else if (tokenIsIdentifier(type) && !this.hasFollowingLineBreak()) { + this.expectPlugin("explicitResourceManagement"); + return true; + } + } + startsAwaitUsing() { + let next = this.nextTokenInLineStart(); + if (this.isUnparsedContextual(next, "using")) { + next = this.nextTokenInLineStartSince(next + 5); + const nextCh = this.codePointAtPos(next); + if (this.chStartsBindingIdentifier(nextCh, next)) { + this.expectPlugin("explicitResourceManagement"); + return true; + } + } + return false; + } + parseModuleItem() { + return this.parseStatementLike(1 | 2 | 4 | 8); + } + parseStatementListItem() { + return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8)); + } + parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) { + let flags = 0; + if (this.options.annexB && !this.state.strict) { + flags |= 4; + if (allowLabeledFunction) { + flags |= 8; + } + } + return this.parseStatementLike(flags); + } + parseStatement() { + return this.parseStatementLike(0); + } + parseStatementLike(flags) { + let decorators = null; + if (this.match(26)) { + decorators = this.parseDecorators(true); + } + return this.parseStatementContent(flags, decorators); + } + parseStatementContent(flags, decorators) { + const starttype = this.state.type; + const node = this.startNode(); + const allowDeclaration = !!(flags & 2); + const allowFunctionDeclaration = !!(flags & 4); + const topLevel = flags & 1; + switch (starttype) { + case 60: + return this.parseBreakContinueStatement(node, true); + case 63: + return this.parseBreakContinueStatement(node, false); + case 64: + return this.parseDebuggerStatement(node); + case 90: + return this.parseDoWhileStatement(node); + case 91: + return this.parseForStatement(node); + case 68: + if (this.lookaheadCharCode() === 46) break; + if (!allowFunctionDeclaration) { + this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc); + } + return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration); + case 80: + if (!allowDeclaration) this.unexpected(); + return this.parseClass(this.maybeTakeDecorators(decorators, node), true); + case 69: + return this.parseIfStatement(node); + case 70: + return this.parseReturnStatement(node); + case 71: + return this.parseSwitchStatement(node); + case 72: + return this.parseThrowStatement(node); + case 73: + return this.parseTryStatement(node); + case 96: + if (!this.state.containsEsc && this.startsAwaitUsing()) { + if (!this.isAwaitAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, node); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, node); + } + this.next(); + return this.parseVarStatement(node, "await using"); + } + break; + case 107: + if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifier()) { + break; + } + this.expectPlugin("explicitResourceManagement"); + if (!this.scope.inModule && this.scope.inTopLevel) { + this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc); + } else if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + return this.parseVarStatement(node, "using"); + case 100: + { + if (this.state.containsEsc) { + break; + } + const next = this.nextTokenStart(); + const nextCh = this.codePointAtPos(next); + if (nextCh !== 91) { + if (!allowDeclaration && this.hasFollowingLineBreak()) break; + if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) { + break; + } + } + } + case 75: + { + if (!allowDeclaration) { + this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc); + } + } + case 74: + { + const kind = this.state.value; + return this.parseVarStatement(node, kind); + } + case 92: + return this.parseWhileStatement(node); + case 76: + return this.parseWithStatement(node); + case 5: + return this.parseBlock(); + case 13: + return this.parseEmptyStatement(node); + case 83: + { + const nextTokenCharCode = this.lookaheadCharCode(); + if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { + break; + } + } + case 82: + { + if (!this.options.allowImportExportEverywhere && !topLevel) { + this.raise(Errors.UnexpectedImportExport, this.state.startLoc); + } + this.next(); + let result; + if (starttype === 83) { + result = this.parseImport(node); + if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) { + this.sawUnambiguousESM = true; + } + } else { + result = this.parseExport(node, decorators); + if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") { + this.sawUnambiguousESM = true; + } + } + this.assertModuleNodeAllowed(result); + return result; + } + default: + { + if (this.isAsyncFunction()) { + if (!allowDeclaration) { + this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc); + } + this.next(); + return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration); + } + } + } + const maybeName = this.state.value; + const expr = this.parseExpression(); + if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) { + return this.parseLabeledStatement(node, maybeName, expr, flags); + } else { + return this.parseExpressionStatement(node, expr, decorators); + } + } + assertModuleNodeAllowed(node) { + if (!this.options.allowImportExportEverywhere && !this.inModule) { + this.raise(Errors.ImportOutsideModule, node); + } + } + decoratorsEnabledBeforeExport() { + if (this.hasPlugin("decorators-legacy")) return true; + return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false; + } + maybeTakeDecorators(maybeDecorators, classNode, exportNode) { + if (maybeDecorators) { + if (classNode.decorators && classNode.decorators.length > 0) { + if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") { + this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]); + } + classNode.decorators.unshift(...maybeDecorators); + } else { + classNode.decorators = maybeDecorators; + } + this.resetStartLocationFromNode(classNode, maybeDecorators[0]); + if (exportNode) this.resetStartLocationFromNode(exportNode, classNode); + } + return classNode; + } + canHaveLeadingDecorator() { + return this.match(80); + } + parseDecorators(allowExport) { + const decorators = []; + do { + decorators.push(this.parseDecorator()); + } while (this.match(26)); + if (this.match(82)) { + if (!allowExport) { + this.unexpected(); + } + if (!this.decoratorsEnabledBeforeExport()) { + this.raise(Errors.DecoratorExportClass, this.state.startLoc); + } + } else if (!this.canHaveLeadingDecorator()) { + throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc); + } + return decorators; + } + parseDecorator() { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + const node = this.startNode(); + this.next(); + if (this.hasPlugin("decorators")) { + const startLoc = this.state.startLoc; + let expr; + if (this.match(10)) { + const startLoc = this.state.startLoc; + this.next(); + expr = this.parseExpression(); + this.expect(11); + expr = this.wrapParenthesis(startLoc, expr); + const paramsStartLoc = this.state.startLoc; + node.expression = this.parseMaybeDecoratorArguments(expr); + if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) { + this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc); + } + } else { + expr = this.parseIdentifier(false); + while (this.eat(16)) { + const node = this.startNodeAt(startLoc); + node.object = expr; + if (this.match(138)) { + this.classScope.usePrivateName(this.state.value, this.state.startLoc); + node.property = this.parsePrivateName(); + } else { + node.property = this.parseIdentifier(true); + } + node.computed = false; + expr = this.finishNode(node, "MemberExpression"); + } + node.expression = this.parseMaybeDecoratorArguments(expr); + } + } else { + node.expression = this.parseExprSubscripts(); + } + return this.finishNode(node, "Decorator"); + } + parseMaybeDecoratorArguments(expr) { + if (this.eat(10)) { + const node = this.startNodeAtNode(expr); + node.callee = expr; + node.arguments = this.parseCallExpressionArguments(11, false); + this.toReferencedList(node.arguments); + return this.finishNode(node, "CallExpression"); + } + return expr; + } + parseBreakContinueStatement(node, isBreak) { + this.next(); + if (this.isLineTerminator()) { + node.label = null; + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } + this.verifyBreakContinue(node, isBreak); + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + } + verifyBreakContinue(node, isBreak) { + let i; + for (i = 0; i < this.state.labels.length; ++i) { + const lab = this.state.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === 1)) { + break; + } + if (node.label && isBreak) break; + } + } + if (i === this.state.labels.length) { + const type = isBreak ? "BreakStatement" : "ContinueStatement"; + this.raise(Errors.IllegalBreakContinue, node, { + type + }); + } + } + parseDebuggerStatement(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); + } + parseHeaderExpression() { + this.expect(10); + const val = this.parseExpression(); + this.expect(11); + return val; + } + parseDoWhileStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + this.expect(92); + node.test = this.parseHeaderExpression(); + this.eat(13); + return this.finishNode(node, "DoWhileStatement"); + } + parseForStatement(node) { + this.next(); + this.state.labels.push(loopLabel); + let awaitAt = null; + if (this.isAwaitAllowed() && this.eatContextual(96)) { + awaitAt = this.state.lastTokStartLoc; + } + this.scope.enter(0); + this.expect(10); + if (this.match(13)) { + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, null); + } + const startsWithLet = this.isContextual(100); + { + const startsWithAwaitUsing = this.isContextual(96) && this.startsAwaitUsing(); + const starsWithUsingDeclaration = startsWithAwaitUsing || this.isContextual(107) && this.startsUsingForOf(); + const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration; + if (this.match(74) || this.match(75) || isLetOrUsing) { + const initNode = this.startNode(); + let kind; + if (startsWithAwaitUsing) { + kind = "await using"; + if (!this.isAwaitAllowed()) { + this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc); + } + this.next(); + } else { + kind = this.state.value; + } + this.next(); + this.parseVar(initNode, true, kind); + const init = this.finishNode(initNode, "VariableDeclaration"); + const isForIn = this.match(58); + if (isForIn && starsWithUsingDeclaration) { + this.raise(Errors.ForInUsing, init); + } + if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) { + return this.parseForIn(node, init, awaitAt); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + } + const startsWithAsync = this.isContextual(95); + const refExpressionErrors = new ExpressionErrors(); + const init = this.parseExpression(true, refExpressionErrors); + const isForOf = this.isContextual(102); + if (isForOf) { + if (startsWithLet) { + this.raise(Errors.ForOfLet, init); + } + if (awaitAt === null && startsWithAsync && init.type === "Identifier") { + this.raise(Errors.ForOfAsync, init); + } + } + if (isForOf || this.match(58)) { + this.checkDestructuringPrivate(refExpressionErrors); + this.toAssignable(init, true); + const type = isForOf ? "ForOfStatement" : "ForInStatement"; + this.checkLVal(init, { + in: { + type + } + }); + return this.parseForIn(node, init, awaitAt); + } else { + this.checkExpressionErrors(refExpressionErrors, true); + } + if (awaitAt !== null) { + this.unexpected(awaitAt); + } + return this.parseFor(node, init); + } + parseFunctionStatement(node, isAsync, isHangingDeclaration) { + this.next(); + return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0)); + } + parseIfStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration(); + node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null; + return this.finishNode(node, "IfStatement"); + } + parseReturnStatement(node) { + if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) { + this.raise(Errors.IllegalReturn, this.state.startLoc); + } + this.next(); + if (this.isLineTerminator()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + return this.finishNode(node, "ReturnStatement"); + } + parseSwitchStatement(node) { + this.next(); + node.discriminant = this.parseHeaderExpression(); + const cases = node.cases = []; + this.expect(5); + this.state.labels.push(switchLabel); + this.scope.enter(0); + let cur; + for (let sawDefault; !this.match(8);) { + if (this.match(61) || this.match(65)) { + const isCase = this.match(61); + if (cur) this.finishNode(cur, "SwitchCase"); + cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { + this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc); + } + sawDefault = true; + cur.test = null; + } + this.expect(14); + } else { + if (cur) { + cur.consequent.push(this.parseStatementListItem()); + } else { + this.unexpected(); + } + } + } + this.scope.exit(); + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); + } + parseThrowStatement(node) { + this.next(); + if (this.hasPrecedingLineBreak()) { + this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc); + } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); + } + parseCatchClauseParam() { + const param = this.parseBindingAtom(); + this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0); + this.checkLVal(param, { + in: { + type: "CatchClause" + }, + binding: 9 + }); + return param; + } + parseTryStatement(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.match(62)) { + const clause = this.startNode(); + this.next(); + if (this.match(10)) { + this.expect(10); + clause.param = this.parseCatchClauseParam(); + this.expect(11); + } else { + clause.param = null; + this.scope.enter(0); + } + clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false)); + this.scope.exit(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(67) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) { + this.raise(Errors.NoCatchOrFinally, node); + } + return this.finishNode(node, "TryStatement"); + } + parseVarStatement(node, kind, allowMissingInitializer = false) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); + } + parseWhileStatement(node) { + this.next(); + node.test = this.parseHeaderExpression(); + this.state.labels.push(loopLabel); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); + } + parseWithStatement(node) { + if (this.state.strict) { + this.raise(Errors.StrictWith, this.state.startLoc); + } + this.next(); + node.object = this.parseHeaderExpression(); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + return this.finishNode(node, "WithStatement"); + } + parseEmptyStatement(node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); + } + parseLabeledStatement(node, maybeName, expr, flags) { + for (const label of this.state.labels) { + if (label.name === maybeName) { + this.raise(Errors.LabelRedeclaration, expr, { + labelName: maybeName + }); + } + } + const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null; + for (let i = this.state.labels.length - 1; i >= 0; i--) { + const label = this.state.labels[i]; + if (label.statementStart === node.start) { + label.statementStart = this.state.start; + label.kind = kind; + } else { + break; + } + } + this.state.labels.push({ + name: maybeName, + kind: kind, + statementStart: this.state.start + }); + node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement(); + this.state.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); + } + parseExpressionStatement(node, expr, decorators) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); + } + parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) { + const node = this.startNode(); + if (allowDirectives) { + this.state.strictErrors.clear(); + } + this.expect(5); + if (createNewLexicalScope) { + this.scope.enter(0); + } + this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse); + if (createNewLexicalScope) { + this.scope.exit(); + } + return this.finishNode(node, "BlockStatement"); + } + isValidDirective(stmt) { + return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; + } + parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) { + const body = node.body = []; + const directives = node.directives = []; + this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse); + } + parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { + const oldStrict = this.state.strict; + let hasStrictModeDirective = false; + let parsedNonDirective = false; + while (!this.match(end)) { + const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem(); + if (directives && !parsedNonDirective) { + if (this.isValidDirective(stmt)) { + const directive = this.stmtToDirective(stmt); + directives.push(directive); + if (!hasStrictModeDirective && directive.value.value === "use strict") { + hasStrictModeDirective = true; + this.setStrict(true); + } + continue; + } + parsedNonDirective = true; + this.state.strictErrors.clear(); + } + body.push(stmt); + } + afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective); + if (!oldStrict) { + this.setStrict(false); + } + this.next(); + } + parseFor(node, init) { + node.init = init; + this.semicolon(false); + node.test = this.match(13) ? null : this.parseExpression(); + this.semicolon(false); + node.update = this.match(11) ? null : this.parseExpression(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, "ForStatement"); + } + parseForIn(node, init, awaitAt) { + const isForIn = this.match(58); + this.next(); + if (isForIn) { + if (awaitAt !== null) this.unexpected(awaitAt); + } else { + node.await = awaitAt !== null; + } + if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { + this.raise(Errors.ForInOfLoopInitializer, init, { + type: isForIn ? "ForInStatement" : "ForOfStatement" + }); + } + if (init.type === "AssignmentPattern") { + this.raise(Errors.InvalidLhs, init, { + ancestor: { + type: "ForStatement" + } + }); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); + this.expect(11); + node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); + this.scope.exit(); + this.state.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); + } + parseVar(node, isFor, kind, allowMissingInitializer = false) { + const declarations = node.declarations = []; + node.kind = kind; + for (;;) { + const decl = this.startNode(); + this.parseVarId(decl, kind); + decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); + if (decl.init === null && !allowMissingInitializer) { + if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind: "destructuring" + }); + } else if (kind === "const" && !(this.match(58) || this.isContextual(102))) { + this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { + kind: "const" + }); + } + } + declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(12)) break; + } + return node; + } + parseVarId(decl, kind) { + const id = this.parseBindingAtom(); + this.checkLVal(id, { + in: { + type: "VariableDeclarator" + }, + binding: kind === "var" ? 5 : 8201 + }); + decl.id = id; + } + parseAsyncFunctionExpression(node) { + return this.parseFunction(node, 8); + } + parseFunction(node, flags = 0) { + const hangingDeclaration = flags & 2; + const isDeclaration = !!(flags & 1); + const requireId = isDeclaration && !(flags & 4); + const isAsync = !!(flags & 8); + this.initFunction(node, isAsync); + if (this.match(55)) { + if (hangingDeclaration) { + this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc); + } + this.next(); + node.generator = true; + } + if (isDeclaration) { + node.id = this.parseFunctionId(requireId); + } + const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; + this.state.maybeInArrowParameters = false; + this.scope.enter(2); + this.prodParam.enter(functionFlags(isAsync, node.generator)); + if (!isDeclaration) { + node.id = this.parseFunctionId(); + } + this.parseFunctionParams(node, false); + this.withSmartMixTopicForbiddingContext(() => { + this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression"); + }); + this.prodParam.exit(); + this.scope.exit(); + if (isDeclaration && !hangingDeclaration) { + this.registerFunctionStatementId(node); + } + this.state.maybeInArrowParameters = oldMaybeInArrowParameters; + return node; + } + parseFunctionId(requireId) { + return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null; + } + parseFunctionParams(node, isConstructor) { + this.expect(10); + this.expressionScope.enter(newParameterDeclarationScope()); + node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0)); + this.expressionScope.exit(); + } + registerFunctionStatementId(node) { + if (!node.id) return; + this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start); + } + parseClass(node, isStatement, optionalId) { + this.next(); + const oldStrict = this.state.strict; + this.state.strict = true; + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + node.body = this.parseClassBody(!!node.superClass, oldStrict); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); + } + isClassProperty() { + return this.match(29) || this.match(13) || this.match(8); + } + isClassMethod() { + return this.match(10); + } + isNonstaticConstructor(method) { + return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor"); + } + parseClassBody(hadSuperClass, oldStrict) { + this.classScope.enter(); + const state = { + hadConstructor: false, + hadSuperClass + }; + let decorators = []; + const classBody = this.startNode(); + classBody.body = []; + this.expect(5); + this.withSmartMixTopicForbiddingContext(() => { + while (!this.match(8)) { + if (this.eat(13)) { + if (decorators.length > 0) { + throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc); + } + continue; + } + if (this.match(26)) { + decorators.push(this.parseDecorator()); + continue; + } + const member = this.startNode(); + if (decorators.length) { + member.decorators = decorators; + this.resetStartLocationFromNode(member, decorators[0]); + decorators = []; + } + this.parseClassMember(classBody, member, state); + if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { + this.raise(Errors.DecoratorConstructor, member); + } + } + }); + this.state.strict = oldStrict; + this.next(); + if (decorators.length) { + throw this.raise(Errors.TrailingDecorator, this.state.startLoc); + } + this.classScope.exit(); + return this.finishNode(classBody, "ClassBody"); + } + parseClassMemberFromModifier(classBody, member) { + const key = this.parseIdentifier(true); + if (this.isClassMethod()) { + const method = member; + method.kind = "method"; + method.computed = false; + method.key = key; + method.static = false; + this.pushClassMethod(classBody, method, false, false, false, false); + return true; + } else if (this.isClassProperty()) { + const prop = member; + prop.computed = false; + prop.key = key; + prop.static = false; + classBody.body.push(this.parseClassProperty(prop)); + return true; + } + this.resetPreviousNodeTrailingComments(key); + return false; + } + parseClassMember(classBody, member, state) { + const isStatic = this.isContextual(106); + if (isStatic) { + if (this.parseClassMemberFromModifier(classBody, member)) { + return; + } + if (this.eat(5)) { + this.parseClassStaticBlock(classBody, member); + return; + } + } + this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); + } + parseClassMemberWithIsStatic(classBody, member, state, isStatic) { + const publicMethod = member; + const privateMethod = member; + const publicProp = member; + const privateProp = member; + const accessorProp = member; + const method = publicMethod; + const publicMember = publicMethod; + member.static = isStatic; + this.parsePropertyNamePrefixOperator(member); + if (this.eat(55)) { + method.kind = "method"; + const isPrivateName = this.match(138); + this.parseClassElementName(method); + if (isPrivateName) { + this.pushClassPrivateMethod(classBody, privateMethod, true, false); + return; + } + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsGenerator, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, true, false, false, false); + return; + } + const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc; + const isPrivate = this.match(138); + const key = this.parseClassElementName(member); + const maybeQuestionTokenStartLoc = this.state.startLoc; + this.parsePostMemberNameModifiers(publicMember); + if (this.isClassMethod()) { + method.kind = "method"; + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + return; + } + const isConstructor = this.isNonstaticConstructor(publicMethod); + let allowsDirectSuper = false; + if (isConstructor) { + publicMethod.kind = "constructor"; + if (state.hadConstructor && !this.hasPlugin("typescript")) { + this.raise(Errors.DuplicateConstructor, key); + } + if (isConstructor && this.hasPlugin("typescript") && member.override) { + this.raise(Errors.OverrideOnConstructor, key); + } + state.hadConstructor = true; + allowsDirectSuper = state.hadSuperClass; + } + this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); + } else if (this.isClassProperty()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else if (isContextual && key.name === "async" && !this.isLineTerminator()) { + this.resetPreviousNodeTrailingComments(key); + const isGenerator = this.eat(55); + if (publicMember.optional) { + this.unexpected(maybeQuestionTokenStartLoc); + } + method.kind = "method"; + const isPrivate = this.match(138); + this.parseClassElementName(method); + this.parsePostMemberNameModifiers(publicMember); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAsync, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); + } + } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(55) && this.isLineTerminator())) { + this.resetPreviousNodeTrailingComments(key); + method.kind = key.name; + const isPrivate = this.match(138); + this.parseClassElementName(publicMethod); + if (isPrivate) { + this.pushClassPrivateMethod(classBody, privateMethod, false, false); + } else { + if (this.isNonstaticConstructor(publicMethod)) { + this.raise(Errors.ConstructorIsAccessor, publicMethod.key); + } + this.pushClassMethod(classBody, publicMethod, false, false, false, false); + } + this.checkGetterSetterParams(publicMethod); + } else if (isContextual && key.name === "accessor" && !this.isLineTerminator()) { + this.expectPlugin("decoratorAutoAccessors"); + this.resetPreviousNodeTrailingComments(key); + const isPrivate = this.match(138); + this.parseClassElementName(publicProp); + this.pushClassAccessorProperty(classBody, accessorProp, isPrivate); + } else if (this.isLineTerminator()) { + if (isPrivate) { + this.pushClassPrivateProperty(classBody, privateProp); + } else { + this.pushClassProperty(classBody, publicProp); + } + } else { + this.unexpected(); + } + } + parseClassElementName(member) { + const { + type, + value + } = this.state; + if ((type === 132 || type === 133) && member.static && value === "prototype") { + this.raise(Errors.StaticPrototype, this.state.startLoc); + } + if (type === 138) { + if (value === "constructor") { + this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc); + } + const key = this.parsePrivateName(); + member.key = key; + return key; + } + return this.parsePropertyName(member); + } + parseClassStaticBlock(classBody, member) { + var _member$decorators; + this.scope.enter(64 | 128 | 16); + const oldLabels = this.state.labels; + this.state.labels = []; + this.prodParam.enter(0); + const body = member.body = []; + this.parseBlockOrModuleBlockBody(body, undefined, false, 8); + this.prodParam.exit(); + this.scope.exit(); + this.state.labels = oldLabels; + classBody.body.push(this.finishNode(member, "StaticBlock")); + if ((_member$decorators = member.decorators) != null && _member$decorators.length) { + this.raise(Errors.DecoratorStaticBlock, member); + } + } + pushClassProperty(classBody, prop) { + if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) { + this.raise(Errors.ConstructorClassField, prop.key); + } + classBody.body.push(this.parseClassProperty(prop)); + } + pushClassPrivateProperty(classBody, prop) { + const node = this.parseClassPrivateProperty(prop); + classBody.body.push(node); + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + pushClassAccessorProperty(classBody, prop, isPrivate) { + if (!isPrivate && !prop.computed) { + const key = prop.key; + if (key.name === "constructor" || key.value === "constructor") { + this.raise(Errors.ConstructorClassField, key); + } + } + const node = this.parseClassAccessorProperty(prop); + classBody.body.push(node); + if (isPrivate) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start); + } + } + pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { + classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); + } + pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { + const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true); + classBody.body.push(node); + const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0; + this.declareClassPrivateMethodInScope(node, kind); + } + declareClassPrivateMethodInScope(node, kind) { + this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start); + } + parsePostMemberNameModifiers(methodOrProp) {} + parseClassPrivateProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassPrivateProperty"); + } + parseClassProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassProperty"); + } + parseClassAccessorProperty(node) { + this.parseInitializer(node); + this.semicolon(); + return this.finishNode(node, "ClassAccessorProperty"); + } + parseInitializer(node) { + this.scope.enter(64 | 16); + this.expressionScope.enter(newExpressionScope()); + this.prodParam.enter(0); + node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null; + this.expressionScope.exit(); + this.prodParam.exit(); + this.scope.exit(); + } + parseClassId(node, isStatement, optionalId, bindingType = 8331) { + if (tokenIsIdentifier(this.state.type)) { + node.id = this.parseIdentifier(); + if (isStatement) { + this.declareNameFromIdentifier(node.id, bindingType); + } + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + throw this.raise(Errors.MissingClassName, this.state.startLoc); + } + } + } + parseClassSuper(node) { + node.superClass = this.eat(81) ? this.parseExprSubscripts() : null; + } + parseExport(node, decorators) { + const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true); + const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier); + const parseAfterDefault = !hasDefault || this.eat(12); + const hasStar = parseAfterDefault && this.eatExportStar(node); + const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); + const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12)); + const isFromRequired = hasDefault || hasStar; + if (hasStar && !hasNamespace) { + if (hasDefault) this.unexpected(); + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, true); + return this.finishNode(node, "ExportAllDeclaration"); + } + const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); + if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) { + this.unexpected(null, 5); + } + if (hasNamespace && parseAfterNamespace) { + this.unexpected(null, 98); + } + let hasDeclaration; + if (isFromRequired || hasSpecifiers) { + hasDeclaration = false; + if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.parseExportFrom(node, isFromRequired); + } else { + hasDeclaration = this.maybeParseExportDeclaration(node); + } + if (isFromRequired || hasSpecifiers || hasDeclaration) { + var _node2$declaration; + const node2 = node; + this.checkExport(node2, true, false, !!node2.source); + if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, node2.declaration, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + return this.finishNode(node2, "ExportNamedDeclaration"); + } + if (this.eat(65)) { + const node2 = node; + const decl = this.parseExportDefaultExpression(); + node2.declaration = decl; + if (decl.type === "ClassDeclaration") { + this.maybeTakeDecorators(decorators, decl, node2); + } else if (decorators) { + throw this.raise(Errors.UnsupportedDecoratorExport, node); + } + this.checkExport(node2, true, true); + return this.finishNode(node2, "ExportDefaultDeclaration"); + } + this.unexpected(null, 5); + } + eatExportStar(node) { + return this.eat(55); + } + maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) { + this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start); + const id = maybeDefaultIdentifier || this.parseIdentifier(true); + const specifier = this.startNodeAtNode(id); + specifier.exported = id; + node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; + return true; + } + return false; + } + maybeParseExportNamespaceSpecifier(node) { + if (this.isContextual(93)) { + if (!node.specifiers) node.specifiers = []; + const specifier = this.startNodeAt(this.state.lastTokStartLoc); + this.next(); + specifier.exported = this.parseModuleExportName(); + node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); + return true; + } + return false; + } + maybeParseExportNamedSpecifiers(node) { + if (this.match(5)) { + if (!node.specifiers) node.specifiers = []; + const isTypeExport = node.exportKind === "type"; + node.specifiers.push(...this.parseExportSpecifiers(isTypeExport)); + node.source = null; + node.declaration = null; + if (this.hasPlugin("importAssertions")) { + node.assertions = []; + } + return true; + } + return false; + } + maybeParseExportDeclaration(node) { + if (this.shouldParseExportDeclaration()) { + node.specifiers = []; + node.source = null; + if (this.hasPlugin("importAssertions")) { + node.assertions = []; + } + node.declaration = this.parseExportDeclaration(node); + return true; + } + return false; + } + isAsyncFunction() { + if (!this.isContextual(95)) return false; + const next = this.nextTokenInLineStart(); + return this.isUnparsedContextual(next, "function"); + } + parseExportDefaultExpression() { + const expr = this.startNode(); + if (this.match(68)) { + this.next(); + return this.parseFunction(expr, 1 | 4); + } else if (this.isAsyncFunction()) { + this.next(); + this.next(); + return this.parseFunction(expr, 1 | 4 | 8); + } + if (this.match(80)) { + return this.parseClass(expr, true, true); + } + if (this.match(26)) { + if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true); + } + if (this.match(75) || this.match(74) || this.isLet()) { + throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc); + } + const res = this.parseMaybeAssignAllowIn(); + this.semicolon(); + return res; + } + parseExportDeclaration(node) { + if (this.match(80)) { + const node = this.parseClass(this.startNode(), true, false); + return node; + } + return this.parseStatementListItem(); + } + isExportDefaultSpecifier() { + const { + type + } = this.state; + if (tokenIsIdentifier(type)) { + if (type === 95 && !this.state.containsEsc || type === 100) { + return false; + } + if ((type === 130 || type === 129) && !this.state.containsEsc) { + const { + type: nextType + } = this.lookahead(); + if (tokenIsIdentifier(nextType) && nextType !== 98 || nextType === 5) { + this.expectOnePlugin(["flow", "typescript"]); + return false; + } + } + } else if (!this.match(65)) { + return false; + } + const next = this.nextTokenStart(); + const hasFrom = this.isUnparsedContextual(next, "from"); + if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) { + return true; + } + if (this.match(65) && hasFrom) { + const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); + return nextAfterFrom === 34 || nextAfterFrom === 39; + } + return false; + } + parseExportFrom(node, expect) { + if (this.eatContextual(98)) { + node.source = this.parseImportSource(); + this.checkExport(node); + this.maybeParseImportAttributes(node); + this.checkJSONModuleImport(node); + } else if (expect) { + this.unexpected(); + } + this.semicolon(); + } + shouldParseExportDeclaration() { + const { + type + } = this.state; + if (type === 26) { + this.expectOnePlugin(["decorators", "decorators-legacy"]); + if (this.hasPlugin("decorators")) { + if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { + this.raise(Errors.DecoratorBeforeExport, this.state.startLoc); + } + return true; + } + } + return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction(); + } + checkExport(node, checkNames, isDefault, isFrom) { + if (checkNames) { + var _node$specifiers; + if (isDefault) { + this.checkDuplicateExports(node, "default"); + if (this.hasPlugin("exportDefaultFrom")) { + var _declaration$extra; + const declaration = node.declaration; + if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { + this.raise(Errors.ExportDefaultFromAsIdentifier, declaration); + } + } + } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) { + for (const specifier of node.specifiers) { + const { + exported + } = specifier; + const exportName = exported.type === "Identifier" ? exported.name : exported.value; + this.checkDuplicateExports(specifier, exportName); + if (!isFrom && specifier.local) { + const { + local + } = specifier; + if (local.type !== "Identifier") { + this.raise(Errors.ExportBindingIsString, specifier, { + localName: local.value, + exportName + }); + } else { + this.checkReservedWord(local.name, local.loc.start, true, false); + this.scope.checkLocalExport(local); + } + } + } + } else if (node.declaration) { + if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { + const id = node.declaration.id; + if (!id) throw new Error("Assertion failure"); + this.checkDuplicateExports(node, id.name); + } else if (node.declaration.type === "VariableDeclaration") { + for (const declaration of node.declaration.declarations) { + this.checkDeclaration(declaration.id); + } + } + } + } + } + checkDeclaration(node) { + if (node.type === "Identifier") { + this.checkDuplicateExports(node, node.name); + } else if (node.type === "ObjectPattern") { + for (const prop of node.properties) { + this.checkDeclaration(prop); + } + } else if (node.type === "ArrayPattern") { + for (const elem of node.elements) { + if (elem) { + this.checkDeclaration(elem); + } + } + } else if (node.type === "ObjectProperty") { + this.checkDeclaration(node.value); + } else if (node.type === "RestElement") { + this.checkDeclaration(node.argument); + } else if (node.type === "AssignmentPattern") { + this.checkDeclaration(node.left); + } + } + checkDuplicateExports(node, exportName) { + if (this.exportedIdentifiers.has(exportName)) { + if (exportName === "default") { + this.raise(Errors.DuplicateDefaultExport, node); + } else { + this.raise(Errors.DuplicateExport, node, { + exportName + }); + } + } + this.exportedIdentifiers.add(exportName); + } + parseExportSpecifiers(isInTypeExport) { + const nodes = []; + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + this.expect(12); + if (this.eat(8)) break; + } + const isMaybeTypeOnly = this.isContextual(130); + const isString = this.match(133); + const node = this.startNode(); + node.local = this.parseModuleExportName(); + nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly)); + } + return nodes; + } + parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) { + if (this.eatContextual(93)) { + node.exported = this.parseModuleExportName(); + } else if (isString) { + node.exported = cloneStringLiteral(node.local); + } else if (!node.exported) { + node.exported = cloneIdentifier(node.local); + } + return this.finishNode(node, "ExportSpecifier"); + } + parseModuleExportName() { + if (this.match(133)) { + const result = this.parseStringLiteral(this.state.value); + const surrogate = result.value.match(loneSurrogate); + if (surrogate) { + this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, { + surrogateCharCode: surrogate[0].charCodeAt(0) + }); + } + return result; + } + return this.parseIdentifier(true); + } + isJSONModuleImport(node) { + if (node.assertions != null) { + return node.assertions.some(({ + key, + value + }) => { + return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type"); + }); + } + return false; + } + checkImportReflection(node) { + const { + specifiers + } = node; + const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null; + if (node.phase === "source") { + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start); + } + } else if (node.phase === "defer") { + if (singleBindingType !== "ImportNamespaceSpecifier") { + this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start); + } + } else if (node.module) { + var _node$assertions; + if (singleBindingType !== "ImportDefaultSpecifier") { + this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start); + } + if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) { + this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start); + } + } + } + checkJSONModuleImport(node) { + if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") { + const { + specifiers + } = node; + if (specifiers != null) { + const nonDefaultNamedSpecifier = specifiers.find(specifier => { + let imported; + if (specifier.type === "ExportSpecifier") { + imported = specifier.local; + } else if (specifier.type === "ImportSpecifier") { + imported = specifier.imported; + } + if (imported !== undefined) { + return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default"; + } + }); + if (nonDefaultNamedSpecifier !== undefined) { + this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start); + } + } + } + } + isPotentialImportPhase(isExport) { + if (isExport) return false; + return this.isContextual(105) || this.isContextual(97) || this.isContextual(127); + } + applyImportPhase(node, isExport, phase, loc) { + if (isExport) { + return; + } + if (phase === "module") { + this.expectPlugin("importReflection", loc); + node.module = true; + } else if (this.hasPlugin("importReflection")) { + node.module = false; + } + if (phase === "source") { + this.expectPlugin("sourcePhaseImports", loc); + node.phase = "source"; + } else if (phase === "defer") { + this.expectPlugin("deferredImportEvaluation", loc); + node.phase = "defer"; + } else if (this.hasPlugin("sourcePhaseImports")) { + node.phase = null; + } + } + parseMaybeImportPhase(node, isExport) { + if (!this.isPotentialImportPhase(isExport)) { + this.applyImportPhase(node, isExport, null); + return null; + } + const phaseIdentifier = this.parseIdentifier(true); + const { + type + } = this.state; + const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + if (isImportPhase) { + this.resetPreviousIdentifierLeadingComments(phaseIdentifier); + this.applyImportPhase(node, isExport, phaseIdentifier.name, phaseIdentifier.loc.start); + return null; + } else { + this.applyImportPhase(node, isExport, null); + return phaseIdentifier; + } + } + isPrecedingIdImportPhase(phase) { + const { + type + } = this.state; + return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; + } + parseImport(node) { + if (this.match(133)) { + return this.parseImportSourceAndAttributes(node); + } + return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false)); + } + parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) { + node.specifiers = []; + const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier); + const parseNext = !hasDefault || this.eat(12); + const hasStar = parseNext && this.maybeParseStarImportSpecifier(node); + if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); + this.expectContextual(98); + return this.parseImportSourceAndAttributes(node); + } + parseImportSourceAndAttributes(node) { + var _node$specifiers2; + (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = []; + node.source = this.parseImportSource(); + this.maybeParseImportAttributes(node); + this.checkImportReflection(node); + this.checkJSONModuleImport(node); + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + parseImportSource() { + if (!this.match(133)) this.unexpected(); + return this.parseExprAtom(); + } + parseImportSpecifierLocal(node, specifier, type) { + specifier.local = this.parseIdentifier(); + node.specifiers.push(this.finishImportSpecifier(specifier, type)); + } + finishImportSpecifier(specifier, type, bindingType = 8201) { + this.checkLVal(specifier.local, { + in: { + type + }, + binding: bindingType + }); + return this.finishNode(specifier, type); + } + parseImportAttributes() { + this.expect(5); + const attrs = []; + const attrNames = new Set(); + do { + if (this.match(8)) { + break; + } + const node = this.startNode(); + const keyName = this.state.value; + if (attrNames.has(keyName)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, { + key: keyName + }); + } + attrNames.add(keyName); + if (this.match(133)) { + node.key = this.parseStringLiteral(keyName); + } else { + node.key = this.parseIdentifier(true); + } + this.expect(14); + if (!this.match(133)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + this.expect(8); + return attrs; + } + parseModuleAttributes() { + const attrs = []; + const attributes = new Set(); + do { + const node = this.startNode(); + node.key = this.parseIdentifier(true); + if (node.key.name !== "type") { + this.raise(Errors.ModuleAttributeDifferentFromType, node.key); + } + if (attributes.has(node.key.name)) { + this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, { + key: node.key.name + }); + } + attributes.add(node.key.name); + this.expect(14); + if (!this.match(133)) { + throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc); + } + node.value = this.parseStringLiteral(this.state.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(12)); + return attrs; + } + maybeParseImportAttributes(node) { + let attributes; + let useWith = false; + if (this.match(76)) { + if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) { + return; + } + this.next(); + { + if (this.hasPlugin("moduleAttributes")) { + attributes = this.parseModuleAttributes(); + } else { + this.expectImportAttributesPlugin(); + attributes = this.parseImportAttributes(); + } + } + useWith = true; + } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) { + if (this.hasPlugin("importAttributes")) { + if (this.getPluginOption("importAttributes", "deprecatedAssertSyntax") !== true) { + this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc); + } + this.addExtra(node, "deprecatedAssertSyntax", true); + } else { + this.expectOnePlugin(["importAttributes", "importAssertions"]); + } + this.next(); + attributes = this.parseImportAttributes(); + } else if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { + attributes = []; + } else { + if (this.hasPlugin("moduleAttributes")) { + attributes = []; + } else return; + } + if (!useWith && this.hasPlugin("importAssertions")) { + node.assertions = attributes; + } else { + node.attributes = attributes; + } + } + maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) { + if (maybeDefaultIdentifier) { + const specifier = this.startNodeAtNode(maybeDefaultIdentifier); + specifier.local = maybeDefaultIdentifier; + node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier")); + return true; + } else if (tokenIsKeywordOrIdentifier(this.state.type)) { + this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier"); + return true; + } + return false; + } + maybeParseStarImportSpecifier(node) { + if (this.match(55)) { + const specifier = this.startNode(); + this.next(); + this.expectContextual(93); + this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier"); + return true; + } + return false; + } + parseNamedImportSpecifiers(node) { + let first = true; + this.expect(5); + while (!this.eat(8)) { + if (first) { + first = false; + } else { + if (this.eat(14)) { + throw this.raise(Errors.DestructureNamedImport, this.state.startLoc); + } + this.expect(12); + if (this.eat(8)) break; + } + const specifier = this.startNode(); + const importedIsString = this.match(133); + const isMaybeTypeOnly = this.isContextual(130); + specifier.imported = this.parseModuleExportName(); + const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined); + node.specifiers.push(importSpecifier); + } + } + parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { + if (this.eatContextual(93)) { + specifier.local = this.parseIdentifier(); + } else { + const { + imported + } = specifier; + if (importedIsString) { + throw this.raise(Errors.ImportBindingIsString, specifier, { + importName: imported.value + }); + } + this.checkReservedWord(imported.name, specifier.loc.start, true, true); + if (!specifier.local) { + specifier.local = cloneIdentifier(imported); + } + } + return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType); + } + isThisParam(param) { + return param.type === "Identifier" && param.name === "this"; + } +} +let Parser$2 = class Parser extends StatementParser { + constructor(options, input) { + options = getOptions(options); + super(options, input); + this.options = options; + this.initializeScopes(); + this.plugins = pluginsMap(this.options.plugins); + this.filename = options.sourceFilename; + } + getScopeHandler() { + return ScopeHandler; + } + parse() { + this.enterInitialScopes(); + const file = this.startNode(); + const program = this.startNode(); + this.nextToken(); + file.errors = null; + this.parseTopLevel(file, program); + file.errors = this.state.errors; + file.comments.length = this.state.commentsLen; + return file; + } +}; +function pluginsMap(plugins) { + const pluginMap = new Map(); + for (const plugin of plugins) { + const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}]; + if (!pluginMap.has(name)) pluginMap.set(name, options || {}); + } + return pluginMap; +} +function parse$9(input, options) { + var _options; + if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { + options = Object.assign({}, options); + try { + options.sourceType = "module"; + const parser = getParser(options, input); + const ast = parser.parse(); + if (parser.sawUnambiguousESM) { + return ast; + } + if (parser.ambiguousScriptDifferentAst) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused) {} + } else { + ast.program.sourceType = "script"; + } + return ast; + } catch (moduleError) { + try { + options.sourceType = "script"; + return getParser(options, input).parse(); + } catch (_unused2) {} + throw moduleError; + } + } else { + return getParser(options, input).parse(); + } +} +function parseExpression(input, options) { + const parser = getParser(options, input); + if (parser.options.strictMode) { + parser.state.strict = true; + } + return parser.getExpression(); +} +function generateExportedTokenTypes(internalTokenTypes) { + const tokenTypes = {}; + for (const typeName of Object.keys(internalTokenTypes)) { + tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]); + } + return tokenTypes; +} +const tokTypes = generateExportedTokenTypes(tt); +function getParser(options, input) { + let cls = Parser$2; + if (options != null && options.plugins) { + validatePlugins(options.plugins); + cls = getParserClass(options.plugins); + } + return new cls(options, input); +} +const parserClassCache = {}; +function getParserClass(pluginsFromOptions) { + const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name)); + const key = pluginList.join("/"); + let cls = parserClassCache[key]; + if (!cls) { + cls = Parser$2; + for (const plugin of pluginList) { + cls = mixinPlugins[plugin](cls); + } + parserClassCache[key] = cls; + } + return cls; +} +var parse_1$1 = lib.parse = parse$9; +var parseExpression_1 = lib.parseExpression = parseExpression; +lib.tokTypes = tokTypes; + +// @ts-check +/** @typedef { import('estree').BaseNode} BaseNode */ + +/** @typedef {{ + skip: () => void; + remove: () => void; + replace: (node: BaseNode) => void; +}} WalkerContext */ + +class WalkerBase { + constructor() { + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {BaseNode | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + * @param {BaseNode} node + */ + replace(parent, prop, index, node) { + if (parent) { + if (index !== null) { + parent[prop][index] = node; + } else { + parent[prop] = node; + } + } + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + */ + remove(parent, prop, index) { + if (parent) { + if (index !== null) { + parent[prop].splice(index, 1); + } else { + delete parent[prop]; + } + } + } +} + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./walker.js').WalkerContext} WalkerContext */ + +/** @typedef {( + * this: WalkerContext, + * node: BaseNode, + * parent: BaseNode, + * key: string, + * index: number + * ) => void} SyncHandler */ + +class SyncWalker extends WalkerBase { + /** + * + * @param {SyncHandler} enter + * @param {SyncHandler} leave + */ + constructor(enter, leave) { + super(); + + /** @type {SyncHandler} */ + this.enter = enter; + + /** @type {SyncHandler} */ + this.leave = leave; + } + + /** + * + * @param {BaseNode} node + * @param {BaseNode} parent + * @param {string} [prop] + * @param {number} [index] + * @returns {BaseNode} + */ + visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + for (const key in node) { + const value = node[key]; + + if (typeof value !== "object") { + continue; + } else if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + if (value[i] !== null && typeof value[i].type === 'string') { + if (!this.visit(value[i], node, key, i)) { + // removed + i--; + } + } + } + } else if (value !== null && typeof value.type === "string") { + this.visit(value, node, key, null); + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +} + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./sync.js').SyncHandler} SyncHandler */ +/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ + +/** + * + * @param {BaseNode} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {BaseNode} + */ +function walk$2(ast, { enter, leave }) { + const instance = new SyncWalker(enter, leave); + return instance.visit(ast, null); +} + +function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = /* @__PURE__ */ Object.create(null)) { + const rootExp = root.type === "Program" ? root.body[0].type === "ExpressionStatement" && root.body[0].expression : root; + walk$2(root, { + enter(node, parent) { + parent && parentStack.push(parent); + if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) { + return this.skip(); + } + if (node.type === "Identifier") { + const isLocal = !!knownIds[node.name]; + const isRefed = isReferencedIdentifier(node, parent, parentStack); + if (includeAll || isRefed && !isLocal) { + onIdentifier(node, parent, parentStack, isRefed, isLocal); + } + } else if (node.type === "ObjectProperty" && (parent == null ? void 0 : parent.type) === "ObjectPattern") { + node.inPattern = true; + } else if (isFunctionType(node)) { + if (node.scopeIds) { + node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); + } else { + walkFunctionParams( + node, + (id) => markScopeIdentifier(node, id, knownIds) + ); + } + } else if (node.type === "BlockStatement") { + if (node.scopeIds) { + node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); + } else { + walkBlockDeclarations( + node, + (id) => markScopeIdentifier(node, id, knownIds) + ); + } + } + }, + leave(node, parent) { + parent && parentStack.pop(); + if (node !== rootExp && node.scopeIds) { + for (const id of node.scopeIds) { + knownIds[id]--; + if (knownIds[id] === 0) { + delete knownIds[id]; + } + } + } + } + }); +} +function isReferencedIdentifier(id, parent, parentStack) { + if (!parent) { + return true; + } + if (id.name === "arguments") { + return false; + } + if (isReferenced(id, parent)) { + return true; + } + switch (parent.type) { + case "AssignmentExpression": + case "AssignmentPattern": + return true; + case "ObjectPattern": + case "ArrayPattern": + return isInDestructureAssignment(parent, parentStack); + } + return false; +} +function isInDestructureAssignment(parent, parentStack) { + if (parent && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) { + let i = parentStack.length; + while (i--) { + const p = parentStack[i]; + if (p.type === "AssignmentExpression") { + return true; + } else if (p.type !== "ObjectProperty" && !p.type.endsWith("Pattern")) { + break; + } + } + } + return false; +} +function isInNewExpression(parentStack) { + let i = parentStack.length; + while (i--) { + const p = parentStack[i]; + if (p.type === "NewExpression") { + return true; + } else if (p.type !== "MemberExpression") { + break; + } + } + return false; +} +function walkFunctionParams(node, onIdent) { + for (const p of node.params) { + for (const id of extractIdentifiers$1(p)) { + onIdent(id); + } + } +} +function walkBlockDeclarations(block, onIdent) { + for (const stmt of block.body) { + if (stmt.type === "VariableDeclaration") { + if (stmt.declare) + continue; + for (const decl of stmt.declarations) { + for (const id of extractIdentifiers$1(decl.id)) { + onIdent(id); + } + } + } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") { + if (stmt.declare || !stmt.id) + continue; + onIdent(stmt.id); + } else if (stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement") { + const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left; + if (variable && variable.type === "VariableDeclaration") { + for (const decl of variable.declarations) { + for (const id of extractIdentifiers$1(decl.id)) { + onIdent(id); + } + } + } + } + } +} +function extractIdentifiers$1(param, nodes = []) { + switch (param.type) { + case "Identifier": + nodes.push(param); + break; + case "MemberExpression": + let object = param; + while (object.type === "MemberExpression") { + object = object.object; + } + nodes.push(object); + break; + case "ObjectPattern": + for (const prop of param.properties) { + if (prop.type === "RestElement") { + extractIdentifiers$1(prop.argument, nodes); + } else { + extractIdentifiers$1(prop.value, nodes); + } + } + break; + case "ArrayPattern": + param.elements.forEach((element) => { + if (element) + extractIdentifiers$1(element, nodes); + }); + break; + case "RestElement": + extractIdentifiers$1(param.argument, nodes); + break; + case "AssignmentPattern": + extractIdentifiers$1(param.left, nodes); + break; + } + return nodes; +} +function markKnownIds(name, knownIds) { + if (name in knownIds) { + knownIds[name]++; + } else { + knownIds[name] = 1; + } +} +function markScopeIdentifier(node, child, knownIds) { + const { name } = child; + if (node.scopeIds && node.scopeIds.has(name)) { + return; + } + markKnownIds(name, knownIds); + (node.scopeIds || (node.scopeIds = /* @__PURE__ */ new Set())).add(name); +} +const isFunctionType = (node) => { + return /Function(?:Expression|Declaration)$|Method$/.test(node.type); +}; +const isStaticProperty = (node) => node && (node.type === "ObjectProperty" || node.type === "ObjectMethod") && !node.computed; +const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node; +function isReferenced(node, parent, grandparent) { + switch (parent.type) { + case "MemberExpression": + case "OptionalMemberExpression": + if (parent.property === node) { + return !!parent.computed; + } + return parent.object === node; + case "JSXMemberExpression": + return parent.object === node; + case "VariableDeclarator": + return parent.init === node; + case "ArrowFunctionExpression": + return parent.body === node; + case "PrivateName": + return false; + case "ClassMethod": + case "ClassPrivateMethod": + case "ObjectMethod": + if (parent.key === node) { + return !!parent.computed; + } + return false; + case "ObjectProperty": + if (parent.key === node) { + return !!parent.computed; + } + return !grandparent || grandparent.type !== "ObjectPattern"; + case "ClassProperty": + if (parent.key === node) { + return !!parent.computed; + } + return true; + case "ClassPrivateProperty": + return parent.key !== node; + case "ClassDeclaration": + case "ClassExpression": + return parent.superClass === node; + case "AssignmentExpression": + return parent.right === node; + case "AssignmentPattern": + return parent.right === node; + case "LabeledStatement": + return false; + case "CatchClause": + return false; + case "RestElement": + return false; + case "BreakStatement": + case "ContinueStatement": + return false; + case "FunctionDeclaration": + case "FunctionExpression": + return false; + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + return false; + case "ExportSpecifier": + if (grandparent == null ? void 0 : grandparent.source) { + return false; + } + return parent.local === node; + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + return false; + case "ImportAttribute": + return false; + case "JSXAttribute": + return false; + case "ObjectPattern": + case "ArrayPattern": + return false; + case "MetaProperty": + return false; + case "ObjectTypeProperty": + return parent.key !== node; + case "TSEnumMember": + return parent.id !== node; + case "TSPropertySignature": + if (parent.key === node) { + return !!parent.computed; + } + return true; + } + return true; +} +const TS_NODE_TYPES = [ + "TSAsExpression", + // foo as number + "TSTypeAssertion", + // (<number>foo) + "TSNonNullExpression", + // foo! + "TSInstantiationExpression", + // foo<string> + "TSSatisfiesExpression" + // foo satisfies T +]; +function unwrapTSNode(node) { + if (TS_NODE_TYPES.includes(node.type)) { + return unwrapTSNode(node.expression); + } else { + return node; + } +} + +const isStaticExp = (p) => p.type === 4 && p.isStatic; +function isCoreComponent(tag) { + switch (tag) { + case "Teleport": + case "teleport": + return TELEPORT; + case "Suspense": + case "suspense": + return SUSPENSE; + case "KeepAlive": + case "keep-alive": + return KEEP_ALIVE; + case "BaseTransition": + case "base-transition": + return BASE_TRANSITION; + } +} +const nonIdentifierRE = /^\d|[^\$\w]/; +const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name); +const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/; +const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/; +const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g; +const isMemberExpressionBrowser = (path) => { + path = path.trim().replace(whitespaceRE, (s) => s.trim()); + let state = 0 /* inMemberExp */; + let stateStack = []; + let currentOpenBracketCount = 0; + let currentOpenParensCount = 0; + let currentStringType = null; + for (let i = 0; i < path.length; i++) { + const char = path.charAt(i); + switch (state) { + case 0 /* inMemberExp */: + if (char === "[") { + stateStack.push(state); + state = 1 /* inBrackets */; + currentOpenBracketCount++; + } else if (char === "(") { + stateStack.push(state); + state = 2 /* inParens */; + currentOpenParensCount++; + } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) { + return false; + } + break; + case 1 /* inBrackets */: + if (char === `'` || char === `"` || char === "`") { + stateStack.push(state); + state = 3 /* inString */; + currentStringType = char; + } else if (char === `[`) { + currentOpenBracketCount++; + } else if (char === `]`) { + if (!--currentOpenBracketCount) { + state = stateStack.pop(); + } + } + break; + case 2 /* inParens */: + if (char === `'` || char === `"` || char === "`") { + stateStack.push(state); + state = 3 /* inString */; + currentStringType = char; + } else if (char === `(`) { + currentOpenParensCount++; + } else if (char === `)`) { + if (i === path.length - 1) { + return false; + } + if (!--currentOpenParensCount) { + state = stateStack.pop(); + } + } + break; + case 3 /* inString */: + if (char === currentStringType) { + state = stateStack.pop(); + currentStringType = null; + } + break; + } + } + return !currentOpenBracketCount && !currentOpenParensCount; +}; +const isMemberExpressionNode = (path, context) => { + try { + let ret = parseExpression_1(path, { + plugins: context.expressionPlugins + }); + ret = unwrapTSNode(ret); + return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier" && ret.name !== "undefined"; + } catch (e) { + return false; + } +}; +const isMemberExpression = isMemberExpressionNode; +function advancePositionWithClone(pos, source, numberOfCharacters = source.length) { + return advancePositionWithMutation( + { + offset: pos.offset, + line: pos.line, + column: pos.column + }, + source, + numberOfCharacters + ); +} +function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) { + let linesCount = 0; + let lastNewLinePos = -1; + for (let i = 0; i < numberOfCharacters; i++) { + if (source.charCodeAt(i) === 10) { + linesCount++; + lastNewLinePos = i; + } + } + pos.offset += numberOfCharacters; + pos.line += linesCount; + pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos; + return pos; +} +function assert(condition, msg) { + if (!condition) { + throw new Error(msg || `unexpected compiler condition`); + } +} +function findDir(node, name, allowEmpty = false) { + for (let i = 0; i < node.props.length; i++) { + const p = node.props[i]; + if (p.type === 7 && (allowEmpty || p.exp) && (isString$2(name) ? p.name === name : name.test(p.name))) { + return p; + } + } +} +function findProp(node, name, dynamicOnly = false, allowEmpty = false) { + for (let i = 0; i < node.props.length; i++) { + const p = node.props[i]; + if (p.type === 6) { + if (dynamicOnly) + continue; + if (p.name === name && (p.value || allowEmpty)) { + return p; + } + } else if (p.name === "bind" && (p.exp || allowEmpty) && isStaticArgOf(p.arg, name)) { + return p; + } + } +} +function isStaticArgOf(arg, name) { + return !!(arg && isStaticExp(arg) && arg.content === name); +} +function hasDynamicKeyVBind(node) { + return node.props.some( + (p) => p.type === 7 && p.name === "bind" && (!p.arg || // v-bind="obj" + p.arg.type !== 4 || // v-bind:[_ctx.foo] + !p.arg.isStatic) + // v-bind:[foo] + ); +} +function isText$1(node) { + return node.type === 5 || node.type === 2; +} +function isVSlot(p) { + return p.type === 7 && p.name === "slot"; +} +function isTemplateNode(node) { + return node.type === 1 && node.tagType === 3; +} +function isSlotOutlet(node) { + return node.type === 1 && node.tagType === 2; +} +const propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]); +function getUnnormalizedProps(props, callPath = []) { + if (props && !isString$2(props) && props.type === 14) { + const callee = props.callee; + if (!isString$2(callee) && propsHelperSet.has(callee)) { + return getUnnormalizedProps( + props.arguments[0], + callPath.concat(props) + ); + } + } + return [props, callPath]; +} +function injectProp(node, prop, context) { + let propsWithInjection; + let props = node.type === 13 ? node.props : node.arguments[2]; + let callPath = []; + let parentCall; + if (props && !isString$2(props) && props.type === 14) { + const ret = getUnnormalizedProps(props); + props = ret[0]; + callPath = ret[1]; + parentCall = callPath[callPath.length - 1]; + } + if (props == null || isString$2(props)) { + propsWithInjection = createObjectExpression([prop]); + } else if (props.type === 14) { + const first = props.arguments[0]; + if (!isString$2(first) && first.type === 15) { + if (!hasProp(prop, first)) { + first.properties.unshift(prop); + } + } else { + if (props.callee === TO_HANDLERS) { + propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [ + createObjectExpression([prop]), + props + ]); + } else { + props.arguments.unshift(createObjectExpression([prop])); + } + } + !propsWithInjection && (propsWithInjection = props); + } else if (props.type === 15) { + if (!hasProp(prop, props)) { + props.properties.unshift(prop); + } + propsWithInjection = props; + } else { + propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [ + createObjectExpression([prop]), + props + ]); + if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) { + parentCall = callPath[callPath.length - 2]; + } + } + if (node.type === 13) { + if (parentCall) { + parentCall.arguments[0] = propsWithInjection; + } else { + node.props = propsWithInjection; + } + } else { + if (parentCall) { + parentCall.arguments[0] = propsWithInjection; + } else { + node.arguments[2] = propsWithInjection; + } + } +} +function hasProp(prop, props) { + let result = false; + if (prop.key.type === 4) { + const propKeyName = prop.key.content; + result = props.properties.some( + (p) => p.key.type === 4 && p.key.content === propKeyName + ); + } + return result; +} +function toValidAssetId(name, type) { + return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => { + return searchValue === "-" ? "_" : name.charCodeAt(replaceValue).toString(); + })}`; +} +function hasScopeRef(node, ids) { + if (!node || Object.keys(ids).length === 0) { + return false; + } + switch (node.type) { + case 1: + for (let i = 0; i < node.props.length; i++) { + const p = node.props[i]; + if (p.type === 7 && (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) { + return true; + } + } + return node.children.some((c) => hasScopeRef(c, ids)); + case 11: + if (hasScopeRef(node.source, ids)) { + return true; + } + return node.children.some((c) => hasScopeRef(c, ids)); + case 9: + return node.branches.some((b) => hasScopeRef(b, ids)); + case 10: + if (hasScopeRef(node.condition, ids)) { + return true; + } + return node.children.some((c) => hasScopeRef(c, ids)); + case 4: + return !node.isStatic && isSimpleIdentifier(node.content) && !!ids[node.content]; + case 8: + return node.children.some((c) => isObject$2(c) && hasScopeRef(c, ids)); + case 5: + case 12: + return hasScopeRef(node.content, ids); + case 2: + case 3: + return false; + default: + return false; + } +} +function getMemoedVNodeCall(node) { + if (node.type === 14 && node.callee === WITH_MEMO) { + return node.arguments[1].returns; + } else { + return node; + } +} +const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; + +const defaultParserOptions = { + parseMode: "base", + ns: 0, + delimiters: [`{{`, `}}`], + getNamespace: () => 0, + isVoidTag: NO, + isPreTag: NO, + isCustomElement: NO, + onError: defaultOnError, + onWarn: defaultOnWarn, + comments: true, + prefixIdentifiers: false +}; +let currentOptions = defaultParserOptions; +let currentRoot = null; +let currentInput = ""; +let currentOpenTag = null; +let currentProp = null; +let currentAttrValue = ""; +let currentAttrStartIndex = -1; +let currentAttrEndIndex = -1; +let inPre = 0; +let inVPre = false; +let currentVPreBoundary = null; +const stack = []; +const tokenizer$2 = new Tokenizer$1(stack, { + onerr: emitError, + ontext(start, end) { + onText(getSlice(start, end), start, end); + }, + ontextentity(char, start, end) { + onText(char, start, end); + }, + oninterpolation(start, end) { + if (inVPre) { + return onText(getSlice(start, end), start, end); + } + let innerStart = start + tokenizer$2.delimiterOpen.length; + let innerEnd = end - tokenizer$2.delimiterClose.length; + while (isWhitespace$1(currentInput.charCodeAt(innerStart))) { + innerStart++; + } + while (isWhitespace$1(currentInput.charCodeAt(innerEnd - 1))) { + innerEnd--; + } + let exp = getSlice(innerStart, innerEnd); + if (exp.includes("&")) { + { + exp = decodeHTML(exp); + } + } + addNode({ + type: 5, + content: createExp(exp, false, getLoc(innerStart, innerEnd)), + loc: getLoc(start, end) + }); + }, + onopentagname(start, end) { + const name = getSlice(start, end); + currentOpenTag = { + type: 1, + tag: name, + ns: currentOptions.getNamespace(name, stack[0], currentOptions.ns), + tagType: 0, + // will be refined on tag close + props: [], + children: [], + loc: getLoc(start - 1, end), + codegenNode: void 0 + }; + }, + onopentagend(end) { + endOpenTag(end); + }, + onclosetag(start, end) { + const name = getSlice(start, end); + if (!currentOptions.isVoidTag(name)) { + let found = false; + for (let i = 0; i < stack.length; i++) { + const e = stack[i]; + if (e.tag.toLowerCase() === name.toLowerCase()) { + found = true; + if (i > 0) { + emitError(24, stack[0].loc.start.offset); + } + for (let j = 0; j <= i; j++) { + const el = stack.shift(); + onCloseTag(el, end, j < i); + } + break; + } + } + if (!found) { + emitError(23, backTrack(start, 60)); + } + } + }, + onselfclosingtag(end) { + var _a; + const name = currentOpenTag.tag; + currentOpenTag.isSelfClosing = true; + endOpenTag(end); + if (((_a = stack[0]) == null ? void 0 : _a.tag) === name) { + onCloseTag(stack.shift(), end); + } + }, + onattribname(start, end) { + currentProp = { + type: 6, + name: getSlice(start, end), + nameLoc: getLoc(start, end), + value: void 0, + loc: getLoc(start) + }; + }, + ondirname(start, end) { + const raw = getSlice(start, end); + const name = raw === "." || raw === ":" ? "bind" : raw === "@" ? "on" : raw === "#" ? "slot" : raw.slice(2); + if (!inVPre && name === "") { + emitError(26, start); + } + if (inVPre || name === "") { + currentProp = { + type: 6, + name: raw, + nameLoc: getLoc(start, end), + value: void 0, + loc: getLoc(start) + }; + } else { + currentProp = { + type: 7, + name, + rawName: raw, + exp: void 0, + arg: void 0, + modifiers: raw === "." ? ["prop"] : [], + loc: getLoc(start) + }; + if (name === "pre") { + inVPre = tokenizer$2.inVPre = true; + currentVPreBoundary = currentOpenTag; + const props = currentOpenTag.props; + for (let i = 0; i < props.length; i++) { + if (props[i].type === 7) { + props[i] = dirToAttr(props[i]); + } + } + } + } + }, + ondirarg(start, end) { + if (start === end) + return; + const arg = getSlice(start, end); + if (inVPre) { + currentProp.name += arg; + setLocEnd(currentProp.nameLoc, end); + } else { + const isStatic = arg[0] !== `[`; + currentProp.arg = createExp( + isStatic ? arg : arg.slice(1, -1), + isStatic, + getLoc(start, end), + isStatic ? 3 : 0 + ); + } + }, + ondirmodifier(start, end) { + const mod = getSlice(start, end); + if (inVPre) { + currentProp.name += "." + mod; + setLocEnd(currentProp.nameLoc, end); + } else if (currentProp.name === "slot") { + const arg = currentProp.arg; + if (arg) { + arg.content += "." + mod; + setLocEnd(arg.loc, end); + } + } else { + currentProp.modifiers.push(mod); + } + }, + onattribdata(start, end) { + currentAttrValue += getSlice(start, end); + if (currentAttrStartIndex < 0) + currentAttrStartIndex = start; + currentAttrEndIndex = end; + }, + onattribentity(char, start, end) { + currentAttrValue += char; + if (currentAttrStartIndex < 0) + currentAttrStartIndex = start; + currentAttrEndIndex = end; + }, + onattribnameend(end) { + const start = currentProp.loc.start.offset; + const name = getSlice(start, end); + if (currentProp.type === 7) { + currentProp.rawName = name; + } + if (currentOpenTag.props.some( + (p) => (p.type === 7 ? p.rawName : p.name) === name + )) { + emitError(2, start); + } + }, + onattribend(quote, end) { + if (currentOpenTag && currentProp) { + setLocEnd(currentProp.loc, end); + if (quote !== 0) { + if (currentProp.type === 6) { + if (currentProp.name === "class") { + currentAttrValue = condense(currentAttrValue).trim(); + } + if (quote === 1 && !currentAttrValue) { + emitError(13, end); + } + currentProp.value = { + type: 2, + content: currentAttrValue, + loc: quote === 1 ? getLoc(currentAttrStartIndex, currentAttrEndIndex) : getLoc(currentAttrStartIndex - 1, currentAttrEndIndex + 1) + }; + if (tokenizer$2.inSFCRoot && currentOpenTag.tag === "template" && currentProp.name === "lang" && currentAttrValue && currentAttrValue !== "html") { + tokenizer$2.enterRCDATA(toCharCodes(`</template`), 0); + } + } else { + let expParseMode = 0 /* Normal */; + { + if (currentProp.name === "for") { + expParseMode = 3 /* Skip */; + } else if (currentProp.name === "slot") { + expParseMode = 1 /* Params */; + } else if (currentProp.name === "on" && currentAttrValue.includes(";")) { + expParseMode = 2 /* Statements */; + } + } + currentProp.exp = createExp( + currentAttrValue, + false, + getLoc(currentAttrStartIndex, currentAttrEndIndex), + 0, + expParseMode + ); + if (currentProp.name === "for") { + currentProp.forParseResult = parseForExpression(currentProp.exp); + } + } + } + if (currentProp.type !== 7 || currentProp.name !== "pre") { + currentOpenTag.props.push(currentProp); + } + } + currentAttrValue = ""; + currentAttrStartIndex = currentAttrEndIndex = -1; + }, + oncomment(start, end) { + if (currentOptions.comments) { + addNode({ + type: 3, + content: getSlice(start, end), + loc: getLoc(start - 4, end + 3) + }); + } + }, + onend() { + const end = currentInput.length; + if (tokenizer$2.state !== 1) { + switch (tokenizer$2.state) { + case 5: + case 8: + emitError(5, end); + break; + case 3: + case 4: + emitError( + 25, + tokenizer$2.sectionStart + ); + break; + case 28: + if (tokenizer$2.currentSequence === Sequences.CdataEnd) { + emitError(6, end); + } else { + emitError(7, end); + } + break; + case 6: + case 7: + case 9: + case 11: + case 12: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + case 19: + case 20: + case 21: + emitError(9, end); + break; + } + } + for (let index = 0; index < stack.length; index++) { + onCloseTag(stack[index], end - 1); + emitError(24, stack[index].loc.start.offset); + } + }, + oncdata(start, end) { + if (stack[0].ns !== 0) { + onText(getSlice(start, end), start, end); + } else { + emitError(1, start - 9); + } + }, + onprocessinginstruction(start) { + if ((stack[0] ? stack[0].ns : currentOptions.ns) === 0) { + emitError( + 21, + start - 1 + ); + } + } +}); +const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; +const stripParensRE = /^\(|\)$/g; +function parseForExpression(input) { + const loc = input.loc; + const exp = input.content; + const inMatch = exp.match(forAliasRE); + if (!inMatch) + return; + const [, LHS, RHS] = inMatch; + const createAliasExpression = (content, offset, asParam = false) => { + const start = loc.start.offset + offset; + const end = start + content.length; + return createExp( + content, + false, + getLoc(start, end), + 0, + asParam ? 1 /* Params */ : 0 /* Normal */ + ); + }; + const result = { + source: createAliasExpression(RHS.trim(), exp.indexOf(RHS, LHS.length)), + value: void 0, + key: void 0, + index: void 0, + finalized: false + }; + let valueContent = LHS.trim().replace(stripParensRE, "").trim(); + const trimmedOffset = LHS.indexOf(valueContent); + const iteratorMatch = valueContent.match(forIteratorRE); + if (iteratorMatch) { + valueContent = valueContent.replace(forIteratorRE, "").trim(); + const keyContent = iteratorMatch[1].trim(); + let keyOffset; + if (keyContent) { + keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length); + result.key = createAliasExpression(keyContent, keyOffset, true); + } + if (iteratorMatch[2]) { + const indexContent = iteratorMatch[2].trim(); + if (indexContent) { + result.index = createAliasExpression( + indexContent, + exp.indexOf( + indexContent, + result.key ? keyOffset + keyContent.length : trimmedOffset + valueContent.length + ), + true + ); + } + } + } + if (valueContent) { + result.value = createAliasExpression(valueContent, trimmedOffset, true); + } + return result; +} +function getSlice(start, end) { + return currentInput.slice(start, end); +} +function endOpenTag(end) { + if (tokenizer$2.inSFCRoot) { + currentOpenTag.innerLoc = getLoc(end + 1, end + 1); + } + addNode(currentOpenTag); + const { tag, ns } = currentOpenTag; + if (ns === 0 && currentOptions.isPreTag(tag)) { + inPre++; + } + if (currentOptions.isVoidTag(tag)) { + onCloseTag(currentOpenTag, end); + } else { + stack.unshift(currentOpenTag); + if (ns === 1 || ns === 2) { + tokenizer$2.inXML = true; + } + } + currentOpenTag = null; +} +function onText(content, start, end) { + const parent = stack[0] || currentRoot; + const lastNode = parent.children[parent.children.length - 1]; + if ((lastNode == null ? void 0 : lastNode.type) === 2) { + lastNode.content += content; + setLocEnd(lastNode.loc, end); + } else { + parent.children.push({ + type: 2, + content, + loc: getLoc(start, end) + }); + } +} +function onCloseTag(el, end, isImplied = false) { + if (isImplied) { + setLocEnd(el.loc, backTrack(end, 60)); + } else { + setLocEnd(el.loc, end + 1); + } + if (tokenizer$2.inSFCRoot) { + if (el.children.length) { + el.innerLoc.end = extend({}, el.children[el.children.length - 1].loc.end); + } else { + el.innerLoc.end = extend({}, el.innerLoc.start); + } + el.innerLoc.source = getSlice( + el.innerLoc.start.offset, + el.innerLoc.end.offset + ); + } + const { tag, ns } = el; + if (!inVPre) { + if (tag === "slot") { + el.tagType = 2; + } else if (isFragmentTemplate(el)) { + el.tagType = 3; + } else if (isComponent(el)) { + el.tagType = 1; + } + } + if (!tokenizer$2.inRCDATA) { + el.children = condenseWhitespace(el.children, el.tag); + } + if (ns === 0 && currentOptions.isPreTag(tag)) { + inPre--; + } + if (currentVPreBoundary === el) { + inVPre = tokenizer$2.inVPre = false; + currentVPreBoundary = null; + } + if (tokenizer$2.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) { + tokenizer$2.inXML = false; + } +} +function backTrack(index, c) { + let i = index; + while (currentInput.charCodeAt(i) !== c && i >= 0) + i--; + return i; +} +const specialTemplateDir = /* @__PURE__ */ new Set(["if", "else", "else-if", "for", "slot"]); +function isFragmentTemplate({ tag, props }) { + if (tag === "template") { + for (let i = 0; i < props.length; i++) { + if (props[i].type === 7 && specialTemplateDir.has(props[i].name)) { + return true; + } + } + } + return false; +} +function isComponent({ tag, props }) { + var _a; + if (currentOptions.isCustomElement(tag)) { + return false; + } + if (tag === "component" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || ((_a = currentOptions.isBuiltInComponent) == null ? void 0 : _a.call(currentOptions, tag)) || currentOptions.isNativeTag && !currentOptions.isNativeTag(tag)) { + return true; + } + for (let i = 0; i < props.length; i++) { + const p = props[i]; + if (p.type === 6) { + if (p.name === "is" && p.value) { + if (p.value.content.startsWith("vue:")) { + return true; + } + } + } + } + return false; +} +function isUpperCase(c) { + return c > 64 && c < 91; +} +const windowsNewlineRE = /\r\n/g; +function condenseWhitespace(nodes, tag) { + var _a, _b; + const shouldCondense = currentOptions.whitespace !== "preserve"; + let removedWhitespace = false; + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (node.type === 2) { + if (!inPre) { + if (isAllWhitespace(node.content)) { + const prev = (_a = nodes[i - 1]) == null ? void 0 : _a.type; + const next = (_b = nodes[i + 1]) == null ? void 0 : _b.type; + if (!prev || !next || shouldCondense && (prev === 3 && (next === 3 || next === 1) || prev === 1 && (next === 3 || next === 1 && hasNewlineChar(node.content)))) { + removedWhitespace = true; + nodes[i] = null; + } else { + node.content = " "; + } + } else if (shouldCondense) { + node.content = condense(node.content); + } + } else { + node.content = node.content.replace(windowsNewlineRE, "\n"); + } + } + } + if (inPre && tag && currentOptions.isPreTag(tag)) { + const first = nodes[0]; + if (first && first.type === 2) { + first.content = first.content.replace(/^\r?\n/, ""); + } + } + return removedWhitespace ? nodes.filter(Boolean) : nodes; +} +function isAllWhitespace(str) { + for (let i = 0; i < str.length; i++) { + if (!isWhitespace$1(str.charCodeAt(i))) { + return false; + } + } + return true; +} +function hasNewlineChar(str) { + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + if (c === 10 || c === 13) { + return true; + } + } + return false; +} +function condense(str) { + let ret = ""; + let prevCharIsWhitespace = false; + for (let i = 0; i < str.length; i++) { + if (isWhitespace$1(str.charCodeAt(i))) { + if (!prevCharIsWhitespace) { + ret += " "; + prevCharIsWhitespace = true; + } + } else { + ret += str[i]; + prevCharIsWhitespace = false; + } + } + return ret; +} +function addNode(node) { + (stack[0] || currentRoot).children.push(node); +} +function getLoc(start, end) { + return { + start: tokenizer$2.getPos(start), + // @ts-expect-error allow late attachment + end: end == null ? end : tokenizer$2.getPos(end), + // @ts-expect-error allow late attachment + source: end == null ? end : getSlice(start, end) + }; +} +function setLocEnd(loc, end) { + loc.end = tokenizer$2.getPos(end); + loc.source = getSlice(loc.start.offset, end); +} +function dirToAttr(dir) { + const attr = { + type: 6, + name: dir.rawName, + nameLoc: getLoc( + dir.loc.start.offset, + dir.loc.start.offset + dir.rawName.length + ), + value: void 0, + loc: dir.loc + }; + if (dir.exp) { + const loc = dir.exp.loc; + if (loc.end.offset < dir.loc.end.offset) { + loc.start.offset--; + loc.start.column--; + loc.end.offset++; + loc.end.column++; + } + attr.value = { + type: 2, + content: dir.exp.content, + loc + }; + } + return attr; +} +function createExp(content, isStatic = false, loc, constType = 0, parseMode = 0 /* Normal */) { + const exp = createSimpleExpression(content, isStatic, loc, constType); + if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 /* Skip */ && content.trim()) { + if (isSimpleIdentifier(content)) { + exp.ast = null; + return exp; + } + try { + const plugins = currentOptions.expressionPlugins; + const options = { + plugins: plugins ? [...plugins, "typescript"] : ["typescript"] + }; + if (parseMode === 2 /* Statements */) { + exp.ast = parse_1$1(` ${content} `, options).program; + } else if (parseMode === 1 /* Params */) { + exp.ast = parseExpression_1(`(${content})=>{}`, options); + } else { + exp.ast = parseExpression_1(`(${content})`, options); + } + } catch (e) { + exp.ast = false; + emitError(45, loc.start.offset, e.message); + } + } + return exp; +} +function emitError(code, index, message) { + currentOptions.onError( + createCompilerError(code, getLoc(index, index), void 0, message) + ); +} +function reset() { + tokenizer$2.reset(); + currentOpenTag = null; + currentProp = null; + currentAttrValue = ""; + currentAttrStartIndex = -1; + currentAttrEndIndex = -1; + stack.length = 0; +} +function baseParse(input, options) { + reset(); + currentInput = input; + currentOptions = extend({}, defaultParserOptions); + if (options) { + let key; + for (key in options) { + if (options[key] != null) { + currentOptions[key] = options[key]; + } + } + } + { + if (currentOptions.decodeEntities) { + console.warn( + `[@vue/compiler-core] decodeEntities option is passed but will be ignored in non-browser builds.` + ); + } + } + tokenizer$2.mode = currentOptions.parseMode === "html" ? 1 : currentOptions.parseMode === "sfc" ? 2 : 0; + tokenizer$2.inXML = currentOptions.ns === 1 || currentOptions.ns === 2; + const delimiters = options == null ? void 0 : options.delimiters; + if (delimiters) { + tokenizer$2.delimiterOpen = toCharCodes(delimiters[0]); + tokenizer$2.delimiterClose = toCharCodes(delimiters[1]); + } + const root = currentRoot = createRoot([], input); + tokenizer$2.parse(currentInput); + root.loc = getLoc(0, input.length); + root.children = condenseWhitespace(root.children); + currentRoot = null; + return root; +} + +function hoistStatic(root, context) { + walk$1( + root, + context, + // Root node is unfortunately non-hoistable due to potential parent + // fallthrough attributes. + isSingleElementRoot(root, root.children[0]) + ); +} +function isSingleElementRoot(root, child) { + const { children } = root; + return children.length === 1 && child.type === 1 && !isSlotOutlet(child); +} +function walk$1(node, context, doNotHoistNode = false) { + const { children } = node; + const originalCount = children.length; + let hoistedCount = 0; + for (let i = 0; i < children.length; i++) { + const child = children[i]; + if (child.type === 1 && child.tagType === 0) { + const constantType = doNotHoistNode ? 0 : getConstantType(child, context); + if (constantType > 0) { + if (constantType >= 2) { + child.codegenNode.patchFlag = -1 + (` /* HOISTED */` ); + child.codegenNode = context.hoist(child.codegenNode); + hoistedCount++; + continue; + } + } else { + const codegenNode = child.codegenNode; + if (codegenNode.type === 13) { + const flag = getPatchFlag(codegenNode); + if ((!flag || flag === 512 || flag === 1) && getGeneratedPropsConstantType(child, context) >= 2) { + const props = getNodeProps(child); + if (props) { + codegenNode.props = context.hoist(props); + } + } + if (codegenNode.dynamicProps) { + codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps); + } + } + } + } + if (child.type === 1) { + const isComponent = child.tagType === 1; + if (isComponent) { + context.scopes.vSlot++; + } + walk$1(child, context); + if (isComponent) { + context.scopes.vSlot--; + } + } else if (child.type === 11) { + walk$1(child, context, child.children.length === 1); + } else if (child.type === 9) { + for (let i2 = 0; i2 < child.branches.length; i2++) { + walk$1( + child.branches[i2], + context, + child.branches[i2].children.length === 1 + ); + } + } + } + if (hoistedCount && context.transformHoist) { + context.transformHoist(children, context, node); + } + if (hoistedCount && hoistedCount === originalCount && node.type === 1 && node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && isArray$3(node.codegenNode.children)) { + const hoisted = context.hoist( + createArrayExpression(node.codegenNode.children) + ); + if (context.hmr) { + hoisted.content = `[...${hoisted.content}]`; + } + node.codegenNode.children = hoisted; + } +} +function getConstantType(node, context) { + const { constantCache } = context; + switch (node.type) { + case 1: + if (node.tagType !== 0) { + return 0; + } + const cached = constantCache.get(node); + if (cached !== void 0) { + return cached; + } + const codegenNode = node.codegenNode; + if (codegenNode.type !== 13) { + return 0; + } + if (codegenNode.isBlock && node.tag !== "svg" && node.tag !== "foreignObject") { + return 0; + } + const flag = getPatchFlag(codegenNode); + if (!flag) { + let returnType2 = 3; + const generatedPropsType = getGeneratedPropsConstantType(node, context); + if (generatedPropsType === 0) { + constantCache.set(node, 0); + return 0; + } + if (generatedPropsType < returnType2) { + returnType2 = generatedPropsType; + } + for (let i = 0; i < node.children.length; i++) { + const childType = getConstantType(node.children[i], context); + if (childType === 0) { + constantCache.set(node, 0); + return 0; + } + if (childType < returnType2) { + returnType2 = childType; + } + } + if (returnType2 > 1) { + for (let i = 0; i < node.props.length; i++) { + const p = node.props[i]; + if (p.type === 7 && p.name === "bind" && p.exp) { + const expType = getConstantType(p.exp, context); + if (expType === 0) { + constantCache.set(node, 0); + return 0; + } + if (expType < returnType2) { + returnType2 = expType; + } + } + } + } + if (codegenNode.isBlock) { + for (let i = 0; i < node.props.length; i++) { + const p = node.props[i]; + if (p.type === 7) { + constantCache.set(node, 0); + return 0; + } + } + context.removeHelper(OPEN_BLOCK); + context.removeHelper( + getVNodeBlockHelper(context.inSSR, codegenNode.isComponent) + ); + codegenNode.isBlock = false; + context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent)); + } + constantCache.set(node, returnType2); + return returnType2; + } else { + constantCache.set(node, 0); + return 0; + } + case 2: + case 3: + return 3; + case 9: + case 11: + case 10: + return 0; + case 5: + case 12: + return getConstantType(node.content, context); + case 4: + return node.constType; + case 8: + let returnType = 3; + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + if (isString$2(child) || isSymbol$1(child)) { + continue; + } + const childType = getConstantType(child, context); + if (childType === 0) { + return 0; + } else if (childType < returnType) { + returnType = childType; + } + } + return returnType; + default: + return 0; + } +} +const allowHoistedHelperSet = /* @__PURE__ */ new Set([ + NORMALIZE_CLASS, + NORMALIZE_STYLE, + NORMALIZE_PROPS, + GUARD_REACTIVE_PROPS +]); +function getConstantTypeOfHelperCall(value, context) { + if (value.type === 14 && !isString$2(value.callee) && allowHoistedHelperSet.has(value.callee)) { + const arg = value.arguments[0]; + if (arg.type === 4) { + return getConstantType(arg, context); + } else if (arg.type === 14) { + return getConstantTypeOfHelperCall(arg, context); + } + } + return 0; +} +function getGeneratedPropsConstantType(node, context) { + let returnType = 3; + const props = getNodeProps(node); + if (props && props.type === 15) { + const { properties } = props; + for (let i = 0; i < properties.length; i++) { + const { key, value } = properties[i]; + const keyType = getConstantType(key, context); + if (keyType === 0) { + return keyType; + } + if (keyType < returnType) { + returnType = keyType; + } + let valueType; + if (value.type === 4) { + valueType = getConstantType(value, context); + } else if (value.type === 14) { + valueType = getConstantTypeOfHelperCall(value, context); + } else { + valueType = 0; + } + if (valueType === 0) { + return valueType; + } + if (valueType < returnType) { + returnType = valueType; + } + } + } + return returnType; +} +function getNodeProps(node) { + const codegenNode = node.codegenNode; + if (codegenNode.type === 13) { + return codegenNode.props; + } +} +function getPatchFlag(node) { + const flag = node.patchFlag; + return flag ? parseInt(flag, 10) : void 0; +} + +function createTransformContext(root, { + filename = "", + prefixIdentifiers = false, + hoistStatic: hoistStatic2 = false, + hmr = false, + cacheHandlers = false, + nodeTransforms = [], + directiveTransforms = {}, + transformHoist = null, + isBuiltInComponent = NOOP, + isCustomElement = NOOP, + expressionPlugins = [], + scopeId = null, + slotted = true, + ssr = false, + inSSR = false, + ssrCssVars = ``, + bindingMetadata = EMPTY_OBJ, + inline = false, + isTS = false, + onError = defaultOnError, + onWarn = defaultOnWarn, + compatConfig +}) { + const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/); + const context = { + // options + filename, + selfName: nameMatch && capitalize$1(camelize(nameMatch[1])), + prefixIdentifiers, + hoistStatic: hoistStatic2, + hmr, + cacheHandlers, + nodeTransforms, + directiveTransforms, + transformHoist, + isBuiltInComponent, + isCustomElement, + expressionPlugins, + scopeId, + slotted, + ssr, + inSSR, + ssrCssVars, + bindingMetadata, + inline, + isTS, + onError, + onWarn, + compatConfig, + // state + root, + helpers: /* @__PURE__ */ new Map(), + components: /* @__PURE__ */ new Set(), + directives: /* @__PURE__ */ new Set(), + hoists: [], + imports: [], + constantCache: /* @__PURE__ */ new WeakMap(), + temps: 0, + cached: 0, + identifiers: /* @__PURE__ */ Object.create(null), + scopes: { + vFor: 0, + vSlot: 0, + vPre: 0, + vOnce: 0 + }, + parent: null, + currentNode: root, + childIndex: 0, + inVOnce: false, + // methods + helper(name) { + const count = context.helpers.get(name) || 0; + context.helpers.set(name, count + 1); + return name; + }, + removeHelper(name) { + const count = context.helpers.get(name); + if (count) { + const currentCount = count - 1; + if (!currentCount) { + context.helpers.delete(name); + } else { + context.helpers.set(name, currentCount); + } + } + }, + helperString(name) { + return `_${helperNameMap[context.helper(name)]}`; + }, + replaceNode(node) { + { + if (!context.currentNode) { + throw new Error(`Node being replaced is already removed.`); + } + if (!context.parent) { + throw new Error(`Cannot replace root node.`); + } + } + context.parent.children[context.childIndex] = context.currentNode = node; + }, + removeNode(node) { + if (!context.parent) { + throw new Error(`Cannot remove root node.`); + } + const list = context.parent.children; + const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1; + if (removalIndex < 0) { + throw new Error(`node being removed is not a child of current parent`); + } + if (!node || node === context.currentNode) { + context.currentNode = null; + context.onNodeRemoved(); + } else { + if (context.childIndex > removalIndex) { + context.childIndex--; + context.onNodeRemoved(); + } + } + context.parent.children.splice(removalIndex, 1); + }, + onNodeRemoved: NOOP, + addIdentifiers(exp) { + { + if (isString$2(exp)) { + addId(exp); + } else if (exp.identifiers) { + exp.identifiers.forEach(addId); + } else if (exp.type === 4) { + addId(exp.content); + } + } + }, + removeIdentifiers(exp) { + { + if (isString$2(exp)) { + removeId(exp); + } else if (exp.identifiers) { + exp.identifiers.forEach(removeId); + } else if (exp.type === 4) { + removeId(exp.content); + } + } + }, + hoist(exp) { + if (isString$2(exp)) + exp = createSimpleExpression(exp); + context.hoists.push(exp); + const identifier = createSimpleExpression( + `_hoisted_${context.hoists.length}`, + false, + exp.loc, + 2 + ); + identifier.hoisted = exp; + return identifier; + }, + cache(exp, isVNode = false) { + return createCacheExpression(context.cached++, exp, isVNode); + } + }; + function addId(id) { + const { identifiers } = context; + if (identifiers[id] === void 0) { + identifiers[id] = 0; + } + identifiers[id]++; + } + function removeId(id) { + context.identifiers[id]--; + } + return context; +} +function transform(root, options) { + const context = createTransformContext(root, options); + traverseNode(root, context); + if (options.hoistStatic) { + hoistStatic(root, context); + } + if (!options.ssr) { + createRootCodegen(root, context); + } + root.helpers = /* @__PURE__ */ new Set([...context.helpers.keys()]); + root.components = [...context.components]; + root.directives = [...context.directives]; + root.imports = context.imports; + root.hoists = context.hoists; + root.temps = context.temps; + root.cached = context.cached; + root.transformed = true; +} +function createRootCodegen(root, context) { + const { helper } = context; + const { children } = root; + if (children.length === 1) { + const child = children[0]; + if (isSingleElementRoot(root, child) && child.codegenNode) { + const codegenNode = child.codegenNode; + if (codegenNode.type === 13) { + convertToBlock(codegenNode, context); + } + root.codegenNode = codegenNode; + } else { + root.codegenNode = child; + } + } else if (children.length > 1) { + let patchFlag = 64; + let patchFlagText = PatchFlagNames[64]; + if (children.filter((c) => c.type !== 3).length === 1) { + patchFlag |= 2048; + patchFlagText += `, ${PatchFlagNames[2048]}`; + } + root.codegenNode = createVNodeCall( + context, + helper(FRAGMENT), + void 0, + root.children, + patchFlag + (` /* ${patchFlagText} */` ), + void 0, + void 0, + true, + void 0, + false + ); + } else ; +} +function traverseChildren(parent, context) { + let i = 0; + const nodeRemoved = () => { + i--; + }; + for (; i < parent.children.length; i++) { + const child = parent.children[i]; + if (isString$2(child)) + continue; + context.parent = parent; + context.childIndex = i; + context.onNodeRemoved = nodeRemoved; + traverseNode(child, context); + } +} +function traverseNode(node, context) { + context.currentNode = node; + const { nodeTransforms } = context; + const exitFns = []; + for (let i2 = 0; i2 < nodeTransforms.length; i2++) { + const onExit = nodeTransforms[i2](node, context); + if (onExit) { + if (isArray$3(onExit)) { + exitFns.push(...onExit); + } else { + exitFns.push(onExit); + } + } + if (!context.currentNode) { + return; + } else { + node = context.currentNode; + } + } + switch (node.type) { + case 3: + if (!context.ssr) { + context.helper(CREATE_COMMENT); + } + break; + case 5: + if (!context.ssr) { + context.helper(TO_DISPLAY_STRING); + } + break; + case 9: + for (let i2 = 0; i2 < node.branches.length; i2++) { + traverseNode(node.branches[i2], context); + } + break; + case 10: + case 11: + case 1: + case 0: + traverseChildren(node, context); + break; + } + context.currentNode = node; + let i = exitFns.length; + while (i--) { + exitFns[i](); + } +} +function createStructuralDirectiveTransform(name, fn) { + const matches = isString$2(name) ? (n) => n === name : (n) => name.test(n); + return (node, context) => { + if (node.type === 1) { + const { props } = node; + if (node.tagType === 3 && props.some(isVSlot)) { + return; + } + const exitFns = []; + for (let i = 0; i < props.length; i++) { + const prop = props[i]; + if (prop.type === 7 && matches(prop.name)) { + props.splice(i, 1); + i--; + const onExit = fn(node, prop, context); + if (onExit) + exitFns.push(onExit); + } + } + return exitFns; + } + }; +} + +var sourceMap$2 = {}; + +var sourceMapGenerator$1 = {}; + +var base64Vlq$1 = {}; + +var base64$3 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +base64$3.encode = function (number) { + if (0 <= number && number < intToCharMap$1.length) { + return intToCharMap$1[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +base64$3.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64$2 = base64$3; + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT$1 = 5; + +// binary: 100000 +var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1; + +// binary: 011111 +var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned$1(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned$1(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +base64Vlq$1.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned$1(aValue); + + do { + digit = vlq & VLQ_BASE_MASK$1; + vlq >>>= VLQ_BASE_SHIFT$1; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT$1; + } + encoded += base64$2.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64$2.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT$1); + digit &= VLQ_BASE_MASK$1; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT$1; + } while (continuation); + + aOutParam.value = fromVLQSigned$1(result); + aOutParam.rest = aIndex; +}; + +var util$c = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + var MAX_CACHED_INPUTS = 32; + + /** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ + function lruMemoize(f) { + var cache = []; + + return function(input) { + for (var i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + var temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + var result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; + } + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '<dir>/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + var normalize = lruMemoize(function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + var parts = []; + var start = 0; + var i = 0; + while (true) { + start = i; + i = path.indexOf("/", start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === "/") { + i++; + } + } + } + + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + }); + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { + var cmp; + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; +} (util$c)); + +var arraySet$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$b = util$c; +var has$1 = Object.prototype.hasOwnProperty; +var hasNativeMap$1 = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet$5() { + this._array = []; + this._set = hasNativeMap$1 ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet$5.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet$5(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet$5.prototype.size = function ArraySet_size() { + return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet$5.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap$1 ? aStr : util$b.toSetString(aStr); + var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$1.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap$1) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet$5.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap$1) { + return this._set.has(aStr); + } else { + var sStr = util$b.toSetString(aStr); + return has$1.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet$5.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap$1) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util$b.toSetString(aStr); + if (has$1.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet$5.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet$5.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +arraySet$1.ArraySet = ArraySet$5; + +var mappingList$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$a = util$c; + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter$1(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util$a.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList$3() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList$3.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList$3.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter$1(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList$3.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util$a.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +mappingList$1.MappingList = MappingList$3; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ$3 = base64Vlq$1; +var util$9 = util$c; +var ArraySet$4 = arraySet$1.ArraySet; +var MappingList$2 = mappingList$1.MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator$8(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util$9.getArg(aArgs, 'file', null); + this._sourceRoot = util$9.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util$9.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet$4(); + this._names = new ArraySet$4(); + this._mappings = new MappingList$2(); + this._sourcesContents = null; +} + +SourceMapGenerator$8.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator$8.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator$8({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util$9.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util$9.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator$8.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util$9.getArg(aArgs, 'generated'); + var original = util$9.getArg(aArgs, 'original', null); + var source = util$9.getArg(aArgs, 'source', null); + var name = util$9.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator$8.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util$9.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util$9.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util$9.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator$8.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util$9.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet$4(); + var newNames = new ArraySet$4(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util$9.join(aSourceMapPath, mapping.source); + } + if (sourceRoot != null) { + mapping.source = util$9.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util$9.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util$9.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator$8.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator$8.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = ''; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util$9.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ$3.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ$3.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ$3.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ$3.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ$3.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator$8.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util$9.relative(aSourceRoot, source); + } + var key = util$9.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator$8.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator$8.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator$8; + +var sourceMapConsumer$1 = {}; + +var binarySearch$3 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; +} (binarySearch$3)); + +var quickSort$3 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +function SortTemplate(comparator) { + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + + return doQuickSort; +} + +function cloneSort(comparator) { + let template = SortTemplate.toString(); + let templateFn = new Function(`return ${template}`)(); + return templateFn(comparator); +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + +let sortCache = new WeakMap(); +quickSort$3.quickSort = function (ary, comparator, start = 0) { + let doQuickSort = sortCache.get(comparator); + if (doQuickSort === void 0) { + doQuickSort = cloneSort(comparator); + sortCache.set(comparator, doQuickSort); + } + doQuickSort(ary, comparator, start, ary.length - 1); +}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$8 = util$c; +var binarySearch$2 = binarySearch$3; +var ArraySet$3 = arraySet$1.ArraySet; +var base64VLQ$2 = base64Vlq$1; +var quickSort$2 = quickSort$3.quickSort; + +function SourceMapConsumer$6(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$8.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL); +} + +SourceMapConsumer$6.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL); +}; + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer$6.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer$6.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer$6.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer$6.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer$6.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer$6.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer$6.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer$6.GENERATED_ORDER = 1; +SourceMapConsumer$6.ORIGINAL_ORDER = 2; + +SourceMapConsumer$6.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer$6.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer$6.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer$6.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer$6.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer$6.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + var boundCallback = aCallback.bind(context); + var names = this._names; + var sources = this._sources; + var sourceMapURL = this._sourceMapURL; + + for (var i = 0, n = mappings.length; i < n; i++) { + var mapping = mappings[i]; + var source = mapping.source === null ? null : sources.at(mapping.source); + source = util$8.computeSourceURL(sourceRoot, source, sourceMapURL); + boundCallback({ + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : names.at(mapping.name) + }); + } + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer$6.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util$8.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util$8.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util$8.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$8.compareByOriginalPositions, + binarySearch$2.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util$8.getArg(mapping, 'generatedLine', null), + column: util$8.getArg(mapping, 'generatedColumn', null), + lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util$8.getArg(mapping, 'generatedLine', null), + column: util$8.getArg(mapping, 'generatedColumn', null), + lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer$6; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer$1(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$8.parseSourceMapInput(aSourceMap); + } + + var version = util$8.getArg(sourceMap, 'version'); + var sources = util$8.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util$8.getArg(sourceMap, 'names', []); + var sourceRoot = util$8.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util$8.getArg(sourceMap, 'sourcesContent', null); + var mappings = util$8.getArg(sourceMap, 'mappings'); + var file = util$8.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util$8.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util$8.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util$8.isAbsolute(sourceRoot) && util$8.isAbsolute(source) + ? util$8.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet$3.fromArray(names.map(String), true); + this._sources = ArraySet$3.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util$8.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype); +BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$6; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer$1.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$8.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer$1.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer$1.prototype); + + var names = smc._names = ArraySet$3.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet$3.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util$8.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping$1; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort$2(smc.__originalMappings, util$8.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer$1.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer$1.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping$1() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + +const compareGenerated = util$8.compareByGeneratedPositionsDeflatedNoLine; +function sortGenerated(array, start) { + let l = array.length; + let n = array.length - start; + if (n <= 1) { + return; + } else if (n == 2) { + let a = array[start]; + let b = array[start + 1]; + if (compareGenerated(a, b) > 0) { + array[start] = b; + array[start + 1] = a; + } + } else if (n < 20) { + for (let i = start; i < l; i++) { + for (let j = i; j > start; j--) { + let a = array[j - 1]; + let b = array[j]; + if (compareGenerated(a, b) <= 0) { + break; + } + array[j - 1] = b; + array[j] = a; + } + } + } else { + quickSort$2(array, compareGenerated, start); + } +} +BasicSourceMapConsumer$1.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, segment, end, value; + + let subarrayStart = 0; + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + + sortGenerated(generatedMappings, subarrayStart); + subarrayStart = generatedMappings.length; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping$1(); + mapping.generatedLine = generatedLine; + + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + aStr.slice(index, end); + + segment = []; + while (index < end) { + base64VLQ$2.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + let currentSource = mapping.source; + while (originalMappings.length <= currentSource) { + originalMappings.push(null); + } + if (originalMappings[currentSource] === null) { + originalMappings[currentSource] = []; + } + originalMappings[currentSource].push(mapping); + } + } + } + + sortGenerated(generatedMappings, subarrayStart); + this.__generatedMappings = generatedMappings; + + for (var i = 0; i < originalMappings.length; i++) { + if (originalMappings[i] != null) { + quickSort$2(originalMappings[i], util$8.compareByOriginalPositionsNoSource); + } + } + this.__originalMappings = [].concat(...originalMappings); + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer$1.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch$2.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer$1.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer$1.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$8.getArg(aArgs, 'line'), + generatedColumn: util$8.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util$8.compareByGeneratedPositionsDeflated, + util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util$8.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util$8.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util$8.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util$8.getArg(mapping, 'originalLine', null), + column: util$8.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer$1.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer$1.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$8.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util$8.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer$1.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util$8.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util$8.getArg(aArgs, 'line'), + originalColumn: util$8.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$8.compareByOriginalPositions, + util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util$8.getArg(mapping, 'generatedLine', null), + column: util$8.getArg(mapping, 'generatedColumn', null), + lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer$1; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer$1(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$8.parseSourceMapInput(aSourceMap); + } + + var version = util$8.getArg(sourceMap, 'version'); + var sections = util$8.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet$3(); + this._names = new ArraySet$3(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util$8.getArg(s, 'offset'); + var offsetLine = util$8.getArg(offset, 'line'); + var offsetColumn = util$8.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer$6(util$8.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype); +IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$6; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer$1.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer$1.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer$1.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$8.getArg(aArgs, 'line'), + generatedColumn: util$8.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch$2.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer$1.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer$1.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer$1.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util$8.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer$1.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util$8.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort$2(this.__generatedMappings, util$8.compareByGeneratedPositionsDeflated); + quickSort$2(this.__originalMappings, util$8.compareByOriginalPositions); + }; + +sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer$1; + +var sourceNode$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator$7 = sourceMapGenerator$1.SourceMapGenerator; +var util$7 = util$c; + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE$1 = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE$1 = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode$1 = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode$1(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode$1] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode$1.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode$1(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE$1); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util$7.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util$7.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode$1(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode$1.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode$1] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode$1.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode$1] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode$1.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode$1]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode$1.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode$1.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode$1]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode$1.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util$7.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode$1.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode$1]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util$7.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode$1.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode$1.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator$7(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE$1) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +sourceNode$1.SourceNode = SourceNode$1; + +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator$6 = sourceMap$2.SourceMapGenerator = sourceMapGenerator$1.SourceMapGenerator; +var SourceMapConsumer$5 = sourceMap$2.SourceMapConsumer = sourceMapConsumer$1.SourceMapConsumer; +sourceMap$2.SourceNode = sourceNode$1.SourceNode; + +const PURE_ANNOTATION = `/*#__PURE__*/`; +const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`; +function createCodegenContext(ast, { + mode = "function", + prefixIdentifiers = mode === "module", + sourceMap = false, + filename = `template.vue.html`, + scopeId = null, + optimizeImports = false, + runtimeGlobalName = `Vue`, + runtimeModuleName = `vue`, + ssrRuntimeModuleName = "vue/server-renderer", + ssr = false, + isTS = false, + inSSR = false +}) { + const context = { + mode, + prefixIdentifiers, + sourceMap, + filename, + scopeId, + optimizeImports, + runtimeGlobalName, + runtimeModuleName, + ssrRuntimeModuleName, + ssr, + isTS, + inSSR, + source: ast.source, + code: ``, + column: 1, + line: 1, + offset: 0, + indentLevel: 0, + pure: false, + map: void 0, + helper(key) { + return `_${helperNameMap[key]}`; + }, + push(code, newlineIndex = -2 /* None */, node) { + context.code += code; + if (context.map) { + if (node) { + let name; + if (node.type === 4 && !node.isStatic) { + const content = node.content.replace(/^_ctx\./, ""); + if (content !== node.content && isSimpleIdentifier(content)) { + name = content; + } + } + addMapping(node.loc.start, name); + } + if (newlineIndex === -3 /* Unknown */) { + advancePositionWithMutation(context, code); + } else { + context.offset += code.length; + if (newlineIndex === -2 /* None */) { + context.column += code.length; + } else { + if (newlineIndex === -1 /* End */) { + newlineIndex = code.length - 1; + } + context.line++; + context.column = code.length - newlineIndex; + } + } + if (node && node.loc !== locStub) { + addMapping(node.loc.end); + } + } + }, + indent() { + newline(++context.indentLevel); + }, + deindent(withoutNewLine = false) { + if (withoutNewLine) { + --context.indentLevel; + } else { + newline(--context.indentLevel); + } + }, + newline() { + newline(context.indentLevel); + } + }; + function newline(n) { + context.push("\n" + ` `.repeat(n), 0 /* Start */); + } + function addMapping(loc, name = null) { + const { _names, _mappings } = context.map; + if (name !== null && !_names.has(name)) + _names.add(name); + _mappings.add({ + originalLine: loc.line, + originalColumn: loc.column - 1, + // source-map column is 0 based + generatedLine: context.line, + generatedColumn: context.column - 1, + source: filename, + // @ts-expect-error it is possible to be null + name + }); + } + if (sourceMap) { + context.map = new SourceMapGenerator$6(); + context.map.setSourceContent(filename, context.source); + context.map._sources.add(filename); + } + return context; +} +function generate(ast, options = {}) { + const context = createCodegenContext(ast, options); + if (options.onContextCreated) + options.onContextCreated(context); + const { + mode, + push, + prefixIdentifiers, + indent, + deindent, + newline, + scopeId, + ssr + } = context; + const helpers = Array.from(ast.helpers); + const hasHelpers = helpers.length > 0; + const useWithBlock = !prefixIdentifiers && mode !== "module"; + const genScopeId = scopeId != null && mode === "module"; + const isSetupInlined = !!options.inline; + const preambleContext = isSetupInlined ? createCodegenContext(ast, options) : context; + if (mode === "module") { + genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined); + } else { + genFunctionPreamble(ast, preambleContext); + } + const functionName = ssr ? `ssrRender` : `render`; + const args = ssr ? ["_ctx", "_push", "_parent", "_attrs"] : ["_ctx", "_cache"]; + if (options.bindingMetadata && !options.inline) { + args.push("$props", "$setup", "$data", "$options"); + } + const signature = options.isTS ? args.map((arg) => `${arg}: any`).join(",") : args.join(", "); + if (isSetupInlined) { + push(`(${signature}) => {`); + } else { + push(`function ${functionName}(${signature}) {`); + } + indent(); + if (useWithBlock) { + push(`with (_ctx) {`); + indent(); + if (hasHelpers) { + push( + `const { ${helpers.map(aliasHelper).join(", ")} } = _Vue +`, + -1 /* End */ + ); + newline(); + } + } + if (ast.components.length) { + genAssets(ast.components, "component", context); + if (ast.directives.length || ast.temps > 0) { + newline(); + } + } + if (ast.directives.length) { + genAssets(ast.directives, "directive", context); + if (ast.temps > 0) { + newline(); + } + } + if (ast.temps > 0) { + push(`let `); + for (let i = 0; i < ast.temps; i++) { + push(`${i > 0 ? `, ` : ``}_temp${i}`); + } + } + if (ast.components.length || ast.directives.length || ast.temps) { + push(` +`, 0 /* Start */); + newline(); + } + if (!ssr) { + push(`return `); + } + if (ast.codegenNode) { + genNode(ast.codegenNode, context); + } else { + push(`null`); + } + if (useWithBlock) { + deindent(); + push(`}`); + } + deindent(); + push(`}`); + return { + ast, + code: context.code, + preamble: isSetupInlined ? preambleContext.code : ``, + map: context.map ? context.map.toJSON() : void 0 + }; +} +function genFunctionPreamble(ast, context) { + const { + ssr, + prefixIdentifiers, + push, + newline, + runtimeModuleName, + runtimeGlobalName, + ssrRuntimeModuleName + } = context; + const VueBinding = ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName; + const helpers = Array.from(ast.helpers); + if (helpers.length > 0) { + if (prefixIdentifiers) { + push( + `const { ${helpers.map(aliasHelper).join(", ")} } = ${VueBinding} +`, + -1 /* End */ + ); + } else { + push(`const _Vue = ${VueBinding} +`, -1 /* End */); + if (ast.hoists.length) { + const staticHelpers = [ + CREATE_VNODE, + CREATE_ELEMENT_VNODE, + CREATE_COMMENT, + CREATE_TEXT, + CREATE_STATIC + ].filter((helper) => helpers.includes(helper)).map(aliasHelper).join(", "); + push(`const { ${staticHelpers} } = _Vue +`, -1 /* End */); + } + } + } + if (ast.ssrHelpers && ast.ssrHelpers.length) { + push( + `const { ${ast.ssrHelpers.map(aliasHelper).join(", ")} } = require("${ssrRuntimeModuleName}") +`, + -1 /* End */ + ); + } + genHoists(ast.hoists, context); + newline(); + push(`return `); +} +function genModulePreamble(ast, context, genScopeId, inline) { + const { + push, + newline, + optimizeImports, + runtimeModuleName, + ssrRuntimeModuleName + } = context; + if (genScopeId && ast.hoists.length) { + ast.helpers.add(PUSH_SCOPE_ID); + ast.helpers.add(POP_SCOPE_ID); + } + if (ast.helpers.size) { + const helpers = Array.from(ast.helpers); + if (optimizeImports) { + push( + `import { ${helpers.map((s) => helperNameMap[s]).join(", ")} } from ${JSON.stringify(runtimeModuleName)} +`, + -1 /* End */ + ); + push( + ` +// Binding optimization for webpack code-split +const ${helpers.map((s) => `_${helperNameMap[s]} = ${helperNameMap[s]}`).join(", ")} +`, + -1 /* End */ + ); + } else { + push( + `import { ${helpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from ${JSON.stringify(runtimeModuleName)} +`, + -1 /* End */ + ); + } + } + if (ast.ssrHelpers && ast.ssrHelpers.length) { + push( + `import { ${ast.ssrHelpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from "${ssrRuntimeModuleName}" +`, + -1 /* End */ + ); + } + if (ast.imports.length) { + genImports(ast.imports, context); + newline(); + } + genHoists(ast.hoists, context); + newline(); + if (!inline) { + push(`export `); + } +} +function genAssets(assets, type, { helper, push, newline, isTS }) { + const resolver = helper( + type === "component" ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE + ); + for (let i = 0; i < assets.length; i++) { + let id = assets[i]; + const maybeSelfReference = id.endsWith("__self"); + if (maybeSelfReference) { + id = id.slice(0, -6); + } + push( + `const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}` + ); + if (i < assets.length - 1) { + newline(); + } + } +} +function genHoists(hoists, context) { + if (!hoists.length) { + return; + } + context.pure = true; + const { push, newline, helper, scopeId, mode } = context; + const genScopeId = scopeId != null && mode !== "function"; + newline(); + if (genScopeId) { + push( + `const _withScopeId = n => (${helper( + PUSH_SCOPE_ID + )}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)` + ); + newline(); + } + for (let i = 0; i < hoists.length; i++) { + const exp = hoists[i]; + if (exp) { + const needScopeIdWrapper = genScopeId && exp.type === 13; + push( + `const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}` + ); + genNode(exp, context); + if (needScopeIdWrapper) { + push(`)`); + } + newline(); + } + } + context.pure = false; +} +function genImports(importsOptions, context) { + if (!importsOptions.length) { + return; + } + importsOptions.forEach((imports) => { + context.push(`import `); + genNode(imports.exp, context); + context.push(` from '${imports.path}'`); + context.newline(); + }); +} +function isText(n) { + return isString$2(n) || n.type === 4 || n.type === 2 || n.type === 5 || n.type === 8; +} +function genNodeListAsArray(nodes, context) { + const multilines = nodes.length > 3 || nodes.some((n) => isArray$3(n) || !isText(n)); + context.push(`[`); + multilines && context.indent(); + genNodeList(nodes, context, multilines); + multilines && context.deindent(); + context.push(`]`); +} +function genNodeList(nodes, context, multilines = false, comma = true) { + const { push, newline } = context; + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (isString$2(node)) { + push(node, -3 /* Unknown */); + } else if (isArray$3(node)) { + genNodeListAsArray(node, context); + } else { + genNode(node, context); + } + if (i < nodes.length - 1) { + if (multilines) { + comma && push(","); + newline(); + } else { + comma && push(", "); + } + } + } +} +function genNode(node, context) { + if (isString$2(node)) { + context.push(node, -3 /* Unknown */); + return; + } + if (isSymbol$1(node)) { + context.push(context.helper(node)); + return; + } + switch (node.type) { + case 1: + case 9: + case 11: + assert( + node.codegenNode != null, + `Codegen node is missing for element/if/for node. Apply appropriate transforms first.` + ); + genNode(node.codegenNode, context); + break; + case 2: + genText(node, context); + break; + case 4: + genExpression(node, context); + break; + case 5: + genInterpolation(node, context); + break; + case 12: + genNode(node.codegenNode, context); + break; + case 8: + genCompoundExpression(node, context); + break; + case 3: + genComment(node, context); + break; + case 13: + genVNodeCall(node, context); + break; + case 14: + genCallExpression(node, context); + break; + case 15: + genObjectExpression(node, context); + break; + case 17: + genArrayExpression(node, context); + break; + case 18: + genFunctionExpression(node, context); + break; + case 19: + genConditionalExpression(node, context); + break; + case 20: + genCacheExpression(node, context); + break; + case 21: + genNodeList(node.body, context, true, false); + break; + case 22: + genTemplateLiteral(node, context); + break; + case 23: + genIfStatement(node, context); + break; + case 24: + genAssignmentExpression(node, context); + break; + case 25: + genSequenceExpression(node, context); + break; + case 26: + genReturnStatement(node, context); + break; + case 10: + break; + default: + { + assert(false, `unhandled codegen node type: ${node.type}`); + const exhaustiveCheck = node; + return exhaustiveCheck; + } + } +} +function genText(node, context) { + context.push(JSON.stringify(node.content), -3 /* Unknown */, node); +} +function genExpression(node, context) { + const { content, isStatic } = node; + context.push( + isStatic ? JSON.stringify(content) : content, + -3 /* Unknown */, + node + ); +} +function genInterpolation(node, context) { + const { push, helper, pure } = context; + if (pure) + push(PURE_ANNOTATION); + push(`${helper(TO_DISPLAY_STRING)}(`); + genNode(node.content, context); + push(`)`); +} +function genCompoundExpression(node, context) { + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + if (isString$2(child)) { + context.push(child, -3 /* Unknown */); + } else { + genNode(child, context); + } + } +} +function genExpressionAsPropertyKey(node, context) { + const { push } = context; + if (node.type === 8) { + push(`[`); + genCompoundExpression(node, context); + push(`]`); + } else if (node.isStatic) { + const text = isSimpleIdentifier(node.content) ? node.content : JSON.stringify(node.content); + push(text, -2 /* None */, node); + } else { + push(`[${node.content}]`, -3 /* Unknown */, node); + } +} +function genComment(node, context) { + const { push, helper, pure } = context; + if (pure) { + push(PURE_ANNOTATION); + } + push( + `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, + -3 /* Unknown */, + node + ); +} +function genVNodeCall(node, context) { + const { push, helper, pure } = context; + const { + tag, + props, + children, + patchFlag, + dynamicProps, + directives, + isBlock, + disableTracking, + isComponent + } = node; + if (directives) { + push(helper(WITH_DIRECTIVES) + `(`); + } + if (isBlock) { + push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `); + } + if (pure) { + push(PURE_ANNOTATION); + } + const callHelper = isBlock ? getVNodeBlockHelper(context.inSSR, isComponent) : getVNodeHelper(context.inSSR, isComponent); + push(helper(callHelper) + `(`, -2 /* None */, node); + genNodeList( + genNullableArgs([tag, props, children, patchFlag, dynamicProps]), + context + ); + push(`)`); + if (isBlock) { + push(`)`); + } + if (directives) { + push(`, `); + genNode(directives, context); + push(`)`); + } +} +function genNullableArgs(args) { + let i = args.length; + while (i--) { + if (args[i] != null) + break; + } + return args.slice(0, i + 1).map((arg) => arg || `null`); +} +function genCallExpression(node, context) { + const { push, helper, pure } = context; + const callee = isString$2(node.callee) ? node.callee : helper(node.callee); + if (pure) { + push(PURE_ANNOTATION); + } + push(callee + `(`, -2 /* None */, node); + genNodeList(node.arguments, context); + push(`)`); +} +function genObjectExpression(node, context) { + const { push, indent, deindent, newline } = context; + const { properties } = node; + if (!properties.length) { + push(`{}`, -2 /* None */, node); + return; + } + const multilines = properties.length > 1 || properties.some((p) => p.value.type !== 4); + push(multilines ? `{` : `{ `); + multilines && indent(); + for (let i = 0; i < properties.length; i++) { + const { key, value } = properties[i]; + genExpressionAsPropertyKey(key, context); + push(`: `); + genNode(value, context); + if (i < properties.length - 1) { + push(`,`); + newline(); + } + } + multilines && deindent(); + push(multilines ? `}` : ` }`); +} +function genArrayExpression(node, context) { + genNodeListAsArray(node.elements, context); +} +function genFunctionExpression(node, context) { + const { push, indent, deindent } = context; + const { params, returns, body, newline, isSlot } = node; + if (isSlot) { + push(`_${helperNameMap[WITH_CTX]}(`); + } + push(`(`, -2 /* None */, node); + if (isArray$3(params)) { + genNodeList(params, context); + } else if (params) { + genNode(params, context); + } + push(`) => `); + if (newline || body) { + push(`{`); + indent(); + } + if (returns) { + if (newline) { + push(`return `); + } + if (isArray$3(returns)) { + genNodeListAsArray(returns, context); + } else { + genNode(returns, context); + } + } else if (body) { + genNode(body, context); + } + if (newline || body) { + deindent(); + push(`}`); + } + if (isSlot) { + push(`)`); + } +} +function genConditionalExpression(node, context) { + const { test, consequent, alternate, newline: needNewline } = node; + const { push, indent, deindent, newline } = context; + if (test.type === 4) { + const needsParens = !isSimpleIdentifier(test.content); + needsParens && push(`(`); + genExpression(test, context); + needsParens && push(`)`); + } else { + push(`(`); + genNode(test, context); + push(`)`); + } + needNewline && indent(); + context.indentLevel++; + needNewline || push(` `); + push(`? `); + genNode(consequent, context); + context.indentLevel--; + needNewline && newline(); + needNewline || push(` `); + push(`: `); + const isNested = alternate.type === 19; + if (!isNested) { + context.indentLevel++; + } + genNode(alternate, context); + if (!isNested) { + context.indentLevel--; + } + needNewline && deindent( + true + /* without newline */ + ); +} +function genCacheExpression(node, context) { + const { push, helper, indent, deindent, newline } = context; + push(`_cache[${node.index}] || (`); + if (node.isVNode) { + indent(); + push(`${helper(SET_BLOCK_TRACKING)}(-1),`); + newline(); + } + push(`_cache[${node.index}] = `); + genNode(node.value, context); + if (node.isVNode) { + push(`,`); + newline(); + push(`${helper(SET_BLOCK_TRACKING)}(1),`); + newline(); + push(`_cache[${node.index}]`); + deindent(); + } + push(`)`); +} +function genTemplateLiteral(node, context) { + const { push, indent, deindent } = context; + push("`"); + const l = node.elements.length; + const multilines = l > 3; + for (let i = 0; i < l; i++) { + const e = node.elements[i]; + if (isString$2(e)) { + push(e.replace(/(`|\$|\\)/g, "\\$1"), -3 /* Unknown */); + } else { + push("${"); + if (multilines) + indent(); + genNode(e, context); + if (multilines) + deindent(); + push("}"); + } + } + push("`"); +} +function genIfStatement(node, context) { + const { push, indent, deindent } = context; + const { test, consequent, alternate } = node; + push(`if (`); + genNode(test, context); + push(`) {`); + indent(); + genNode(consequent, context); + deindent(); + push(`}`); + if (alternate) { + push(` else `); + if (alternate.type === 23) { + genIfStatement(alternate, context); + } else { + push(`{`); + indent(); + genNode(alternate, context); + deindent(); + push(`}`); + } + } +} +function genAssignmentExpression(node, context) { + genNode(node.left, context); + context.push(` = `); + genNode(node.right, context); +} +function genSequenceExpression(node, context) { + context.push(`(`); + genNodeList(node.expressions, context); + context.push(`)`); +} +function genReturnStatement({ returns }, context) { + context.push(`return `); + if (isArray$3(returns)) { + genNodeListAsArray(returns, context); + } else { + genNode(returns, context); + } +} + +const isLiteralWhitelisted = /* @__PURE__ */ makeMap("true,false,null,this"); +const constantBailRE = /\w\s*\(|\.[^\d]/; +const transformExpression = (node, context) => { + if (node.type === 5) { + node.content = processExpression( + node.content, + context + ); + } else if (node.type === 1) { + for (let i = 0; i < node.props.length; i++) { + const dir = node.props[i]; + if (dir.type === 7 && dir.name !== "for") { + const exp = dir.exp; + const arg = dir.arg; + if (exp && exp.type === 4 && !(dir.name === "on" && arg)) { + dir.exp = processExpression( + exp, + context, + // slot args must be processed as function params + dir.name === "slot" + ); + } + if (arg && arg.type === 4 && !arg.isStatic) { + dir.arg = processExpression(arg, context); + } + } + } + } +}; +function processExpression(node, context, asParams = false, asRawStatements = false, localVars = Object.create(context.identifiers)) { + if (!context.prefixIdentifiers || !node.content.trim()) { + return node; + } + const { inline, bindingMetadata } = context; + const rewriteIdentifier = (raw, parent, id) => { + const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw]; + if (inline) { + const isAssignmentLVal = parent && parent.type === "AssignmentExpression" && parent.left === id; + const isUpdateArg = parent && parent.type === "UpdateExpression" && parent.argument === id; + const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack); + const isNewExpression = parent && isInNewExpression(parentStack); + const wrapWithUnref = (raw2) => { + const wrapped = `${context.helperString(UNREF)}(${raw2})`; + return isNewExpression ? `(${wrapped})` : wrapped; + }; + if (isConst(type) || type === "setup-reactive-const" || localVars[raw]) { + return raw; + } else if (type === "setup-ref") { + return `${raw}.value`; + } else if (type === "setup-maybe-ref") { + return isAssignmentLVal || isUpdateArg || isDestructureAssignment ? `${raw}.value` : wrapWithUnref(raw); + } else if (type === "setup-let") { + if (isAssignmentLVal) { + const { right: rVal, operator } = parent; + const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1); + const rExpString = stringifyExpression( + processExpression( + createSimpleExpression(rExp, false), + context, + false, + false, + knownIds + ) + ); + return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore +` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`; + } else if (isUpdateArg) { + id.start = parent.start; + id.end = parent.end; + const { prefix: isPrefix, operator } = parent; + const prefix = isPrefix ? operator : ``; + const postfix = isPrefix ? `` : operator; + return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore +` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`; + } else if (isDestructureAssignment) { + return raw; + } else { + return wrapWithUnref(raw); + } + } else if (type === "props") { + return genPropsAccessExp(raw); + } else if (type === "props-aliased") { + return genPropsAccessExp(bindingMetadata.__propsAliases[raw]); + } + } else { + if (type && type.startsWith("setup") || type === "literal-const") { + return `$setup.${raw}`; + } else if (type === "props-aliased") { + return `$props['${bindingMetadata.__propsAliases[raw]}']`; + } else if (type) { + return `$${type}.${raw}`; + } + } + return `_ctx.${raw}`; + }; + const rawExp = node.content; + const bailConstant = constantBailRE.test(rawExp); + let ast = node.ast; + if (ast === false) { + return node; + } + if (ast === null || !ast && isSimpleIdentifier(rawExp)) { + const isScopeVarReference = context.identifiers[rawExp]; + const isAllowedGlobal = isGloballyAllowed(rawExp); + const isLiteral = isLiteralWhitelisted(rawExp); + if (!asParams && !isScopeVarReference && !isLiteral && (!isAllowedGlobal || bindingMetadata[rawExp])) { + if (isConst(bindingMetadata[rawExp])) { + node.constType = 1; + } + node.content = rewriteIdentifier(rawExp); + } else if (!isScopeVarReference) { + if (isLiteral) { + node.constType = 3; + } else { + node.constType = 2; + } + } + return node; + } + if (!ast) { + const source = asRawStatements ? ` ${rawExp} ` : `(${rawExp})${asParams ? `=>{}` : ``}`; + try { + ast = parse_1$1(source, { + plugins: context.expressionPlugins + }).program; + } catch (e) { + context.onError( + createCompilerError( + 45, + node.loc, + void 0, + e.message + ) + ); + return node; + } + } + const ids = []; + const parentStack = []; + const knownIds = Object.create(context.identifiers); + walkIdentifiers( + ast, + (node2, parent, _, isReferenced, isLocal) => { + if (isStaticPropertyKey(node2, parent)) { + return; + } + const needPrefix = isReferenced && canPrefix(node2); + if (needPrefix && !isLocal) { + if (isStaticProperty(parent) && parent.shorthand) { + node2.prefix = `${node2.name}: `; + } + node2.name = rewriteIdentifier(node2.name, parent, node2); + ids.push(node2); + } else { + if (!(needPrefix && isLocal) && !bailConstant) { + node2.isConstant = true; + } + ids.push(node2); + } + }, + true, + // invoke on ALL identifiers + parentStack, + knownIds + ); + const children = []; + ids.sort((a, b) => a.start - b.start); + ids.forEach((id, i) => { + const start = id.start - 1; + const end = id.end - 1; + const last = ids[i - 1]; + const leadingText = rawExp.slice(last ? last.end - 1 : 0, start); + if (leadingText.length || id.prefix) { + children.push(leadingText + (id.prefix || ``)); + } + const source = rawExp.slice(start, end); + children.push( + createSimpleExpression( + id.name, + false, + { + start: advancePositionWithClone(node.loc.start, source, start), + end: advancePositionWithClone(node.loc.start, source, end), + source + }, + id.isConstant ? 3 : 0 + ) + ); + if (i === ids.length - 1 && end < rawExp.length) { + children.push(rawExp.slice(end)); + } + }); + let ret; + if (children.length) { + ret = createCompoundExpression(children, node.loc); + ret.ast = ast; + } else { + ret = node; + ret.constType = bailConstant ? 0 : 3; + } + ret.identifiers = Object.keys(knownIds); + return ret; +} +function canPrefix(id) { + if (isGloballyAllowed(id.name)) { + return false; + } + if (id.name === "require") { + return false; + } + return true; +} +function stringifyExpression(exp) { + if (isString$2(exp)) { + return exp; + } else if (exp.type === 4) { + return exp.content; + } else { + return exp.children.map(stringifyExpression).join(""); + } +} +function isConst(type) { + return type === "setup-const" || type === "literal-const"; +} + +const transformIf = createStructuralDirectiveTransform( + /^(if|else|else-if)$/, + (node, dir, context) => { + return processIf(node, dir, context, (ifNode, branch, isRoot) => { + const siblings = context.parent.children; + let i = siblings.indexOf(ifNode); + let key = 0; + while (i-- >= 0) { + const sibling = siblings[i]; + if (sibling && sibling.type === 9) { + key += sibling.branches.length; + } + } + return () => { + if (isRoot) { + ifNode.codegenNode = createCodegenNodeForBranch( + branch, + key, + context + ); + } else { + const parentCondition = getParentCondition(ifNode.codegenNode); + parentCondition.alternate = createCodegenNodeForBranch( + branch, + key + ifNode.branches.length - 1, + context + ); + } + }; + }); + } +); +function processIf(node, dir, context, processCodegen) { + if (dir.name !== "else" && (!dir.exp || !dir.exp.content.trim())) { + const loc = dir.exp ? dir.exp.loc : node.loc; + context.onError( + createCompilerError(28, dir.loc) + ); + dir.exp = createSimpleExpression(`true`, false, loc); + } + if (context.prefixIdentifiers && dir.exp) { + dir.exp = processExpression(dir.exp, context); + } + if (dir.name === "if") { + const branch = createIfBranch(node, dir); + const ifNode = { + type: 9, + loc: node.loc, + branches: [branch] + }; + context.replaceNode(ifNode); + if (processCodegen) { + return processCodegen(ifNode, branch, true); + } + } else { + const siblings = context.parent.children; + const comments = []; + let i = siblings.indexOf(node); + while (i-- >= -1) { + const sibling = siblings[i]; + if (sibling && sibling.type === 3) { + context.removeNode(sibling); + comments.unshift(sibling); + continue; + } + if (sibling && sibling.type === 2 && !sibling.content.trim().length) { + context.removeNode(sibling); + continue; + } + if (sibling && sibling.type === 9) { + if (dir.name === "else-if" && sibling.branches[sibling.branches.length - 1].condition === void 0) { + context.onError( + createCompilerError(30, node.loc) + ); + } + context.removeNode(); + const branch = createIfBranch(node, dir); + if (comments.length && // #3619 ignore comments if the v-if is direct child of <transition> + !(context.parent && context.parent.type === 1 && (context.parent.tag === "transition" || context.parent.tag === "Transition"))) { + branch.children = [...comments, ...branch.children]; + } + { + const key = branch.userKey; + if (key) { + sibling.branches.forEach(({ userKey }) => { + if (isSameKey(userKey, key)) { + context.onError( + createCompilerError( + 29, + branch.userKey.loc + ) + ); + } + }); + } + } + sibling.branches.push(branch); + const onExit = processCodegen && processCodegen(sibling, branch, false); + traverseNode(branch, context); + if (onExit) + onExit(); + context.currentNode = null; + } else { + context.onError( + createCompilerError(30, node.loc) + ); + } + break; + } + } +} +function createIfBranch(node, dir) { + const isTemplateIf = node.tagType === 3; + return { + type: 10, + loc: node.loc, + condition: dir.name === "else" ? void 0 : dir.exp, + children: isTemplateIf && !findDir(node, "for") ? node.children : [node], + userKey: findProp(node, `key`), + isTemplateIf + }; +} +function createCodegenNodeForBranch(branch, keyIndex, context) { + if (branch.condition) { + return createConditionalExpression( + branch.condition, + createChildrenCodegenNode(branch, keyIndex, context), + // make sure to pass in asBlock: true so that the comment node call + // closes the current block. + createCallExpression(context.helper(CREATE_COMMENT), [ + '"v-if"' , + "true" + ]) + ); + } else { + return createChildrenCodegenNode(branch, keyIndex, context); + } +} +function createChildrenCodegenNode(branch, keyIndex, context) { + const { helper } = context; + const keyProperty = createObjectProperty( + `key`, + createSimpleExpression( + `${keyIndex}`, + false, + locStub, + 2 + ) + ); + const { children } = branch; + const firstChild = children[0]; + const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1; + if (needFragmentWrapper) { + if (children.length === 1 && firstChild.type === 11) { + const vnodeCall = firstChild.codegenNode; + injectProp(vnodeCall, keyProperty, context); + return vnodeCall; + } else { + let patchFlag = 64; + let patchFlagText = PatchFlagNames[64]; + if (!branch.isTemplateIf && children.filter((c) => c.type !== 3).length === 1) { + patchFlag |= 2048; + patchFlagText += `, ${PatchFlagNames[2048]}`; + } + return createVNodeCall( + context, + helper(FRAGMENT), + createObjectExpression([keyProperty]), + children, + patchFlag + (` /* ${patchFlagText} */` ), + void 0, + void 0, + true, + false, + false, + branch.loc + ); + } + } else { + const ret = firstChild.codegenNode; + const vnodeCall = getMemoedVNodeCall(ret); + if (vnodeCall.type === 13) { + convertToBlock(vnodeCall, context); + } + injectProp(vnodeCall, keyProperty, context); + return ret; + } +} +function isSameKey(a, b) { + if (!a || a.type !== b.type) { + return false; + } + if (a.type === 6) { + if (a.value.content !== b.value.content) { + return false; + } + } else { + const exp = a.exp; + const branchExp = b.exp; + if (exp.type !== branchExp.type) { + return false; + } + if (exp.type !== 4 || exp.isStatic !== branchExp.isStatic || exp.content !== branchExp.content) { + return false; + } + } + return true; +} +function getParentCondition(node) { + while (true) { + if (node.type === 19) { + if (node.alternate.type === 19) { + node = node.alternate; + } else { + return node; + } + } else if (node.type === 20) { + node = node.value; + } + } +} + +const transformFor = createStructuralDirectiveTransform( + "for", + (node, dir, context) => { + const { helper, removeHelper } = context; + return processFor(node, dir, context, (forNode) => { + const renderExp = createCallExpression(helper(RENDER_LIST), [ + forNode.source + ]); + const isTemplate = isTemplateNode(node); + const memo = findDir(node, "memo"); + const keyProp = findProp(node, `key`); + const keyExp = keyProp && (keyProp.type === 6 ? createSimpleExpression(keyProp.value.content, true) : keyProp.exp); + const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null; + if (isTemplate) { + if (memo) { + memo.exp = processExpression( + memo.exp, + context + ); + } + if (keyProperty && keyProp.type !== 6) { + keyProperty.value = processExpression( + keyProperty.value, + context + ); + } + } + const isStableFragment = forNode.source.type === 4 && forNode.source.constType > 0; + const fragmentFlag = isStableFragment ? 64 : keyProp ? 128 : 256; + forNode.codegenNode = createVNodeCall( + context, + helper(FRAGMENT), + void 0, + renderExp, + fragmentFlag + (` /* ${PatchFlagNames[fragmentFlag]} */` ), + void 0, + void 0, + true, + !isStableFragment, + false, + node.loc + ); + return () => { + let childBlock; + const { children } = forNode; + if (isTemplate) { + node.children.some((c) => { + if (c.type === 1) { + const key = findProp(c, "key"); + if (key) { + context.onError( + createCompilerError( + 33, + key.loc + ) + ); + return true; + } + } + }); + } + const needFragmentWrapper = children.length !== 1 || children[0].type !== 1; + const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? node.children[0] : null; + if (slotOutlet) { + childBlock = slotOutlet.codegenNode; + if (isTemplate && keyProperty) { + injectProp(childBlock, keyProperty, context); + } + } else if (needFragmentWrapper) { + childBlock = createVNodeCall( + context, + helper(FRAGMENT), + keyProperty ? createObjectExpression([keyProperty]) : void 0, + node.children, + 64 + (` /* ${PatchFlagNames[64]} */` ), + void 0, + void 0, + true, + void 0, + false + ); + } else { + childBlock = children[0].codegenNode; + if (isTemplate && keyProperty) { + injectProp(childBlock, keyProperty, context); + } + if (childBlock.isBlock !== !isStableFragment) { + if (childBlock.isBlock) { + removeHelper(OPEN_BLOCK); + removeHelper( + getVNodeBlockHelper(context.inSSR, childBlock.isComponent) + ); + } else { + removeHelper( + getVNodeHelper(context.inSSR, childBlock.isComponent) + ); + } + } + childBlock.isBlock = !isStableFragment; + if (childBlock.isBlock) { + helper(OPEN_BLOCK); + helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent)); + } else { + helper(getVNodeHelper(context.inSSR, childBlock.isComponent)); + } + } + if (memo) { + const loop = createFunctionExpression( + createForLoopParams(forNode.parseResult, [ + createSimpleExpression(`_cached`) + ]) + ); + loop.body = createBlockStatement([ + createCompoundExpression([`const _memo = (`, memo.exp, `)`]), + createCompoundExpression([ + `if (_cached`, + ...keyExp ? [` && _cached.key === `, keyExp] : [], + ` && ${context.helperString( + IS_MEMO_SAME + )}(_cached, _memo)) return _cached` + ]), + createCompoundExpression([`const _item = `, childBlock]), + createSimpleExpression(`_item.memo = _memo`), + createSimpleExpression(`return _item`) + ]); + renderExp.arguments.push( + loop, + createSimpleExpression(`_cache`), + createSimpleExpression(String(context.cached++)) + ); + } else { + renderExp.arguments.push( + createFunctionExpression( + createForLoopParams(forNode.parseResult), + childBlock, + true + ) + ); + } + }; + }); + } +); +function processFor(node, dir, context, processCodegen) { + if (!dir.exp) { + context.onError( + createCompilerError(31, dir.loc) + ); + return; + } + const parseResult = dir.forParseResult; + if (!parseResult) { + context.onError( + createCompilerError(32, dir.loc) + ); + return; + } + finalizeForParseResult(parseResult, context); + const { addIdentifiers, removeIdentifiers, scopes } = context; + const { source, value, key, index } = parseResult; + const forNode = { + type: 11, + loc: dir.loc, + source, + valueAlias: value, + keyAlias: key, + objectIndexAlias: index, + parseResult, + children: isTemplateNode(node) ? node.children : [node] + }; + context.replaceNode(forNode); + scopes.vFor++; + if (context.prefixIdentifiers) { + value && addIdentifiers(value); + key && addIdentifiers(key); + index && addIdentifiers(index); + } + const onExit = processCodegen && processCodegen(forNode); + return () => { + scopes.vFor--; + if (context.prefixIdentifiers) { + value && removeIdentifiers(value); + key && removeIdentifiers(key); + index && removeIdentifiers(index); + } + if (onExit) + onExit(); + }; +} +function finalizeForParseResult(result, context) { + if (result.finalized) + return; + if (context.prefixIdentifiers) { + result.source = processExpression( + result.source, + context + ); + if (result.key) { + result.key = processExpression( + result.key, + context, + true + ); + } + if (result.index) { + result.index = processExpression( + result.index, + context, + true + ); + } + if (result.value) { + result.value = processExpression( + result.value, + context, + true + ); + } + } + result.finalized = true; +} +function createForLoopParams({ value, key, index }, memoArgs = []) { + return createParamsList([value, key, index, ...memoArgs]); +} +function createParamsList(args) { + let i = args.length; + while (i--) { + if (args[i]) + break; + } + return args.slice(0, i + 1).map((arg, i2) => arg || createSimpleExpression(`_`.repeat(i2 + 1), false)); +} + +const defaultFallback = createSimpleExpression(`undefined`, false); +const trackSlotScopes = (node, context) => { + if (node.type === 1 && (node.tagType === 1 || node.tagType === 3)) { + const vSlot = findDir(node, "slot"); + if (vSlot) { + const slotProps = vSlot.exp; + if (context.prefixIdentifiers) { + slotProps && context.addIdentifiers(slotProps); + } + context.scopes.vSlot++; + return () => { + if (context.prefixIdentifiers) { + slotProps && context.removeIdentifiers(slotProps); + } + context.scopes.vSlot--; + }; + } + } +}; +const trackVForSlotScopes = (node, context) => { + let vFor; + if (isTemplateNode(node) && node.props.some(isVSlot) && (vFor = findDir(node, "for"))) { + const result = vFor.forParseResult; + if (result) { + finalizeForParseResult(result, context); + const { value, key, index } = result; + const { addIdentifiers, removeIdentifiers } = context; + value && addIdentifiers(value); + key && addIdentifiers(key); + index && addIdentifiers(index); + return () => { + value && removeIdentifiers(value); + key && removeIdentifiers(key); + index && removeIdentifiers(index); + }; + } + } +}; +const buildClientSlotFn = (props, _vForExp, children, loc) => createFunctionExpression( + props, + children, + false, + true, + children.length ? children[0].loc : loc +); +function buildSlots(node, context, buildSlotFn = buildClientSlotFn) { + context.helper(WITH_CTX); + const { children, loc } = node; + const slotsProperties = []; + const dynamicSlots = []; + let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0; + if (!context.ssr && context.prefixIdentifiers) { + hasDynamicSlots = hasScopeRef(node, context.identifiers); + } + const onComponentSlot = findDir(node, "slot", true); + if (onComponentSlot) { + const { arg, exp } = onComponentSlot; + if (arg && !isStaticExp(arg)) { + hasDynamicSlots = true; + } + slotsProperties.push( + createObjectProperty( + arg || createSimpleExpression("default", true), + buildSlotFn(exp, void 0, children, loc) + ) + ); + } + let hasTemplateSlots = false; + let hasNamedDefaultSlot = false; + const implicitDefaultChildren = []; + const seenSlotNames = /* @__PURE__ */ new Set(); + let conditionalBranchIndex = 0; + for (let i = 0; i < children.length; i++) { + const slotElement = children[i]; + let slotDir; + if (!isTemplateNode(slotElement) || !(slotDir = findDir(slotElement, "slot", true))) { + if (slotElement.type !== 3) { + implicitDefaultChildren.push(slotElement); + } + continue; + } + if (onComponentSlot) { + context.onError( + createCompilerError(37, slotDir.loc) + ); + break; + } + hasTemplateSlots = true; + const { children: slotChildren, loc: slotLoc } = slotElement; + const { + arg: slotName = createSimpleExpression(`default`, true), + exp: slotProps, + loc: dirLoc + } = slotDir; + let staticSlotName; + if (isStaticExp(slotName)) { + staticSlotName = slotName ? slotName.content : `default`; + } else { + hasDynamicSlots = true; + } + const vFor = findDir(slotElement, "for"); + const slotFunction = buildSlotFn(slotProps, vFor, slotChildren, slotLoc); + let vIf; + let vElse; + if (vIf = findDir(slotElement, "if")) { + hasDynamicSlots = true; + dynamicSlots.push( + createConditionalExpression( + vIf.exp, + buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), + defaultFallback + ) + ); + } else if (vElse = findDir( + slotElement, + /^else(-if)?$/, + true + /* allowEmpty */ + )) { + let j = i; + let prev; + while (j--) { + prev = children[j]; + if (prev.type !== 3) { + break; + } + } + if (prev && isTemplateNode(prev) && findDir(prev, "if")) { + children.splice(i, 1); + i--; + let conditional = dynamicSlots[dynamicSlots.length - 1]; + while (conditional.alternate.type === 19) { + conditional = conditional.alternate; + } + conditional.alternate = vElse.exp ? createConditionalExpression( + vElse.exp, + buildDynamicSlot( + slotName, + slotFunction, + conditionalBranchIndex++ + ), + defaultFallback + ) : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++); + } else { + context.onError( + createCompilerError(30, vElse.loc) + ); + } + } else if (vFor) { + hasDynamicSlots = true; + const parseResult = vFor.forParseResult; + if (parseResult) { + finalizeForParseResult(parseResult, context); + dynamicSlots.push( + createCallExpression(context.helper(RENDER_LIST), [ + parseResult.source, + createFunctionExpression( + createForLoopParams(parseResult), + buildDynamicSlot(slotName, slotFunction), + true + ) + ]) + ); + } else { + context.onError( + createCompilerError( + 32, + vFor.loc + ) + ); + } + } else { + if (staticSlotName) { + if (seenSlotNames.has(staticSlotName)) { + context.onError( + createCompilerError( + 38, + dirLoc + ) + ); + continue; + } + seenSlotNames.add(staticSlotName); + if (staticSlotName === "default") { + hasNamedDefaultSlot = true; + } + } + slotsProperties.push(createObjectProperty(slotName, slotFunction)); + } + } + if (!onComponentSlot) { + const buildDefaultSlotProperty = (props, children2) => { + const fn = buildSlotFn(props, void 0, children2, loc); + return createObjectProperty(`default`, fn); + }; + if (!hasTemplateSlots) { + slotsProperties.push(buildDefaultSlotProperty(void 0, children)); + } else if (implicitDefaultChildren.length && // #3766 + // with whitespace: 'preserve', whitespaces between slots will end up in + // implicitDefaultChildren. Ignore if all implicit children are whitespaces. + implicitDefaultChildren.some((node2) => isNonWhitespaceContent(node2))) { + if (hasNamedDefaultSlot) { + context.onError( + createCompilerError( + 39, + implicitDefaultChildren[0].loc + ) + ); + } else { + slotsProperties.push( + buildDefaultSlotProperty(void 0, implicitDefaultChildren) + ); + } + } + } + const slotFlag = hasDynamicSlots ? 2 : hasForwardedSlots(node.children) ? 3 : 1; + let slots = createObjectExpression( + slotsProperties.concat( + createObjectProperty( + `_`, + // 2 = compiled but dynamic = can skip normalization, but must run diff + // 1 = compiled and static = can skip normalization AND diff as optimized + createSimpleExpression( + slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), + false + ) + ) + ), + loc + ); + if (dynamicSlots.length) { + slots = createCallExpression(context.helper(CREATE_SLOTS), [ + slots, + createArrayExpression(dynamicSlots) + ]); + } + return { + slots, + hasDynamicSlots + }; +} +function buildDynamicSlot(name, fn, index) { + const props = [ + createObjectProperty(`name`, name), + createObjectProperty(`fn`, fn) + ]; + if (index != null) { + props.push( + createObjectProperty(`key`, createSimpleExpression(String(index), true)) + ); + } + return createObjectExpression(props); +} +function hasForwardedSlots(children) { + for (let i = 0; i < children.length; i++) { + const child = children[i]; + switch (child.type) { + case 1: + if (child.tagType === 2 || hasForwardedSlots(child.children)) { + return true; + } + break; + case 9: + if (hasForwardedSlots(child.branches)) + return true; + break; + case 10: + case 11: + if (hasForwardedSlots(child.children)) + return true; + break; + } + } + return false; +} +function isNonWhitespaceContent(node) { + if (node.type !== 2 && node.type !== 12) + return true; + return node.type === 2 ? !!node.content.trim() : isNonWhitespaceContent(node.content); +} + +const directiveImportMap = /* @__PURE__ */ new WeakMap(); +const transformElement = (node, context) => { + return function postTransformElement() { + node = context.currentNode; + if (!(node.type === 1 && (node.tagType === 0 || node.tagType === 1))) { + return; + } + const { tag, props } = node; + const isComponent = node.tagType === 1; + let vnodeTag = isComponent ? resolveComponentType(node, context) : `"${tag}"`; + const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT; + let vnodeProps; + let vnodeChildren; + let vnodePatchFlag; + let patchFlag = 0; + let vnodeDynamicProps; + let dynamicPropNames; + let vnodeDirectives; + let shouldUseBlock = ( + // dynamic component may resolve to plain elements + isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent && // <svg> and <foreignObject> must be forced into blocks so that block + // updates inside get proper isSVG flag at runtime. (#639, #643) + // This is technically web-specific, but splitting the logic out of core + // leads to too much unnecessary complexity. + (tag === "svg" || tag === "foreignObject") + ); + if (props.length > 0) { + const propsBuildResult = buildProps( + node, + context, + void 0, + isComponent, + isDynamicComponent + ); + vnodeProps = propsBuildResult.props; + patchFlag = propsBuildResult.patchFlag; + dynamicPropNames = propsBuildResult.dynamicPropNames; + const directives = propsBuildResult.directives; + vnodeDirectives = directives && directives.length ? createArrayExpression( + directives.map((dir) => buildDirectiveArgs(dir, context)) + ) : void 0; + if (propsBuildResult.shouldUseBlock) { + shouldUseBlock = true; + } + } + if (node.children.length > 0) { + if (vnodeTag === KEEP_ALIVE) { + shouldUseBlock = true; + patchFlag |= 1024; + if (node.children.length > 1) { + context.onError( + createCompilerError(46, { + start: node.children[0].loc.start, + end: node.children[node.children.length - 1].loc.end, + source: "" + }) + ); + } + } + const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling + vnodeTag !== TELEPORT && // explained above. + vnodeTag !== KEEP_ALIVE; + if (shouldBuildAsSlots) { + const { slots, hasDynamicSlots } = buildSlots(node, context); + vnodeChildren = slots; + if (hasDynamicSlots) { + patchFlag |= 1024; + } + } else if (node.children.length === 1 && vnodeTag !== TELEPORT) { + const child = node.children[0]; + const type = child.type; + const hasDynamicTextChild = type === 5 || type === 8; + if (hasDynamicTextChild && getConstantType(child, context) === 0) { + patchFlag |= 1; + } + if (hasDynamicTextChild || type === 2) { + vnodeChildren = child; + } else { + vnodeChildren = node.children; + } + } else { + vnodeChildren = node.children; + } + } + if (patchFlag !== 0) { + { + if (patchFlag < 0) { + vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`; + } else { + const flagNames = Object.keys(PatchFlagNames).map(Number).filter((n) => n > 0 && patchFlag & n).map((n) => PatchFlagNames[n]).join(`, `); + vnodePatchFlag = patchFlag + ` /* ${flagNames} */`; + } + } + if (dynamicPropNames && dynamicPropNames.length) { + vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames); + } + } + node.codegenNode = createVNodeCall( + context, + vnodeTag, + vnodeProps, + vnodeChildren, + vnodePatchFlag, + vnodeDynamicProps, + vnodeDirectives, + !!shouldUseBlock, + false, + isComponent, + node.loc + ); + }; +}; +function resolveComponentType(node, context, ssr = false) { + let { tag } = node; + const isExplicitDynamic = isComponentTag(tag); + const isProp = findProp(node, "is"); + if (isProp) { + if (isExplicitDynamic || false) { + const exp = isProp.type === 6 ? isProp.value && createSimpleExpression(isProp.value.content, true) : isProp.exp; + if (exp) { + return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [ + exp + ]); + } + } else if (isProp.type === 6 && isProp.value.content.startsWith("vue:")) { + tag = isProp.value.content.slice(4); + } + } + const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag); + if (builtIn) { + if (!ssr) + context.helper(builtIn); + return builtIn; + } + { + const fromSetup = resolveSetupReference(tag, context); + if (fromSetup) { + return fromSetup; + } + const dotIndex = tag.indexOf("."); + if (dotIndex > 0) { + const ns = resolveSetupReference(tag.slice(0, dotIndex), context); + if (ns) { + return ns + tag.slice(dotIndex); + } + } + } + if (context.selfName && capitalize$1(camelize(tag)) === context.selfName) { + context.helper(RESOLVE_COMPONENT); + context.components.add(tag + `__self`); + return toValidAssetId(tag, `component`); + } + context.helper(RESOLVE_COMPONENT); + context.components.add(tag); + return toValidAssetId(tag, `component`); +} +function resolveSetupReference(name, context) { + const bindings = context.bindingMetadata; + if (!bindings || bindings.__isScriptSetup === false) { + return; + } + const camelName = camelize(name); + const PascalName = capitalize$1(camelName); + const checkType = (type) => { + if (bindings[name] === type) { + return name; + } + if (bindings[camelName] === type) { + return camelName; + } + if (bindings[PascalName] === type) { + return PascalName; + } + }; + const fromConst = checkType("setup-const") || checkType("setup-reactive-const") || checkType("literal-const"); + if (fromConst) { + return context.inline ? ( + // in inline mode, const setup bindings (e.g. imports) can be used as-is + fromConst + ) : `$setup[${JSON.stringify(fromConst)}]`; + } + const fromMaybeRef = checkType("setup-let") || checkType("setup-ref") || checkType("setup-maybe-ref"); + if (fromMaybeRef) { + return context.inline ? ( + // setup scope bindings that may be refs need to be unrefed + `${context.helperString(UNREF)}(${fromMaybeRef})` + ) : `$setup[${JSON.stringify(fromMaybeRef)}]`; + } + const fromProps = checkType("props"); + if (fromProps) { + return `${context.helperString(UNREF)}(${context.inline ? "__props" : "$props"}[${JSON.stringify(fromProps)}])`; + } +} +function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) { + const { tag, loc: elementLoc, children } = node; + let properties = []; + const mergeArgs = []; + const runtimeDirectives = []; + const hasChildren = children.length > 0; + let shouldUseBlock = false; + let patchFlag = 0; + let hasRef = false; + let hasClassBinding = false; + let hasStyleBinding = false; + let hasHydrationEventBinding = false; + let hasDynamicKeys = false; + let hasVnodeHook = false; + const dynamicPropNames = []; + const pushMergeArg = (arg) => { + if (properties.length) { + mergeArgs.push( + createObjectExpression(dedupeProperties(properties), elementLoc) + ); + properties = []; + } + if (arg) + mergeArgs.push(arg); + }; + const analyzePatchFlag = ({ key, value }) => { + if (isStaticExp(key)) { + const name = key.content; + const isEventHandler = isOn(name); + if (isEventHandler && (!isComponent || isDynamicComponent) && // omit the flag for click handlers because hydration gives click + // dedicated fast path. + name.toLowerCase() !== "onclick" && // omit v-model handlers + name !== "onUpdate:modelValue" && // omit onVnodeXXX hooks + !isReservedProp(name)) { + hasHydrationEventBinding = true; + } + if (isEventHandler && isReservedProp(name)) { + hasVnodeHook = true; + } + if (isEventHandler && value.type === 14) { + value = value.arguments[0]; + } + if (value.type === 20 || (value.type === 4 || value.type === 8) && getConstantType(value, context) > 0) { + return; + } + if (name === "ref") { + hasRef = true; + } else if (name === "class") { + hasClassBinding = true; + } else if (name === "style") { + hasStyleBinding = true; + } else if (name !== "key" && !dynamicPropNames.includes(name)) { + dynamicPropNames.push(name); + } + if (isComponent && (name === "class" || name === "style") && !dynamicPropNames.includes(name)) { + dynamicPropNames.push(name); + } + } else { + hasDynamicKeys = true; + } + }; + for (let i = 0; i < props.length; i++) { + const prop = props[i]; + if (prop.type === 6) { + const { loc, name, nameLoc, value } = prop; + let isStatic = true; + if (name === "ref") { + hasRef = true; + if (context.scopes.vFor > 0) { + properties.push( + createObjectProperty( + createSimpleExpression("ref_for", true), + createSimpleExpression("true") + ) + ); + } + if (value && context.inline) { + const binding = context.bindingMetadata[value.content]; + if (binding === "setup-let" || binding === "setup-ref" || binding === "setup-maybe-ref") { + isStatic = false; + properties.push( + createObjectProperty( + createSimpleExpression("ref_key", true), + createSimpleExpression(value.content, true, value.loc) + ) + ); + } + } + } + if (name === "is" && (isComponentTag(tag) || value && value.content.startsWith("vue:") || false)) { + continue; + } + properties.push( + createObjectProperty( + createSimpleExpression(name, true, nameLoc), + createSimpleExpression( + value ? value.content : "", + isStatic, + value ? value.loc : loc + ) + ) + ); + } else { + const { name, arg, exp, loc, modifiers } = prop; + const isVBind = name === "bind"; + const isVOn = name === "on"; + if (name === "slot") { + if (!isComponent) { + context.onError( + createCompilerError(40, loc) + ); + } + continue; + } + if (name === "once" || name === "memo") { + continue; + } + if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag) || false)) { + continue; + } + if (isVOn && ssr) { + continue; + } + if ( + // #938: elements with dynamic keys should be forced into blocks + isVBind && isStaticArgOf(arg, "key") || // inline before-update hooks need to force block so that it is invoked + // before children + isVOn && hasChildren && isStaticArgOf(arg, "vue:before-update") + ) { + shouldUseBlock = true; + } + if (isVBind && isStaticArgOf(arg, "ref") && context.scopes.vFor > 0) { + properties.push( + createObjectProperty( + createSimpleExpression("ref_for", true), + createSimpleExpression("true") + ) + ); + } + if (!arg && (isVBind || isVOn)) { + hasDynamicKeys = true; + if (exp) { + if (isVBind) { + pushMergeArg(); + mergeArgs.push(exp); + } else { + pushMergeArg({ + type: 14, + loc, + callee: context.helper(TO_HANDLERS), + arguments: isComponent ? [exp] : [exp, `true`] + }); + } + } else { + context.onError( + createCompilerError( + isVBind ? 34 : 35, + loc + ) + ); + } + continue; + } + if (isVBind && modifiers.includes("prop")) { + patchFlag |= 32; + } + const directiveTransform = context.directiveTransforms[name]; + if (directiveTransform) { + const { props: props2, needRuntime } = directiveTransform(prop, node, context); + !ssr && props2.forEach(analyzePatchFlag); + if (isVOn && arg && !isStaticExp(arg)) { + pushMergeArg(createObjectExpression(props2, elementLoc)); + } else { + properties.push(...props2); + } + if (needRuntime) { + runtimeDirectives.push(prop); + if (isSymbol$1(needRuntime)) { + directiveImportMap.set(prop, needRuntime); + } + } + } else if (!isBuiltInDirective(name)) { + runtimeDirectives.push(prop); + if (hasChildren) { + shouldUseBlock = true; + } + } + } + } + let propsExpression = void 0; + if (mergeArgs.length) { + pushMergeArg(); + if (mergeArgs.length > 1) { + propsExpression = createCallExpression( + context.helper(MERGE_PROPS), + mergeArgs, + elementLoc + ); + } else { + propsExpression = mergeArgs[0]; + } + } else if (properties.length) { + propsExpression = createObjectExpression( + dedupeProperties(properties), + elementLoc + ); + } + if (hasDynamicKeys) { + patchFlag |= 16; + } else { + if (hasClassBinding && !isComponent) { + patchFlag |= 2; + } + if (hasStyleBinding && !isComponent) { + patchFlag |= 4; + } + if (dynamicPropNames.length) { + patchFlag |= 8; + } + if (hasHydrationEventBinding) { + patchFlag |= 32; + } + } + if (!shouldUseBlock && (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) { + patchFlag |= 512; + } + if (!context.inSSR && propsExpression) { + switch (propsExpression.type) { + case 15: + let classKeyIndex = -1; + let styleKeyIndex = -1; + let hasDynamicKey = false; + for (let i = 0; i < propsExpression.properties.length; i++) { + const key = propsExpression.properties[i].key; + if (isStaticExp(key)) { + if (key.content === "class") { + classKeyIndex = i; + } else if (key.content === "style") { + styleKeyIndex = i; + } + } else if (!key.isHandlerKey) { + hasDynamicKey = true; + } + } + const classProp = propsExpression.properties[classKeyIndex]; + const styleProp = propsExpression.properties[styleKeyIndex]; + if (!hasDynamicKey) { + if (classProp && !isStaticExp(classProp.value)) { + classProp.value = createCallExpression( + context.helper(NORMALIZE_CLASS), + [classProp.value] + ); + } + if (styleProp && // the static style is compiled into an object, + // so use `hasStyleBinding` to ensure that it is a dynamic style binding + (hasStyleBinding || styleProp.value.type === 4 && styleProp.value.content.trim()[0] === `[` || // v-bind:style and style both exist, + // v-bind:style with static literal object + styleProp.value.type === 17)) { + styleProp.value = createCallExpression( + context.helper(NORMALIZE_STYLE), + [styleProp.value] + ); + } + } else { + propsExpression = createCallExpression( + context.helper(NORMALIZE_PROPS), + [propsExpression] + ); + } + break; + case 14: + break; + default: + propsExpression = createCallExpression( + context.helper(NORMALIZE_PROPS), + [ + createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [ + propsExpression + ]) + ] + ); + break; + } + } + return { + props: propsExpression, + directives: runtimeDirectives, + patchFlag, + dynamicPropNames, + shouldUseBlock + }; +} +function dedupeProperties(properties) { + const knownProps = /* @__PURE__ */ new Map(); + const deduped = []; + for (let i = 0; i < properties.length; i++) { + const prop = properties[i]; + if (prop.key.type === 8 || !prop.key.isStatic) { + deduped.push(prop); + continue; + } + const name = prop.key.content; + const existing = knownProps.get(name); + if (existing) { + if (name === "style" || name === "class" || isOn(name)) { + mergeAsArray(existing, prop); + } + } else { + knownProps.set(name, prop); + deduped.push(prop); + } + } + return deduped; +} +function mergeAsArray(existing, incoming) { + if (existing.value.type === 17) { + existing.value.elements.push(incoming.value); + } else { + existing.value = createArrayExpression( + [existing.value, incoming.value], + existing.loc + ); + } +} +function buildDirectiveArgs(dir, context) { + const dirArgs = []; + const runtime = directiveImportMap.get(dir); + if (runtime) { + dirArgs.push(context.helperString(runtime)); + } else { + const fromSetup = resolveSetupReference("v-" + dir.name, context); + if (fromSetup) { + dirArgs.push(fromSetup); + } else { + context.helper(RESOLVE_DIRECTIVE); + context.directives.add(dir.name); + dirArgs.push(toValidAssetId(dir.name, `directive`)); + } + } + const { loc } = dir; + if (dir.exp) + dirArgs.push(dir.exp); + if (dir.arg) { + if (!dir.exp) { + dirArgs.push(`void 0`); + } + dirArgs.push(dir.arg); + } + if (Object.keys(dir.modifiers).length) { + if (!dir.arg) { + if (!dir.exp) { + dirArgs.push(`void 0`); + } + dirArgs.push(`void 0`); + } + const trueExpression = createSimpleExpression(`true`, false, loc); + dirArgs.push( + createObjectExpression( + dir.modifiers.map( + (modifier) => createObjectProperty(modifier, trueExpression) + ), + loc + ) + ); + } + return createArrayExpression(dirArgs, dir.loc); +} +function stringifyDynamicPropNames(props) { + let propsNamesString = `[`; + for (let i = 0, l = props.length; i < l; i++) { + propsNamesString += JSON.stringify(props[i]); + if (i < l - 1) + propsNamesString += ", "; + } + return propsNamesString + `]`; +} +function isComponentTag(tag) { + return tag === "component" || tag === "Component"; +} + +const transformSlotOutlet = (node, context) => { + if (isSlotOutlet(node)) { + const { children, loc } = node; + const { slotName, slotProps } = processSlotOutlet(node, context); + const slotArgs = [ + context.prefixIdentifiers ? `_ctx.$slots` : `$slots`, + slotName, + "{}", + "undefined", + "true" + ]; + let expectedLen = 2; + if (slotProps) { + slotArgs[2] = slotProps; + expectedLen = 3; + } + if (children.length) { + slotArgs[3] = createFunctionExpression([], children, false, false, loc); + expectedLen = 4; + } + if (context.scopeId && !context.slotted) { + expectedLen = 5; + } + slotArgs.splice(expectedLen); + node.codegenNode = createCallExpression( + context.helper(RENDER_SLOT), + slotArgs, + loc + ); + } +}; +function processSlotOutlet(node, context) { + let slotName = `"default"`; + let slotProps = void 0; + const nonNameProps = []; + for (let i = 0; i < node.props.length; i++) { + const p = node.props[i]; + if (p.type === 6) { + if (p.value) { + if (p.name === "name") { + slotName = JSON.stringify(p.value.content); + } else { + p.name = camelize(p.name); + nonNameProps.push(p); + } + } + } else { + if (p.name === "bind" && isStaticArgOf(p.arg, "name")) { + if (p.exp) { + slotName = p.exp; + } else if (p.arg && p.arg.type === 4) { + const name = camelize(p.arg.content); + slotName = p.exp = createSimpleExpression(name, false, p.arg.loc); + { + slotName = p.exp = processExpression(p.exp, context); + } + } + } else { + if (p.name === "bind" && p.arg && isStaticExp(p.arg)) { + p.arg.content = camelize(p.arg.content); + } + nonNameProps.push(p); + } + } + } + if (nonNameProps.length > 0) { + const { props, directives } = buildProps( + node, + context, + nonNameProps, + false, + false + ); + slotProps = props; + if (directives.length) { + context.onError( + createCompilerError( + 36, + directives[0].loc + ) + ); + } + } + return { + slotName, + slotProps + }; +} + +const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/; +const transformOn$1 = (dir, node, context, augmentor) => { + const { loc, modifiers, arg } = dir; + if (!dir.exp && !modifiers.length) { + context.onError(createCompilerError(35, loc)); + } + let eventName; + if (arg.type === 4) { + if (arg.isStatic) { + let rawName = arg.content; + if (rawName.startsWith("vnode")) { + context.onError(createCompilerError(51, arg.loc)); + } + if (rawName.startsWith("vue:")) { + rawName = `vnode-${rawName.slice(4)}`; + } + const eventString = node.tagType !== 0 || rawName.startsWith("vnode") || !/[A-Z]/.test(rawName) ? ( + // for non-element and vnode lifecycle event listeners, auto convert + // it to camelCase. See issue #2249 + toHandlerKey(camelize(rawName)) + ) : ( + // preserve case for plain element listeners that have uppercase + // letters, as these may be custom elements' custom events + `on:${rawName}` + ); + eventName = createSimpleExpression(eventString, true, arg.loc); + } else { + eventName = createCompoundExpression([ + `${context.helperString(TO_HANDLER_KEY)}(`, + arg, + `)` + ]); + } + } else { + eventName = arg; + eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`); + eventName.children.push(`)`); + } + let exp = dir.exp; + if (exp && !exp.content.trim()) { + exp = void 0; + } + let shouldCache = context.cacheHandlers && !exp && !context.inVOnce; + if (exp) { + const isMemberExp = isMemberExpression(exp.content, context); + const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content)); + const hasMultipleStatements = exp.content.includes(`;`); + if (context.prefixIdentifiers) { + isInlineStatement && context.addIdentifiers(`$event`); + exp = dir.exp = processExpression( + exp, + context, + false, + hasMultipleStatements + ); + isInlineStatement && context.removeIdentifiers(`$event`); + shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once + !context.inVOnce && // runtime constants don't need to be cached + // (this is analyzed by compileScript in SFC <script setup>) + !(exp.type === 4 && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component - + // we need to use the original function to preserve arity, + // e.g. <transition> relies on checking cb.length to determine + // transition end handling. Inline function is ok since its arity + // is preserved even when cached. + !(isMemberExp && node.tagType === 1) && // bail if the function references closure variables (v-for, v-slot) + // it must be passed fresh to avoid stale values. + !hasScopeRef(exp, context.identifiers); + if (shouldCache && isMemberExp) { + if (exp.type === 4) { + exp.content = `${exp.content} && ${exp.content}(...args)`; + } else { + exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`]; + } + } + } + if (isInlineStatement || shouldCache && isMemberExp) { + exp = createCompoundExpression([ + `${isInlineStatement ? context.isTS ? `($event: any)` : `$event` : `${context.isTS ? ` +//@ts-ignore +` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`, + exp, + hasMultipleStatements ? `}` : `)` + ]); + } + } + let ret = { + props: [ + createObjectProperty( + eventName, + exp || createSimpleExpression(`() => {}`, false, loc) + ) + ] + }; + if (augmentor) { + ret = augmentor(ret); + } + if (shouldCache) { + ret.props[0].value = context.cache(ret.props[0].value); + } + ret.props.forEach((p) => p.key.isHandlerKey = true); + return ret; +}; + +const transformBind = (dir, _node, context) => { + const { modifiers, loc } = dir; + const arg = dir.arg; + let { exp } = dir; + if (exp && exp.type === 4 && !exp.content.trim()) { + { + context.onError( + createCompilerError(34, loc) + ); + return { + props: [ + createObjectProperty(arg, createSimpleExpression("", true, loc)) + ] + }; + } + } + if (!exp) { + if (arg.type !== 4 || !arg.isStatic) { + context.onError( + createCompilerError( + 52, + arg.loc + ) + ); + return { + props: [ + createObjectProperty(arg, createSimpleExpression("", true, loc)) + ] + }; + } + const propName = camelize(arg.content); + exp = dir.exp = createSimpleExpression(propName, false, arg.loc); + { + exp = dir.exp = processExpression(exp, context); + } + } + if (arg.type !== 4) { + arg.children.unshift(`(`); + arg.children.push(`) || ""`); + } else if (!arg.isStatic) { + arg.content = `${arg.content} || ""`; + } + if (modifiers.includes("camel")) { + if (arg.type === 4) { + if (arg.isStatic) { + arg.content = camelize(arg.content); + } else { + arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`; + } + } else { + arg.children.unshift(`${context.helperString(CAMELIZE)}(`); + arg.children.push(`)`); + } + } + if (!context.inSSR) { + if (modifiers.includes("prop")) { + injectPrefix(arg, "."); + } + if (modifiers.includes("attr")) { + injectPrefix(arg, "^"); + } + } + return { + props: [createObjectProperty(arg, exp)] + }; +}; +const injectPrefix = (arg, prefix) => { + if (arg.type === 4) { + if (arg.isStatic) { + arg.content = prefix + arg.content; + } else { + arg.content = `\`${prefix}\${${arg.content}}\``; + } + } else { + arg.children.unshift(`'${prefix}' + (`); + arg.children.push(`)`); + } +}; + +const transformText = (node, context) => { + if (node.type === 0 || node.type === 1 || node.type === 11 || node.type === 10) { + return () => { + const children = node.children; + let currentContainer = void 0; + let hasText = false; + for (let i = 0; i < children.length; i++) { + const child = children[i]; + if (isText$1(child)) { + hasText = true; + for (let j = i + 1; j < children.length; j++) { + const next = children[j]; + if (isText$1(next)) { + if (!currentContainer) { + currentContainer = children[i] = createCompoundExpression( + [child], + child.loc + ); + } + currentContainer.children.push(` + `, next); + children.splice(j, 1); + j--; + } else { + currentContainer = void 0; + break; + } + } + } + } + if (!hasText || // if this is a plain element with a single text child, leave it + // as-is since the runtime has dedicated fast path for this by directly + // setting textContent of the element. + // for component root it's always normalized anyway. + children.length === 1 && (node.type === 0 || node.type === 1 && node.tagType === 0 && // #3756 + // custom directives can potentially add DOM elements arbitrarily, + // we need to avoid setting textContent of the element at runtime + // to avoid accidentally overwriting the DOM elements added + // by the user through custom directives. + !node.props.find( + (p) => p.type === 7 && !context.directiveTransforms[p.name] + ) && // in compat mode, <template> tags with no special directives + // will be rendered as a fragment so its children must be + // converted into vnodes. + true)) { + return; + } + for (let i = 0; i < children.length; i++) { + const child = children[i]; + if (isText$1(child) || child.type === 8) { + const callArgs = []; + if (child.type !== 2 || child.content !== " ") { + callArgs.push(child); + } + if (!context.ssr && getConstantType(child, context) === 0) { + callArgs.push( + 1 + (` /* ${PatchFlagNames[1]} */` ) + ); + } + children[i] = { + type: 12, + content: child, + loc: child.loc, + codegenNode: createCallExpression( + context.helper(CREATE_TEXT), + callArgs + ) + }; + } + } + }; + } +}; + +const seen$1 = /* @__PURE__ */ new WeakSet(); +const transformOnce = (node, context) => { + if (node.type === 1 && findDir(node, "once", true)) { + if (seen$1.has(node) || context.inVOnce || context.inSSR) { + return; + } + seen$1.add(node); + context.inVOnce = true; + context.helper(SET_BLOCK_TRACKING); + return () => { + context.inVOnce = false; + const cur = context.currentNode; + if (cur.codegenNode) { + cur.codegenNode = context.cache( + cur.codegenNode, + true + /* isVNode */ + ); + } + }; + } +}; + +const transformModel$1 = (dir, node, context) => { + const { exp, arg } = dir; + if (!exp) { + context.onError( + createCompilerError(41, dir.loc) + ); + return createTransformProps(); + } + const rawExp = exp.loc.source; + const expString = exp.type === 4 ? exp.content : rawExp; + const bindingType = context.bindingMetadata[rawExp]; + if (bindingType === "props" || bindingType === "props-aliased") { + context.onError(createCompilerError(44, exp.loc)); + return createTransformProps(); + } + const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref"); + if (!expString.trim() || !isMemberExpression(expString, context) && !maybeRef) { + context.onError( + createCompilerError(42, exp.loc) + ); + return createTransformProps(); + } + if (context.prefixIdentifiers && isSimpleIdentifier(expString) && context.identifiers[expString]) { + context.onError( + createCompilerError(43, exp.loc) + ); + return createTransformProps(); + } + const propName = arg ? arg : createSimpleExpression("modelValue", true); + const eventName = arg ? isStaticExp(arg) ? `onUpdate:${camelize(arg.content)}` : createCompoundExpression(['"onUpdate:" + ', arg]) : `onUpdate:modelValue`; + let assignmentExp; + const eventArg = context.isTS ? `($event: any)` : `$event`; + if (maybeRef) { + if (bindingType === "setup-ref") { + assignmentExp = createCompoundExpression([ + `${eventArg} => ((`, + createSimpleExpression(rawExp, false, exp.loc), + `).value = $event)` + ]); + } else { + const altAssignment = bindingType === "setup-let" ? `${rawExp} = $event` : `null`; + assignmentExp = createCompoundExpression([ + `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`, + createSimpleExpression(rawExp, false, exp.loc), + `).value = $event : ${altAssignment})` + ]); + } + } else { + assignmentExp = createCompoundExpression([ + `${eventArg} => ((`, + exp, + `) = $event)` + ]); + } + const props = [ + // modelValue: foo + createObjectProperty(propName, dir.exp), + // "onUpdate:modelValue": $event => (foo = $event) + createObjectProperty(eventName, assignmentExp) + ]; + if (context.prefixIdentifiers && !context.inVOnce && context.cacheHandlers && !hasScopeRef(exp, context.identifiers)) { + props[1].value = context.cache(props[1].value); + } + if (dir.modifiers.length && node.tagType === 1) { + const modifiers = dir.modifiers.map((m) => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`).join(`, `); + const modifiersKey = arg ? isStaticExp(arg) ? `${arg.content}Modifiers` : createCompoundExpression([arg, ' + "Modifiers"']) : `modelModifiers`; + props.push( + createObjectProperty( + modifiersKey, + createSimpleExpression( + `{ ${modifiers} }`, + false, + dir.loc, + 2 + ) + ) + ); + } + return createTransformProps(props); +}; +function createTransformProps(props = []) { + return { props }; +} + +const seen = /* @__PURE__ */ new WeakSet(); +const transformMemo = (node, context) => { + if (node.type === 1) { + const dir = findDir(node, "memo"); + if (!dir || seen.has(node)) { + return; + } + seen.add(node); + return () => { + const codegenNode = node.codegenNode || context.currentNode.codegenNode; + if (codegenNode && codegenNode.type === 13) { + if (node.tagType !== 1) { + convertToBlock(codegenNode, context); + } + node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [ + dir.exp, + createFunctionExpression(void 0, codegenNode), + `_cache`, + String(context.cached++) + ]); + } + }; + } +}; + +function getBaseTransformPreset(prefixIdentifiers) { + return [ + [ + transformOnce, + transformIf, + transformMemo, + transformFor, + ...[], + ...prefixIdentifiers ? [ + // order is important + trackVForSlotScopes, + transformExpression + ] : [], + transformSlotOutlet, + transformElement, + trackSlotScopes, + transformText + ], + { + on: transformOn$1, + bind: transformBind, + model: transformModel$1 + } + ]; +} +function baseCompile(source, options = {}) { + const onError = options.onError || defaultOnError; + const isModuleMode = options.mode === "module"; + const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode; + if (!prefixIdentifiers && options.cacheHandlers) { + onError(createCompilerError(49)); + } + if (options.scopeId && !isModuleMode) { + onError(createCompilerError(50)); + } + const resolvedOptions = extend({}, options, { + prefixIdentifiers + }); + const ast = isString$2(source) ? baseParse(source, resolvedOptions) : source; + const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers); + if (options.isTS) { + const { expressionPlugins } = options; + if (!expressionPlugins || !expressionPlugins.includes("typescript")) { + options.expressionPlugins = [...expressionPlugins || [], "typescript"]; + } + } + transform( + ast, + extend({}, resolvedOptions, { + nodeTransforms: [ + ...nodeTransforms, + ...options.nodeTransforms || [] + // user transforms + ], + directiveTransforms: extend( + {}, + directiveTransforms, + options.directiveTransforms || {} + // user transforms + ) + }) + ); + return generate(ast, resolvedOptions); +} + +const BindingTypes = { + "DATA": "data", + "PROPS": "props", + "PROPS_ALIASED": "props-aliased", + "SETUP_LET": "setup-let", + "SETUP_CONST": "setup-const", + "SETUP_REACTIVE_CONST": "setup-reactive-const", + "SETUP_MAYBE_REF": "setup-maybe-ref", + "SETUP_REF": "setup-ref", + "OPTIONS": "options", + "LITERAL_CONST": "literal-const" +}; + +const noopDirectiveTransform = () => ({ props: [] }); + +const V_MODEL_RADIO = Symbol(`vModelRadio` ); +const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` ); +const V_MODEL_TEXT = Symbol(`vModelText` ); +const V_MODEL_SELECT = Symbol(`vModelSelect` ); +const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` ); +const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` ); +const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` ); +const V_SHOW = Symbol(`vShow` ); +const TRANSITION = Symbol(`Transition` ); +const TRANSITION_GROUP = Symbol(`TransitionGroup` ); +registerRuntimeHelpers({ + [V_MODEL_RADIO]: `vModelRadio`, + [V_MODEL_CHECKBOX]: `vModelCheckbox`, + [V_MODEL_TEXT]: `vModelText`, + [V_MODEL_SELECT]: `vModelSelect`, + [V_MODEL_DYNAMIC]: `vModelDynamic`, + [V_ON_WITH_MODIFIERS]: `withModifiers`, + [V_ON_WITH_KEYS]: `withKeys`, + [V_SHOW]: `vShow`, + [TRANSITION]: `Transition`, + [TRANSITION_GROUP]: `TransitionGroup` +}); + +const parserOptions = { + parseMode: "html", + isVoidTag, + isNativeTag: (tag) => isHTMLTag(tag) || isSVGTag(tag) || isMathMLTag(tag), + isPreTag: (tag) => tag === "pre", + decodeEntities: void 0, + isBuiltInComponent: (tag) => { + if (tag === "Transition" || tag === "transition") { + return TRANSITION; + } else if (tag === "TransitionGroup" || tag === "transition-group") { + return TRANSITION_GROUP; + } + }, + // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher + getNamespace(tag, parent, rootNamespace) { + let ns = parent ? parent.ns : rootNamespace; + if (parent && ns === 2) { + if (parent.tag === "annotation-xml") { + if (tag === "svg") { + return 1; + } + if (parent.props.some( + (a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml") + )) { + ns = 0; + } + } else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") { + ns = 0; + } + } else if (parent && ns === 1) { + if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") { + ns = 0; + } + } + if (ns === 0) { + if (tag === "svg") { + return 1; + } + if (tag === "math") { + return 2; + } + } + return ns; + } +}; + +const transformStyle = (node) => { + if (node.type === 1) { + node.props.forEach((p, i) => { + if (p.type === 6 && p.name === "style" && p.value) { + node.props[i] = { + type: 7, + name: `bind`, + arg: createSimpleExpression(`style`, true, p.loc), + exp: parseInlineCSS(p.value.content, p.loc), + modifiers: [], + loc: p.loc + }; + } + }); + } +}; +const parseInlineCSS = (cssText, loc) => { + const normalized = parseStringStyle(cssText); + return createSimpleExpression( + JSON.stringify(normalized), + false, + loc, + 3 + ); +}; + +function createDOMCompilerError(code, loc) { + return createCompilerError( + code, + loc, + DOMErrorMessages + ); +} +const DOMErrorCodes = { + "X_V_HTML_NO_EXPRESSION": 53, + "53": "X_V_HTML_NO_EXPRESSION", + "X_V_HTML_WITH_CHILDREN": 54, + "54": "X_V_HTML_WITH_CHILDREN", + "X_V_TEXT_NO_EXPRESSION": 55, + "55": "X_V_TEXT_NO_EXPRESSION", + "X_V_TEXT_WITH_CHILDREN": 56, + "56": "X_V_TEXT_WITH_CHILDREN", + "X_V_MODEL_ON_INVALID_ELEMENT": 57, + "57": "X_V_MODEL_ON_INVALID_ELEMENT", + "X_V_MODEL_ARG_ON_ELEMENT": 58, + "58": "X_V_MODEL_ARG_ON_ELEMENT", + "X_V_MODEL_ON_FILE_INPUT_ELEMENT": 59, + "59": "X_V_MODEL_ON_FILE_INPUT_ELEMENT", + "X_V_MODEL_UNNECESSARY_VALUE": 60, + "60": "X_V_MODEL_UNNECESSARY_VALUE", + "X_V_SHOW_NO_EXPRESSION": 61, + "61": "X_V_SHOW_NO_EXPRESSION", + "X_TRANSITION_INVALID_CHILDREN": 62, + "62": "X_TRANSITION_INVALID_CHILDREN", + "X_IGNORED_SIDE_EFFECT_TAG": 63, + "63": "X_IGNORED_SIDE_EFFECT_TAG", + "__EXTEND_POINT__": 64, + "64": "__EXTEND_POINT__" +}; +const DOMErrorMessages = { + [53]: `v-html is missing expression.`, + [54]: `v-html will override element children.`, + [55]: `v-text is missing expression.`, + [56]: `v-text will override element children.`, + [57]: `v-model can only be used on <input>, <textarea> and <select> elements.`, + [58]: `v-model argument is not supported on plain elements.`, + [59]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`, + [60]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`, + [61]: `v-show is missing expression.`, + [62]: `<Transition> expects exactly one child element or component.`, + [63]: `Tags with side effect (<script> and <style>) are ignored in client component templates.` +}; + +const transformVHtml = (dir, node, context) => { + const { exp, loc } = dir; + if (!exp) { + context.onError( + createDOMCompilerError(53, loc) + ); + } + if (node.children.length) { + context.onError( + createDOMCompilerError(54, loc) + ); + node.children.length = 0; + } + return { + props: [ + createObjectProperty( + createSimpleExpression(`innerHTML`, true, loc), + exp || createSimpleExpression("", true) + ) + ] + }; +}; + +const transformVText = (dir, node, context) => { + const { exp, loc } = dir; + if (!exp) { + context.onError( + createDOMCompilerError(55, loc) + ); + } + if (node.children.length) { + context.onError( + createDOMCompilerError(56, loc) + ); + node.children.length = 0; + } + return { + props: [ + createObjectProperty( + createSimpleExpression(`textContent`, true), + exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression( + context.helperString(TO_DISPLAY_STRING), + [exp], + loc + ) : createSimpleExpression("", true) + ) + ] + }; +}; + +const transformModel = (dir, node, context) => { + const baseResult = transformModel$1(dir, node, context); + if (!baseResult.props.length || node.tagType === 1) { + return baseResult; + } + if (dir.arg) { + context.onError( + createDOMCompilerError( + 58, + dir.arg.loc + ) + ); + } + function checkDuplicatedValue() { + const value = findDir(node, "bind"); + if (value && isStaticArgOf(value.arg, "value")) { + context.onError( + createDOMCompilerError( + 60, + value.loc + ) + ); + } + } + const { tag } = node; + const isCustomElement = context.isCustomElement(tag); + if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) { + let directiveToUse = V_MODEL_TEXT; + let isInvalidType = false; + if (tag === "input" || isCustomElement) { + const type = findProp(node, `type`); + if (type) { + if (type.type === 7) { + directiveToUse = V_MODEL_DYNAMIC; + } else if (type.value) { + switch (type.value.content) { + case "radio": + directiveToUse = V_MODEL_RADIO; + break; + case "checkbox": + directiveToUse = V_MODEL_CHECKBOX; + break; + case "file": + isInvalidType = true; + context.onError( + createDOMCompilerError( + 59, + dir.loc + ) + ); + break; + default: + checkDuplicatedValue(); + break; + } + } + } else if (hasDynamicKeyVBind(node)) { + directiveToUse = V_MODEL_DYNAMIC; + } else { + checkDuplicatedValue(); + } + } else if (tag === "select") { + directiveToUse = V_MODEL_SELECT; + } else { + checkDuplicatedValue(); + } + if (!isInvalidType) { + baseResult.needRuntime = context.helper(directiveToUse); + } + } else { + context.onError( + createDOMCompilerError( + 57, + dir.loc + ) + ); + } + baseResult.props = baseResult.props.filter( + (p) => !(p.key.type === 4 && p.key.content === "modelValue") + ); + return baseResult; +}; + +const isEventOptionModifier = /* @__PURE__ */ makeMap(`passive,once,capture`); +const isNonKeyModifier = /* @__PURE__ */ makeMap( + // event propagation management + `stop,prevent,self,ctrl,shift,alt,meta,exact,middle` +); +const maybeKeyModifier = /* @__PURE__ */ makeMap("left,right"); +const isKeyboardEvent = /* @__PURE__ */ makeMap( + `onkeyup,onkeydown,onkeypress`, + true +); +const resolveModifiers = (key, modifiers, context, loc) => { + const keyModifiers = []; + const nonKeyModifiers = []; + const eventOptionModifiers = []; + for (let i = 0; i < modifiers.length; i++) { + const modifier = modifiers[i]; + if (isEventOptionModifier(modifier)) { + eventOptionModifiers.push(modifier); + } else { + if (maybeKeyModifier(modifier)) { + if (isStaticExp(key)) { + if (isKeyboardEvent(key.content)) { + keyModifiers.push(modifier); + } else { + nonKeyModifiers.push(modifier); + } + } else { + keyModifiers.push(modifier); + nonKeyModifiers.push(modifier); + } + } else { + if (isNonKeyModifier(modifier)) { + nonKeyModifiers.push(modifier); + } else { + keyModifiers.push(modifier); + } + } + } + } + return { + keyModifiers, + nonKeyModifiers, + eventOptionModifiers + }; +}; +const transformClick = (key, event) => { + const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === "onclick"; + return isStaticClick ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([ + `(`, + key, + `) === "onClick" ? "${event}" : (`, + key, + `)` + ]) : key; +}; +const transformOn = (dir, node, context) => { + return transformOn$1(dir, node, context, (baseResult) => { + const { modifiers } = dir; + if (!modifiers.length) + return baseResult; + let { key, value: handlerExp } = baseResult.props[0]; + const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc); + if (nonKeyModifiers.includes("right")) { + key = transformClick(key, `onContextmenu`); + } + if (nonKeyModifiers.includes("middle")) { + key = transformClick(key, `onMouseup`); + } + if (nonKeyModifiers.length) { + handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [ + handlerExp, + JSON.stringify(nonKeyModifiers) + ]); + } + if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard + (!isStaticExp(key) || isKeyboardEvent(key.content))) { + handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [ + handlerExp, + JSON.stringify(keyModifiers) + ]); + } + if (eventOptionModifiers.length) { + const modifierPostfix = eventOptionModifiers.map(capitalize$1).join(""); + key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]); + } + return { + props: [createObjectProperty(key, handlerExp)] + }; + }); +}; + +const transformShow = (dir, node, context) => { + const { exp, loc } = dir; + if (!exp) { + context.onError( + createDOMCompilerError(61, loc) + ); + } + return { + props: [], + needRuntime: context.helper(V_SHOW) + }; +}; + +const transformTransition = (node, context) => { + if (node.type === 1 && node.tagType === 1) { + const component = context.isBuiltInComponent(node.tag); + if (component === TRANSITION) { + return () => { + if (!node.children.length) { + return; + } + if (hasMultipleChildren(node)) { + context.onError( + createDOMCompilerError( + 62, + { + start: node.children[0].loc.start, + end: node.children[node.children.length - 1].loc.end, + source: "" + } + ) + ); + } + const child = node.children[0]; + if (child.type === 1) { + for (const p of child.props) { + if (p.type === 7 && p.name === "show") { + node.props.push({ + type: 6, + name: "persisted", + nameLoc: node.loc, + value: void 0, + loc: node.loc + }); + } + } + } + }; + } + } +}; +function hasMultipleChildren(node) { + const children = node.children = node.children.filter( + (c) => c.type !== 3 && !(c.type === 2 && !c.content.trim()) + ); + const child = children[0]; + return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren); +} + +const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g; +const stringifyStatic = (children, context, parent) => { + if (context.scopes.vSlot > 0) { + return; + } + let nc = 0; + let ec = 0; + const currentChunk = []; + const stringifyCurrentChunk = (currentIndex) => { + if (nc >= 20 || ec >= 5) { + const staticCall = createCallExpression(context.helper(CREATE_STATIC), [ + JSON.stringify( + currentChunk.map((node) => stringifyNode(node, context)).join("") + ).replace(expReplaceRE, `" + $1 + "`), + // the 2nd argument indicates the number of DOM nodes this static vnode + // will insert / hydrate + String(currentChunk.length) + ]); + replaceHoist(currentChunk[0], staticCall, context); + if (currentChunk.length > 1) { + for (let i2 = 1; i2 < currentChunk.length; i2++) { + replaceHoist(currentChunk[i2], null, context); + } + const deleteCount = currentChunk.length - 1; + children.splice(currentIndex - currentChunk.length + 1, deleteCount); + return deleteCount; + } + } + return 0; + }; + let i = 0; + for (; i < children.length; i++) { + const child = children[i]; + const hoisted = getHoistedNode(child); + if (hoisted) { + const node = child; + const result = analyzeNode(node); + if (result) { + nc += result[0]; + ec += result[1]; + currentChunk.push(node); + continue; + } + } + i -= stringifyCurrentChunk(i); + nc = 0; + ec = 0; + currentChunk.length = 0; + } + stringifyCurrentChunk(i); +}; +const getHoistedNode = (node) => (node.type === 1 && node.tagType === 0 || node.type == 12) && node.codegenNode && node.codegenNode.type === 4 && node.codegenNode.hoisted; +const dataAriaRE = /^(data|aria)-/; +const isStringifiableAttr = (name, ns) => { + return (ns === 0 ? isKnownHtmlAttr(name) : ns === 1 ? isKnownSvgAttr(name) : false) || dataAriaRE.test(name); +}; +const replaceHoist = (node, replacement, context) => { + const hoistToReplace = node.codegenNode.hoisted; + context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement; +}; +const isNonStringifiable = /* @__PURE__ */ makeMap( + `caption,thead,tr,th,tbody,td,tfoot,colgroup,col` +); +function analyzeNode(node) { + if (node.type === 1 && isNonStringifiable(node.tag)) { + return false; + } + if (node.type === 12) { + return [1, 0]; + } + let nc = 1; + let ec = node.props.length > 0 ? 1 : 0; + let bailed = false; + const bail = () => { + bailed = true; + return false; + }; + function walk(node2) { + for (let i = 0; i < node2.props.length; i++) { + const p = node2.props[i]; + if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) { + return bail(); + } + if (p.type === 7 && p.name === "bind") { + if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) { + return bail(); + } + if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) { + return bail(); + } + } + } + for (let i = 0; i < node2.children.length; i++) { + nc++; + const child = node2.children[i]; + if (child.type === 1) { + if (child.props.length > 0) { + ec++; + } + walk(child); + if (bailed) { + return false; + } + } + } + return true; + } + return walk(node) ? [nc, ec] : false; +} +function stringifyNode(node, context) { + if (isString$2(node)) { + return node; + } + if (isSymbol$1(node)) { + return ``; + } + switch (node.type) { + case 1: + return stringifyElement(node, context); + case 2: + return escapeHtml(node.content); + case 3: + return `<!--${escapeHtml(node.content)}-->`; + case 5: + return escapeHtml(toDisplayString(evaluateConstant(node.content))); + case 8: + return escapeHtml(evaluateConstant(node)); + case 12: + return stringifyNode(node.content, context); + default: + return ""; + } +} +function stringifyElement(node, context) { + let res = `<${node.tag}`; + let innerHTML = ""; + for (let i = 0; i < node.props.length; i++) { + const p = node.props[i]; + if (p.type === 6) { + res += ` ${p.name}`; + if (p.value) { + res += `="${escapeHtml(p.value.content)}"`; + } + } else if (p.type === 7) { + if (p.name === "bind") { + const exp = p.exp; + if (exp.content[0] === "_") { + res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`; + continue; + } + if (isBooleanAttr(p.arg.content) && exp.content === "false") { + continue; + } + let evaluated = evaluateConstant(exp); + if (evaluated != null) { + const arg = p.arg && p.arg.content; + if (arg === "class") { + evaluated = normalizeClass(evaluated); + } else if (arg === "style") { + evaluated = stringifyStyle(normalizeStyle(evaluated)); + } + res += ` ${p.arg.content}="${escapeHtml( + evaluated + )}"`; + } + } else if (p.name === "html") { + innerHTML = evaluateConstant(p.exp); + } else if (p.name === "text") { + innerHTML = escapeHtml( + toDisplayString(evaluateConstant(p.exp)) + ); + } + } + } + if (context.scopeId) { + res += ` ${context.scopeId}`; + } + res += `>`; + if (innerHTML) { + res += innerHTML; + } else { + for (let i = 0; i < node.children.length; i++) { + res += stringifyNode(node.children[i], context); + } + } + if (!isVoidTag(node.tag)) { + res += `</${node.tag}>`; + } + return res; +} +function evaluateConstant(exp) { + if (exp.type === 4) { + return new Function(`return (${exp.content})`)(); + } else { + let res = ``; + exp.children.forEach((c) => { + if (isString$2(c) || isSymbol$1(c)) { + return; + } + if (c.type === 2) { + res += c.content; + } else if (c.type === 5) { + res += toDisplayString(evaluateConstant(c.content)); + } else { + res += evaluateConstant(c); + } + }); + return res; + } +} + +const ignoreSideEffectTags = (node, context) => { + if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) { + context.onError( + createDOMCompilerError( + 63, + node.loc + ) + ); + context.removeNode(); + } +}; + +const DOMNodeTransforms = [ + transformStyle, + ...[transformTransition] +]; +const DOMDirectiveTransforms = { + cloak: noopDirectiveTransform, + html: transformVHtml, + text: transformVText, + model: transformModel, + // override compiler-core + on: transformOn, + // override compiler-core + show: transformShow +}; +function compile$1(src, options = {}) { + return baseCompile( + src, + extend({}, parserOptions, options, { + nodeTransforms: [ + // ignore <script> and <tag> + // this is not put inside DOMNodeTransforms because that list is used + // by compiler-ssr to generate vnode fallback branches + ignoreSideEffectTags, + ...DOMNodeTransforms, + ...options.nodeTransforms || [] + ], + directiveTransforms: extend( + {}, + DOMDirectiveTransforms, + options.directiveTransforms || {} + ), + transformHoist: stringifyStatic + }) + ); +} +function parse$8(template, options = {}) { + return baseParse(template, extend({}, parserOptions, options)); +} + +var CompilerDOM = /*#__PURE__*/Object.freeze({ + __proto__: null, + BASE_TRANSITION: BASE_TRANSITION, + BindingTypes: BindingTypes, + CAMELIZE: CAMELIZE, + CAPITALIZE: CAPITALIZE, + CREATE_BLOCK: CREATE_BLOCK, + CREATE_COMMENT: CREATE_COMMENT, + CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK, + CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE, + CREATE_SLOTS: CREATE_SLOTS, + CREATE_STATIC: CREATE_STATIC, + CREATE_TEXT: CREATE_TEXT, + CREATE_VNODE: CREATE_VNODE, + CompilerDeprecationTypes: CompilerDeprecationTypes, + ConstantTypes: ConstantTypes, + DOMDirectiveTransforms: DOMDirectiveTransforms, + DOMErrorCodes: DOMErrorCodes, + DOMErrorMessages: DOMErrorMessages, + DOMNodeTransforms: DOMNodeTransforms, + ElementTypes: ElementTypes, + ErrorCodes: ErrorCodes, + FRAGMENT: FRAGMENT, + GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS, + IS_MEMO_SAME: IS_MEMO_SAME, + IS_REF: IS_REF, + KEEP_ALIVE: KEEP_ALIVE, + MERGE_PROPS: MERGE_PROPS, + NORMALIZE_CLASS: NORMALIZE_CLASS, + NORMALIZE_PROPS: NORMALIZE_PROPS, + NORMALIZE_STYLE: NORMALIZE_STYLE, + Namespaces: Namespaces, + NodeTypes: NodeTypes, + OPEN_BLOCK: OPEN_BLOCK, + POP_SCOPE_ID: POP_SCOPE_ID, + PUSH_SCOPE_ID: PUSH_SCOPE_ID, + RENDER_LIST: RENDER_LIST, + RENDER_SLOT: RENDER_SLOT, + RESOLVE_COMPONENT: RESOLVE_COMPONENT, + RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE, + RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT, + RESOLVE_FILTER: RESOLVE_FILTER, + SET_BLOCK_TRACKING: SET_BLOCK_TRACKING, + SUSPENSE: SUSPENSE, + TELEPORT: TELEPORT, + TO_DISPLAY_STRING: TO_DISPLAY_STRING, + TO_HANDLERS: TO_HANDLERS, + TO_HANDLER_KEY: TO_HANDLER_KEY, + TRANSITION: TRANSITION, + TRANSITION_GROUP: TRANSITION_GROUP, + TS_NODE_TYPES: TS_NODE_TYPES, + UNREF: UNREF, + V_MODEL_CHECKBOX: V_MODEL_CHECKBOX, + V_MODEL_DYNAMIC: V_MODEL_DYNAMIC, + V_MODEL_RADIO: V_MODEL_RADIO, + V_MODEL_SELECT: V_MODEL_SELECT, + V_MODEL_TEXT: V_MODEL_TEXT, + V_ON_WITH_KEYS: V_ON_WITH_KEYS, + V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS, + V_SHOW: V_SHOW, + WITH_CTX: WITH_CTX, + WITH_DIRECTIVES: WITH_DIRECTIVES, + WITH_MEMO: WITH_MEMO, + advancePositionWithClone: advancePositionWithClone, + advancePositionWithMutation: advancePositionWithMutation, + assert: assert, + baseCompile: baseCompile, + baseParse: baseParse, + buildDirectiveArgs: buildDirectiveArgs, + buildProps: buildProps, + buildSlots: buildSlots, + checkCompatEnabled: checkCompatEnabled, + compile: compile$1, + convertToBlock: convertToBlock, + createArrayExpression: createArrayExpression, + createAssignmentExpression: createAssignmentExpression, + createBlockStatement: createBlockStatement, + createCacheExpression: createCacheExpression, + createCallExpression: createCallExpression, + createCompilerError: createCompilerError, + createCompoundExpression: createCompoundExpression, + createConditionalExpression: createConditionalExpression, + createDOMCompilerError: createDOMCompilerError, + createForLoopParams: createForLoopParams, + createFunctionExpression: createFunctionExpression, + createIfStatement: createIfStatement, + createInterpolation: createInterpolation, + createObjectExpression: createObjectExpression, + createObjectProperty: createObjectProperty, + createReturnStatement: createReturnStatement, + createRoot: createRoot, + createSequenceExpression: createSequenceExpression, + createSimpleExpression: createSimpleExpression, + createStructuralDirectiveTransform: createStructuralDirectiveTransform, + createTemplateLiteral: createTemplateLiteral, + createTransformContext: createTransformContext, + createVNodeCall: createVNodeCall, + errorMessages: errorMessages$1, + extractIdentifiers: extractIdentifiers$1, + findDir: findDir, + findProp: findProp, + forAliasRE: forAliasRE, + generate: generate, + generateCodeFrame: generateCodeFrame, + getBaseTransformPreset: getBaseTransformPreset, + getConstantType: getConstantType, + getMemoedVNodeCall: getMemoedVNodeCall, + getVNodeBlockHelper: getVNodeBlockHelper, + getVNodeHelper: getVNodeHelper, + hasDynamicKeyVBind: hasDynamicKeyVBind, + hasScopeRef: hasScopeRef, + helperNameMap: helperNameMap, + injectProp: injectProp, + isCoreComponent: isCoreComponent, + isFunctionType: isFunctionType, + isInDestructureAssignment: isInDestructureAssignment, + isInNewExpression: isInNewExpression, + isMemberExpression: isMemberExpression, + isMemberExpressionBrowser: isMemberExpressionBrowser, + isMemberExpressionNode: isMemberExpressionNode, + isReferencedIdentifier: isReferencedIdentifier, + isSimpleIdentifier: isSimpleIdentifier, + isSlotOutlet: isSlotOutlet, + isStaticArgOf: isStaticArgOf, + isStaticExp: isStaticExp, + isStaticProperty: isStaticProperty, + isStaticPropertyKey: isStaticPropertyKey, + isTemplateNode: isTemplateNode, + isText: isText$1, + isVSlot: isVSlot, + locStub: locStub, + noopDirectiveTransform: noopDirectiveTransform, + parse: parse$8, + parserOptions: parserOptions, + processExpression: processExpression, + processFor: processFor, + processIf: processIf, + processSlotOutlet: processSlotOutlet, + registerRuntimeHelpers: registerRuntimeHelpers, + resolveComponentType: resolveComponentType, + stringifyExpression: stringifyExpression, + toValidAssetId: toValidAssetId, + trackSlotScopes: trackSlotScopes, + trackVForSlotScopes: trackVForSlotScopes, + transform: transform, + transformBind: transformBind, + transformElement: transformElement, + transformExpression: transformExpression, + transformModel: transformModel$1, + transformOn: transformOn$1, + transformStyle: transformStyle, + traverseNode: traverseNode, + unwrapTSNode: unwrapTSNode, + walkBlockDeclarations: walkBlockDeclarations, + walkFunctionParams: walkFunctionParams, + walkIdentifiers: walkIdentifiers, + warnDeprecation: warnDeprecation +}); + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +function resolve$2() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : '/'; + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +} +// path.normalize(path) +// posix version +function normalize$1(path) { + var isPathAbsolute = isAbsolute$1(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isPathAbsolute).join('/'); + + if (!path && !isPathAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isPathAbsolute ? '/' : '') + path; +} +// posix version +function isAbsolute$1(path) { + return path.charAt(0) === '/'; +} + +// posix version +function join$1() { + var paths = Array.prototype.slice.call(arguments, 0); + return normalize$1(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +} + + +// path.relative(from, to) +// posix version +function relative$1(from, to) { + from = resolve$2(from).substr(1); + to = resolve$2(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +} + +var sep$1 = '/'; +var delimiter$1 = ':'; + +function dirname$2(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +} + +function basename(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +} + + +function extname(path) { + return splitPath(path)[3]; +} +var path = { + extname: extname, + basename: basename, + dirname: dirname$2, + sep: sep$1, + delimiter: delimiter$1, + relative: relative$1, + join: join$1, + isAbsolute: isAbsolute$1, + normalize: normalize$1, + resolve: resolve$2 +}; +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' ? + function (str, start, len) { return str.substr(start, len) } : + function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +var _polyfillNode_path = /*#__PURE__*/Object.freeze({ + __proto__: null, + basename: basename, + default: path, + delimiter: delimiter$1, + dirname: dirname$2, + extname: extname, + isAbsolute: isAbsolute$1, + join: join$1, + normalize: normalize$1, + relative: relative$1, + resolve: resolve$2, + sep: sep$1 +}); + +const UNKNOWN_TYPE = "Unknown"; +function resolveObjectKey(node, computed) { + switch (node.type) { + case "StringLiteral": + case "NumericLiteral": + return String(node.value); + case "Identifier": + if (!computed) + return node.name; + } + return void 0; +} +function concatStrings(strs) { + return strs.filter((s) => !!s).join(", "); +} +function isLiteralNode(node) { + return node.type.endsWith("Literal"); +} +function isCallOf(node, test) { + return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name))); +} +function toRuntimeTypeString(types) { + return types.length > 1 ? `[${types.join(", ")}]` : types[0]; +} +function getImportedName(specifier) { + if (specifier.type === "ImportSpecifier") + return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value; + else if (specifier.type === "ImportNamespaceSpecifier") + return "*"; + return "default"; +} +function getId(node) { + return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null; +} +const normalize = (path.posix || path).normalize; +const windowsSlashRE = /\\/g; +function normalizePath(p) { + return normalize(p.replace(windowsSlashRE, "/")); +} +const joinPaths = (path.posix || path).join; +const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/; +function getEscapedPropName(key) { + return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key; +} +const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g; +function getEscapedCssVarName(key, doubleEscape) { + return key.replace( + cssVarNameEscapeSymbolsRE, + (s) => doubleEscape ? `\\\\${s}` : `\\${s}` + ); +} + +function pad$1 (hash, len) { + while (hash.length < len) { + hash = '0' + hash; + } + return hash; +} + +function fold (hash, text) { + var i; + var chr; + var len; + if (text.length === 0) { + return hash; + } + for (i = 0, len = text.length; i < len; i++) { + chr = text.charCodeAt(i); + hash = ((hash << 5) - hash) + chr; + hash |= 0; + } + return hash < 0 ? hash * -2 : hash; +} + +function foldObject (hash, o, seen) { + return Object.keys(o).sort().reduce(foldKey, hash); + function foldKey (hash, key) { + return foldValue(hash, o[key], key, seen); + } +} + +function foldValue (input, value, key, seen) { + var hash = fold(fold(fold(input, key), toString$2(value)), typeof value); + if (value === null) { + return fold(hash, 'null'); + } + if (value === undefined) { + return fold(hash, 'undefined'); + } + if (typeof value === 'object' || typeof value === 'function') { + if (seen.indexOf(value) !== -1) { + return fold(hash, '[Circular]' + key); + } + seen.push(value); + + var objHash = foldObject(hash, value, seen); + + if (!('valueOf' in value) || typeof value.valueOf !== 'function') { + return objHash; + } + + try { + return fold(objHash, String(value.valueOf())) + } catch (err) { + return fold(objHash, '[valueOf exception]' + (err.stack || err.message)) + } + } + return fold(hash, value.toString()); +} + +function toString$2 (o) { + return Object.prototype.toString.call(o); +} + +function sum (o) { + return pad$1(foldValue(0, o, '', []).toString(16), 8); +} + +var hashSum = sum; + +var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSum); + +const CSS_VARS_HELPER = `useCssVars`; +function genCssVarsFromList(vars, id, isProd, isSSR = false) { + return `{ + ${vars.map( + (key) => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})` + ).join(",\n ")} +}`; +} +function genVarName(id, raw, isProd, isSSR = false) { + if (isProd) { + return hash(id + raw); + } else { + return `${id}-${getEscapedCssVarName(raw, isSSR)}`; + } +} +function normalizeExpression(exp) { + exp = exp.trim(); + if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) { + return exp.slice(1, -1); + } + return exp; +} +const vBindRE = /v-bind\s*\(/g; +function parseCssVars(sfc) { + const vars = []; + sfc.styles.forEach((style) => { + let match; + const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, ""); + while (match = vBindRE.exec(content)) { + const start = match.index + match[0].length; + const end = lexBinding(content, start); + if (end !== null) { + const variable = normalizeExpression(content.slice(start, end)); + if (!vars.includes(variable)) { + vars.push(variable); + } + } + } + }); + return vars; +} +function lexBinding(content, start) { + let state = 0 /* inParens */; + let parenDepth = 0; + for (let i = start; i < content.length; i++) { + const char = content.charAt(i); + switch (state) { + case 0 /* inParens */: + if (char === `'`) { + state = 1 /* inSingleQuoteString */; + } else if (char === `"`) { + state = 2 /* inDoubleQuoteString */; + } else if (char === `(`) { + parenDepth++; + } else if (char === `)`) { + if (parenDepth > 0) { + parenDepth--; + } else { + return i; + } + } + break; + case 1 /* inSingleQuoteString */: + if (char === `'`) { + state = 0 /* inParens */; + } + break; + case 2 /* inDoubleQuoteString */: + if (char === `"`) { + state = 0 /* inParens */; + } + break; + } + } + return null; +} +const cssVarsPlugin = (opts) => { + const { id, isProd } = opts; + return { + postcssPlugin: "vue-sfc-vars", + Declaration(decl) { + const value = decl.value; + if (vBindRE.test(value)) { + vBindRE.lastIndex = 0; + let transformed = ""; + let lastIndex = 0; + let match; + while (match = vBindRE.exec(value)) { + const start = match.index + match[0].length; + const end = lexBinding(value, start); + if (end !== null) { + const variable = normalizeExpression(value.slice(start, end)); + transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`; + lastIndex = end + 1; + } + } + decl.value = transformed + value.slice(lastIndex); + } + } + }; +}; +cssVarsPlugin.postcss = true; +function genCssVarsCode(vars, bindings, id, isProd) { + const varsExp = genCssVarsFromList(vars, id, isProd); + const exp = createSimpleExpression(varsExp, false); + const context = createTransformContext(createRoot([]), { + prefixIdentifiers: true, + inline: true, + bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings + }); + const transformed = processExpression(exp, context); + const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => { + return typeof c === "string" ? c : c.content; + }).join(""); + return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`; +} +function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) { + return ` +import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue' +const __injectCSSVars__ = () => { +${genCssVarsCode( + cssVars, + bindings, + id, + isProd + )}} +const __setup__ = ${defaultVar}.setup +${defaultVar}.setup = __setup__ + ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) } + : __injectCSSVars__ +`; +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version$1 = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var browser$1 = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version$1, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +function createCache(max = 500) { + { + return /* @__PURE__ */ new Map(); + } +} + +function isImportUsed(local, sfc) { + return resolveTemplateUsedIdentifiers(sfc).has(local); +} +const templateUsageCheckCache = createCache(); +function resolveTemplateUsedIdentifiers(sfc) { + const { content, ast } = sfc.template; + const cached = templateUsageCheckCache.get(content); + if (cached) { + return cached; + } + const ids = /* @__PURE__ */ new Set(); + ast.children.forEach(walk); + function walk(node) { + var _a; + switch (node.type) { + case 1: + let tag = node.tag; + if (tag.includes(".")) + tag = tag.split(".")[0].trim(); + if (!parserOptions.isNativeTag(tag) && !parserOptions.isBuiltInComponent(tag)) { + ids.add(camelize(tag)); + ids.add(capitalize$1(camelize(tag))); + } + for (let i = 0; i < node.props.length; i++) { + const prop = node.props[i]; + if (prop.type === 7) { + if (!isBuiltInDirective(prop.name)) { + ids.add(`v${capitalize$1(camelize(prop.name))}`); + } + if (prop.arg && !prop.arg.isStatic) { + extractIdentifiers(ids, prop.arg); + } + if (prop.name === "for") { + extractIdentifiers(ids, prop.forParseResult.source); + } else if (prop.exp) { + extractIdentifiers(ids, prop.exp); + } + } + if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) { + ids.add(prop.value.content); + } + } + node.children.forEach(walk); + break; + case 5: + extractIdentifiers(ids, node.content); + break; + } + } + templateUsageCheckCache.set(content, ids); + return ids; +} +function extractIdentifiers(ids, node) { + if (node.ast) { + walkIdentifiers(node.ast, (n) => ids.add(n.name)); + } else if (node.ast === null) { + ids.add(node.content); + } +} + +var __defProp$a = Object.defineProperty; +var __defProps$9 = Object.defineProperties; +var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$a = Object.getOwnPropertySymbols; +var __hasOwnProp$a = Object.prototype.hasOwnProperty; +var __propIsEnum$a = Object.prototype.propertyIsEnumerable; +var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$a = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$a.call(b, prop)) + __defNormalProp$a(a, prop, b[prop]); + if (__getOwnPropSymbols$a) + for (var prop of __getOwnPropSymbols$a(b)) { + if (__propIsEnum$a.call(b, prop)) + __defNormalProp$a(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b)); +const DEFAULT_FILENAME = "anonymous.vue"; +const parseCache$1 = createCache(); +function genCacheKey(source, options) { + var _a; + return source + JSON.stringify( + __spreadProps$9(__spreadValues$a({}, options), { + compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse } + }), + (_, val) => typeof val === "function" ? val.toString() : val + ); +} +function parse$7(source, options = {}) { + const sourceKey = genCacheKey(source, options); + const cache = parseCache$1.get(sourceKey); + if (cache) { + return cache; + } + const { + sourceMap = true, + filename = DEFAULT_FILENAME, + sourceRoot = "", + pad = false, + ignoreEmpty = true, + compiler = CompilerDOM, + templateParseOptions = {}, + parseExpressions = true + } = options; + const descriptor = { + filename, + source, + template: null, + script: null, + scriptSetup: null, + styles: [], + customBlocks: [], + cssVars: [], + slotted: false, + shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor) + }; + const errors = []; + const ast = compiler.parse(source, __spreadProps$9(__spreadValues$a({ + parseMode: "sfc", + prefixIdentifiers: parseExpressions + }, templateParseOptions), { + onError: (e) => { + errors.push(e); + } + })); + ast.children.forEach((node) => { + if (node.type !== 1) { + return; + } + if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) { + return; + } + switch (node.tag) { + case "template": + if (!descriptor.template) { + const templateBlock = descriptor.template = createBlock( + node, + source, + false + ); + if (!templateBlock.attrs.src) { + templateBlock.ast = createRoot(node.children, source); + } + if (templateBlock.attrs.functional) { + const err = new SyntaxError( + `<template functional> is no longer supported in Vue 3, since functional components no longer have significant performance difference from stateful ones. Just use a normal <template> instead.` + ); + err.loc = node.props.find( + (p) => p.type === 6 && p.name === "functional" + ).loc; + errors.push(err); + } + } else { + errors.push(createDuplicateBlockError(node)); + } + break; + case "script": + const scriptBlock = createBlock(node, source, pad); + const isSetup = !!scriptBlock.attrs.setup; + if (isSetup && !descriptor.scriptSetup) { + descriptor.scriptSetup = scriptBlock; + break; + } + if (!isSetup && !descriptor.script) { + descriptor.script = scriptBlock; + break; + } + errors.push(createDuplicateBlockError(node, isSetup)); + break; + case "style": + const styleBlock = createBlock(node, source, pad); + if (styleBlock.attrs.vars) { + errors.push( + new SyntaxError( + `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231` + ) + ); + } + descriptor.styles.push(styleBlock); + break; + default: + descriptor.customBlocks.push(createBlock(node, source, pad)); + break; + } + }); + if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) { + errors.push( + new SyntaxError( + `At least one <template> or <script> is required in a single file component.` + ) + ); + } + if (descriptor.scriptSetup) { + if (descriptor.scriptSetup.src) { + errors.push( + new SyntaxError( + `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.` + ) + ); + descriptor.scriptSetup = null; + } + if (descriptor.script && descriptor.script.src) { + errors.push( + new SyntaxError( + `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.` + ) + ); + descriptor.script = null; + } + } + let templateColumnOffset = 0; + if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) { + [descriptor.template.content, templateColumnOffset] = dedent( + descriptor.template.content + ); + } + if (sourceMap) { + const genMap = (block, columnOffset = 0) => { + if (block && !block.src) { + block.map = generateSourceMap( + filename, + source, + block.content, + sourceRoot, + !pad || block.type === "template" ? block.loc.start.line - 1 : 0, + columnOffset + ); + } + }; + genMap(descriptor.template, templateColumnOffset); + genMap(descriptor.script); + descriptor.styles.forEach((s) => genMap(s)); + descriptor.customBlocks.forEach((s) => genMap(s)); + } + descriptor.cssVars = parseCssVars(descriptor); + const slottedRE = /(?:::v-|:)slotted\(/; + descriptor.slotted = descriptor.styles.some( + (s) => s.scoped && slottedRE.test(s.content) + ); + const result = { + descriptor, + errors + }; + parseCache$1.set(sourceKey, result); + return result; +} +function createDuplicateBlockError(node, isScriptSetup = false) { + const err = new SyntaxError( + `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element` + ); + err.loc = node.loc; + return err; +} +function createBlock(node, source, pad) { + const type = node.tag; + const loc = node.innerLoc; + const attrs = {}; + const block = { + type, + content: source.slice(loc.start.offset, loc.end.offset), + loc, + attrs + }; + if (pad) { + block.content = padContent(source, block, pad) + block.content; + } + node.props.forEach((p) => { + if (p.type === 6) { + const name = p.name; + attrs[name] = p.value ? p.value.content || true : true; + if (name === "lang") { + block.lang = p.value && p.value.content; + } else if (name === "src") { + block.src = p.value && p.value.content; + } else if (type === "style") { + if (name === "scoped") { + block.scoped = true; + } else if (name === "module") { + block.module = attrs[name]; + } + } else if (type === "script" && name === "setup") { + block.setup = attrs.setup; + } + } + }); + return block; +} +const splitRE = /\r?\n/g; +const emptyRE = /^(?:\/\/)?\s*$/; +const replaceRE = /./g; +function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) { + const map = new SourceMapGenerator$6({ + file: filename.replace(/\\/g, "/"), + sourceRoot: sourceRoot.replace(/\\/g, "/") + }); + map.setSourceContent(filename, source); + map._sources.add(filename); + generated.split(splitRE).forEach((line, index) => { + if (!emptyRE.test(line)) { + const originalLine = index + 1 + lineOffset; + const generatedLine = index + 1; + for (let i = 0; i < line.length; i++) { + if (!/\s/.test(line[i])) { + map._mappings.add({ + originalLine, + originalColumn: i + columnOffset, + generatedLine, + generatedColumn: i, + source: filename, + // @ts-expect-error + name: null + }); + } + } + } + }); + return map.toJSON(); +} +function padContent(content, block, pad) { + content = content.slice(0, block.loc.start.offset); + if (pad === "space") { + return content.replace(replaceRE, " "); + } else { + const offset = content.split(splitRE).length; + const padChar = block.type === "script" && !block.lang ? "//\n" : "\n"; + return Array(offset).join(padChar); + } +} +function hasSrc(node) { + return node.props.some((p) => { + if (p.type !== 6) { + return false; + } + return p.name === "src"; + }); +} +function isEmpty(node) { + for (let i = 0; i < node.children.length; i++) { + const child = node.children[i]; + if (child.type !== 2 || child.content.trim() !== "") { + return false; + } + } + return true; +} +function hmrShouldReload(prevImports, next) { + if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") { + return false; + } + for (const key in prevImports) { + if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) { + return true; + } + } + return false; +} +function dedent(s) { + const lines = s.split("\n"); + const minIndent = lines.reduce(function(minIndent2, line) { + var _a, _b; + if (line.trim() === "") { + return minIndent2; + } + const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0; + return Math.min(indent, minIndent2); + }, Infinity); + if (minIndent === 0) { + return [s, minIndent]; + } + return [ + lines.map(function(line) { + return line.slice(minIndent); + }).join("\n"), + minIndent + ]; +} + +/*! https://mths.be/punycode v1.4.1 by @mathias */ + + +/** Highest positive signed 32-bit float value */ +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' +var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map$1(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map$1(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see <https://mathiasbynens.be/notes/javascript-encoding> + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +} + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +} + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +function encode$1(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */ ; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +} + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) ? + 'xn--' + encode$1(string) : + string; + }); +} + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString$1 = {}.toString; + +var isArray$2 = Array.isArray || function (arr) { + return toString$1.call(arr) == '[object Array]'; +}; + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> + * @license MIT + */ +/* eslint-disable no-proto */ + + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer$1.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$1(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer$1 (arg, encodingOrOffset, length) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { + return new Buffer$1(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer$1.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer$1._augment = function (arr) { + arr.__proto__ = Buffer$1.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer$1.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer$1.TYPED_ARRAY_SUPPORT) { + Buffer$1.prototype.__proto__ = Uint8Array.prototype; + Buffer$1.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer$1[Symbol.species] === Buffer$1) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer$1.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer$1.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer$1.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer$1.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$2(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer$1.isBuffer = isBuffer$1; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer$1.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer$1.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer$1.concat = function concat (list, length) { + if (!isArray$2(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer$1.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer$1.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer$1.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer$1.prototype._isBuffer = true; + +function swap$1 (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer$1.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap$1(this, i, i + 1); + } + return this +}; + +Buffer$1.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap$1(this, i, i + 3); + swap$1(this, i + 1, i + 2); + } + return this +}; + +Buffer$1.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap$1(this, i, i + 7); + swap$1(this, i + 1, i + 6); + swap$1(this, i + 2, i + 5); + swap$1(this, i + 3, i + 4); + } + return this +}; + +Buffer$1.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer$1.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$1.compare(this, b) === 0 +}; + +Buffer$1.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '<Buffer ' + str + '>' +}; + +Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer$1.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer$1.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer$1.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer$1.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer$1.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$1.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$1(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer$1.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer$1(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +function format$1(f) { + if (!isString$1(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject$1(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (browser$1.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (browser$1.throwDeprecation) { + throw new Error(msg); + } else if (browser$1.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = browser$1.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format$1.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString$1(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray$1(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString$1(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty$2(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty$2(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray$1(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString$1(arg) { + return typeof arg === 'string'; +} + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject$1(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject$1(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject$1(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject$1(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer(maybeBuf) { + return Buffer$1.isBuffer(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format$1.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject$1(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty$2(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +promisify.custom = kCustomPromisifiedSymbol; + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { browser$1.nextTick(cb.bind(null, null, ret)); }, + function(rej) { browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); + return callbackified; +} + +var _polyfillNode_util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject$1, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString$1, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray$1, + inspect: inspect, + deprecate: deprecate, + format: format$1, + debuglog: debuglog, + promisify: promisify, + callbackify: callbackify, +}; + +var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + _extend: _extend, + callbackify: callbackify, + debuglog: debuglog, + default: _polyfillNode_util, + deprecate: deprecate, + format: format$1, + inherits: inherits$1, + inspect: inspect, + isArray: isArray$1, + isBoolean: isBoolean, + isBuffer: isBuffer, + isDate: isDate, + isError: isError, + isFunction: isFunction, + isNull: isNull, + isNullOrUndefined: isNullOrUndefined, + isNumber: isNumber, + isObject: isObject$1, + isPrimitive: isPrimitive, + isRegExp: isRegExp, + isString: isString$1, + isSymbol: isSymbol, + isUndefined: isUndefined, + log: log, + promisify: promisify +}); + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty$1(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; +function stringifyPrimitive(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +} + +function stringify$5 (obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +} +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +function parse$6(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty$1(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +} + +// WHATWG API +const URL$1 = global$1.URL; +const URLSearchParams = global$1.URLSearchParams; +var _polyfillNode_url = { + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject, + fileURLToPath: urlFileURLToPath, + format: urlFormat, + Url: Url, + + // WHATWG API + URL: URL$1, + URLSearchParams, +}; +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject$1(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + return parse$5(this, url, parseQueryString, slashesDenoteHost); +}; + +function parse$5(self, url, parseQueryString, slashesDenoteHost) { + if (!isString$1(url)) { + throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + self.path = rest; + self.href = rest; + self.pathname = simplePath[1]; + if (simplePath[2]) { + self.search = simplePath[2]; + if (parseQueryString) { + self.query = parse$6(self.search.substr(1)); + } else { + self.query = self.search.substr(1); + } + } else if (parseQueryString) { + self.search = ''; + self.query = {}; + } + return self; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + self.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + self.slashes = true; + } + } + var i, hec, l, p; + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + self.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + self.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + parseHost(self); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + self.hostname = self.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = self.hostname[0] === '[' && + self.hostname[self.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = self.hostname.split(/\./); + for (i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + self.hostname = validParts.join('.'); + break; + } + } + } + } + + if (self.hostname.length > hostnameMaxLen) { + self.hostname = ''; + } else { + // hostnames are always lower case. + self.hostname = self.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + self.hostname = toASCII(self.hostname); + } + + p = self.port ? ':' + self.port : ''; + var h = self.hostname || ''; + self.host = h + p; + self.href += self.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + self.hostname = self.hostname.substr(1, self.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + self.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + self.search = rest.substr(qm); + self.query = rest.substr(qm + 1); + if (parseQueryString) { + self.query = parse$6(self.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + self.search = ''; + self.query = {}; + } + if (rest) self.pathname = rest; + if (slashedProtocol[lowerProto] && + self.hostname && !self.pathname) { + self.pathname = '/'; + } + + //to support http.request + if (self.pathname || self.search) { + p = self.pathname || ''; + var s = self.search || ''; + self.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + self.href = format(self); + return self; +} + +function urlFileURLToPath(path) { + if (typeof path === 'string') + path = new Url().parse(path); + else if (!(path instanceof Url)) + throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path)); + if (path.protocol !== 'file:') + throw new TypeError('The URL must be of scheme file'); + return getPathFromURLPosix(path); +} + +function getPathFromURLPosix(url) { + const pathname = url.pathname; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === '%') { + const third = pathname.codePointAt(n + 2) | 0x20; + if (pathname[n + 1] === '2' && third === 102) { + throw new TypeError( + 'must not include encoded / characters' + ); + } + } + } + return decodeURIComponent(pathname); +} + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (isString$1(obj)) obj = parse$5({}, obj); + return format(obj); +} + +function format(self) { + var auth = self.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = self.protocol || '', + pathname = self.pathname || '', + hash = self.hash || '', + host = false, + query = ''; + + if (self.host) { + host = auth + self.host; + } else if (self.hostname) { + host = auth + (self.hostname.indexOf(':') === -1 ? + self.hostname : + '[' + this.hostname + ']'); + if (self.port) { + host += ':' + self.port; + } + } + + if (self.query && + isObject$1(self.query) && + Object.keys(self.query).length) { + query = stringify$5(self.query); + } + + var search = self.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (self.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +} + +Url.prototype.format = function() { + return format(this); +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (isString$1(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + var relPath; + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + relPath = relative.pathname && relative.pathname.split('/') || []; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + var authInHost; + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + return parseHost(this); +}; + +function parseHost(self) { + var host = self.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + self.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) self.hostname = host; +} + +var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + URL: URL$1, + URLSearchParams: URLSearchParams, + Url: Url, + default: _polyfillNode_url, + fileURLToPath: urlFileURLToPath, + format: urlFormat, + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject +}); + +function isRelativeUrl(url) { + const firstChar = url.charAt(0); + return firstChar === "." || firstChar === "~" || firstChar === "@"; +} +const externalRE = /^(https?:)?\/\//; +function isExternalUrl(url) { + return externalRE.test(url); +} +const dataUrlRE = /^\s*data:/i; +function isDataUrl(url) { + return dataUrlRE.test(url); +} +function parseUrl(url) { + const firstChar = url.charAt(0); + if (firstChar === "~") { + const secondChar = url.charAt(1); + url = url.slice(secondChar === "/" ? 2 : 1); + } + return parseUriParts(url); +} +function parseUriParts(urlString) { + return urlParse(isString$2(urlString) ? urlString : "", false, true); +} + +var __defProp$9 = Object.defineProperty; +var __defProps$8 = Object.defineProperties; +var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols; +var __hasOwnProp$9 = Object.prototype.hasOwnProperty; +var __propIsEnum$9 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$9 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$9.call(b, prop)) + __defNormalProp$9(a, prop, b[prop]); + if (__getOwnPropSymbols$9) + for (var prop of __getOwnPropSymbols$9(b)) { + if (__propIsEnum$9.call(b, prop)) + __defNormalProp$9(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b)); +const defaultAssetUrlOptions = { + base: null, + includeAbsolute: false, + tags: { + video: ["src", "poster"], + source: ["src"], + img: ["src"], + image: ["xlink:href", "href"], + use: ["xlink:href", "href"] + } +}; +const normalizeOptions = (options) => { + if (Object.keys(options).some((key) => isArray$3(options[key]))) { + return __spreadProps$8(__spreadValues$9({}, defaultAssetUrlOptions), { + tags: options + }); + } + return __spreadValues$9(__spreadValues$9({}, defaultAssetUrlOptions), options); +}; +const createAssetUrlTransformWithOptions = (options) => { + return (node, context) => transformAssetUrl(node, context, options); +}; +const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => { + if (node.type === 1) { + if (!node.props.length) { + return; + } + const tags = options.tags || defaultAssetUrlOptions.tags; + const attrs = tags[node.tag]; + const wildCardAttrs = tags["*"]; + if (!attrs && !wildCardAttrs) { + return; + } + const assetAttrs = (attrs || []).concat(wildCardAttrs || []); + node.props.forEach((attr, index) => { + if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value || isExternalUrl(attr.value.content) || isDataUrl(attr.value.content) || attr.value.content[0] === "#" || !options.includeAbsolute && !isRelativeUrl(attr.value.content)) { + return; + } + const url = parseUrl(attr.value.content); + if (options.base && attr.value.content[0] === ".") { + const base = parseUrl(options.base); + const protocol = base.protocol || ""; + const host = base.host ? protocol + "//" + base.host : ""; + const basePath = base.path || "/"; + attr.value.content = host + (path.posix || path).join(basePath, url.path + (url.hash || "")); + return; + } + const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context); + node.props[index] = { + type: 7, + name: "bind", + arg: createSimpleExpression(attr.name, true, attr.loc), + exp, + modifiers: [], + loc: attr.loc + }; + }); + } +}; +function getImportsExpressionExp(path2, hash, loc, context) { + if (path2) { + let name; + let exp; + const existingIndex = context.imports.findIndex((i) => i.path === path2); + if (existingIndex > -1) { + name = `_imports_${existingIndex}`; + exp = context.imports[existingIndex].exp; + } else { + name = `_imports_${context.imports.length}`; + exp = createSimpleExpression( + name, + false, + loc, + 3 + ); + context.imports.push({ + exp, + path: decodeURIComponent(path2) + }); + } + if (!hash) { + return exp; + } + const hashExp = `${name} + '${hash}'`; + const finalExp = createSimpleExpression( + hashExp, + false, + loc, + 3 + ); + if (!context.hoistStatic) { + return finalExp; + } + const existingHoistIndex = context.hoists.findIndex((h) => { + return h && h.type === 4 && !h.isStatic && h.content === hashExp; + }); + if (existingHoistIndex > -1) { + return createSimpleExpression( + `_hoisted_${existingHoistIndex + 1}`, + false, + loc, + 3 + ); + } + return context.hoist(finalExp); + } else { + return createSimpleExpression(`''`, false, loc, 3); + } +} + +const srcsetTags = ["img", "source"]; +const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; +const createSrcsetTransformWithOptions = (options) => { + return (node, context) => transformSrcset(node, context, options); +}; +const transformSrcset = (node, context, options = defaultAssetUrlOptions) => { + if (node.type === 1) { + if (srcsetTags.includes(node.tag) && node.props.length) { + node.props.forEach((attr, index) => { + if (attr.name === "srcset" && attr.type === 6) { + if (!attr.value) + return; + const value = attr.value.content; + if (!value) + return; + const imageCandidates = value.split(",").map((s) => { + const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2); + return { url, descriptor }; + }); + for (let i = 0; i < imageCandidates.length; i++) { + const { url } = imageCandidates[i]; + if (isDataUrl(url)) { + imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url; + imageCandidates.splice(i, 1); + } + } + const shouldProcessUrl = (url) => { + return !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url)); + }; + if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) { + return; + } + if (options.base) { + const base = options.base; + const set = []; + let needImportTransform = false; + imageCandidates.forEach((candidate) => { + let { url, descriptor } = candidate; + descriptor = descriptor ? ` ${descriptor}` : ``; + if (url[0] === ".") { + candidate.url = (path.posix || path).join(base, url); + set.push(candidate.url + descriptor); + } else if (shouldProcessUrl(url)) { + needImportTransform = true; + } else { + set.push(url + descriptor); + } + }); + if (!needImportTransform) { + attr.value.content = set.join(", "); + return; + } + } + const compoundExpression = createCompoundExpression([], attr.loc); + imageCandidates.forEach(({ url, descriptor }, index2) => { + if (shouldProcessUrl(url)) { + const { path: path2 } = parseUrl(url); + let exp2; + if (path2) { + const existingImportsIndex = context.imports.findIndex( + (i) => i.path === path2 + ); + if (existingImportsIndex > -1) { + exp2 = createSimpleExpression( + `_imports_${existingImportsIndex}`, + false, + attr.loc, + 3 + ); + } else { + exp2 = createSimpleExpression( + `_imports_${context.imports.length}`, + false, + attr.loc, + 3 + ); + context.imports.push({ exp: exp2, path: path2 }); + } + compoundExpression.children.push(exp2); + } + } else { + const exp2 = createSimpleExpression( + `"${url}"`, + false, + attr.loc, + 3 + ); + compoundExpression.children.push(exp2); + } + const isNotLast = imageCandidates.length - 1 > index2; + if (descriptor && isNotLast) { + compoundExpression.children.push(` + ' ${descriptor}, ' + `); + } else if (descriptor) { + compoundExpression.children.push(` + ' ${descriptor}'`); + } else if (isNotLast) { + compoundExpression.children.push(` + ', ' + `); + } + }); + let exp = compoundExpression; + if (context.hoistStatic) { + exp = context.hoist(compoundExpression); + exp.constType = 3; + } + node.props[index] = { + type: 7, + name: "bind", + arg: createSimpleExpression("srcset", true, attr.loc), + exp, + modifiers: [], + loc: attr.loc + }; + } + }); + } + } +}; + +const SSR_INTERPOLATE = Symbol(`ssrInterpolate`); +const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`); +const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`); +const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`); +const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`); +const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`); +const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`); +const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`); +const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`); +const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`); +const SSR_RENDER_LIST = Symbol(`ssrRenderList`); +const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`); +const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`); +const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`); +const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`); +const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`); +const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`); +const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`); +const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`); +const ssrHelpers = { + [SSR_INTERPOLATE]: `ssrInterpolate`, + [SSR_RENDER_VNODE]: `ssrRenderVNode`, + [SSR_RENDER_COMPONENT]: `ssrRenderComponent`, + [SSR_RENDER_SLOT]: `ssrRenderSlot`, + [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`, + [SSR_RENDER_CLASS]: `ssrRenderClass`, + [SSR_RENDER_STYLE]: `ssrRenderStyle`, + [SSR_RENDER_ATTRS]: `ssrRenderAttrs`, + [SSR_RENDER_ATTR]: `ssrRenderAttr`, + [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`, + [SSR_RENDER_LIST]: `ssrRenderList`, + [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`, + [SSR_LOOSE_EQUAL]: `ssrLooseEqual`, + [SSR_LOOSE_CONTAIN]: `ssrLooseContain`, + [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`, + [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`, + [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`, + [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`, + [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps` +}; +registerRuntimeHelpers(ssrHelpers); + +const ssrTransformIf = createStructuralDirectiveTransform( + /^(if|else|else-if)$/, + processIf +); +function ssrProcessIf(node, context, disableNestedFragments = false) { + const [rootBranch] = node.branches; + const ifStatement = createIfStatement( + rootBranch.condition, + processIfBranch(rootBranch, context, disableNestedFragments) + ); + context.pushStatement(ifStatement); + let currentIf = ifStatement; + for (let i = 1; i < node.branches.length; i++) { + const branch = node.branches[i]; + const branchBlockStatement = processIfBranch( + branch, + context, + disableNestedFragments + ); + if (branch.condition) { + currentIf = currentIf.alternate = createIfStatement( + branch.condition, + branchBlockStatement + ); + } else { + currentIf.alternate = branchBlockStatement; + } + } + if (!currentIf.alternate) { + currentIf.alternate = createBlockStatement([ + createCallExpression(`_push`, ["`<!---->`"]) + ]); + } +} +function processIfBranch(branch, context, disableNestedFragments = false) { + const { children } = branch; + const needFragmentWrapper = !disableNestedFragments && (children.length !== 1 || children[0].type !== 1) && // optimize away nested fragments when the only child is a ForNode + !(children.length === 1 && children[0].type === 11); + return processChildrenAsStatement(branch, context, needFragmentWrapper); +} + +const ssrTransformFor = createStructuralDirectiveTransform( + "for", + processFor +); +function ssrProcessFor(node, context, disableNestedFragments = false) { + const needFragmentWrapper = !disableNestedFragments && (node.children.length !== 1 || node.children[0].type !== 1); + const renderLoop = createFunctionExpression( + createForLoopParams(node.parseResult) + ); + renderLoop.body = processChildrenAsStatement( + node, + context, + needFragmentWrapper + ); + if (!disableNestedFragments) { + context.pushStringPart(`<!--[-->`); + } + context.pushStatement( + createCallExpression(context.helper(SSR_RENDER_LIST), [ + node.source, + renderLoop + ]) + ); + if (!disableNestedFragments) { + context.pushStringPart(`<!--]-->`); + } +} + +const ssrTransformSlotOutlet = (node, context) => { + if (isSlotOutlet(node)) { + const { slotName, slotProps } = processSlotOutlet(node, context); + const args = [ + `_ctx.$slots`, + slotName, + slotProps || `{}`, + // fallback content placeholder. will be replaced in the process phase + `null`, + `_push`, + `_parent` + ]; + if (context.scopeId && context.slotted !== false) { + args.push(`"${context.scopeId}-s"`); + } + let method = SSR_RENDER_SLOT; + const parent = context.parent; + let componentType; + if (parent && parent.type === 1 && parent.tagType === 1 && ((componentType = resolveComponentType(parent, context, true)) === TRANSITION || componentType === TRANSITION_GROUP) && parent.children.filter((c) => c.type === 1).length === 1) { + method = SSR_RENDER_SLOT_INNER; + if (!(context.scopeId && context.slotted !== false)) { + args.push("null"); + } + args.push("true"); + } + node.ssrCodegenNode = createCallExpression(context.helper(method), args); + } +}; +function ssrProcessSlotOutlet(node, context) { + const renderCall = node.ssrCodegenNode; + if (node.children.length) { + const fallbackRenderFn = createFunctionExpression([]); + fallbackRenderFn.body = processChildrenAsStatement(node, context); + renderCall.arguments[3] = fallbackRenderFn; + } + if (context.withSlotScopeId) { + const slotScopeId = renderCall.arguments[6]; + renderCall.arguments[6] = slotScopeId ? `${slotScopeId} + _scopeId` : `_scopeId`; + } + context.pushStatement(node.ssrCodegenNode); +} + +function createSSRCompilerError(code, loc) { + return createCompilerError(code, loc, SSRErrorMessages); +} +const SSRErrorMessages = { + [65]: `Unsafe attribute name for SSR.`, + [66]: `Missing the 'to' prop on teleport element.`, + [67]: `Invalid AST node during SSR transform.` +}; + +function ssrProcessTeleport(node, context) { + const targetProp = findProp(node, "to"); + if (!targetProp) { + context.onError( + createSSRCompilerError(66, node.loc) + ); + return; + } + let target; + if (targetProp.type === 6) { + target = targetProp.value && createSimpleExpression(targetProp.value.content, true); + } else { + target = targetProp.exp; + } + if (!target) { + context.onError( + createSSRCompilerError( + 66, + targetProp.loc + ) + ); + return; + } + const disabledProp = findProp( + node, + "disabled", + false, + true + /* allow empty */ + ); + const disabled = disabledProp ? disabledProp.type === 6 ? `true` : disabledProp.exp || `false` : `false`; + const contentRenderFn = createFunctionExpression( + [`_push`], + void 0, + // Body is added later + true, + // newline + false, + // isSlot + node.loc + ); + contentRenderFn.body = processChildrenAsStatement(node, context); + context.pushStatement( + createCallExpression(context.helper(SSR_RENDER_TELEPORT), [ + `_push`, + contentRenderFn, + target, + disabled, + `_parent` + ]) + ); +} + +const wipMap$3 = /* @__PURE__ */ new WeakMap(); +function ssrTransformSuspense(node, context) { + return () => { + if (node.children.length) { + const wipEntry = { + slotsExp: null, + // to be immediately set + wipSlots: [] + }; + wipMap$3.set(node, wipEntry); + wipEntry.slotsExp = buildSlots( + node, + context, + (_props, _vForExp, children, loc) => { + const fn = createFunctionExpression( + [], + void 0, + // no return, assign body later + true, + // newline + false, + // suspense slots are not treated as normal slots + loc + ); + wipEntry.wipSlots.push({ + fn, + children + }); + return fn; + } + ).slots; + } + }; +} +function ssrProcessSuspense(node, context) { + const wipEntry = wipMap$3.get(node); + if (!wipEntry) { + return; + } + const { slotsExp, wipSlots } = wipEntry; + for (let i = 0; i < wipSlots.length; i++) { + const slot = wipSlots[i]; + slot.fn.body = processChildrenAsStatement(slot, context); + } + context.pushStatement( + createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [ + `_push`, + slotsExp + ]) + ); +} + +const rawChildrenMap = /* @__PURE__ */ new WeakMap(); +const ssrTransformElement = (node, context) => { + if (node.type !== 1 || node.tagType !== 0) { + return; + } + return function ssrPostTransformElement() { + const openTag = [`<${node.tag}`]; + const needTagForRuntime = node.tag === "textarea" || node.tag.indexOf("-") > 0; + const hasDynamicVBind = hasDynamicKeyVBind(node); + const hasCustomDir = node.props.some( + (p) => p.type === 7 && !isBuiltInDirective(p.name) + ); + const needMergeProps = hasDynamicVBind || hasCustomDir; + if (needMergeProps) { + const { props, directives } = buildProps( + node, + context, + node.props, + false, + false, + true + ); + if (props || directives.length) { + const mergedProps = buildSSRProps(props, directives, context); + const propsExp = createCallExpression( + context.helper(SSR_RENDER_ATTRS), + [mergedProps] + ); + if (node.tag === "textarea") { + const existingText = node.children[0]; + if (!existingText || existingText.type !== 5) { + const tempId = `_temp${context.temps++}`; + propsExp.arguments = [ + createAssignmentExpression( + createSimpleExpression(tempId, false), + mergedProps + ) + ]; + rawChildrenMap.set( + node, + createCallExpression(context.helper(SSR_INTERPOLATE), [ + createConditionalExpression( + createSimpleExpression(`"value" in ${tempId}`, false), + createSimpleExpression(`${tempId}.value`, false), + createSimpleExpression( + existingText ? existingText.content : ``, + true + ), + false + ) + ]) + ); + } + } else if (node.tag === "input") { + const vModel = findVModel(node); + if (vModel) { + const tempId = `_temp${context.temps++}`; + const tempExp = createSimpleExpression(tempId, false); + propsExp.arguments = [ + createSequenceExpression([ + createAssignmentExpression(tempExp, mergedProps), + createCallExpression(context.helper(MERGE_PROPS), [ + tempExp, + createCallExpression( + context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), + [ + tempExp, + // existing props + vModel.exp + // model + ] + ) + ]) + ]) + ]; + } + } + if (needTagForRuntime) { + propsExp.arguments.push(`"${node.tag}"`); + } + openTag.push(propsExp); + } + } + let dynamicClassBinding = void 0; + let staticClassBinding = void 0; + let dynamicStyleBinding = void 0; + for (let i = 0; i < node.props.length; i++) { + const prop = node.props[i]; + if (node.tag === "input" && isTrueFalseValue(prop)) { + continue; + } + if (prop.type === 7) { + if (prop.name === "html" && prop.exp) { + rawChildrenMap.set(node, prop.exp); + } else if (prop.name === "text" && prop.exp) { + node.children = [createInterpolation(prop.exp, prop.loc)]; + } else if (prop.name === "slot") { + context.onError( + createCompilerError(40, prop.loc) + ); + } else if (isTextareaWithValue(node, prop) && prop.exp) { + if (!needMergeProps) { + node.children = [createInterpolation(prop.exp, prop.loc)]; + } + } else if (!needMergeProps && prop.name !== "on") { + const directiveTransform = context.directiveTransforms[prop.name]; + if (directiveTransform) { + const { props, ssrTagParts } = directiveTransform( + prop, + node, + context + ); + if (ssrTagParts) { + openTag.push(...ssrTagParts); + } + for (let j = 0; j < props.length; j++) { + const { key, value } = props[j]; + if (isStaticExp(key)) { + let attrName = key.content; + if (attrName === "key" || attrName === "ref") { + continue; + } + if (attrName === "class") { + openTag.push( + ` class="`, + dynamicClassBinding = createCallExpression( + context.helper(SSR_RENDER_CLASS), + [value] + ), + `"` + ); + } else if (attrName === "style") { + if (dynamicStyleBinding) { + mergeCall(dynamicStyleBinding, value); + } else { + openTag.push( + ` style="`, + dynamicStyleBinding = createCallExpression( + context.helper(SSR_RENDER_STYLE), + [value] + ), + `"` + ); + } + } else { + attrName = node.tag.indexOf("-") > 0 ? attrName : propsToAttrMap[attrName] || attrName.toLowerCase(); + if (isBooleanAttr(attrName)) { + openTag.push( + createConditionalExpression( + createCallExpression( + context.helper(SSR_INCLUDE_BOOLEAN_ATTR), + [value] + ), + createSimpleExpression(" " + attrName, true), + createSimpleExpression("", true), + false + ) + ); + } else if (isSSRSafeAttrName(attrName)) { + openTag.push( + createCallExpression(context.helper(SSR_RENDER_ATTR), [ + key, + value + ]) + ); + } else { + context.onError( + createSSRCompilerError( + 65, + key.loc + ) + ); + } + } + } else { + const args = [key, value]; + if (needTagForRuntime) { + args.push(`"${node.tag}"`); + } + openTag.push( + createCallExpression( + context.helper(SSR_RENDER_DYNAMIC_ATTR), + args + ) + ); + } + } + } + } + } else { + const name = prop.name; + if (node.tag === "textarea" && name === "value" && prop.value) { + rawChildrenMap.set(node, escapeHtml(prop.value.content)); + } else if (!needMergeProps) { + if (name === "key" || name === "ref") { + continue; + } + if (name === "class" && prop.value) { + staticClassBinding = JSON.stringify(prop.value.content); + } + openTag.push( + ` ${prop.name}` + (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``) + ); + } + } + } + if (dynamicClassBinding && staticClassBinding) { + mergeCall(dynamicClassBinding, staticClassBinding); + removeStaticBinding(openTag, "class"); + } + if (context.scopeId) { + openTag.push(` ${context.scopeId}`); + } + node.ssrCodegenNode = createTemplateLiteral(openTag); + }; +}; +function buildSSRProps(props, directives, context) { + let mergePropsArgs = []; + if (props) { + if (props.type === 14) { + mergePropsArgs = props.arguments; + } else { + mergePropsArgs.push(props); + } + } + if (directives.length) { + for (const dir of directives) { + mergePropsArgs.push( + createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [ + `_ctx`, + ...buildDirectiveArgs(dir, context).elements + ]) + ); + } + } + return mergePropsArgs.length > 1 ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs) : mergePropsArgs[0]; +} +function isTrueFalseValue(prop) { + if (prop.type === 7) { + return prop.name === "bind" && prop.arg && isStaticExp(prop.arg) && (prop.arg.content === "true-value" || prop.arg.content === "false-value"); + } else { + return prop.name === "true-value" || prop.name === "false-value"; + } +} +function isTextareaWithValue(node, prop) { + return !!(node.tag === "textarea" && prop.name === "bind" && isStaticArgOf(prop.arg, "value")); +} +function mergeCall(call, arg) { + const existing = call.arguments[0]; + if (existing.type === 17) { + existing.elements.push(arg); + } else { + call.arguments[0] = createArrayExpression([existing, arg]); + } +} +function removeStaticBinding(tag, binding) { + const regExp = new RegExp(`^ ${binding}=".+"$`); + const i = tag.findIndex((e) => typeof e === "string" && regExp.test(e)); + if (i > -1) { + tag.splice(i, 1); + } +} +function findVModel(node) { + return node.props.find( + (p) => p.type === 7 && p.name === "model" && p.exp + ); +} +function ssrProcessElement(node, context) { + const isVoidTag = context.options.isVoidTag || NO; + const elementsToAdd = node.ssrCodegenNode.elements; + for (let j = 0; j < elementsToAdd.length; j++) { + context.pushStringPart(elementsToAdd[j]); + } + if (context.withSlotScopeId) { + context.pushStringPart(createSimpleExpression(`_scopeId`, false)); + } + context.pushStringPart(`>`); + const rawChildren = rawChildrenMap.get(node); + if (rawChildren) { + context.pushStringPart(rawChildren); + } else if (node.children.length) { + processChildren(node, context); + } + if (!isVoidTag(node.tag)) { + context.pushStringPart(`</${node.tag}>`); + } +} + +const wipMap$2 = /* @__PURE__ */ new WeakMap(); +function ssrTransformTransitionGroup(node, context) { + return () => { + const tag = findProp(node, "tag"); + if (tag) { + const otherProps = node.props.filter((p) => p !== tag); + const { props, directives } = buildProps( + node, + context, + otherProps, + true, + false, + true + ); + let propsExp = null; + if (props || directives.length) { + propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [ + buildSSRProps(props, directives, context) + ]); + } + wipMap$2.set(node, { + tag, + propsExp, + scopeId: context.scopeId || null + }); + } + }; +} +function ssrProcessTransitionGroup(node, context) { + const entry = wipMap$2.get(node); + if (entry) { + const { tag, propsExp, scopeId } = entry; + if (tag.type === 7) { + context.pushStringPart(`<`); + context.pushStringPart(tag.exp); + if (propsExp) { + context.pushStringPart(propsExp); + } + if (scopeId) { + context.pushStringPart(` ${scopeId}`); + } + context.pushStringPart(`>`); + processChildren( + node, + context, + false, + /** + * TransitionGroup has the special runtime behavior of flattening and + * concatenating all children into a single fragment (in order for them to + * be patched using the same key map) so we need to account for that here + * by disabling nested fragment wrappers from being generated. + */ + true + ); + context.pushStringPart(`</`); + context.pushStringPart(tag.exp); + context.pushStringPart(`>`); + } else { + context.pushStringPart(`<${tag.value.content}`); + if (propsExp) { + context.pushStringPart(propsExp); + } + if (scopeId) { + context.pushStringPart(` ${scopeId}`); + } + context.pushStringPart(`>`); + processChildren(node, context, false, true); + context.pushStringPart(`</${tag.value.content}>`); + } + } else { + processChildren(node, context, true, true); + } +} + +const wipMap$1 = /* @__PURE__ */ new WeakMap(); +function ssrTransformTransition(node, context) { + return () => { + const appear = findProp(node, "appear", false, true); + wipMap$1.set(node, !!appear); + }; +} +function ssrProcessTransition(node, context) { + node.children = node.children.filter((c) => c.type !== 3); + const appear = wipMap$1.get(node); + if (appear) { + context.pushStringPart(`<template>`); + processChildren(node, context, false, true); + context.pushStringPart(`</template>`); + } else { + processChildren(node, context, false, true); + } +} + +var __defProp$8 = Object.defineProperty; +var __defProps$7 = Object.defineProperties; +var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols; +var __hasOwnProp$8 = Object.prototype.hasOwnProperty; +var __propIsEnum$8 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$8 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$8.call(b, prop)) + __defNormalProp$8(a, prop, b[prop]); + if (__getOwnPropSymbols$8) + for (var prop of __getOwnPropSymbols$8(b)) { + if (__propIsEnum$8.call(b, prop)) + __defNormalProp$8(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b)); +const wipMap = /* @__PURE__ */ new WeakMap(); +const WIP_SLOT = Symbol(); +const componentTypeMap = /* @__PURE__ */ new WeakMap(); +const ssrTransformComponent = (node, context) => { + if (node.type !== 1 || node.tagType !== 1) { + return; + } + const component = resolveComponentType( + node, + context, + true + /* ssr */ + ); + const isDynamicComponent = isObject$2(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT; + componentTypeMap.set(node, component); + if (isSymbol$1(component)) { + if (component === SUSPENSE) { + return ssrTransformSuspense(node, context); + } else if (component === TRANSITION_GROUP) { + return ssrTransformTransitionGroup(node, context); + } else if (component === TRANSITION) { + return ssrTransformTransition(node); + } + return; + } + const vnodeBranches = []; + const clonedNode = clone(node); + return function ssrPostTransformComponent() { + if (clonedNode.children.length) { + buildSlots(clonedNode, context, (props, vFor, children) => { + vnodeBranches.push( + createVNodeSlotBranch(props, vFor, children, context) + ); + return createFunctionExpression(void 0); + }); + } + let propsExp = `null`; + if (node.props.length) { + const { props, directives } = buildProps( + node, + context, + void 0, + true, + isDynamicComponent + ); + if (props || directives.length) { + propsExp = buildSSRProps(props, directives, context); + } + } + const wipEntries = []; + wipMap.set(node, wipEntries); + const buildSSRSlotFn = (props, _vForExp, children, loc) => { + const param0 = props && stringifyExpression(props) || `_`; + const fn = createFunctionExpression( + [param0, `_push`, `_parent`, `_scopeId`], + void 0, + // no return, assign body later + true, + // newline + true, + // isSlot + loc + ); + wipEntries.push({ + type: WIP_SLOT, + fn, + children, + // also collect the corresponding vnode branch built earlier + vnodeBranch: vnodeBranches[wipEntries.length] + }); + return fn; + }; + const slots = node.children.length ? buildSlots(node, context, buildSSRSlotFn).slots : `null`; + if (typeof component !== "string") { + node.ssrCodegenNode = createCallExpression( + context.helper(SSR_RENDER_VNODE), + [ + `_push`, + createCallExpression(context.helper(CREATE_VNODE), [ + component, + propsExp, + slots + ]), + `_parent` + ] + ); + } else { + node.ssrCodegenNode = createCallExpression( + context.helper(SSR_RENDER_COMPONENT), + [component, propsExp, slots, `_parent`] + ); + } + }; +}; +function ssrProcessComponent(node, context, parent) { + const component = componentTypeMap.get(node); + if (!node.ssrCodegenNode) { + if (component === TELEPORT) { + return ssrProcessTeleport(node, context); + } else if (component === SUSPENSE) { + return ssrProcessSuspense(node, context); + } else if (component === TRANSITION_GROUP) { + return ssrProcessTransitionGroup(node, context); + } else { + if (parent.type === WIP_SLOT) { + context.pushStringPart(``); + } + if (component === TRANSITION) { + return ssrProcessTransition(node, context); + } + processChildren(node, context); + } + } else { + const wipEntries = wipMap.get(node) || []; + for (let i = 0; i < wipEntries.length; i++) { + const { fn, vnodeBranch } = wipEntries[i]; + fn.body = createIfStatement( + createSimpleExpression(`_push`, false), + processChildrenAsStatement( + wipEntries[i], + context, + false, + true + ), + vnodeBranch + ); + } + if (context.withSlotScopeId) { + node.ssrCodegenNode.arguments.push(`_scopeId`); + } + if (typeof component === "string") { + context.pushStatement( + createCallExpression(`_push`, [node.ssrCodegenNode]) + ); + } else { + context.pushStatement(node.ssrCodegenNode); + } + } +} +const rawOptionsMap = /* @__PURE__ */ new WeakMap(); +const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true); +const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms]; +const vnodeDirectiveTransforms = __spreadValues$8(__spreadValues$8({}, baseDirectiveTransforms), DOMDirectiveTransforms); +function createVNodeSlotBranch(slotProps, vFor, children, parentContext) { + const rawOptions = rawOptionsMap.get(parentContext.root); + const subOptions = __spreadProps$7(__spreadValues$8({}, rawOptions), { + // overwrite with vnode-based transforms + nodeTransforms: [ + ...vnodeNodeTransforms, + ...rawOptions.nodeTransforms || [] + ], + directiveTransforms: __spreadValues$8(__spreadValues$8({}, vnodeDirectiveTransforms), rawOptions.directiveTransforms || {}) + }); + const wrapperProps = []; + if (slotProps) { + wrapperProps.push({ + type: 7, + name: "slot", + exp: slotProps, + arg: void 0, + modifiers: [], + loc: locStub + }); + } + if (vFor) { + wrapperProps.push(extend({}, vFor)); + } + const wrapperNode = { + type: 1, + ns: 0, + tag: "template", + tagType: 3, + props: wrapperProps, + children, + loc: locStub, + codegenNode: void 0 + }; + subTransform(wrapperNode, subOptions, parentContext); + return createReturnStatement(children); +} +function subTransform(node, options, parentContext) { + const childRoot = createRoot([node]); + const childContext = createTransformContext(childRoot, options); + childContext.ssr = false; + childContext.scopes = __spreadValues$8({}, parentContext.scopes); + childContext.identifiers = __spreadValues$8({}, parentContext.identifiers); + childContext.imports = parentContext.imports; + traverseNode(childRoot, childContext); + ["helpers", "components", "directives"].forEach((key) => { + childContext[key].forEach((value, helperKey) => { + if (key === "helpers") { + const parentCount = parentContext.helpers.get(helperKey); + if (parentCount === void 0) { + parentContext.helpers.set(helperKey, value); + } else { + parentContext.helpers.set(helperKey, value + parentCount); + } + } else { + parentContext[key].add(value); + } + }); + }); +} +function clone(v) { + if (isArray$3(v)) { + return v.map(clone); + } else if (isPlainObject(v)) { + const res = {}; + for (const key in v) { + res[key] = clone(v[key]); + } + return res; + } else { + return v; + } +} + +function ssrCodegenTransform(ast, options) { + const context = createSSRTransformContext(ast, options); + if (options.ssrCssVars) { + const cssContext = createTransformContext(createRoot([]), options); + const varsExp = processExpression( + createSimpleExpression(options.ssrCssVars, false), + cssContext + ); + context.body.push( + createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]) + ); + Array.from(cssContext.helpers.keys()).forEach((helper) => { + ast.helpers.add(helper); + }); + } + const isFragment = ast.children.length > 1 && ast.children.some((c) => !isText$1(c)); + processChildren(ast, context, isFragment); + ast.codegenNode = createBlockStatement(context.body); + ast.ssrHelpers = Array.from( + /* @__PURE__ */ new Set([ + ...Array.from(ast.helpers).filter((h) => h in ssrHelpers), + ...context.helpers + ]) + ); + ast.helpers = new Set(Array.from(ast.helpers).filter((h) => !(h in ssrHelpers))); +} +function createSSRTransformContext(root, options, helpers = /* @__PURE__ */ new Set(), withSlotScopeId = false) { + const body = []; + let currentString = null; + return { + root, + options, + body, + helpers, + withSlotScopeId, + onError: options.onError || ((e) => { + throw e; + }), + helper(name) { + helpers.add(name); + return name; + }, + pushStringPart(part) { + if (!currentString) { + const currentCall = createCallExpression(`_push`); + body.push(currentCall); + currentString = createTemplateLiteral([]); + currentCall.arguments.push(currentString); + } + const bufferedElements = currentString.elements; + const lastItem = bufferedElements[bufferedElements.length - 1]; + if (isString$2(part) && isString$2(lastItem)) { + bufferedElements[bufferedElements.length - 1] += part; + } else { + bufferedElements.push(part); + } + }, + pushStatement(statement) { + currentString = null; + body.push(statement); + } + }; +} +function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) { + return createSSRTransformContext( + parent.root, + parent.options, + parent.helpers, + withSlotScopeId + ); +} +function processChildren(parent, context, asFragment = false, disableNestedFragments = false) { + if (asFragment) { + context.pushStringPart(`<!--[-->`); + } + const { children } = parent; + for (let i = 0; i < children.length; i++) { + const child = children[i]; + switch (child.type) { + case 1: + switch (child.tagType) { + case 0: + ssrProcessElement(child, context); + break; + case 1: + ssrProcessComponent(child, context, parent); + break; + case 2: + ssrProcessSlotOutlet(child, context); + break; + case 3: + break; + default: + context.onError( + createSSRCompilerError( + 67, + child.loc + ) + ); + const exhaustiveCheck2 = child; + return exhaustiveCheck2; + } + break; + case 2: + context.pushStringPart(escapeHtml(child.content)); + break; + case 3: + context.pushStringPart(`<!--${child.content}-->`); + break; + case 5: + context.pushStringPart( + createCallExpression(context.helper(SSR_INTERPOLATE), [ + child.content + ]) + ); + break; + case 9: + ssrProcessIf(child, context, disableNestedFragments); + break; + case 11: + ssrProcessFor(child, context, disableNestedFragments); + break; + case 10: + break; + case 12: + case 8: + break; + default: + context.onError( + createSSRCompilerError( + 67, + child.loc + ) + ); + const exhaustiveCheck = child; + return exhaustiveCheck; + } + } + if (asFragment) { + context.pushStringPart(`<!--]-->`); + } +} +function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) { + const childContext = createChildContext(parentContext, withSlotScopeId); + processChildren(parent, childContext, asFragment); + return createBlockStatement(childContext.body); +} + +const ssrTransformModel = (dir, node, context) => { + const model = dir.exp; + function checkDuplicatedValue() { + const value = findProp(node, "value"); + if (value) { + context.onError( + createDOMCompilerError( + 60, + value.loc + ) + ); + } + } + function processOption(plainNode) { + if (plainNode.tag === "option") { + if (plainNode.props.findIndex((p) => p.name === "selected") === -1) { + const value = findValueBinding(plainNode); + plainNode.ssrCodegenNode.elements.push( + createConditionalExpression( + createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [ + createConditionalExpression( + createCallExpression(`Array.isArray`, [model]), + createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [ + model, + value + ]), + createCallExpression(context.helper(SSR_LOOSE_EQUAL), [ + model, + value + ]) + ) + ]), + createSimpleExpression(" selected", true), + createSimpleExpression("", true), + false + ) + ); + } + } else if (plainNode.tag === "optgroup") { + plainNode.children.forEach( + (option) => processOption(option) + ); + } + } + if (node.tagType === 0) { + const res = { props: [] }; + const defaultProps = [ + // default value binding for text type inputs + createObjectProperty(`value`, model) + ]; + if (node.tag === "input") { + const type = findProp(node, "type"); + if (type) { + const value = findValueBinding(node); + if (type.type === 7) { + res.ssrTagParts = [ + createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [ + type.exp, + model, + value + ]) + ]; + } else if (type.value) { + switch (type.value.content) { + case "radio": + res.props = [ + createObjectProperty( + `checked`, + createCallExpression(context.helper(SSR_LOOSE_EQUAL), [ + model, + value + ]) + ) + ]; + break; + case "checkbox": + const trueValueBinding = findProp(node, "true-value"); + if (trueValueBinding) { + const trueValue = trueValueBinding.type === 6 ? JSON.stringify(trueValueBinding.value.content) : trueValueBinding.exp; + res.props = [ + createObjectProperty( + `checked`, + createCallExpression(context.helper(SSR_LOOSE_EQUAL), [ + model, + trueValue + ]) + ) + ]; + } else { + res.props = [ + createObjectProperty( + `checked`, + createConditionalExpression( + createCallExpression(`Array.isArray`, [model]), + createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [ + model, + value + ]), + model + ) + ) + ]; + } + break; + case "file": + context.onError( + createDOMCompilerError( + 59, + dir.loc + ) + ); + break; + default: + checkDuplicatedValue(); + res.props = defaultProps; + break; + } + } + } else if (hasDynamicKeyVBind(node)) ; else { + checkDuplicatedValue(); + res.props = defaultProps; + } + } else if (node.tag === "textarea") { + checkDuplicatedValue(); + node.children = [createInterpolation(model, model.loc)]; + } else if (node.tag === "select") { + node.children.forEach((child) => { + if (child.type === 1) { + processOption(child); + } + }); + } else { + context.onError( + createDOMCompilerError( + 57, + dir.loc + ) + ); + } + return res; + } else { + return transformModel$1(dir, node, context); + } +}; +function findValueBinding(node) { + const valueBinding = findProp(node, "value"); + return valueBinding ? valueBinding.type === 7 ? valueBinding.exp : createSimpleExpression(valueBinding.value.content, true) : createSimpleExpression(`null`, false); +} + +const ssrTransformShow = (dir, node, context) => { + if (!dir.exp) { + context.onError( + createDOMCompilerError(61) + ); + } + return { + props: [ + createObjectProperty( + `style`, + createConditionalExpression( + dir.exp, + createSimpleExpression(`null`, false), + createObjectExpression([ + createObjectProperty( + `display`, + createSimpleExpression(`none`, true) + ) + ]), + false + ) + ) + ] + }; +}; + +const filterChild = (node) => node.children.filter((n) => n.type !== 3); +const hasSingleChild = (node) => filterChild(node).length === 1; +const ssrInjectFallthroughAttrs = (node, context) => { + if (node.type === 0) { + context.identifiers._attrs = 1; + } + if (node.type === 1 && node.tagType === 1 && (node.tag === "transition" || node.tag === "Transition" || node.tag === "KeepAlive" || node.tag === "keep-alive")) { + const rootChildren = filterChild(context.root); + if (rootChildren.length === 1 && rootChildren[0] === node) { + if (hasSingleChild(node)) { + injectFallthroughAttrs(node.children[0]); + } + return; + } + } + const parent = context.parent; + if (!parent || parent.type !== 0) { + return; + } + if (node.type === 10 && hasSingleChild(node)) { + let hasEncounteredIf = false; + for (const c of filterChild(parent)) { + if (c.type === 9 || c.type === 1 && findDir(c, "if")) { + if (hasEncounteredIf) + return; + hasEncounteredIf = true; + } else if ( + // node before v-if + !hasEncounteredIf || // non else nodes + !(c.type === 1 && findDir(c, /else/, true)) + ) { + return; + } + } + injectFallthroughAttrs(node.children[0]); + } else if (hasSingleChild(parent)) { + injectFallthroughAttrs(node); + } +}; +function injectFallthroughAttrs(node) { + if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) { + node.props.push({ + type: 7, + name: "bind", + arg: void 0, + exp: createSimpleExpression(`_attrs`, false), + modifiers: [], + loc: locStub + }); + } +} + +const ssrInjectCssVars = (node, context) => { + if (!context.ssrCssVars) { + return; + } + if (node.type === 0) { + context.identifiers._cssVars = 1; + } + const parent = context.parent; + if (!parent || parent.type !== 0) { + return; + } + if (node.type === 10) { + for (const child of node.children) { + injectCssVars(child); + } + } else { + injectCssVars(node); + } +}; +function injectCssVars(node) { + if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) { + if (node.tag === "suspense" || node.tag === "Suspense") { + for (const child of node.children) { + if (child.type === 1 && child.tagType === 3) { + child.children.forEach(injectCssVars); + } else { + injectCssVars(child); + } + } + } else { + node.props.push({ + type: 7, + name: "bind", + arg: void 0, + exp: createSimpleExpression(`_cssVars`, false), + modifiers: [], + loc: locStub + }); + } + } +} + +var __defProp$7 = Object.defineProperty; +var __defProps$6 = Object.defineProperties; +var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols; +var __hasOwnProp$7 = Object.prototype.hasOwnProperty; +var __propIsEnum$7 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$7 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$7.call(b, prop)) + __defNormalProp$7(a, prop, b[prop]); + if (__getOwnPropSymbols$7) + for (var prop of __getOwnPropSymbols$7(b)) { + if (__propIsEnum$7.call(b, prop)) + __defNormalProp$7(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b)); +function compile(source, options = {}) { + options = __spreadProps$6(__spreadValues$7(__spreadValues$7({}, options), parserOptions), { + ssr: true, + inSSR: true, + scopeId: options.mode === "function" ? null : options.scopeId, + // always prefix since compiler-ssr doesn't have size concern + prefixIdentifiers: true, + // disable optimizations that are unnecessary for ssr + cacheHandlers: false, + hoistStatic: false + }); + const ast = typeof source === "string" ? baseParse(source, options) : source; + rawOptionsMap.set(ast, options); + transform(ast, __spreadProps$6(__spreadValues$7({}, options), { + hoistStatic: false, + nodeTransforms: [ + ssrTransformIf, + ssrTransformFor, + trackVForSlotScopes, + transformExpression, + ssrTransformSlotOutlet, + ssrInjectFallthroughAttrs, + ssrInjectCssVars, + ssrTransformElement, + ssrTransformComponent, + trackSlotScopes, + transformStyle, + ...options.nodeTransforms || [] + // user transforms + ], + directiveTransforms: __spreadValues$7({ + // reusing core v-bind + bind: transformBind, + on: transformOn$1, + // model and show have dedicated SSR handling + model: ssrTransformModel, + show: ssrTransformShow, + // the following are ignored during SSR + // on: noopDirectiveTransform, + cloak: noopDirectiveTransform, + once: noopDirectiveTransform, + memo: noopDirectiveTransform + }, options.directiveTransforms || {}) + })); + ssrCodegenTransform(ast, options); + return generate(ast, options); +} + +var CompilerSSR = /*#__PURE__*/Object.freeze({ + __proto__: null, + compile: compile +}); + +var _polyfillNode_fs = {}; + +var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _polyfillNode_fs +}); + +var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1); + +var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path); + +var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1); + +const hasWarned = {}; +function warnOnce$3(msg) { + const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production"; + if (!isNodeProd && true && !hasWarned[msg]) { + hasWarned[msg] = true; + warn(msg); + } +} +function warn(msg) { + console.warn( + `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m +` + ); +} + +var __defProp$6 = Object.defineProperty; +var __defProps$5 = Object.defineProperties; +var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols; +var __hasOwnProp$6 = Object.prototype.hasOwnProperty; +var __propIsEnum$6 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$6 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$6.call(b, prop)) + __defNormalProp$6(a, prop, b[prop]); + if (__getOwnPropSymbols$6) + for (var prop of __getOwnPropSymbols$6(b)) { + if (__propIsEnum$6.call(b, prop)) + __defNormalProp$6(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b)); +function preprocess$1({ source, filename, preprocessOptions }, preprocessor) { + let res = ""; + let err = null; + preprocessor.render( + source, + __spreadValues$6({ filename }, preprocessOptions), + (_err, _res) => { + if (_err) + err = _err; + res = _res; + } + ); + if (err) + throw err; + return res; +} +function compileTemplate(options) { + const { preprocessLang, preprocessCustomRequire } = options; + if (preprocessLang && !preprocessCustomRequire) { + throw new Error( + `[@vue/compiler-sfc] Template preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor in the shape of { render(): string }.` + ); + } + const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : void 0 : false; + if (preprocessor) { + try { + return doCompileTemplate(__spreadProps$5(__spreadValues$6({}, options), { + source: preprocess$1(options, preprocessor), + ast: void 0 + // invalidate AST if template goes through preprocessor + })); + } catch (e) { + return { + code: `export default function render() {}`, + source: options.source, + tips: [], + errors: [e] + }; + } + } else if (preprocessLang) { + return { + code: `export default function render() {}`, + source: options.source, + tips: [ + `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.` + ], + errors: [ + `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.` + ] + }; + } else { + return doCompileTemplate(options); + } +} +function doCompileTemplate({ + filename, + id, + scoped, + slotted, + inMap, + source, + ast: inAST, + ssr = false, + ssrCssVars, + isProd = false, + compiler, + compilerOptions = {}, + transformAssetUrls +}) { + const errors = []; + const warnings = []; + let nodeTransforms = []; + if (isObject$2(transformAssetUrls)) { + const assetOptions = normalizeOptions(transformAssetUrls); + nodeTransforms = [ + createAssetUrlTransformWithOptions(assetOptions), + createSrcsetTransformWithOptions(assetOptions) + ]; + } else if (transformAssetUrls !== false) { + nodeTransforms = [transformAssetUrl, transformSrcset]; + } + if (ssr && !ssrCssVars) { + warnOnce$3( + `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.\`.` + ); + } + if (!id) { + warnOnce$3(`compileTemplate now requires the \`id\` option.\`.`); + id = ""; + } + const shortId = id.replace(/^data-v-/, ""); + const longId = `data-v-${shortId}`; + const defaultCompiler = ssr ? CompilerSSR : CompilerDOM; + compiler = compiler || defaultCompiler; + if (compiler !== defaultCompiler) { + inAST = void 0; + } + if (inAST == null ? void 0 : inAST.transformed) { + const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, __spreadProps$5(__spreadValues$6({ + prefixIdentifiers: true + }, compilerOptions), { + parseMode: "sfc", + onError: (e) => errors.push(e) + })); + const template = newAST.children.find( + (node) => node.type === 1 && node.tag === "template" + ); + inAST = createRoot(template.children, inAST.source); + } + let { code, ast, preamble, map } = compiler.compile(inAST || source, __spreadProps$5(__spreadValues$6({ + mode: "module", + prefixIdentifiers: true, + hoistStatic: true, + cacheHandlers: true, + ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "", + scopeId: scoped ? longId : void 0, + slotted, + sourceMap: true + }, compilerOptions), { + hmr: !isProd, + nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), + filename, + onError: (e) => errors.push(e), + onWarn: (w) => warnings.push(w) + })); + if (inMap && !inAST) { + if (map) { + map = mapLines(inMap, map); + } + if (errors.length) { + patchErrors(errors, source, inMap); + } + } + const tips = warnings.map((w) => { + let msg = w.message; + if (w.loc) { + msg += ` +${generateCodeFrame( + (inAST == null ? void 0 : inAST.source) || source, + w.loc.start.offset, + w.loc.end.offset + )}`; + } + return msg; + }); + return { code, ast, preamble, source, errors, tips, map }; +} +function mapLines(oldMap, newMap) { + if (!oldMap) + return newMap; + if (!newMap) + return oldMap; + const oldMapConsumer = new SourceMapConsumer$5(oldMap); + const newMapConsumer = new SourceMapConsumer$5(newMap); + const mergedMapGenerator = new SourceMapGenerator$6(); + newMapConsumer.eachMapping((m) => { + if (m.originalLine == null) { + return; + } + const origPosInOldMap = oldMapConsumer.originalPositionFor({ + line: m.originalLine, + column: m.originalColumn + }); + if (origPosInOldMap.source == null) { + return; + } + mergedMapGenerator.addMapping({ + generated: { + line: m.generatedLine, + column: m.generatedColumn + }, + original: { + line: origPosInOldMap.line, + // map line + // use current column, since the oldMap produced by @vue/compiler-sfc + // does not + column: m.originalColumn + }, + source: origPosInOldMap.source, + name: origPosInOldMap.name + }); + }); + const generator = mergedMapGenerator; + oldMapConsumer.sources.forEach((sourceFile) => { + generator._sources.add(sourceFile); + const sourceContent = oldMapConsumer.sourceContentFor(sourceFile); + if (sourceContent != null) { + mergedMapGenerator.setSourceContent(sourceFile, sourceContent); + } + }); + generator._sourceRoot = oldMap.sourceRoot; + generator._file = oldMap.file; + return generator.toJSON(); +} +function patchErrors(errors, source, inMap) { + const originalSource = inMap.sourcesContent[0]; + const offset = originalSource.indexOf(source); + const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1; + errors.forEach((err) => { + if (err.loc) { + err.loc.start.line += lineOffset; + err.loc.start.offset += offset; + if (err.loc.end !== err.loc.start) { + err.loc.end.line += lineOffset; + err.loc.end.offset += offset; + } + } + }); +} + +var picocolors = {exports: {}}; + +// MIT lisence +// from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js + +function isatty() { + return false; +} + +function ReadStream() { + throw new Error('tty.ReadStream is not implemented'); +} + +function WriteStream() { + throw new Error('tty.ReadStream is not implemented'); +} + +var _polyfillNode_tty = { + isatty: isatty, + ReadStream: ReadStream, + WriteStream: WriteStream +}; + +var _polyfillNode_tty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + ReadStream: ReadStream, + WriteStream: WriteStream, + default: _polyfillNode_tty, + isatty: isatty +}); + +var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_tty$1); + +let tty = require$$0; + +let isColorSupported = + !("NO_COLOR" in ({}) || browser$1.argv.includes("--no-color")) && + ("FORCE_COLOR" in ({}) || + browser$1.argv.includes("--color") || + "" === "win32" || + (tty.isatty(1) && browser$1.env.TERM !== "dumb") || + "CI" in ({})); + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input; + let index = string.indexOf(close, open.length); + return ~index + ? open + replaceClose(string, close, replace, index) + close + : open + string + close + }; + +let replaceClose = (string, close, replace, index) => { + let start = string.substring(0, index) + replace; + let end = string.substring(index + close.length); + let nextIndex = end.indexOf(close); + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end +}; + +let createColors = (enabled = isColorSupported) => ({ + isColorSupported: enabled, + reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, + bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, + dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, + italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, + underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, + inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, + hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, + strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, + black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, + red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, + green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, + yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, + blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, + magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, + cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, + white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, + gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, + bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, + bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, + bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, + bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, + bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, + bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, + bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, + bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, +}); + +picocolors.exports = createColors(); +picocolors.exports.createColors = createColors; + +var picocolorsExports = picocolors.exports; + +const SINGLE_QUOTE = "'".charCodeAt(0); +const DOUBLE_QUOTE = '"'.charCodeAt(0); +const BACKSLASH = '\\'.charCodeAt(0); +const SLASH = '/'.charCodeAt(0); +const NEWLINE = '\n'.charCodeAt(0); +const SPACE = ' '.charCodeAt(0); +const FEED = '\f'.charCodeAt(0); +const TAB = '\t'.charCodeAt(0); +const CR = '\r'.charCodeAt(0); +const OPEN_SQUARE = '['.charCodeAt(0); +const CLOSE_SQUARE = ']'.charCodeAt(0); +const OPEN_PARENTHESES = '('.charCodeAt(0); +const CLOSE_PARENTHESES = ')'.charCodeAt(0); +const OPEN_CURLY = '{'.charCodeAt(0); +const CLOSE_CURLY = '}'.charCodeAt(0); +const SEMICOLON = ';'.charCodeAt(0); +const ASTERISK = '*'.charCodeAt(0); +const COLON = ':'.charCodeAt(0); +const AT = '@'.charCodeAt(0); + +const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g; +const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g; +const RE_BAD_BRACKET = /.[\r\n"'(/\\]/; +const RE_HEX_ESCAPE = /[\da-f]/i; + +var tokenize$1 = function tokenizer(input, options = {}) { + let css = input.css.valueOf(); + let ignore = options.ignoreErrors; + + let code, next, quote, content, escape; + let escaped, escapePos, prev, n, currentToken; + + let length = css.length; + let pos = 0; + let buffer = []; + let returned = []; + + function position() { + return pos + } + + function unclosed(what) { + throw input.error('Unclosed ' + what, pos) + } + + function endOfFile() { + return returned.length === 0 && pos >= length + } + + function nextToken(opts) { + if (returned.length) return returned.pop() + if (pos >= length) return + + let ignoreUnclosed = opts ? opts.ignoreUnclosed : false; + + code = css.charCodeAt(pos); + + switch (code) { + case NEWLINE: + case SPACE: + case TAB: + case CR: + case FEED: { + next = pos; + do { + next += 1; + code = css.charCodeAt(next); + } while ( + code === SPACE || + code === NEWLINE || + code === TAB || + code === CR || + code === FEED + ) + + currentToken = ['space', css.slice(pos, next)]; + pos = next - 1; + break + } + + case OPEN_SQUARE: + case CLOSE_SQUARE: + case OPEN_CURLY: + case CLOSE_CURLY: + case COLON: + case SEMICOLON: + case CLOSE_PARENTHESES: { + let controlChar = String.fromCharCode(code); + currentToken = [controlChar, controlChar, pos]; + break + } + + case OPEN_PARENTHESES: { + prev = buffer.length ? buffer.pop()[1] : ''; + n = css.charCodeAt(pos + 1); + if ( + prev === 'url' && + n !== SINGLE_QUOTE && + n !== DOUBLE_QUOTE && + n !== SPACE && + n !== NEWLINE && + n !== TAB && + n !== FEED && + n !== CR + ) { + next = pos; + do { + escaped = false; + next = css.indexOf(')', next + 1); + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos; + break + } else { + unclosed('bracket'); + } + } + escapePos = next; + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1; + escaped = !escaped; + } + } while (escaped) + + currentToken = ['brackets', css.slice(pos, next + 1), pos, next]; + + pos = next; + } else { + next = css.indexOf(')', pos + 1); + content = css.slice(pos, next + 1); + + if (next === -1 || RE_BAD_BRACKET.test(content)) { + currentToken = ['(', '(', pos]; + } else { + currentToken = ['brackets', content, pos, next]; + pos = next; + } + } + + break + } + + case SINGLE_QUOTE: + case DOUBLE_QUOTE: { + quote = code === SINGLE_QUOTE ? "'" : '"'; + next = pos; + do { + escaped = false; + next = css.indexOf(quote, next + 1); + if (next === -1) { + if (ignore || ignoreUnclosed) { + next = pos + 1; + break + } else { + unclosed('string'); + } + } + escapePos = next; + while (css.charCodeAt(escapePos - 1) === BACKSLASH) { + escapePos -= 1; + escaped = !escaped; + } + } while (escaped) + + currentToken = ['string', css.slice(pos, next + 1), pos, next]; + pos = next; + break + } + + case AT: { + RE_AT_END.lastIndex = pos + 1; + RE_AT_END.test(css); + if (RE_AT_END.lastIndex === 0) { + next = css.length - 1; + } else { + next = RE_AT_END.lastIndex - 2; + } + + currentToken = ['at-word', css.slice(pos, next + 1), pos, next]; + + pos = next; + break + } + + case BACKSLASH: { + next = pos; + escape = true; + while (css.charCodeAt(next + 1) === BACKSLASH) { + next += 1; + escape = !escape; + } + code = css.charCodeAt(next + 1); + if ( + escape && + code !== SLASH && + code !== SPACE && + code !== NEWLINE && + code !== TAB && + code !== CR && + code !== FEED + ) { + next += 1; + if (RE_HEX_ESCAPE.test(css.charAt(next))) { + while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) { + next += 1; + } + if (css.charCodeAt(next + 1) === SPACE) { + next += 1; + } + } + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next]; + + pos = next; + break + } + + default: { + if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { + next = css.indexOf('*/', pos + 2) + 1; + if (next === 0) { + if (ignore || ignoreUnclosed) { + next = css.length; + } else { + unclosed('comment'); + } + } + + currentToken = ['comment', css.slice(pos, next + 1), pos, next]; + pos = next; + } else { + RE_WORD_END.lastIndex = pos + 1; + RE_WORD_END.test(css); + if (RE_WORD_END.lastIndex === 0) { + next = css.length - 1; + } else { + next = RE_WORD_END.lastIndex - 2; + } + + currentToken = ['word', css.slice(pos, next + 1), pos, next]; + buffer.push(currentToken); + pos = next; + } + + break + } + } + + pos++; + return currentToken + } + + function back(token) { + returned.push(token); + } + + return { + back, + endOfFile, + nextToken, + position + } +}; + +let pico$1 = picocolorsExports; + +let tokenizer$1 = tokenize$1; + +let Input$5; + +function registerInput(dependant) { + Input$5 = dependant; +} + +const HIGHLIGHT_THEME = { + ';': pico$1.yellow, + ':': pico$1.yellow, + '(': pico$1.cyan, + ')': pico$1.cyan, + '[': pico$1.yellow, + ']': pico$1.yellow, + '{': pico$1.yellow, + '}': pico$1.yellow, + 'at-word': pico$1.cyan, + 'brackets': pico$1.cyan, + 'call': pico$1.cyan, + 'class': pico$1.yellow, + 'comment': pico$1.gray, + 'hash': pico$1.magenta, + 'string': pico$1.green +}; + +function getTokenType([type, value], processor) { + if (type === 'word') { + if (value[0] === '.') { + return 'class' + } + if (value[0] === '#') { + return 'hash' + } + } + + if (!processor.endOfFile()) { + let next = processor.nextToken(); + processor.back(next); + if (next[0] === 'brackets' || next[0] === '(') return 'call' + } + + return type +} + +function terminalHighlight$2(css) { + let processor = tokenizer$1(new Input$5(css), { ignoreErrors: true }); + let result = ''; + while (!processor.endOfFile()) { + let token = processor.nextToken(); + let color = HIGHLIGHT_THEME[getTokenType(token, processor)]; + if (color) { + result += token[1] + .split(/\r?\n/) + .map(i => color(i)) + .join('\n'); + } else { + result += token[1]; + } + } + return result +} + +terminalHighlight$2.registerInput = registerInput; + +var terminalHighlight_1 = terminalHighlight$2; + +let pico = picocolorsExports; + +let terminalHighlight$1 = terminalHighlight_1; + +let CssSyntaxError$3 = class CssSyntaxError extends Error { + constructor(message, line, column, source, file, plugin) { + super(message); + this.name = 'CssSyntaxError'; + this.reason = message; + + if (file) { + this.file = file; + } + if (source) { + this.source = source; + } + if (plugin) { + this.plugin = plugin; + } + if (typeof line !== 'undefined' && typeof column !== 'undefined') { + if (typeof line === 'number') { + this.line = line; + this.column = column; + } else { + this.line = line.line; + this.column = line.column; + this.endLine = column.line; + this.endColumn = column.column; + } + } + + this.setMessage(); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, CssSyntaxError); + } + } + + setMessage() { + this.message = this.plugin ? this.plugin + ': ' : ''; + this.message += this.file ? this.file : '<css input>'; + if (typeof this.line !== 'undefined') { + this.message += ':' + this.line + ':' + this.column; + } + this.message += ': ' + this.reason; + } + + showSourceCode(color) { + if (!this.source) return '' + + let css = this.source; + if (color == null) color = pico.isColorSupported; + if (terminalHighlight$1) { + if (color) css = terminalHighlight$1(css); + } + + let lines = css.split(/\r?\n/); + let start = Math.max(this.line - 3, 0); + let end = Math.min(this.line + 2, lines.length); + + let maxWidth = String(end).length; + + let mark, aside; + if (color) { + let { bold, gray, red } = pico.createColors(true); + mark = text => bold(red(text)); + aside = text => gray(text); + } else { + mark = aside = str => str; + } + + return lines + .slice(start, end) + .map((line, index) => { + let number = start + 1 + index; + let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '; + if (number === this.line) { + let spacing = + aside(gutter.replace(/\d/g, ' ')) + + line.slice(0, this.column - 1).replace(/[^\t]/g, ' '); + return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^') + } + return ' ' + aside(gutter) + line + }) + .join('\n') + } + + toString() { + let code = this.showSourceCode(); + if (code) { + code = '\n\n' + code + '\n'; + } + return this.name + ': ' + this.message + code + } +}; + +var cssSyntaxError = CssSyntaxError$3; +CssSyntaxError$3.default = CssSyntaxError$3; + +var symbols = {}; + +symbols.isClean = Symbol('isClean'); + +symbols.my = Symbol('my'); + +const DEFAULT_RAW = { + after: '\n', + beforeClose: '\n', + beforeComment: '\n', + beforeDecl: '\n', + beforeOpen: ' ', + beforeRule: '\n', + colon: ': ', + commentLeft: ' ', + commentRight: ' ', + emptyBody: '', + indent: ' ', + semicolon: false +}; + +function capitalize(str) { + return str[0].toUpperCase() + str.slice(1) +} + +let Stringifier$2 = class Stringifier { + constructor(builder) { + this.builder = builder; + } + + atrule(node, semicolon) { + let name = '@' + node.name; + let params = node.params ? this.rawValue(node, 'params') : ''; + + if (typeof node.raws.afterName !== 'undefined') { + name += node.raws.afterName; + } else if (params) { + name += ' '; + } + + if (node.nodes) { + this.block(node, name + params); + } else { + let end = (node.raws.between || '') + (semicolon ? ';' : ''); + this.builder(name + params + end, node); + } + } + + beforeAfter(node, detect) { + let value; + if (node.type === 'decl') { + value = this.raw(node, null, 'beforeDecl'); + } else if (node.type === 'comment') { + value = this.raw(node, null, 'beforeComment'); + } else if (detect === 'before') { + value = this.raw(node, null, 'beforeRule'); + } else { + value = this.raw(node, null, 'beforeClose'); + } + + let buf = node.parent; + let depth = 0; + while (buf && buf.type !== 'root') { + depth += 1; + buf = buf.parent; + } + + if (value.includes('\n')) { + let indent = this.raw(node, null, 'indent'); + if (indent.length) { + for (let step = 0; step < depth; step++) value += indent; + } + } + + return value + } + + block(node, start) { + let between = this.raw(node, 'between', 'beforeOpen'); + this.builder(start + between + '{', node, 'start'); + + let after; + if (node.nodes && node.nodes.length) { + this.body(node); + after = this.raw(node, 'after'); + } else { + after = this.raw(node, 'after', 'emptyBody'); + } + + if (after) this.builder(after); + this.builder('}', node, 'end'); + } + + body(node) { + let last = node.nodes.length - 1; + while (last > 0) { + if (node.nodes[last].type !== 'comment') break + last -= 1; + } + + let semicolon = this.raw(node, 'semicolon'); + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + let before = this.raw(child, 'before'); + if (before) this.builder(before); + this.stringify(child, last !== i || semicolon); + } + } + + comment(node) { + let left = this.raw(node, 'left', 'commentLeft'); + let right = this.raw(node, 'right', 'commentRight'); + this.builder('/*' + left + node.text + right + '*/', node); + } + + decl(node, semicolon) { + let between = this.raw(node, 'between', 'colon'); + let string = node.prop + between + this.rawValue(node, 'value'); + + if (node.important) { + string += node.raws.important || ' !important'; + } + + if (semicolon) string += ';'; + this.builder(string, node); + } + + document(node) { + this.body(node); + } + + raw(node, own, detect) { + let value; + if (!detect) detect = own; + + // Already had + if (own) { + value = node.raws[own]; + if (typeof value !== 'undefined') return value + } + + let parent = node.parent; + + if (detect === 'before') { + // Hack for first rule in CSS + if (!parent || (parent.type === 'root' && parent.first === node)) { + return '' + } + + // `root` nodes in `document` should use only their own raws + if (parent && parent.type === 'document') { + return '' + } + } + + // Floating child without parent + if (!parent) return DEFAULT_RAW[detect] + + // Detect style by other nodes + let root = node.root(); + if (!root.rawCache) root.rawCache = {}; + if (typeof root.rawCache[detect] !== 'undefined') { + return root.rawCache[detect] + } + + if (detect === 'before' || detect === 'after') { + return this.beforeAfter(node, detect) + } else { + let method = 'raw' + capitalize(detect); + if (this[method]) { + value = this[method](root, node); + } else { + root.walk(i => { + value = i.raws[own]; + if (typeof value !== 'undefined') return false + }); + } + } + + if (typeof value === 'undefined') value = DEFAULT_RAW[detect]; + + root.rawCache[detect] = value; + return value + } + + rawBeforeClose(root) { + let value; + root.walk(i => { + if (i.nodes && i.nodes.length > 0) { + if (typeof i.raws.after !== 'undefined') { + value = i.raws.after; + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, ''); + } + return false + } + } + }); + if (value) value = value.replace(/\S/g, ''); + return value + } + + rawBeforeComment(root, node) { + let value; + root.walkComments(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before; + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, ''); + } + return false + } + }); + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeDecl'); + } else if (value) { + value = value.replace(/\S/g, ''); + } + return value + } + + rawBeforeDecl(root, node) { + let value; + root.walkDecls(i => { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before; + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, ''); + } + return false + } + }); + if (typeof value === 'undefined') { + value = this.raw(node, null, 'beforeRule'); + } else if (value) { + value = value.replace(/\S/g, ''); + } + return value + } + + rawBeforeOpen(root) { + let value; + root.walk(i => { + if (i.type !== 'decl') { + value = i.raws.between; + if (typeof value !== 'undefined') return false + } + }); + return value + } + + rawBeforeRule(root) { + let value; + root.walk(i => { + if (i.nodes && (i.parent !== root || root.first !== i)) { + if (typeof i.raws.before !== 'undefined') { + value = i.raws.before; + if (value.includes('\n')) { + value = value.replace(/[^\n]+$/, ''); + } + return false + } + } + }); + if (value) value = value.replace(/\S/g, ''); + return value + } + + rawColon(root) { + let value; + root.walkDecls(i => { + if (typeof i.raws.between !== 'undefined') { + value = i.raws.between.replace(/[^\s:]/g, ''); + return false + } + }); + return value + } + + rawEmptyBody(root) { + let value; + root.walk(i => { + if (i.nodes && i.nodes.length === 0) { + value = i.raws.after; + if (typeof value !== 'undefined') return false + } + }); + return value + } + + rawIndent(root) { + if (root.raws.indent) return root.raws.indent + let value; + root.walk(i => { + let p = i.parent; + if (p && p !== root && p.parent && p.parent === root) { + if (typeof i.raws.before !== 'undefined') { + let parts = i.raws.before.split('\n'); + value = parts[parts.length - 1]; + value = value.replace(/\S/g, ''); + return false + } + } + }); + return value + } + + rawSemicolon(root) { + let value; + root.walk(i => { + if (i.nodes && i.nodes.length && i.last.type === 'decl') { + value = i.raws.semicolon; + if (typeof value !== 'undefined') return false + } + }); + return value + } + + rawValue(node, prop) { + let value = node[prop]; + let raw = node.raws[prop]; + if (raw && raw.value === value) { + return raw.raw + } + + return value + } + + root(node) { + this.body(node); + if (node.raws.after) this.builder(node.raws.after); + } + + rule(node) { + this.block(node, this.rawValue(node, 'selector')); + if (node.raws.ownSemicolon) { + this.builder(node.raws.ownSemicolon, node, 'end'); + } + } + + stringify(node, semicolon) { + /* c8 ignore start */ + if (!this[node.type]) { + throw new Error( + 'Unknown AST node type ' + + node.type + + '. ' + + 'Maybe you need to change PostCSS stringifier.' + ) + } + /* c8 ignore stop */ + this[node.type](node, semicolon); + } +}; + +var stringifier = Stringifier$2; +Stringifier$2.default = Stringifier$2; + +let Stringifier$1 = stringifier; + +function stringify$4(node, builder) { + let str = new Stringifier$1(builder); + str.stringify(node); +} + +var stringify_1 = stringify$4; +stringify$4.default = stringify$4; + +let { isClean: isClean$2, my: my$2 } = symbols; +let CssSyntaxError$2 = cssSyntaxError; +let Stringifier = stringifier; +let stringify$3 = stringify_1; + +function cloneNode(obj, parent) { + let cloned = new obj.constructor(); + + for (let i in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, i)) { + /* c8 ignore next 2 */ + continue + } + if (i === 'proxyCache') continue + let value = obj[i]; + let type = typeof value; + + if (i === 'parent' && type === 'object') { + if (parent) cloned[i] = parent; + } else if (i === 'source') { + cloned[i] = value; + } else if (Array.isArray(value)) { + cloned[i] = value.map(j => cloneNode(j, cloned)); + } else { + if (type === 'object' && value !== null) value = cloneNode(value); + cloned[i] = value; + } + } + + return cloned +} + +let Node$4 = class Node { + constructor(defaults = {}) { + this.raws = {}; + this[isClean$2] = false; + this[my$2] = true; + + for (let name in defaults) { + if (name === 'nodes') { + this.nodes = []; + for (let node of defaults[name]) { + if (typeof node.clone === 'function') { + this.append(node.clone()); + } else { + this.append(node); + } + } + } else { + this[name] = defaults[name]; + } + } + } + + addToError(error) { + error.postcssNode = this; + if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { + let s = this.source; + error.stack = error.stack.replace( + /\n\s{4}at /, + `$&${s.input.from}:${s.start.line}:${s.start.column}$&` + ); + } + return error + } + + after(add) { + this.parent.insertAfter(this, add); + return this + } + + assign(overrides = {}) { + for (let name in overrides) { + this[name] = overrides[name]; + } + return this + } + + before(add) { + this.parent.insertBefore(this, add); + return this + } + + cleanRaws(keepBetween) { + delete this.raws.before; + delete this.raws.after; + if (!keepBetween) delete this.raws.between; + } + + clone(overrides = {}) { + let cloned = cloneNode(this); + for (let name in overrides) { + cloned[name] = overrides[name]; + } + return cloned + } + + cloneAfter(overrides = {}) { + let cloned = this.clone(overrides); + this.parent.insertAfter(this, cloned); + return cloned + } + + cloneBefore(overrides = {}) { + let cloned = this.clone(overrides); + this.parent.insertBefore(this, cloned); + return cloned + } + + error(message, opts = {}) { + if (this.source) { + let { end, start } = this.rangeBy(opts); + return this.source.input.error( + message, + { column: start.column, line: start.line }, + { column: end.column, line: end.line }, + opts + ) + } + return new CssSyntaxError$2(message) + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (prop === 'root') { + return () => node.root().toProxy() + } else { + return node[prop] + } + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value; + if ( + prop === 'prop' || + prop === 'value' || + prop === 'name' || + prop === 'params' || + prop === 'important' || + /* c8 ignore next */ + prop === 'text' + ) { + node.markDirty(); + } + return true + } + } + } + + markDirty() { + if (this[isClean$2]) { + this[isClean$2] = false; + let next = this; + while ((next = next.parent)) { + next[isClean$2] = false; + } + } + } + + next() { + if (!this.parent) return undefined + let index = this.parent.index(this); + return this.parent.nodes[index + 1] + } + + positionBy(opts, stringRepresentation) { + let pos = this.source.start; + if (opts.index) { + pos = this.positionInside(opts.index, stringRepresentation); + } else if (opts.word) { + stringRepresentation = this.toString(); + let index = stringRepresentation.indexOf(opts.word); + if (index !== -1) pos = this.positionInside(index, stringRepresentation); + } + return pos + } + + positionInside(index, stringRepresentation) { + let string = stringRepresentation || this.toString(); + let column = this.source.start.column; + let line = this.source.start.line; + + for (let i = 0; i < index; i++) { + if (string[i] === '\n') { + column = 1; + line += 1; + } else { + column += 1; + } + } + + return { column, line } + } + + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this); + return this.parent.nodes[index - 1] + } + + rangeBy(opts) { + let start = { + column: this.source.start.column, + line: this.source.start.line + }; + let end = this.source.end + ? { + column: this.source.end.column + 1, + line: this.source.end.line + } + : { + column: start.column + 1, + line: start.line + }; + + if (opts.word) { + let stringRepresentation = this.toString(); + let index = stringRepresentation.indexOf(opts.word); + if (index !== -1) { + start = this.positionInside(index, stringRepresentation); + end = this.positionInside(index + opts.word.length, stringRepresentation); + } + } else { + if (opts.start) { + start = { + column: opts.start.column, + line: opts.start.line + }; + } else if (opts.index) { + start = this.positionInside(opts.index); + } + + if (opts.end) { + end = { + column: opts.end.column, + line: opts.end.line + }; + } else if (opts.endIndex) { + end = this.positionInside(opts.endIndex); + } else if (opts.index) { + end = this.positionInside(opts.index + 1); + } + } + + if ( + end.line < start.line || + (end.line === start.line && end.column <= start.column) + ) { + end = { column: start.column + 1, line: start.line }; + } + + return { end, start } + } + + raw(prop, defaultType) { + let str = new Stringifier(); + return str.raw(this, prop, defaultType) + } + + remove() { + if (this.parent) { + this.parent.removeChild(this); + } + this.parent = undefined; + return this + } + + replaceWith(...nodes) { + if (this.parent) { + let bookmark = this; + let foundSelf = false; + for (let node of nodes) { + if (node === this) { + foundSelf = true; + } else if (foundSelf) { + this.parent.insertAfter(bookmark, node); + bookmark = node; + } else { + this.parent.insertBefore(bookmark, node); + } + } + + if (!foundSelf) { + this.remove(); + } + } + + return this + } + + root() { + let result = this; + while (result.parent && result.parent.type !== 'document') { + result = result.parent; + } + return result + } + + toJSON(_, inputs) { + let fixed = {}; + let emitInputs = inputs == null; + inputs = inputs || new Map(); + let inputsNextIndex = 0; + + for (let name in this) { + if (!Object.prototype.hasOwnProperty.call(this, name)) { + /* c8 ignore next 2 */ + continue + } + if (name === 'parent' || name === 'proxyCache') continue + let value = this[name]; + + if (Array.isArray(value)) { + fixed[name] = value.map(i => { + if (typeof i === 'object' && i.toJSON) { + return i.toJSON(null, inputs) + } else { + return i + } + }); + } else if (typeof value === 'object' && value.toJSON) { + fixed[name] = value.toJSON(null, inputs); + } else if (name === 'source') { + let inputId = inputs.get(value.input); + if (inputId == null) { + inputId = inputsNextIndex; + inputs.set(value.input, inputsNextIndex); + inputsNextIndex++; + } + fixed[name] = { + end: value.end, + inputId, + start: value.start + }; + } else { + fixed[name] = value; + } + } + + if (emitInputs) { + fixed.inputs = [...inputs.keys()].map(input => input.toJSON()); + } + + return fixed + } + + toProxy() { + if (!this.proxyCache) { + this.proxyCache = new Proxy(this, this.getProxyProcessor()); + } + return this.proxyCache + } + + toString(stringifier = stringify$3) { + if (stringifier.stringify) stringifier = stringifier.stringify; + let result = ''; + stringifier(this, i => { + result += i; + }); + return result + } + + warn(result, text, opts) { + let data = { node: this }; + for (let i in opts) data[i] = opts[i]; + return result.warn(text, data) + } + + get proxyOf() { + return this + } +}; + +var node$2 = Node$4; +Node$4.default = Node$4; + +let Node$3 = node$2; + +let Declaration$4 = class Declaration extends Node$3 { + constructor(defaults) { + if ( + defaults && + typeof defaults.value !== 'undefined' && + typeof defaults.value !== 'string' + ) { + defaults = { ...defaults, value: String(defaults.value) }; + } + super(defaults); + this.type = 'decl'; + } + + get variable() { + return this.prop.startsWith('--') || this.prop[0] === '$' + } +}; + +var declaration = Declaration$4; +Declaration$4.default = Declaration$4; + +var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1); + +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = ''; + let i = size; + while (i--) { + id += alphabet[(Math.random() * alphabet.length) | 0]; + } + return id + } +}; +let nanoid$1 = (size = 21) => { + let id = ''; + let i = size; + while (i--) { + id += urlAlphabet[(Math.random() * 64) | 0]; + } + return id +}; +var nonSecure = { nanoid: nanoid$1, customAlphabet }; + +let { SourceMapConsumer: SourceMapConsumer$4, SourceMapGenerator: SourceMapGenerator$5 } = sourceMap$2; +let { existsSync, readFileSync } = require$$0$2; +let { dirname: dirname$1, join } = require$$1; + +function fromBase64(str) { + if (Buffer$1) { + return Buffer$1.from(str, 'base64').toString() + } else { + /* c8 ignore next 2 */ + return window.atob(str) + } +} + +let PreviousMap$2 = class PreviousMap { + constructor(css, opts) { + if (opts.map === false) return + this.loadAnnotation(css); + this.inline = this.startWith(this.annotation, 'data:'); + + let prev = opts.map ? opts.map.prev : undefined; + let text = this.loadMap(opts.from, prev); + if (!this.mapFile && opts.from) { + this.mapFile = opts.from; + } + if (this.mapFile) this.root = dirname$1(this.mapFile); + if (text) this.text = text; + } + + consumer() { + if (!this.consumerCache) { + this.consumerCache = new SourceMapConsumer$4(this.text); + } + return this.consumerCache + } + + decodeInline(text) { + let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/; + let baseUri = /^data:application\/json;base64,/; + let charsetUri = /^data:application\/json;charset=utf-?8,/; + let uri = /^data:application\/json,/; + + if (charsetUri.test(text) || uri.test(text)) { + return decodeURIComponent(text.substr(RegExp.lastMatch.length)) + } + + if (baseCharsetUri.test(text) || baseUri.test(text)) { + return fromBase64(text.substr(RegExp.lastMatch.length)) + } + + let encoding = text.match(/data:application\/json;([^,]+),/)[1]; + throw new Error('Unsupported source map encoding ' + encoding) + } + + getAnnotationURL(sourceMapString) { + return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim() + } + + isMap(map) { + if (typeof map !== 'object') return false + return ( + typeof map.mappings === 'string' || + typeof map._mappings === 'string' || + Array.isArray(map.sections) + ) + } + + loadAnnotation(css) { + let comments = css.match(/\/\*\s*# sourceMappingURL=/gm); + if (!comments) return + + // sourceMappingURLs from comments, strings, etc. + let start = css.lastIndexOf(comments.pop()); + let end = css.indexOf('*/', start); + + if (start > -1 && end > -1) { + // Locate the last sourceMappingURL to avoid pickin + this.annotation = this.getAnnotationURL(css.substring(start, end)); + } + } + + loadFile(path) { + this.root = dirname$1(path); + if (existsSync(path)) { + this.mapFile = path; + return readFileSync(path, 'utf-8').toString().trim() + } + } + + loadMap(file, prev) { + if (prev === false) return false + + if (prev) { + if (typeof prev === 'string') { + return prev + } else if (typeof prev === 'function') { + let prevPath = prev(file); + if (prevPath) { + let map = this.loadFile(prevPath); + if (!map) { + throw new Error( + 'Unable to load previous source map: ' + prevPath.toString() + ) + } + return map + } + } else if (prev instanceof SourceMapConsumer$4) { + return SourceMapGenerator$5.fromSourceMap(prev).toString() + } else if (prev instanceof SourceMapGenerator$5) { + return prev.toString() + } else if (this.isMap(prev)) { + return JSON.stringify(prev) + } else { + throw new Error( + 'Unsupported previous source map format: ' + prev.toString() + ) + } + } else if (this.inline) { + return this.decodeInline(this.annotation) + } else if (this.annotation) { + let map = this.annotation; + if (file) map = join(dirname$1(file), map); + return this.loadFile(map) + } + } + + startWith(string, start) { + if (!string) return false + return string.substr(0, start.length) === start + } + + withContent() { + return !!( + this.consumer().sourcesContent && + this.consumer().sourcesContent.length > 0 + ) + } +}; + +var previousMap = PreviousMap$2; +PreviousMap$2.default = PreviousMap$2; + +let { SourceMapConsumer: SourceMapConsumer$3, SourceMapGenerator: SourceMapGenerator$4 } = sourceMap$2; +let { fileURLToPath, pathToFileURL: pathToFileURL$1 } = require$$2; +let { isAbsolute, resolve: resolve$1 } = require$$1; +let { nanoid } = nonSecure; + +let terminalHighlight = terminalHighlight_1; +let CssSyntaxError$1 = cssSyntaxError; +let PreviousMap$1 = previousMap; + +let fromOffsetCache = Symbol('fromOffsetCache'); + +let sourceMapAvailable$1 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$4); +let pathAvailable$1 = Boolean(resolve$1 && isAbsolute); + +let Input$4 = class Input { + constructor(css, opts = {}) { + if ( + css === null || + typeof css === 'undefined' || + (typeof css === 'object' && !css.toString) + ) { + throw new Error(`PostCSS received ${css} instead of CSS string`) + } + + this.css = css.toString(); + + if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { + this.hasBOM = true; + this.css = this.css.slice(1); + } else { + this.hasBOM = false; + } + + if (opts.from) { + if ( + !pathAvailable$1 || + /^\w+:\/\//.test(opts.from) || + isAbsolute(opts.from) + ) { + this.file = opts.from; + } else { + this.file = resolve$1(opts.from); + } + } + + if (pathAvailable$1 && sourceMapAvailable$1) { + let map = new PreviousMap$1(this.css, opts); + if (map.text) { + this.map = map; + let file = map.consumer().file; + if (!this.file && file) this.file = this.mapResolve(file); + } + } + + if (!this.file) { + this.id = '<input css ' + nanoid(6) + '>'; + } + if (this.map) this.map.file = this.from; + } + + error(message, line, column, opts = {}) { + let result, endLine, endColumn; + + if (line && typeof line === 'object') { + let start = line; + let end = column; + if (typeof start.offset === 'number') { + let pos = this.fromOffset(start.offset); + line = pos.line; + column = pos.col; + } else { + line = start.line; + column = start.column; + } + if (typeof end.offset === 'number') { + let pos = this.fromOffset(end.offset); + endLine = pos.line; + endColumn = pos.col; + } else { + endLine = end.line; + endColumn = end.column; + } + } else if (!column) { + let pos = this.fromOffset(line); + line = pos.line; + column = pos.col; + } + + let origin = this.origin(line, column, endLine, endColumn); + if (origin) { + result = new CssSyntaxError$1( + message, + origin.endLine === undefined + ? origin.line + : { column: origin.column, line: origin.line }, + origin.endLine === undefined + ? origin.column + : { column: origin.endColumn, line: origin.endLine }, + origin.source, + origin.file, + opts.plugin + ); + } else { + result = new CssSyntaxError$1( + message, + endLine === undefined ? line : { column, line }, + endLine === undefined ? column : { column: endColumn, line: endLine }, + this.css, + this.file, + opts.plugin + ); + } + + result.input = { column, endColumn, endLine, line, source: this.css }; + if (this.file) { + if (pathToFileURL$1) { + result.input.url = pathToFileURL$1(this.file).toString(); + } + result.input.file = this.file; + } + + return result + } + + fromOffset(offset) { + let lastLine, lineToIndex; + if (!this[fromOffsetCache]) { + let lines = this.css.split('\n'); + lineToIndex = new Array(lines.length); + let prevIndex = 0; + + for (let i = 0, l = lines.length; i < l; i++) { + lineToIndex[i] = prevIndex; + prevIndex += lines[i].length + 1; + } + + this[fromOffsetCache] = lineToIndex; + } else { + lineToIndex = this[fromOffsetCache]; + } + lastLine = lineToIndex[lineToIndex.length - 1]; + + let min = 0; + if (offset >= lastLine) { + min = lineToIndex.length - 1; + } else { + let max = lineToIndex.length - 2; + let mid; + while (min < max) { + mid = min + ((max - min) >> 1); + if (offset < lineToIndex[mid]) { + max = mid - 1; + } else if (offset >= lineToIndex[mid + 1]) { + min = mid + 1; + } else { + min = mid; + break + } + } + } + return { + col: offset - lineToIndex[min] + 1, + line: min + 1 + } + } + + mapResolve(file) { + if (/^\w+:\/\//.test(file)) { + return file + } + return resolve$1(this.map.consumer().sourceRoot || this.map.root || '.', file) + } + + origin(line, column, endLine, endColumn) { + if (!this.map) return false + let consumer = this.map.consumer(); + + let from = consumer.originalPositionFor({ column, line }); + if (!from.source) return false + + let to; + if (typeof endLine === 'number') { + to = consumer.originalPositionFor({ column: endColumn, line: endLine }); + } + + let fromUrl; + + if (isAbsolute(from.source)) { + fromUrl = pathToFileURL$1(from.source); + } else { + fromUrl = new URL( + from.source, + this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile) + ); + } + + let result = { + column: from.column, + endColumn: to && to.column, + endLine: to && to.line, + line: from.line, + url: fromUrl.toString() + }; + + if (fromUrl.protocol === 'file:') { + if (fileURLToPath) { + result.file = fileURLToPath(fromUrl); + } else { + /* c8 ignore next 2 */ + throw new Error(`file: protocol is not available in this PostCSS build`) + } + } + + let source = consumer.sourceContentFor(from.source); + if (source) result.source = source; + + return result + } + + toJSON() { + let json = {}; + for (let name of ['hasBOM', 'css', 'file', 'id']) { + if (this[name] != null) { + json[name] = this[name]; + } + } + if (this.map) { + json.map = { ...this.map }; + if (json.map.consumerCache) { + json.map.consumerCache = undefined; + } + } + return json + } + + get from() { + return this.file || this.id + } +}; + +var input = Input$4; +Input$4.default = Input$4; + +if (terminalHighlight && terminalHighlight.registerInput) { + terminalHighlight.registerInput(Input$4); +} + +let { SourceMapConsumer: SourceMapConsumer$2, SourceMapGenerator: SourceMapGenerator$3 } = sourceMap$2; +let { dirname, relative, resolve, sep } = require$$1; +let { pathToFileURL } = require$$2; + +let Input$3 = input; + +let sourceMapAvailable = Boolean(SourceMapConsumer$2 && SourceMapGenerator$3); +let pathAvailable = Boolean(dirname && resolve && relative && sep); + +let MapGenerator$2 = class MapGenerator { + constructor(stringify, root, opts, cssString) { + this.stringify = stringify; + this.mapOpts = opts.map || {}; + this.root = root; + this.opts = opts; + this.css = cssString; + this.originalCSS = cssString; + this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute; + + this.memoizedFileURLs = new Map(); + this.memoizedPaths = new Map(); + this.memoizedURLs = new Map(); + } + + addAnnotation() { + let content; + + if (this.isInline()) { + content = + 'data:application/json;base64,' + this.toBase64(this.map.toString()); + } else if (typeof this.mapOpts.annotation === 'string') { + content = this.mapOpts.annotation; + } else if (typeof this.mapOpts.annotation === 'function') { + content = this.mapOpts.annotation(this.opts.to, this.root); + } else { + content = this.outputFile() + '.map'; + } + let eol = '\n'; + if (this.css.includes('\r\n')) eol = '\r\n'; + + this.css += eol + '/*# sourceMappingURL=' + content + ' */'; + } + + applyPrevMaps() { + for (let prev of this.previous()) { + let from = this.toUrl(this.path(prev.file)); + let root = prev.root || dirname(prev.file); + let map; + + if (this.mapOpts.sourcesContent === false) { + map = new SourceMapConsumer$2(prev.text); + if (map.sourcesContent) { + map.sourcesContent = null; + } + } else { + map = prev.consumer(); + } + + this.map.applySourceMap(map, from, this.toUrl(this.path(root))); + } + } + + clearAnnotation() { + if (this.mapOpts.annotation === false) return + + if (this.root) { + let node; + for (let i = this.root.nodes.length - 1; i >= 0; i--) { + node = this.root.nodes[i]; + if (node.type !== 'comment') continue + if (node.text.indexOf('# sourceMappingURL=') === 0) { + this.root.removeChild(i); + } + } + } else if (this.css) { + this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, ''); + } + } + + generate() { + this.clearAnnotation(); + if (pathAvailable && sourceMapAvailable && this.isMap()) { + return this.generateMap() + } else { + let result = ''; + this.stringify(this.root, i => { + result += i; + }); + return [result] + } + } + + generateMap() { + if (this.root) { + this.generateString(); + } else if (this.previous().length === 1) { + let prev = this.previous()[0].consumer(); + prev.file = this.outputFile(); + this.map = SourceMapGenerator$3.fromSourceMap(prev); + } else { + this.map = new SourceMapGenerator$3({ file: this.outputFile() }); + this.map.addMapping({ + generated: { column: 0, line: 1 }, + original: { column: 0, line: 1 }, + source: this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '<no source>' + }); + } + + if (this.isSourcesContent()) this.setSourcesContent(); + if (this.root && this.previous().length > 0) this.applyPrevMaps(); + if (this.isAnnotation()) this.addAnnotation(); + + if (this.isInline()) { + return [this.css] + } else { + return [this.css, this.map] + } + } + + generateString() { + this.css = ''; + this.map = new SourceMapGenerator$3({ file: this.outputFile() }); + + let line = 1; + let column = 1; + + let noSource = '<no source>'; + let mapping = { + generated: { column: 0, line: 0 }, + original: { column: 0, line: 0 }, + source: '' + }; + + let lines, last; + this.stringify(this.root, (str, node, type) => { + this.css += str; + + if (node && type !== 'end') { + mapping.generated.line = line; + mapping.generated.column = column - 1; + if (node.source && node.source.start) { + mapping.source = this.sourcePath(node); + mapping.original.line = node.source.start.line; + mapping.original.column = node.source.start.column - 1; + this.map.addMapping(mapping); + } else { + mapping.source = noSource; + mapping.original.line = 1; + mapping.original.column = 0; + this.map.addMapping(mapping); + } + } + + lines = str.match(/\n/g); + if (lines) { + line += lines.length; + last = str.lastIndexOf('\n'); + column = str.length - last; + } else { + column += str.length; + } + + if (node && type !== 'start') { + let p = node.parent || { raws: {} }; + let childless = + node.type === 'decl' || (node.type === 'atrule' && !node.nodes); + if (!childless || node !== p.last || p.raws.semicolon) { + if (node.source && node.source.end) { + mapping.source = this.sourcePath(node); + mapping.original.line = node.source.end.line; + mapping.original.column = node.source.end.column - 1; + mapping.generated.line = line; + mapping.generated.column = column - 2; + this.map.addMapping(mapping); + } else { + mapping.source = noSource; + mapping.original.line = 1; + mapping.original.column = 0; + mapping.generated.line = line; + mapping.generated.column = column - 1; + this.map.addMapping(mapping); + } + } + } + }); + } + + isAnnotation() { + if (this.isInline()) { + return true + } + if (typeof this.mapOpts.annotation !== 'undefined') { + return this.mapOpts.annotation + } + if (this.previous().length) { + return this.previous().some(i => i.annotation) + } + return true + } + + isInline() { + if (typeof this.mapOpts.inline !== 'undefined') { + return this.mapOpts.inline + } + + let annotation = this.mapOpts.annotation; + if (typeof annotation !== 'undefined' && annotation !== true) { + return false + } + + if (this.previous().length) { + return this.previous().some(i => i.inline) + } + return true + } + + isMap() { + if (typeof this.opts.map !== 'undefined') { + return !!this.opts.map + } + return this.previous().length > 0 + } + + isSourcesContent() { + if (typeof this.mapOpts.sourcesContent !== 'undefined') { + return this.mapOpts.sourcesContent + } + if (this.previous().length) { + return this.previous().some(i => i.withContent()) + } + return true + } + + outputFile() { + if (this.opts.to) { + return this.path(this.opts.to) + } else if (this.opts.from) { + return this.path(this.opts.from) + } else { + return 'to.css' + } + } + + path(file) { + if (this.mapOpts.absolute) return file + if (file.charCodeAt(0) === 60 /* `<` */) return file + if (/^\w+:\/\//.test(file)) return file + let cached = this.memoizedPaths.get(file); + if (cached) return cached + + let from = this.opts.to ? dirname(this.opts.to) : '.'; + + if (typeof this.mapOpts.annotation === 'string') { + from = dirname(resolve(from, this.mapOpts.annotation)); + } + + let path = relative(from, file); + this.memoizedPaths.set(file, path); + + return path + } + + previous() { + if (!this.previousMaps) { + this.previousMaps = []; + if (this.root) { + this.root.walk(node => { + if (node.source && node.source.input.map) { + let map = node.source.input.map; + if (!this.previousMaps.includes(map)) { + this.previousMaps.push(map); + } + } + }); + } else { + let input = new Input$3(this.originalCSS, this.opts); + if (input.map) this.previousMaps.push(input.map); + } + } + + return this.previousMaps + } + + setSourcesContent() { + let already = {}; + if (this.root) { + this.root.walk(node => { + if (node.source) { + let from = node.source.input.from; + if (from && !already[from]) { + already[from] = true; + let fromUrl = this.usesFileUrls + ? this.toFileUrl(from) + : this.toUrl(this.path(from)); + this.map.setSourceContent(fromUrl, node.source.input.css); + } + } + }); + } else if (this.css) { + let from = this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '<no source>'; + this.map.setSourceContent(from, this.css); + } + } + + sourcePath(node) { + if (this.mapOpts.from) { + return this.toUrl(this.mapOpts.from) + } else if (this.usesFileUrls) { + return this.toFileUrl(node.source.input.from) + } else { + return this.toUrl(this.path(node.source.input.from)) + } + } + + toBase64(str) { + if (Buffer$1) { + return Buffer$1.from(str).toString('base64') + } else { + return window.btoa(unescape(encodeURIComponent(str))) + } + } + + toFileUrl(path) { + let cached = this.memoizedFileURLs.get(path); + if (cached) return cached + + if (pathToFileURL) { + let fileURL = pathToFileURL(path).toString(); + this.memoizedFileURLs.set(path, fileURL); + + return fileURL + } else { + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } + + toUrl(path) { + let cached = this.memoizedURLs.get(path); + if (cached) return cached + + if (sep === '\\') { + path = path.replace(/\\/g, '/'); + } + + let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent); + this.memoizedURLs.set(path, url); + + return url + } +}; + +var mapGenerator = MapGenerator$2; + +let Node$2 = node$2; + +let Comment$4 = class Comment extends Node$2 { + constructor(defaults) { + super(defaults); + this.type = 'comment'; + } +}; + +var comment$3 = Comment$4; +Comment$4.default = Comment$4; + +let { isClean: isClean$1, my: my$1 } = symbols; +let Declaration$3 = declaration; +let Comment$3 = comment$3; +let Node$1 = node$2; + +let parse$4, Rule$4, AtRule$4, Root$6; + +function cleanSource(nodes) { + return nodes.map(i => { + if (i.nodes) i.nodes = cleanSource(i.nodes); + delete i.source; + return i + }) +} + +function markDirtyUp(node) { + node[isClean$1] = false; + if (node.proxyOf.nodes) { + for (let i of node.proxyOf.nodes) { + markDirtyUp(i); + } + } +} + +let Container$7 = class Container extends Node$1 { + append(...children) { + for (let child of children) { + let nodes = this.normalize(child, this.last); + for (let node of nodes) this.proxyOf.nodes.push(node); + } + + this.markDirty(); + + return this + } + + cleanRaws(keepBetween) { + super.cleanRaws(keepBetween); + if (this.nodes) { + for (let node of this.nodes) node.cleanRaws(keepBetween); + } + } + + each(callback) { + if (!this.proxyOf.nodes) return undefined + let iterator = this.getIterator(); + + let index, result; + while (this.indexes[iterator] < this.proxyOf.nodes.length) { + index = this.indexes[iterator]; + result = callback(this.proxyOf.nodes[index], index); + if (result === false) break + + this.indexes[iterator] += 1; + } + + delete this.indexes[iterator]; + return result + } + + every(condition) { + return this.nodes.every(condition) + } + + getIterator() { + if (!this.lastEach) this.lastEach = 0; + if (!this.indexes) this.indexes = {}; + + this.lastEach += 1; + let iterator = this.lastEach; + this.indexes[iterator] = 0; + + return iterator + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (!node[prop]) { + return node[prop] + } else if ( + prop === 'each' || + (typeof prop === 'string' && prop.startsWith('walk')) + ) { + return (...args) => { + return node[prop]( + ...args.map(i => { + if (typeof i === 'function') { + return (child, index) => i(child.toProxy(), index) + } else { + return i + } + }) + ) + } + } else if (prop === 'every' || prop === 'some') { + return cb => { + return node[prop]((child, ...other) => + cb(child.toProxy(), ...other) + ) + } + } else if (prop === 'root') { + return () => node.root().toProxy() + } else if (prop === 'nodes') { + return node.nodes.map(i => i.toProxy()) + } else if (prop === 'first' || prop === 'last') { + return node[prop].toProxy() + } else { + return node[prop] + } + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value; + if (prop === 'name' || prop === 'params' || prop === 'selector') { + node.markDirty(); + } + return true + } + } + } + + index(child) { + if (typeof child === 'number') return child + if (child.proxyOf) child = child.proxyOf; + return this.proxyOf.nodes.indexOf(child) + } + + insertAfter(exist, add) { + let existIndex = this.index(exist); + let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse(); + existIndex = this.index(exist); + for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node); + + let index; + for (let id in this.indexes) { + index = this.indexes[id]; + if (existIndex < index) { + this.indexes[id] = index + nodes.length; + } + } + + this.markDirty(); + + return this + } + + insertBefore(exist, add) { + let existIndex = this.index(exist); + let type = existIndex === 0 ? 'prepend' : false; + let nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse(); + existIndex = this.index(exist); + for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node); + + let index; + for (let id in this.indexes) { + index = this.indexes[id]; + if (existIndex <= index) { + this.indexes[id] = index + nodes.length; + } + } + + this.markDirty(); + + return this + } + + normalize(nodes, sample) { + if (typeof nodes === 'string') { + nodes = cleanSource(parse$4(nodes).nodes); + } else if (typeof nodes === 'undefined') { + nodes = []; + } else if (Array.isArray(nodes)) { + nodes = nodes.slice(0); + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore'); + } + } else if (nodes.type === 'root' && this.type !== 'document') { + nodes = nodes.nodes.slice(0); + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore'); + } + } else if (nodes.type) { + nodes = [nodes]; + } else if (nodes.prop) { + if (typeof nodes.value === 'undefined') { + throw new Error('Value field is missed in node creation') + } else if (typeof nodes.value !== 'string') { + nodes.value = String(nodes.value); + } + nodes = [new Declaration$3(nodes)]; + } else if (nodes.selector) { + nodes = [new Rule$4(nodes)]; + } else if (nodes.name) { + nodes = [new AtRule$4(nodes)]; + } else if (nodes.text) { + nodes = [new Comment$3(nodes)]; + } else { + throw new Error('Unknown node type in node creation') + } + + let processed = nodes.map(i => { + /* c8 ignore next */ + if (!i[my$1]) Container.rebuild(i); + i = i.proxyOf; + if (i.parent) i.parent.removeChild(i); + if (i[isClean$1]) markDirtyUp(i); + if (typeof i.raws.before === 'undefined') { + if (sample && typeof sample.raws.before !== 'undefined') { + i.raws.before = sample.raws.before.replace(/\S/g, ''); + } + } + i.parent = this.proxyOf; + return i + }); + + return processed + } + + prepend(...children) { + children = children.reverse(); + for (let child of children) { + let nodes = this.normalize(child, this.first, 'prepend').reverse(); + for (let node of nodes) this.proxyOf.nodes.unshift(node); + for (let id in this.indexes) { + this.indexes[id] = this.indexes[id] + nodes.length; + } + } + + this.markDirty(); + + return this + } + + push(child) { + child.parent = this; + this.proxyOf.nodes.push(child); + return this + } + + removeAll() { + for (let node of this.proxyOf.nodes) node.parent = undefined; + this.proxyOf.nodes = []; + + this.markDirty(); + + return this + } + + removeChild(child) { + child = this.index(child); + this.proxyOf.nodes[child].parent = undefined; + this.proxyOf.nodes.splice(child, 1); + + let index; + for (let id in this.indexes) { + index = this.indexes[id]; + if (index >= child) { + this.indexes[id] = index - 1; + } + } + + this.markDirty(); + + return this + } + + replaceValues(pattern, opts, callback) { + if (!callback) { + callback = opts; + opts = {}; + } + + this.walkDecls(decl => { + if (opts.props && !opts.props.includes(decl.prop)) return + if (opts.fast && !decl.value.includes(opts.fast)) return + + decl.value = decl.value.replace(pattern, callback); + }); + + this.markDirty(); + + return this + } + + some(condition) { + return this.nodes.some(condition) + } + + walk(callback) { + return this.each((child, i) => { + let result; + try { + result = callback(child, i); + } catch (e) { + throw child.addToError(e) + } + if (result !== false && child.walk) { + result = child.walk(callback); + } + + return result + }) + } + + walkAtRules(name, callback) { + if (!callback) { + callback = name; + return this.walk((child, i) => { + if (child.type === 'atrule') { + return callback(child, i) + } + }) + } + if (name instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'atrule' && name.test(child.name)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'atrule' && child.name === name) { + return callback(child, i) + } + }) + } + + walkComments(callback) { + return this.walk((child, i) => { + if (child.type === 'comment') { + return callback(child, i) + } + }) + } + + walkDecls(prop, callback) { + if (!callback) { + callback = prop; + return this.walk((child, i) => { + if (child.type === 'decl') { + return callback(child, i) + } + }) + } + if (prop instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'decl' && prop.test(child.prop)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'decl' && child.prop === prop) { + return callback(child, i) + } + }) + } + + walkRules(selector, callback) { + if (!callback) { + callback = selector; + + return this.walk((child, i) => { + if (child.type === 'rule') { + return callback(child, i) + } + }) + } + if (selector instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'rule' && selector.test(child.selector)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'rule' && child.selector === selector) { + return callback(child, i) + } + }) + } + + get first() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[0] + } + + get last() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[this.proxyOf.nodes.length - 1] + } +}; + +Container$7.registerParse = dependant => { + parse$4 = dependant; +}; + +Container$7.registerRule = dependant => { + Rule$4 = dependant; +}; + +Container$7.registerAtRule = dependant => { + AtRule$4 = dependant; +}; + +Container$7.registerRoot = dependant => { + Root$6 = dependant; +}; + +var container$1 = Container$7; +Container$7.default = Container$7; + +/* c8 ignore start */ +Container$7.rebuild = node => { + if (node.type === 'atrule') { + Object.setPrototypeOf(node, AtRule$4.prototype); + } else if (node.type === 'rule') { + Object.setPrototypeOf(node, Rule$4.prototype); + } else if (node.type === 'decl') { + Object.setPrototypeOf(node, Declaration$3.prototype); + } else if (node.type === 'comment') { + Object.setPrototypeOf(node, Comment$3.prototype); + } else if (node.type === 'root') { + Object.setPrototypeOf(node, Root$6.prototype); + } + + node[my$1] = true; + + if (node.nodes) { + node.nodes.forEach(child => { + Container$7.rebuild(child); + }); + } +}; + +let Container$6 = container$1; + +let LazyResult$4, Processor$3; + +let Document$3 = class Document extends Container$6 { + constructor(defaults) { + // type needs to be passed to super, otherwise child roots won't be normalized correctly + super({ type: 'document', ...defaults }); + + if (!this.nodes) { + this.nodes = []; + } + } + + toResult(opts = {}) { + let lazy = new LazyResult$4(new Processor$3(), this, opts); + + return lazy.stringify() + } +}; + +Document$3.registerLazyResult = dependant => { + LazyResult$4 = dependant; +}; + +Document$3.registerProcessor = dependant => { + Processor$3 = dependant; +}; + +var document = Document$3; +Document$3.default = Document$3; + +/* eslint-disable no-console */ + +let printed = {}; + +var warnOnce$2 = function warnOnce(message) { + if (printed[message]) return + printed[message] = true; + + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } +}; + +let Warning$2 = class Warning { + constructor(text, opts = {}) { + this.type = 'warning'; + this.text = text; + + if (opts.node && opts.node.source) { + let range = opts.node.rangeBy(opts); + this.line = range.start.line; + this.column = range.start.column; + this.endLine = range.end.line; + this.endColumn = range.end.column; + } + + for (let opt in opts) this[opt] = opts[opt]; + } + + toString() { + if (this.node) { + return this.node.error(this.text, { + index: this.index, + plugin: this.plugin, + word: this.word + }).message + } + + if (this.plugin) { + return this.plugin + ': ' + this.text + } + + return this.text + } +}; + +var warning = Warning$2; +Warning$2.default = Warning$2; + +let Warning$1 = warning; + +let Result$3 = class Result { + constructor(processor, root, opts) { + this.processor = processor; + this.messages = []; + this.root = root; + this.opts = opts; + this.css = undefined; + this.map = undefined; + } + + toString() { + return this.css + } + + warn(text, opts = {}) { + if (!opts.plugin) { + if (this.lastPlugin && this.lastPlugin.postcssPlugin) { + opts.plugin = this.lastPlugin.postcssPlugin; + } + } + + let warning = new Warning$1(text, opts); + this.messages.push(warning); + + return warning + } + + warnings() { + return this.messages.filter(i => i.type === 'warning') + } + + get content() { + return this.css + } +}; + +var result = Result$3; +Result$3.default = Result$3; + +let Container$5 = container$1; + +let AtRule$3 = class AtRule extends Container$5 { + constructor(defaults) { + super(defaults); + this.type = 'atrule'; + } + + append(...children) { + if (!this.proxyOf.nodes) this.nodes = []; + return super.append(...children) + } + + prepend(...children) { + if (!this.proxyOf.nodes) this.nodes = []; + return super.prepend(...children) + } +}; + +var atRule = AtRule$3; +AtRule$3.default = AtRule$3; + +Container$5.registerAtRule(AtRule$3); + +let Container$4 = container$1; + +let LazyResult$3, Processor$2; + +let Root$5 = class Root extends Container$4 { + constructor(defaults) { + super(defaults); + this.type = 'root'; + if (!this.nodes) this.nodes = []; + } + + normalize(child, sample, type) { + let nodes = super.normalize(child); + + if (sample) { + if (type === 'prepend') { + if (this.nodes.length > 1) { + sample.raws.before = this.nodes[1].raws.before; + } else { + delete sample.raws.before; + } + } else if (this.first !== sample) { + for (let node of nodes) { + node.raws.before = sample.raws.before; + } + } + } + + return nodes + } + + removeChild(child, ignore) { + let index = this.index(child); + + if (!ignore && index === 0 && this.nodes.length > 1) { + this.nodes[1].raws.before = this.nodes[index].raws.before; + } + + return super.removeChild(child) + } + + toResult(opts = {}) { + let lazy = new LazyResult$3(new Processor$2(), this, opts); + return lazy.stringify() + } +}; + +Root$5.registerLazyResult = dependant => { + LazyResult$3 = dependant; +}; + +Root$5.registerProcessor = dependant => { + Processor$2 = dependant; +}; + +var root$2 = Root$5; +Root$5.default = Root$5; + +Container$4.registerRoot(Root$5); + +let list$2 = { + comma(string) { + return list$2.split(string, [','], true) + }, + + space(string) { + let spaces = [' ', '\n', '\t']; + return list$2.split(string, spaces) + }, + + split(string, separators, last) { + let array = []; + let current = ''; + let split = false; + + let func = 0; + let inQuote = false; + let prevQuote = ''; + let escape = false; + + for (let letter of string) { + if (escape) { + escape = false; + } else if (letter === '\\') { + escape = true; + } else if (inQuote) { + if (letter === prevQuote) { + inQuote = false; + } + } else if (letter === '"' || letter === "'") { + inQuote = true; + prevQuote = letter; + } else if (letter === '(') { + func += 1; + } else if (letter === ')') { + if (func > 0) func -= 1; + } else if (func === 0) { + if (separators.includes(letter)) split = true; + } + + if (split) { + if (current !== '') array.push(current.trim()); + current = ''; + split = false; + } else { + current += letter; + } + } + + if (last || current !== '') array.push(current.trim()); + return array + } +}; + +var list_1 = list$2; +list$2.default = list$2; + +let Container$3 = container$1; +let list$1 = list_1; + +let Rule$3 = class Rule extends Container$3 { + constructor(defaults) { + super(defaults); + this.type = 'rule'; + if (!this.nodes) this.nodes = []; + } + + get selectors() { + return list$1.comma(this.selector) + } + + set selectors(values) { + let match = this.selector ? this.selector.match(/,\s*/) : null; + let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen'); + this.selector = values.join(sep); + } +}; + +var rule = Rule$3; +Rule$3.default = Rule$3; + +Container$3.registerRule(Rule$3); + +let Declaration$2 = declaration; +let tokenizer = tokenize$1; +let Comment$2 = comment$3; +let AtRule$2 = atRule; +let Root$4 = root$2; +let Rule$2 = rule; + +const SAFE_COMMENT_NEIGHBOR = { + empty: true, + space: true +}; + +function findLastWithPosition(tokens) { + for (let i = tokens.length - 1; i >= 0; i--) { + let token = tokens[i]; + let pos = token[3] || token[2]; + if (pos) return pos + } +} + +let Parser$1 = class Parser { + constructor(input) { + this.input = input; + + this.root = new Root$4(); + this.current = this.root; + this.spaces = ''; + this.semicolon = false; + + this.createTokenizer(); + this.root.source = { input, start: { column: 1, line: 1, offset: 0 } }; + } + + atrule(token) { + let node = new AtRule$2(); + node.name = token[1].slice(1); + if (node.name === '') { + this.unnamedAtrule(node, token); + } + this.init(node, token[2]); + + let type; + let prev; + let shift; + let last = false; + let open = false; + let params = []; + let brackets = []; + + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken(); + type = token[0]; + + if (type === '(' || type === '[') { + brackets.push(type === '(' ? ')' : ']'); + } else if (type === '{' && brackets.length > 0) { + brackets.push('}'); + } else if (type === brackets[brackets.length - 1]) { + brackets.pop(); + } + + if (brackets.length === 0) { + if (type === ';') { + node.source.end = this.getPosition(token[2]); + node.source.end.offset++; + this.semicolon = true; + break + } else if (type === '{') { + open = true; + break + } else if (type === '}') { + if (params.length > 0) { + shift = params.length - 1; + prev = params[shift]; + while (prev && prev[0] === 'space') { + prev = params[--shift]; + } + if (prev) { + node.source.end = this.getPosition(prev[3] || prev[2]); + node.source.end.offset++; + } + } + this.end(token); + break + } else { + params.push(token); + } + } else { + params.push(token); + } + + if (this.tokenizer.endOfFile()) { + last = true; + break + } + } + + node.raws.between = this.spacesAndCommentsFromEnd(params); + if (params.length) { + node.raws.afterName = this.spacesAndCommentsFromStart(params); + this.raw(node, 'params', params); + if (last) { + token = params[params.length - 1]; + node.source.end = this.getPosition(token[3] || token[2]); + node.source.end.offset++; + this.spaces = node.raws.between; + node.raws.between = ''; + } + } else { + node.raws.afterName = ''; + node.params = ''; + } + + if (open) { + node.nodes = []; + this.current = node; + } + } + + checkMissedSemicolon(tokens) { + let colon = this.colon(tokens); + if (colon === false) return + + let founded = 0; + let token; + for (let j = colon - 1; j >= 0; j--) { + token = tokens[j]; + if (token[0] !== 'space') { + founded += 1; + if (founded === 2) break + } + } + // If the token is a word, e.g. `!important`, `red` or any other valid property's value. + // Then we need to return the colon after that word token. [3] is the "end" colon of that word. + // And because we need it after that one we do +1 to get the next one. + throw this.input.error( + 'Missed semicolon', + token[0] === 'word' ? token[3] + 1 : token[2] + ) + } + + colon(tokens) { + let brackets = 0; + let token, type, prev; + for (let [i, element] of tokens.entries()) { + token = element; + type = token[0]; + + if (type === '(') { + brackets += 1; + } + if (type === ')') { + brackets -= 1; + } + if (brackets === 0 && type === ':') { + if (!prev) { + this.doubleColon(token); + } else if (prev[0] === 'word' && prev[1] === 'progid') { + continue + } else { + return i + } + } + + prev = token; + } + return false + } + + comment(token) { + let node = new Comment$2(); + this.init(node, token[2]); + node.source.end = this.getPosition(token[3] || token[2]); + node.source.end.offset++; + + let text = token[1].slice(2, -2); + if (/^\s*$/.test(text)) { + node.text = ''; + node.raws.left = text; + node.raws.right = ''; + } else { + let match = text.match(/^(\s*)([^]*\S)(\s*)$/); + node.text = match[2]; + node.raws.left = match[1]; + node.raws.right = match[3]; + } + } + + createTokenizer() { + this.tokenizer = tokenizer(this.input); + } + + decl(tokens, customProperty) { + let node = new Declaration$2(); + this.init(node, tokens[0][2]); + + let last = tokens[tokens.length - 1]; + if (last[0] === ';') { + this.semicolon = true; + tokens.pop(); + } + + node.source.end = this.getPosition( + last[3] || last[2] || findLastWithPosition(tokens) + ); + node.source.end.offset++; + + while (tokens[0][0] !== 'word') { + if (tokens.length === 1) this.unknownWord(tokens); + node.raws.before += tokens.shift()[1]; + } + node.source.start = this.getPosition(tokens[0][2]); + + node.prop = ''; + while (tokens.length) { + let type = tokens[0][0]; + if (type === ':' || type === 'space' || type === 'comment') { + break + } + node.prop += tokens.shift()[1]; + } + + node.raws.between = ''; + + let token; + while (tokens.length) { + token = tokens.shift(); + + if (token[0] === ':') { + node.raws.between += token[1]; + break + } else { + if (token[0] === 'word' && /\w/.test(token[1])) { + this.unknownWord([token]); + } + node.raws.between += token[1]; + } + } + + if (node.prop[0] === '_' || node.prop[0] === '*') { + node.raws.before += node.prop[0]; + node.prop = node.prop.slice(1); + } + + let firstSpaces = []; + let next; + while (tokens.length) { + next = tokens[0][0]; + if (next !== 'space' && next !== 'comment') break + firstSpaces.push(tokens.shift()); + } + + this.precheckMissedSemicolon(tokens); + + for (let i = tokens.length - 1; i >= 0; i--) { + token = tokens[i]; + if (token[1].toLowerCase() === '!important') { + node.important = true; + let string = this.stringFrom(tokens, i); + string = this.spacesFromEnd(tokens) + string; + if (string !== ' !important') node.raws.important = string; + break + } else if (token[1].toLowerCase() === 'important') { + let cache = tokens.slice(0); + let str = ''; + for (let j = i; j > 0; j--) { + let type = cache[j][0]; + if (str.trim().indexOf('!') === 0 && type !== 'space') { + break + } + str = cache.pop()[1] + str; + } + if (str.trim().indexOf('!') === 0) { + node.important = true; + node.raws.important = str; + tokens = cache; + } + } + + if (token[0] !== 'space' && token[0] !== 'comment') { + break + } + } + + let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment'); + + if (hasWord) { + node.raws.between += firstSpaces.map(i => i[1]).join(''); + firstSpaces = []; + } + this.raw(node, 'value', firstSpaces.concat(tokens), customProperty); + + if (node.value.includes(':') && !customProperty) { + this.checkMissedSemicolon(tokens); + } + } + + doubleColon(token) { + throw this.input.error( + 'Double colon', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } + + emptyRule(token) { + let node = new Rule$2(); + this.init(node, token[2]); + node.selector = ''; + node.raws.between = ''; + this.current = node; + } + + end(token) { + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon; + } + this.semicolon = false; + + this.current.raws.after = (this.current.raws.after || '') + this.spaces; + this.spaces = ''; + + if (this.current.parent) { + this.current.source.end = this.getPosition(token[2]); + this.current.source.end.offset++; + this.current = this.current.parent; + } else { + this.unexpectedClose(token); + } + } + + endFile() { + if (this.current.parent) this.unclosedBlock(); + if (this.current.nodes && this.current.nodes.length) { + this.current.raws.semicolon = this.semicolon; + } + this.current.raws.after = (this.current.raws.after || '') + this.spaces; + this.root.source.end = this.getPosition(this.tokenizer.position()); + } + + freeSemicolon(token) { + this.spaces += token[1]; + if (this.current.nodes) { + let prev = this.current.nodes[this.current.nodes.length - 1]; + if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { + prev.raws.ownSemicolon = this.spaces; + this.spaces = ''; + } + } + } + + // Helpers + + getPosition(offset) { + let pos = this.input.fromOffset(offset); + return { + column: pos.col, + line: pos.line, + offset + } + } + + init(node, offset) { + this.current.push(node); + node.source = { + input: this.input, + start: this.getPosition(offset) + }; + node.raws.before = this.spaces; + this.spaces = ''; + if (node.type !== 'comment') this.semicolon = false; + } + + other(start) { + let end = false; + let type = null; + let colon = false; + let bracket = null; + let brackets = []; + let customProperty = start[1].startsWith('--'); + + let tokens = []; + let token = start; + while (token) { + type = token[0]; + tokens.push(token); + + if (type === '(' || type === '[') { + if (!bracket) bracket = token; + brackets.push(type === '(' ? ')' : ']'); + } else if (customProperty && colon && type === '{') { + if (!bracket) bracket = token; + brackets.push('}'); + } else if (brackets.length === 0) { + if (type === ';') { + if (colon) { + this.decl(tokens, customProperty); + return + } else { + break + } + } else if (type === '{') { + this.rule(tokens); + return + } else if (type === '}') { + this.tokenizer.back(tokens.pop()); + end = true; + break + } else if (type === ':') { + colon = true; + } + } else if (type === brackets[brackets.length - 1]) { + brackets.pop(); + if (brackets.length === 0) bracket = null; + } + + token = this.tokenizer.nextToken(); + } + + if (this.tokenizer.endOfFile()) end = true; + if (brackets.length > 0) this.unclosedBracket(bracket); + + if (end && colon) { + if (!customProperty) { + while (tokens.length) { + token = tokens[tokens.length - 1][0]; + if (token !== 'space' && token !== 'comment') break + this.tokenizer.back(tokens.pop()); + } + } + this.decl(tokens, customProperty); + } else { + this.unknownWord(tokens); + } + } + + parse() { + let token; + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken(); + + switch (token[0]) { + case 'space': + this.spaces += token[1]; + break + + case ';': + this.freeSemicolon(token); + break + + case '}': + this.end(token); + break + + case 'comment': + this.comment(token); + break + + case 'at-word': + this.atrule(token); + break + + case '{': + this.emptyRule(token); + break + + default: + this.other(token); + break + } + } + this.endFile(); + } + + precheckMissedSemicolon(/* tokens */) { + // Hook for Safe Parser + } + + raw(node, prop, tokens, customProperty) { + let token, type; + let length = tokens.length; + let value = ''; + let clean = true; + let next, prev; + + for (let i = 0; i < length; i += 1) { + token = tokens[i]; + type = token[0]; + if (type === 'space' && i === length - 1 && !customProperty) { + clean = false; + } else if (type === 'comment') { + prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty'; + next = tokens[i + 1] ? tokens[i + 1][0] : 'empty'; + if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) { + if (value.slice(-1) === ',') { + clean = false; + } else { + value += token[1]; + } + } else { + clean = false; + } + } else { + value += token[1]; + } + } + if (!clean) { + let raw = tokens.reduce((all, i) => all + i[1], ''); + node.raws[prop] = { raw, value }; + } + node[prop] = value; + } + + rule(tokens) { + tokens.pop(); + + let node = new Rule$2(); + this.init(node, tokens[0][2]); + + node.raws.between = this.spacesAndCommentsFromEnd(tokens); + this.raw(node, 'selector', tokens); + this.current = node; + } + + spacesAndCommentsFromEnd(tokens) { + let lastTokenType; + let spaces = ''; + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0]; + if (lastTokenType !== 'space' && lastTokenType !== 'comment') break + spaces = tokens.pop()[1] + spaces; + } + return spaces + } + + // Errors + + spacesAndCommentsFromStart(tokens) { + let next; + let spaces = ''; + while (tokens.length) { + next = tokens[0][0]; + if (next !== 'space' && next !== 'comment') break + spaces += tokens.shift()[1]; + } + return spaces + } + + spacesFromEnd(tokens) { + let lastTokenType; + let spaces = ''; + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0]; + if (lastTokenType !== 'space') break + spaces = tokens.pop()[1] + spaces; + } + return spaces + } + + stringFrom(tokens, from) { + let result = ''; + for (let i = from; i < tokens.length; i++) { + result += tokens[i][1]; + } + tokens.splice(from, tokens.length - from); + return result + } + + unclosedBlock() { + let pos = this.current.source.start; + throw this.input.error('Unclosed block', pos.line, pos.column) + } + + unclosedBracket(bracket) { + throw this.input.error( + 'Unclosed bracket', + { offset: bracket[2] }, + { offset: bracket[2] + 1 } + ) + } + + unexpectedClose(token) { + throw this.input.error( + 'Unexpected }', + { offset: token[2] }, + { offset: token[2] + 1 } + ) + } + + unknownWord(tokens) { + throw this.input.error( + 'Unknown word', + { offset: tokens[0][2] }, + { offset: tokens[0][2] + tokens[0][1].length } + ) + } + + unnamedAtrule(node, token) { + throw this.input.error( + 'At-rule without name', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } +}; + +var parser$1 = Parser$1; + +let Container$2 = container$1; +let Parser = parser$1; +let Input$2 = input; + +function parse$3(css, opts) { + let input = new Input$2(css, opts); + let parser = new Parser(input); + try { + parser.parse(); + } catch (e) { + if (browser$1.env.NODE_ENV !== 'production') { + if (e.name === 'CssSyntaxError' && opts && opts.from) { + if (/\.scss$/i.test(opts.from)) { + e.message += + '\nYou tried to parse SCSS with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-scss parser'; + } else if (/\.sass/i.test(opts.from)) { + e.message += + '\nYou tried to parse Sass with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-sass parser'; + } else if (/\.less$/i.test(opts.from)) { + e.message += + '\nYou tried to parse Less with ' + + 'the standard CSS parser; ' + + 'try again with the postcss-less parser'; + } + } + } + throw e + } + + return parser.root +} + +var parse_1 = parse$3; +parse$3.default = parse$3; + +Container$2.registerParse(parse$3); + +let { isClean, my } = symbols; +let MapGenerator$1 = mapGenerator; +let stringify$2 = stringify_1; +let Container$1 = container$1; +let Document$2 = document; +let warnOnce$1 = warnOnce$2; +let Result$2 = result; +let parse$2 = parse_1; +let Root$3 = root$2; + +const TYPE_TO_CLASS_NAME = { + atrule: 'AtRule', + comment: 'Comment', + decl: 'Declaration', + document: 'Document', + root: 'Root', + rule: 'Rule' +}; + +const PLUGIN_PROPS = { + AtRule: true, + AtRuleExit: true, + Comment: true, + CommentExit: true, + Declaration: true, + DeclarationExit: true, + Document: true, + DocumentExit: true, + Once: true, + OnceExit: true, + postcssPlugin: true, + prepare: true, + Root: true, + RootExit: true, + Rule: true, + RuleExit: true +}; + +const NOT_VISITORS = { + Once: true, + postcssPlugin: true, + prepare: true +}; + +const CHILDREN = 0; + +function isPromise(obj) { + return typeof obj === 'object' && typeof obj.then === 'function' +} + +function getEvents(node) { + let key = false; + let type = TYPE_TO_CLASS_NAME[node.type]; + if (node.type === 'decl') { + key = node.prop.toLowerCase(); + } else if (node.type === 'atrule') { + key = node.name.toLowerCase(); + } + + if (key && node.append) { + return [ + type, + type + '-' + key, + CHILDREN, + type + 'Exit', + type + 'Exit-' + key + ] + } else if (key) { + return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] + } else if (node.append) { + return [type, CHILDREN, type + 'Exit'] + } else { + return [type, type + 'Exit'] + } +} + +function toStack(node) { + let events; + if (node.type === 'document') { + events = ['Document', CHILDREN, 'DocumentExit']; + } else if (node.type === 'root') { + events = ['Root', CHILDREN, 'RootExit']; + } else { + events = getEvents(node); + } + + return { + eventIndex: 0, + events, + iterator: 0, + node, + visitorIndex: 0, + visitors: [] + } +} + +function cleanMarks(node) { + node[isClean] = false; + if (node.nodes) node.nodes.forEach(i => cleanMarks(i)); + return node +} + +let postcss$2 = {}; + +let LazyResult$2 = class LazyResult { + constructor(processor, css, opts) { + this.stringified = false; + this.processed = false; + + let root; + if ( + typeof css === 'object' && + css !== null && + (css.type === 'root' || css.type === 'document') + ) { + root = cleanMarks(css); + } else if (css instanceof LazyResult || css instanceof Result$2) { + root = cleanMarks(css.root); + if (css.map) { + if (typeof opts.map === 'undefined') opts.map = {}; + if (!opts.map.inline) opts.map.inline = false; + opts.map.prev = css.map; + } + } else { + let parser = parse$2; + if (opts.syntax) parser = opts.syntax.parse; + if (opts.parser) parser = opts.parser; + if (parser.parse) parser = parser.parse; + + try { + root = parser(css, opts); + } catch (error) { + this.processed = true; + this.error = error; + } + + if (root && !root[my]) { + /* c8 ignore next 2 */ + Container$1.rebuild(root); + } + } + + this.result = new Result$2(processor, root, opts); + this.helpers = { ...postcss$2, postcss: postcss$2, result: this.result }; + this.plugins = this.processor.plugins.map(plugin => { + if (typeof plugin === 'object' && plugin.prepare) { + return { ...plugin, ...plugin.prepare(this.result) } + } else { + return plugin + } + }); + } + + async() { + if (this.error) return Promise.reject(this.error) + if (this.processed) return Promise.resolve(this.result) + if (!this.processing) { + this.processing = this.runAsync(); + } + return this.processing + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + getAsyncError() { + throw new Error('Use process(css).then(cb) to work with async plugins') + } + + handleError(error, node) { + let plugin = this.result.lastPlugin; + try { + if (node) node.addToError(error); + this.error = error; + if (error.name === 'CssSyntaxError' && !error.plugin) { + error.plugin = plugin.postcssPlugin; + error.setMessage(); + } else if (plugin.postcssVersion) { + if (browser$1.env.NODE_ENV !== 'production') { + let pluginName = plugin.postcssPlugin; + let pluginVer = plugin.postcssVersion; + let runtimeVer = this.result.processor.version; + let a = pluginVer.split('.'); + let b = runtimeVer.split('.'); + + if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { + // eslint-disable-next-line no-console + console.error( + 'Unknown error from PostCSS plugin. Your current PostCSS ' + + 'version is ' + + runtimeVer + + ', but ' + + pluginName + + ' uses ' + + pluginVer + + '. Perhaps this is the source of the error below.' + ); + } + } + } + } catch (err) { + /* c8 ignore next 3 */ + // eslint-disable-next-line no-console + if (console && console.error) console.error(err); + } + return error + } + + prepareVisitors() { + this.listeners = {}; + let add = (plugin, type, cb) => { + if (!this.listeners[type]) this.listeners[type] = []; + this.listeners[type].push([plugin, cb]); + }; + for (let plugin of this.plugins) { + if (typeof plugin === 'object') { + for (let event in plugin) { + if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { + throw new Error( + `Unknown event ${event} in ${plugin.postcssPlugin}. ` + + `Try to update PostCSS (${this.processor.version} now).` + ) + } + if (!NOT_VISITORS[event]) { + if (typeof plugin[event] === 'object') { + for (let filter in plugin[event]) { + if (filter === '*') { + add(plugin, event, plugin[event][filter]); + } else { + add( + plugin, + event + '-' + filter.toLowerCase(), + plugin[event][filter] + ); + } + } + } else if (typeof plugin[event] === 'function') { + add(plugin, event, plugin[event]); + } + } + } + } + } + this.hasListener = Object.keys(this.listeners).length > 0; + } + + async runAsync() { + this.plugin = 0; + for (let i = 0; i < this.plugins.length; i++) { + let plugin = this.plugins[i]; + let promise = this.runOnRoot(plugin); + if (isPromise(promise)) { + try { + await promise; + } catch (error) { + throw this.handleError(error) + } + } + } + + this.prepareVisitors(); + if (this.hasListener) { + let root = this.result.root; + while (!root[isClean]) { + root[isClean] = true; + let stack = [toStack(root)]; + while (stack.length > 0) { + let promise = this.visitTick(stack); + if (isPromise(promise)) { + try { + await promise; + } catch (e) { + let node = stack[stack.length - 1].node; + throw this.handleError(e, node) + } + } + } + } + + if (this.listeners.OnceExit) { + for (let [plugin, visitor] of this.listeners.OnceExit) { + this.result.lastPlugin = plugin; + try { + if (root.type === 'document') { + let roots = root.nodes.map(subRoot => + visitor(subRoot, this.helpers) + ); + + await Promise.all(roots); + } else { + await visitor(root, this.helpers); + } + } catch (e) { + throw this.handleError(e) + } + } + } + } + + this.processed = true; + return this.stringify() + } + + runOnRoot(plugin) { + this.result.lastPlugin = plugin; + try { + if (typeof plugin === 'object' && plugin.Once) { + if (this.result.root.type === 'document') { + let roots = this.result.root.nodes.map(root => + plugin.Once(root, this.helpers) + ); + + if (isPromise(roots[0])) { + return Promise.all(roots) + } + + return roots + } + + return plugin.Once(this.result.root, this.helpers) + } else if (typeof plugin === 'function') { + return plugin(this.result.root, this.result) + } + } catch (error) { + throw this.handleError(error) + } + } + + stringify() { + if (this.error) throw this.error + if (this.stringified) return this.result + this.stringified = true; + + this.sync(); + + let opts = this.result.opts; + let str = stringify$2; + if (opts.syntax) str = opts.syntax.stringify; + if (opts.stringifier) str = opts.stringifier; + if (str.stringify) str = str.stringify; + + let map = new MapGenerator$1(str, this.result.root, this.result.opts); + let data = map.generate(); + this.result.css = data[0]; + this.result.map = data[1]; + + return this.result + } + + sync() { + if (this.error) throw this.error + if (this.processed) return this.result + this.processed = true; + + if (this.processing) { + throw this.getAsyncError() + } + + for (let plugin of this.plugins) { + let promise = this.runOnRoot(plugin); + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + + this.prepareVisitors(); + if (this.hasListener) { + let root = this.result.root; + while (!root[isClean]) { + root[isClean] = true; + this.walkSync(root); + } + if (this.listeners.OnceExit) { + if (root.type === 'document') { + for (let subRoot of root.nodes) { + this.visitSync(this.listeners.OnceExit, subRoot); + } + } else { + this.visitSync(this.listeners.OnceExit, root); + } + } + } + + return this.result + } + + then(onFulfilled, onRejected) { + if (browser$1.env.NODE_ENV !== 'production') { + if (!('from' in this.opts)) { + warnOnce$1( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ); + } + } + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this.css + } + + visitSync(visitors, node) { + for (let [plugin, visitor] of visitors) { + this.result.lastPlugin = plugin; + let promise; + try { + promise = visitor(node, this.helpers); + } catch (e) { + throw this.handleError(e, node.proxyOf) + } + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + return true + } + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + } + + visitTick(stack) { + let visit = stack[stack.length - 1]; + let { node, visitors } = visit; + + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + stack.pop(); + return + } + + if (visitors.length > 0 && visit.visitorIndex < visitors.length) { + let [plugin, visitor] = visitors[visit.visitorIndex]; + visit.visitorIndex += 1; + if (visit.visitorIndex === visitors.length) { + visit.visitors = []; + visit.visitorIndex = 0; + } + this.result.lastPlugin = plugin; + try { + return visitor(node.toProxy(), this.helpers) + } catch (e) { + throw this.handleError(e, node) + } + } + + if (visit.iterator !== 0) { + let iterator = visit.iterator; + let child; + while ((child = node.nodes[node.indexes[iterator]])) { + node.indexes[iterator] += 1; + if (!child[isClean]) { + child[isClean] = true; + stack.push(toStack(child)); + return + } + } + visit.iterator = 0; + delete node.indexes[iterator]; + } + + let events = visit.events; + while (visit.eventIndex < events.length) { + let event = events[visit.eventIndex]; + visit.eventIndex += 1; + if (event === CHILDREN) { + if (node.nodes && node.nodes.length) { + node[isClean] = true; + visit.iterator = node.getIterator(); + } + return + } else if (this.listeners[event]) { + visit.visitors = this.listeners[event]; + return + } + } + stack.pop(); + } + + walkSync(node) { + node[isClean] = true; + let events = getEvents(node); + for (let event of events) { + if (event === CHILDREN) { + if (node.nodes) { + node.each(child => { + if (!child[isClean]) this.walkSync(child); + }); + } + } else { + let visitors = this.listeners[event]; + if (visitors) { + if (this.visitSync(visitors, node.toProxy())) return + } + } + } + } + + warnings() { + return this.sync().warnings() + } + + get content() { + return this.stringify().content + } + + get css() { + return this.stringify().css + } + + get map() { + return this.stringify().map + } + + get messages() { + return this.sync().messages + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + return this.sync().root + } + + get [Symbol.toStringTag]() { + return 'LazyResult' + } +}; + +LazyResult$2.registerPostcss = dependant => { + postcss$2 = dependant; +}; + +var lazyResult = LazyResult$2; +LazyResult$2.default = LazyResult$2; + +Root$3.registerLazyResult(LazyResult$2); +Document$2.registerLazyResult(LazyResult$2); + +let MapGenerator = mapGenerator; +let stringify$1 = stringify_1; +let warnOnce = warnOnce$2; +let parse$1 = parse_1; +const Result$1 = result; + +let NoWorkResult$1 = class NoWorkResult { + constructor(processor, css, opts) { + css = css.toString(); + this.stringified = false; + + this._processor = processor; + this._css = css; + this._opts = opts; + this._map = undefined; + let root; + + let str = stringify$1; + this.result = new Result$1(this._processor, root, this._opts); + this.result.css = css; + + let self = this; + Object.defineProperty(this.result, 'root', { + get() { + return self.root + } + }); + + let map = new MapGenerator(str, root, this._opts, css); + if (map.isMap()) { + let [generatedCSS, generatedMap] = map.generate(); + if (generatedCSS) { + this.result.css = generatedCSS; + } + if (generatedMap) { + this.result.map = generatedMap; + } + } else { + map.clearAnnotation(); + this.result.css = map.css; + } + } + + async() { + if (this.error) return Promise.reject(this.error) + return Promise.resolve(this.result) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + sync() { + if (this.error) throw this.error + return this.result + } + + then(onFulfilled, onRejected) { + if (browser$1.env.NODE_ENV !== 'production') { + if (!('from' in this._opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ); + } + } + + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this._css + } + + warnings() { + return [] + } + + get content() { + return this.result.css + } + + get css() { + return this.result.css + } + + get map() { + return this.result.map + } + + get messages() { + return [] + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + if (this._root) { + return this._root + } + + let root; + let parser = parse$1; + + try { + root = parser(this._css, this._opts); + } catch (error) { + this.error = error; + } + + if (this.error) { + throw this.error + } else { + this._root = root; + return root + } + } + + get [Symbol.toStringTag]() { + return 'NoWorkResult' + } +}; + +var noWorkResult = NoWorkResult$1; +NoWorkResult$1.default = NoWorkResult$1; + +let NoWorkResult = noWorkResult; +let LazyResult$1 = lazyResult; +let Document$1 = document; +let Root$2 = root$2; + +let Processor$1 = class Processor { + constructor(plugins = []) { + this.version = '8.4.35'; + this.plugins = this.normalize(plugins); + } + + normalize(plugins) { + let normalized = []; + for (let i of plugins) { + if (i.postcss === true) { + i = i(); + } else if (i.postcss) { + i = i.postcss; + } + + if (typeof i === 'object' && Array.isArray(i.plugins)) { + normalized = normalized.concat(i.plugins); + } else if (typeof i === 'object' && i.postcssPlugin) { + normalized.push(i); + } else if (typeof i === 'function') { + normalized.push(i); + } else if (typeof i === 'object' && (i.parse || i.stringify)) { + if (browser$1.env.NODE_ENV !== 'production') { + throw new Error( + 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' + + 'one of the syntax/parser/stringifier options as outlined ' + + 'in your PostCSS runner documentation.' + ) + } + } else { + throw new Error(i + ' is not a PostCSS plugin') + } + } + return normalized + } + + process(css, opts = {}) { + if ( + !this.plugins.length && + !opts.parser && + !opts.stringifier && + !opts.syntax + ) { + return new NoWorkResult(this, css, opts) + } else { + return new LazyResult$1(this, css, opts) + } + } + + use(plugin) { + this.plugins = this.plugins.concat(this.normalize([plugin])); + return this + } +}; + +var processor$1 = Processor$1; +Processor$1.default = Processor$1; + +Root$2.registerProcessor(Processor$1); +Document$1.registerProcessor(Processor$1); + +let Declaration$1 = declaration; +let PreviousMap = previousMap; +let Comment$1 = comment$3; +let AtRule$1 = atRule; +let Input$1 = input; +let Root$1 = root$2; +let Rule$1 = rule; + +function fromJSON$1(json, inputs) { + if (Array.isArray(json)) return json.map(n => fromJSON$1(n)) + + let { inputs: ownInputs, ...defaults } = json; + if (ownInputs) { + inputs = []; + for (let input of ownInputs) { + let inputHydrated = { ...input, __proto__: Input$1.prototype }; + if (inputHydrated.map) { + inputHydrated.map = { + ...inputHydrated.map, + __proto__: PreviousMap.prototype + }; + } + inputs.push(inputHydrated); + } + } + if (defaults.nodes) { + defaults.nodes = json.nodes.map(n => fromJSON$1(n, inputs)); + } + if (defaults.source) { + let { inputId, ...source } = defaults.source; + defaults.source = source; + if (inputId != null) { + defaults.source.input = inputs[inputId]; + } + } + if (defaults.type === 'root') { + return new Root$1(defaults) + } else if (defaults.type === 'decl') { + return new Declaration$1(defaults) + } else if (defaults.type === 'rule') { + return new Rule$1(defaults) + } else if (defaults.type === 'comment') { + return new Comment$1(defaults) + } else if (defaults.type === 'atrule') { + return new AtRule$1(defaults) + } else { + throw new Error('Unknown node type: ' + json.type) + } +} + +var fromJSON_1 = fromJSON$1; +fromJSON$1.default = fromJSON$1; + +let CssSyntaxError = cssSyntaxError; +let Declaration = declaration; +let LazyResult = lazyResult; +let Container = container$1; +let Processor = processor$1; +let stringify = stringify_1; +let fromJSON = fromJSON_1; +let Document = document; +let Warning = warning; +let Comment = comment$3; +let AtRule = atRule; +let Result = result; +let Input = input; +let parse = parse_1; +let list = list_1; +let Rule = rule; +let Root = root$2; +let Node = node$2; + +function postcss(...plugins) { + if (plugins.length === 1 && Array.isArray(plugins[0])) { + plugins = plugins[0]; + } + return new Processor(plugins) +} + +postcss.plugin = function plugin(name, initializer) { + let warningPrinted = false; + function creator(...args) { + // eslint-disable-next-line no-console + if (console && console.warn && !warningPrinted) { + warningPrinted = true; + // eslint-disable-next-line no-console + console.warn( + name + + ': postcss.plugin was deprecated. Migration guide:\n' + + 'https://evilmartians.com/chronicles/postcss-8-plugin-migration' + ); + if (browser$1.env.LANG && browser$1.env.LANG.startsWith('cn')) { + /* c8 ignore next 7 */ + // eslint-disable-next-line no-console + console.warn( + name + + ': 里面 postcss.plugin 被弃用. 迁移指南:\n' + + 'https://www.w3ctech.com/topic/2226' + ); + } + } + let transformer = initializer(...args); + transformer.postcssPlugin = name; + transformer.postcssVersion = new Processor().version; + return transformer + } + + let cache; + Object.defineProperty(creator, 'postcss', { + get() { + if (!cache) cache = creator(); + return cache + } + }); + + creator.process = function (css, processOpts, pluginOpts) { + return postcss([creator(pluginOpts)]).process(css, processOpts) + }; + + return creator +}; + +postcss.stringify = stringify; +postcss.parse = parse; +postcss.fromJSON = fromJSON; +postcss.list = list; + +postcss.comment = defaults => new Comment(defaults); +postcss.atRule = defaults => new AtRule(defaults); +postcss.decl = defaults => new Declaration(defaults); +postcss.rule = defaults => new Rule(defaults); +postcss.root = defaults => new Root(defaults); +postcss.document = defaults => new Document(defaults); + +postcss.CssSyntaxError = CssSyntaxError; +postcss.Declaration = Declaration; +postcss.Container = Container; +postcss.Processor = Processor; +postcss.Document = Document; +postcss.Comment = Comment; +postcss.Warning = Warning; +postcss.AtRule = AtRule; +postcss.Result = Result; +postcss.Input = Input; +postcss.Rule = Rule; +postcss.Root = Root; +postcss.Node = Node; + +LazyResult.registerPostcss(postcss); + +var postcss_1 = postcss; +postcss.default = postcss; + +var postcss$1 = /*@__PURE__*/getDefaultExportFromCjs(postcss_1); + +postcss$1.stringify; +postcss$1.fromJSON; +postcss$1.plugin; +postcss$1.parse; +postcss$1.list; + +postcss$1.document; +postcss$1.comment; +postcss$1.atRule; +postcss$1.rule; +postcss$1.decl; +postcss$1.root; + +postcss$1.CssSyntaxError; +postcss$1.Declaration; +postcss$1.Container; +postcss$1.Processor; +postcss$1.Document; +postcss$1.Comment; +postcss$1.Warning; +postcss$1.AtRule; +postcss$1.Result; +postcss$1.Input; +postcss$1.Rule; +postcss$1.Root; +postcss$1.Node; + +const trimPlugin = () => { + return { + postcssPlugin: "vue-sfc-trim", + Once(root) { + root.walk(({ type, raws }) => { + if (type === "rule" || type === "atrule") { + if (raws.before) + raws.before = "\n"; + if ("after" in raws && raws.after) + raws.after = "\n"; + } + }); + } + }; +}; +trimPlugin.postcss = true; + +var dist = {exports: {}}; + +var processor = {exports: {}}; + +var parser = {exports: {}}; + +var root$1 = {exports: {}}; + +var container = {exports: {}}; + +var node$1 = {exports: {}}; + +var util$6 = {}; + +var unesc = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = unesc; + // Many thanks for this post which made this migration much easier. + // https://mathiasbynens.be/notes/css-escapes + + /** + * + * @param {string} str + * @returns {[string, number]|undefined} + */ + function gobbleHex(str) { + var lower = str.toLowerCase(); + var hex = ''; + var spaceTerminated = false; + for (var i = 0; i < 6 && lower[i] !== undefined; i++) { + var code = lower.charCodeAt(i); + // check to see if we are dealing with a valid hex char [a-f|0-9] + var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; + // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point + spaceTerminated = code === 32; + if (!valid) { + break; + } + hex += lower[i]; + } + if (hex.length === 0) { + return undefined; + } + var codePoint = parseInt(hex, 16); + var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; + // Add special case for + // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point" + // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point + if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) { + return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)]; + } + return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)]; + } + var CONTAINS_ESCAPE = /\\/; + function unesc(str) { + var needToProcess = CONTAINS_ESCAPE.test(str); + if (!needToProcess) { + return str; + } + var ret = ""; + for (var i = 0; i < str.length; i++) { + if (str[i] === "\\") { + var gobbled = gobbleHex(str.slice(i + 1, i + 7)); + if (gobbled !== undefined) { + ret += gobbled[0]; + i += gobbled[1]; + continue; + } + + // Retain a pair of \\ if double escaped `\\\\` + // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e + if (str[i + 1] === "\\") { + ret += "\\"; + i++; + continue; + } + + // if \\ is at the end of the string retain it + // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb + if (str.length === i + 1) { + ret += str[i]; + } + continue; + } + ret += str[i]; + } + return ret; + } + module.exports = exports.default; +} (unesc, unesc.exports)); + +var unescExports = unesc.exports; + +var getProp = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = getProp; + function getProp(obj) { + for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + props[_key - 1] = arguments[_key]; + } + while (props.length > 0) { + var prop = props.shift(); + if (!obj[prop]) { + return undefined; + } + obj = obj[prop]; + } + return obj; + } + module.exports = exports.default; +} (getProp, getProp.exports)); + +var getPropExports = getProp.exports; + +var ensureObject = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = ensureObject; + function ensureObject(obj) { + for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + props[_key - 1] = arguments[_key]; + } + while (props.length > 0) { + var prop = props.shift(); + if (!obj[prop]) { + obj[prop] = {}; + } + obj = obj[prop]; + } + } + module.exports = exports.default; +} (ensureObject, ensureObject.exports)); + +var ensureObjectExports = ensureObject.exports; + +var stripComments = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = stripComments; + function stripComments(str) { + var s = ""; + var commentStart = str.indexOf("/*"); + var lastEnd = 0; + while (commentStart >= 0) { + s = s + str.slice(lastEnd, commentStart); + var commentEnd = str.indexOf("*/", commentStart + 2); + if (commentEnd < 0) { + return s; + } + lastEnd = commentEnd + 2; + commentStart = str.indexOf("/*", lastEnd); + } + s = s + str.slice(lastEnd); + return s; + } + module.exports = exports.default; +} (stripComments, stripComments.exports)); + +var stripCommentsExports = stripComments.exports; + +util$6.__esModule = true; +util$6.unesc = util$6.stripComments = util$6.getProp = util$6.ensureObject = void 0; +var _unesc = _interopRequireDefault$1(unescExports); +util$6.unesc = _unesc["default"]; +var _getProp = _interopRequireDefault$1(getPropExports); +util$6.getProp = _getProp["default"]; +var _ensureObject = _interopRequireDefault$1(ensureObjectExports); +util$6.ensureObject = _ensureObject["default"]; +var _stripComments = _interopRequireDefault$1(stripCommentsExports); +util$6.stripComments = _stripComments["default"]; +function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _util = util$6; + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + var cloneNode = function cloneNode(obj, parent) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + var cloned = new obj.constructor(); + for (var i in obj) { + if (!obj.hasOwnProperty(i)) { + continue; + } + var value = obj[i]; + var type = typeof value; + if (i === 'parent' && type === 'object') { + if (parent) { + cloned[i] = parent; + } + } else if (value instanceof Array) { + cloned[i] = value.map(function (j) { + return cloneNode(j, cloned); + }); + } else { + cloned[i] = cloneNode(value, cloned); + } + } + return cloned; + }; + var Node = /*#__PURE__*/function () { + function Node(opts) { + if (opts === void 0) { + opts = {}; + } + Object.assign(this, opts); + this.spaces = this.spaces || {}; + this.spaces.before = this.spaces.before || ''; + this.spaces.after = this.spaces.after || ''; + } + var _proto = Node.prototype; + _proto.remove = function remove() { + if (this.parent) { + this.parent.removeChild(this); + } + this.parent = undefined; + return this; + }; + _proto.replaceWith = function replaceWith() { + if (this.parent) { + for (var index in arguments) { + this.parent.insertBefore(this, arguments[index]); + } + this.remove(); + } + return this; + }; + _proto.next = function next() { + return this.parent.at(this.parent.index(this) + 1); + }; + _proto.prev = function prev() { + return this.parent.at(this.parent.index(this) - 1); + }; + _proto.clone = function clone(overrides) { + if (overrides === void 0) { + overrides = {}; + } + var cloned = cloneNode(this); + for (var name in overrides) { + cloned[name] = overrides[name]; + } + return cloned; + } + + /** + * Some non-standard syntax doesn't follow normal escaping rules for css. + * This allows non standard syntax to be appended to an existing property + * by specifying the escaped value. By specifying the escaped value, + * illegal characters are allowed to be directly inserted into css output. + * @param {string} name the property to set + * @param {any} value the unescaped value of the property + * @param {string} valueEscaped optional. the escaped value of the property. + */; + _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) { + if (!this.raws) { + this.raws = {}; + } + var originalValue = this[name]; + var originalEscaped = this.raws[name]; + this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first. + if (originalEscaped || valueEscaped !== value) { + this.raws[name] = (originalEscaped || originalValue) + valueEscaped; + } else { + delete this.raws[name]; // delete any escaped value that was created by the setter. + } + } + + /** + * Some non-standard syntax doesn't follow normal escaping rules for css. + * This allows the escaped value to be specified directly, allowing illegal + * characters to be directly inserted into css output. + * @param {string} name the property to set + * @param {any} value the unescaped value of the property + * @param {string} valueEscaped the escaped value of the property. + */; + _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) { + if (!this.raws) { + this.raws = {}; + } + this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. + this.raws[name] = valueEscaped; + } + + /** + * When you want a value to passed through to CSS directly. This method + * deletes the corresponding raw value causing the stringifier to fallback + * to the unescaped value. + * @param {string} name the property to set. + * @param {any} value The value that is both escaped and unescaped. + */; + _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) { + this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. + if (this.raws) { + delete this.raws[name]; + } + } + + /** + * + * @param {number} line The number (starting with 1) + * @param {number} column The column number (starting with 1) + */; + _proto.isAtPosition = function isAtPosition(line, column) { + if (this.source && this.source.start && this.source.end) { + if (this.source.start.line > line) { + return false; + } + if (this.source.end.line < line) { + return false; + } + if (this.source.start.line === line && this.source.start.column > column) { + return false; + } + if (this.source.end.line === line && this.source.end.column < column) { + return false; + } + return true; + } + return undefined; + }; + _proto.stringifyProperty = function stringifyProperty(name) { + return this.raws && this.raws[name] || this[name]; + }; + _proto.valueToString = function valueToString() { + return String(this.stringifyProperty("value")); + }; + _proto.toString = function toString() { + return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join(''); + }; + _createClass(Node, [{ + key: "rawSpaceBefore", + get: function get() { + var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before; + if (rawSpace === undefined) { + rawSpace = this.spaces && this.spaces.before; + } + return rawSpace || ""; + }, + set: function set(raw) { + (0, _util.ensureObject)(this, "raws", "spaces"); + this.raws.spaces.before = raw; + } + }, { + key: "rawSpaceAfter", + get: function get() { + var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after; + if (rawSpace === undefined) { + rawSpace = this.spaces.after; + } + return rawSpace || ""; + }, + set: function set(raw) { + (0, _util.ensureObject)(this, "raws", "spaces"); + this.raws.spaces.after = raw; + } + }]); + return Node; + }(); + exports["default"] = Node; + module.exports = exports.default; +} (node$1, node$1.exports)); + +var nodeExports = node$1.exports; + +var types = {}; + +types.__esModule = true; +types.UNIVERSAL = types.TAG = types.STRING = types.SELECTOR = types.ROOT = types.PSEUDO = types.NESTING = types.ID = types.COMMENT = types.COMBINATOR = types.CLASS = types.ATTRIBUTE = void 0; +var TAG = 'tag'; +types.TAG = TAG; +var STRING = 'string'; +types.STRING = STRING; +var SELECTOR = 'selector'; +types.SELECTOR = SELECTOR; +var ROOT = 'root'; +types.ROOT = ROOT; +var PSEUDO = 'pseudo'; +types.PSEUDO = PSEUDO; +var NESTING = 'nesting'; +types.NESTING = NESTING; +var ID = 'id'; +types.ID = ID; +var COMMENT = 'comment'; +types.COMMENT = COMMENT; +var COMBINATOR = 'combinator'; +types.COMBINATOR = COMBINATOR; +var CLASS = 'class'; +types.CLASS = CLASS; +var ATTRIBUTE = 'attribute'; +types.ATTRIBUTE = ATTRIBUTE; +var UNIVERSAL = 'universal'; +types.UNIVERSAL = UNIVERSAL; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _node = _interopRequireDefault(nodeExports); + var types$1 = _interopRequireWildcard(types); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Container = /*#__PURE__*/function (_Node) { + _inheritsLoose(Container, _Node); + function Container(opts) { + var _this; + _this = _Node.call(this, opts) || this; + if (!_this.nodes) { + _this.nodes = []; + } + return _this; + } + var _proto = Container.prototype; + _proto.append = function append(selector) { + selector.parent = this; + this.nodes.push(selector); + return this; + }; + _proto.prepend = function prepend(selector) { + selector.parent = this; + this.nodes.unshift(selector); + return this; + }; + _proto.at = function at(index) { + return this.nodes[index]; + }; + _proto.index = function index(child) { + if (typeof child === 'number') { + return child; + } + return this.nodes.indexOf(child); + }; + _proto.removeChild = function removeChild(child) { + child = this.index(child); + this.at(child).parent = undefined; + this.nodes.splice(child, 1); + var index; + for (var id in this.indexes) { + index = this.indexes[id]; + if (index >= child) { + this.indexes[id] = index - 1; + } + } + return this; + }; + _proto.removeAll = function removeAll() { + for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) { + var node = _step.value; + node.parent = undefined; + } + this.nodes = []; + return this; + }; + _proto.empty = function empty() { + return this.removeAll(); + }; + _proto.insertAfter = function insertAfter(oldNode, newNode) { + newNode.parent = this; + var oldIndex = this.index(oldNode); + this.nodes.splice(oldIndex + 1, 0, newNode); + newNode.parent = this; + var index; + for (var id in this.indexes) { + index = this.indexes[id]; + if (oldIndex <= index) { + this.indexes[id] = index + 1; + } + } + return this; + }; + _proto.insertBefore = function insertBefore(oldNode, newNode) { + newNode.parent = this; + var oldIndex = this.index(oldNode); + this.nodes.splice(oldIndex, 0, newNode); + newNode.parent = this; + var index; + for (var id in this.indexes) { + index = this.indexes[id]; + if (index <= oldIndex) { + this.indexes[id] = index + 1; + } + } + return this; + }; + _proto._findChildAtPosition = function _findChildAtPosition(line, col) { + var found = undefined; + this.each(function (node) { + if (node.atPosition) { + var foundChild = node.atPosition(line, col); + if (foundChild) { + found = foundChild; + return false; + } + } else if (node.isAtPosition(line, col)) { + found = node; + return false; + } + }); + return found; + } + + /** + * Return the most specific node at the line and column number given. + * The source location is based on the original parsed location, locations aren't + * updated as selector nodes are mutated. + * + * Note that this location is relative to the location of the first character + * of the selector, and not the location of the selector in the overall document + * when used in conjunction with postcss. + * + * If not found, returns undefined. + * @param {number} line The line number of the node to find. (1-based index) + * @param {number} col The column number of the node to find. (1-based index) + */; + _proto.atPosition = function atPosition(line, col) { + if (this.isAtPosition(line, col)) { + return this._findChildAtPosition(line, col) || this; + } else { + return undefined; + } + }; + _proto._inferEndPosition = function _inferEndPosition() { + if (this.last && this.last.source && this.last.source.end) { + this.source = this.source || {}; + this.source.end = this.source.end || {}; + Object.assign(this.source.end, this.last.source.end); + } + }; + _proto.each = function each(callback) { + if (!this.lastEach) { + this.lastEach = 0; + } + if (!this.indexes) { + this.indexes = {}; + } + this.lastEach++; + var id = this.lastEach; + this.indexes[id] = 0; + if (!this.length) { + return undefined; + } + var index, result; + while (this.indexes[id] < this.length) { + index = this.indexes[id]; + result = callback(this.at(index), index); + if (result === false) { + break; + } + this.indexes[id] += 1; + } + delete this.indexes[id]; + if (result === false) { + return false; + } + }; + _proto.walk = function walk(callback) { + return this.each(function (node, i) { + var result = callback(node, i); + if (result !== false && node.length) { + result = node.walk(callback); + } + if (result === false) { + return false; + } + }); + }; + _proto.walkAttributes = function walkAttributes(callback) { + var _this2 = this; + return this.walk(function (selector) { + if (selector.type === types$1.ATTRIBUTE) { + return callback.call(_this2, selector); + } + }); + }; + _proto.walkClasses = function walkClasses(callback) { + var _this3 = this; + return this.walk(function (selector) { + if (selector.type === types$1.CLASS) { + return callback.call(_this3, selector); + } + }); + }; + _proto.walkCombinators = function walkCombinators(callback) { + var _this4 = this; + return this.walk(function (selector) { + if (selector.type === types$1.COMBINATOR) { + return callback.call(_this4, selector); + } + }); + }; + _proto.walkComments = function walkComments(callback) { + var _this5 = this; + return this.walk(function (selector) { + if (selector.type === types$1.COMMENT) { + return callback.call(_this5, selector); + } + }); + }; + _proto.walkIds = function walkIds(callback) { + var _this6 = this; + return this.walk(function (selector) { + if (selector.type === types$1.ID) { + return callback.call(_this6, selector); + } + }); + }; + _proto.walkNesting = function walkNesting(callback) { + var _this7 = this; + return this.walk(function (selector) { + if (selector.type === types$1.NESTING) { + return callback.call(_this7, selector); + } + }); + }; + _proto.walkPseudos = function walkPseudos(callback) { + var _this8 = this; + return this.walk(function (selector) { + if (selector.type === types$1.PSEUDO) { + return callback.call(_this8, selector); + } + }); + }; + _proto.walkTags = function walkTags(callback) { + var _this9 = this; + return this.walk(function (selector) { + if (selector.type === types$1.TAG) { + return callback.call(_this9, selector); + } + }); + }; + _proto.walkUniversals = function walkUniversals(callback) { + var _this10 = this; + return this.walk(function (selector) { + if (selector.type === types$1.UNIVERSAL) { + return callback.call(_this10, selector); + } + }); + }; + _proto.split = function split(callback) { + var _this11 = this; + var current = []; + return this.reduce(function (memo, node, index) { + var split = callback.call(_this11, node); + current.push(node); + if (split) { + memo.push(current); + current = []; + } else if (index === _this11.length - 1) { + memo.push(current); + } + return memo; + }, []); + }; + _proto.map = function map(callback) { + return this.nodes.map(callback); + }; + _proto.reduce = function reduce(callback, memo) { + return this.nodes.reduce(callback, memo); + }; + _proto.every = function every(callback) { + return this.nodes.every(callback); + }; + _proto.some = function some(callback) { + return this.nodes.some(callback); + }; + _proto.filter = function filter(callback) { + return this.nodes.filter(callback); + }; + _proto.sort = function sort(callback) { + return this.nodes.sort(callback); + }; + _proto.toString = function toString() { + return this.map(String).join(''); + }; + _createClass(Container, [{ + key: "first", + get: function get() { + return this.at(0); + } + }, { + key: "last", + get: function get() { + return this.at(this.length - 1); + } + }, { + key: "length", + get: function get() { + return this.nodes.length; + } + }]); + return Container; + }(_node["default"]); + exports["default"] = Container; + module.exports = exports.default; +} (container, container.exports)); + +var containerExports = container.exports; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _container = _interopRequireDefault(containerExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Root = /*#__PURE__*/function (_Container) { + _inheritsLoose(Root, _Container); + function Root(opts) { + var _this; + _this = _Container.call(this, opts) || this; + _this.type = _types.ROOT; + return _this; + } + var _proto = Root.prototype; + _proto.toString = function toString() { + var str = this.reduce(function (memo, selector) { + memo.push(String(selector)); + return memo; + }, []).join(','); + return this.trailingComma ? str + ',' : str; + }; + _proto.error = function error(message, options) { + if (this._error) { + return this._error(message, options); + } else { + return new Error(message); + } + }; + _createClass(Root, [{ + key: "errorGenerator", + set: function set(handler) { + this._error = handler; + } + }]); + return Root; + }(_container["default"]); + exports["default"] = Root; + module.exports = exports.default; +} (root$1, root$1.exports)); + +var rootExports = root$1.exports; + +var selector$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _container = _interopRequireDefault(containerExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Selector = /*#__PURE__*/function (_Container) { + _inheritsLoose(Selector, _Container); + function Selector(opts) { + var _this; + _this = _Container.call(this, opts) || this; + _this.type = _types.SELECTOR; + return _this; + } + return Selector; + }(_container["default"]); + exports["default"] = Selector; + module.exports = exports.default; +} (selector$1, selector$1.exports)); + +var selectorExports = selector$1.exports; + +var className$1 = {exports: {}}; + +/*! https://mths.be/cssesc v3.0.0 by @mathias */ + +var object = {}; +var hasOwnProperty = object.hasOwnProperty; +var merge$2 = function merge(options, defaults) { + if (!options) { + return defaults; + } + var result = {}; + for (var key in defaults) { + // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since + // only recognized option names are used. + result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key]; + } + return result; +}; + +var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/; +var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/; +var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g; + +// https://mathiasbynens.be/notes/css-escapes#css +var cssesc = function cssesc(string, options) { + options = merge$2(options, cssesc.options); + if (options.quotes != 'single' && options.quotes != 'double') { + options.quotes = 'single'; + } + var quote = options.quotes == 'double' ? '"' : '\''; + var isIdentifier = options.isIdentifier; + + var firstChar = string.charAt(0); + var output = ''; + var counter = 0; + var length = string.length; + while (counter < length) { + var character = string.charAt(counter++); + var codePoint = character.charCodeAt(); + var value = void 0; + // If it’s not a printable ASCII character… + if (codePoint < 0x20 || codePoint > 0x7E) { + if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) { + // It’s a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // next character is low surrogate + codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000; + } else { + // It’s an unmatched surrogate; only append this code unit, in case + // the next code unit is the high surrogate of a surrogate pair. + counter--; + } + } + value = '\\' + codePoint.toString(16).toUpperCase() + ' '; + } else { + if (options.escapeEverything) { + if (regexAnySingleEscape.test(character)) { + value = '\\' + character; + } else { + value = '\\' + codePoint.toString(16).toUpperCase() + ' '; + } + } else if (/[\t\n\f\r\x0B]/.test(character)) { + value = '\\' + codePoint.toString(16).toUpperCase() + ' '; + } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) { + value = '\\' + character; + } else { + value = character; + } + } + output += value; + } + + if (isIdentifier) { + if (/^-[-\d]/.test(output)) { + output = '\\-' + output.slice(1); + } else if (/\d/.test(firstChar)) { + output = '\\3' + firstChar + ' ' + output.slice(1); + } + } + + // Remove spaces after `\HEX` escapes that are not followed by a hex digit, + // since they’re redundant. Note that this is only possible if the escape + // sequence isn’t preceded by an odd number of backslashes. + output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) { + if ($1 && $1.length % 2) { + // It’s not safe to remove the space, so don’t. + return $0; + } + // Strip the space. + return ($1 || '') + $2; + }); + + if (!isIdentifier && options.wrap) { + return quote + output + quote; + } + return output; +}; + +// Expose default options (so they can be overridden globally). +cssesc.options = { + 'escapeEverything': false, + 'isIdentifier': false, + 'quotes': 'single', + 'wrap': false +}; + +cssesc.version = '3.0.0'; + +var cssesc_1 = cssesc; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _cssesc = _interopRequireDefault(cssesc_1); + var _util = util$6; + var _node = _interopRequireDefault(nodeExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var ClassName = /*#__PURE__*/function (_Node) { + _inheritsLoose(ClassName, _Node); + function ClassName(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.CLASS; + _this._constructed = true; + return _this; + } + var _proto = ClassName.prototype; + _proto.valueToString = function valueToString() { + return '.' + _Node.prototype.valueToString.call(this); + }; + _createClass(ClassName, [{ + key: "value", + get: function get() { + return this._value; + }, + set: function set(v) { + if (this._constructed) { + var escaped = (0, _cssesc["default"])(v, { + isIdentifier: true + }); + if (escaped !== v) { + (0, _util.ensureObject)(this, "raws"); + this.raws.value = escaped; + } else if (this.raws) { + delete this.raws.value; + } + } + this._value = v; + } + }]); + return ClassName; + }(_node["default"]); + exports["default"] = ClassName; + module.exports = exports.default; +} (className$1, className$1.exports)); + +var classNameExports = className$1.exports; + +var comment$2 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _node = _interopRequireDefault(nodeExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Comment = /*#__PURE__*/function (_Node) { + _inheritsLoose(Comment, _Node); + function Comment(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.COMMENT; + return _this; + } + return Comment; + }(_node["default"]); + exports["default"] = Comment; + module.exports = exports.default; +} (comment$2, comment$2.exports)); + +var commentExports = comment$2.exports; + +var id$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _node = _interopRequireDefault(nodeExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var ID = /*#__PURE__*/function (_Node) { + _inheritsLoose(ID, _Node); + function ID(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.ID; + return _this; + } + var _proto = ID.prototype; + _proto.valueToString = function valueToString() { + return '#' + _Node.prototype.valueToString.call(this); + }; + return ID; + }(_node["default"]); + exports["default"] = ID; + module.exports = exports.default; +} (id$1, id$1.exports)); + +var idExports = id$1.exports; + +var tag$1 = {exports: {}}; + +var namespace = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _cssesc = _interopRequireDefault(cssesc_1); + var _util = util$6; + var _node = _interopRequireDefault(nodeExports); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Namespace = /*#__PURE__*/function (_Node) { + _inheritsLoose(Namespace, _Node); + function Namespace() { + return _Node.apply(this, arguments) || this; + } + var _proto = Namespace.prototype; + _proto.qualifiedName = function qualifiedName(value) { + if (this.namespace) { + return this.namespaceString + "|" + value; + } else { + return value; + } + }; + _proto.valueToString = function valueToString() { + return this.qualifiedName(_Node.prototype.valueToString.call(this)); + }; + _createClass(Namespace, [{ + key: "namespace", + get: function get() { + return this._namespace; + }, + set: function set(namespace) { + if (namespace === true || namespace === "*" || namespace === "&") { + this._namespace = namespace; + if (this.raws) { + delete this.raws.namespace; + } + return; + } + var escaped = (0, _cssesc["default"])(namespace, { + isIdentifier: true + }); + this._namespace = namespace; + if (escaped !== namespace) { + (0, _util.ensureObject)(this, "raws"); + this.raws.namespace = escaped; + } else if (this.raws) { + delete this.raws.namespace; + } + } + }, { + key: "ns", + get: function get() { + return this._namespace; + }, + set: function set(namespace) { + this.namespace = namespace; + } + }, { + key: "namespaceString", + get: function get() { + if (this.namespace) { + var ns = this.stringifyProperty("namespace"); + if (ns === true) { + return ''; + } else { + return ns; + } + } else { + return ''; + } + } + }]); + return Namespace; + }(_node["default"]); + exports["default"] = Namespace; + module.exports = exports.default; +} (namespace, namespace.exports)); + +var namespaceExports = namespace.exports; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _namespace = _interopRequireDefault(namespaceExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Tag = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Tag, _Namespace); + function Tag(opts) { + var _this; + _this = _Namespace.call(this, opts) || this; + _this.type = _types.TAG; + return _this; + } + return Tag; + }(_namespace["default"]); + exports["default"] = Tag; + module.exports = exports.default; +} (tag$1, tag$1.exports)); + +var tagExports = tag$1.exports; + +var string$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _node = _interopRequireDefault(nodeExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var String = /*#__PURE__*/function (_Node) { + _inheritsLoose(String, _Node); + function String(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.STRING; + return _this; + } + return String; + }(_node["default"]); + exports["default"] = String; + module.exports = exports.default; +} (string$1, string$1.exports)); + +var stringExports = string$1.exports; + +var pseudo$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _container = _interopRequireDefault(containerExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Pseudo = /*#__PURE__*/function (_Container) { + _inheritsLoose(Pseudo, _Container); + function Pseudo(opts) { + var _this; + _this = _Container.call(this, opts) || this; + _this.type = _types.PSEUDO; + return _this; + } + var _proto = Pseudo.prototype; + _proto.toString = function toString() { + var params = this.length ? '(' + this.map(String).join(',') + ')' : ''; + return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join(''); + }; + return Pseudo; + }(_container["default"]); + exports["default"] = Pseudo; + module.exports = exports.default; +} (pseudo$1, pseudo$1.exports)); + +var pseudoExports = pseudo$1.exports; + +var attribute$1 = {}; + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +var node = require$$0$1.deprecate; + +(function (exports) { + + exports.__esModule = true; + exports["default"] = void 0; + exports.unescapeValue = unescapeValue; + var _cssesc = _interopRequireDefault(cssesc_1); + var _unesc = _interopRequireDefault(unescExports); + var _namespace = _interopRequireDefault(namespaceExports); + var _types = types; + var _CSSESC_QUOTE_OPTIONS; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var deprecate = node; + var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/; + var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead."); + var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."); + var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now."); + function unescapeValue(value) { + var deprecatedUsage = false; + var quoteMark = null; + var unescaped = value; + var m = unescaped.match(WRAPPED_IN_QUOTES); + if (m) { + quoteMark = m[1]; + unescaped = m[2]; + } + unescaped = (0, _unesc["default"])(unescaped); + if (unescaped !== value) { + deprecatedUsage = true; + } + return { + deprecatedUsage: deprecatedUsage, + unescaped: unescaped, + quoteMark: quoteMark + }; + } + function handleDeprecatedContructorOpts(opts) { + if (opts.quoteMark !== undefined) { + return opts; + } + if (opts.value === undefined) { + return opts; + } + warnOfDeprecatedConstructor(); + var _unescapeValue = unescapeValue(opts.value), + quoteMark = _unescapeValue.quoteMark, + unescaped = _unescapeValue.unescaped; + if (!opts.raws) { + opts.raws = {}; + } + if (opts.raws.value === undefined) { + opts.raws.value = opts.value; + } + opts.value = unescaped; + opts.quoteMark = quoteMark; + return opts; + } + var Attribute = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Attribute, _Namespace); + function Attribute(opts) { + var _this; + if (opts === void 0) { + opts = {}; + } + _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this; + _this.type = _types.ATTRIBUTE; + _this.raws = _this.raws || {}; + Object.defineProperty(_this.raws, 'unquoted', { + get: deprecate(function () { + return _this.value; + }, "attr.raws.unquoted is deprecated. Call attr.value instead."), + set: deprecate(function () { + return _this.value; + }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.") + }); + _this._constructed = true; + return _this; + } + + /** + * Returns the Attribute's value quoted such that it would be legal to use + * in the value of a css file. The original value's quotation setting + * used for stringification is left unchanged. See `setValue(value, options)` + * if you want to control the quote settings of a new value for the attribute. + * + * You can also change the quotation used for the current value by setting quoteMark. + * + * Options: + * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this + * option is not set, the original value for quoteMark will be used. If + * indeterminate, a double quote is used. The legal values are: + * * `null` - the value will be unquoted and characters will be escaped as necessary. + * * `'` - the value will be quoted with a single quote and single quotes are escaped. + * * `"` - the value will be quoted with a double quote and double quotes are escaped. + * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark + * over the quoteMark option value. + * * smart {boolean} - if true, will select a quote mark based on the value + * and the other options specified here. See the `smartQuoteMark()` + * method. + **/ + var _proto = Attribute.prototype; + _proto.getQuotedValue = function getQuotedValue(options) { + if (options === void 0) { + options = {}; + } + var quoteMark = this._determineQuoteMark(options); + var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark]; + var escaped = (0, _cssesc["default"])(this._value, cssescopts); + return escaped; + }; + _proto._determineQuoteMark = function _determineQuoteMark(options) { + return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options); + } + + /** + * Set the unescaped value with the specified quotation options. The value + * provided must not include any wrapping quote marks -- those quotes will + * be interpreted as part of the value and escaped accordingly. + */; + _proto.setValue = function setValue(value, options) { + if (options === void 0) { + options = {}; + } + this._value = value; + this._quoteMark = this._determineQuoteMark(options); + this._syncRawValue(); + } + + /** + * Intelligently select a quoteMark value based on the value's contents. If + * the value is a legal CSS ident, it will not be quoted. Otherwise a quote + * mark will be picked that minimizes the number of escapes. + * + * If there's no clear winner, the quote mark from these options is used, + * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is + * true). If the quoteMark is unspecified, a double quote is used. + * + * @param options This takes the quoteMark and preferCurrentQuoteMark options + * from the quoteValue method. + */; + _proto.smartQuoteMark = function smartQuoteMark(options) { + var v = this.value; + var numSingleQuotes = v.replace(/[^']/g, '').length; + var numDoubleQuotes = v.replace(/[^"]/g, '').length; + if (numSingleQuotes + numDoubleQuotes === 0) { + var escaped = (0, _cssesc["default"])(v, { + isIdentifier: true + }); + if (escaped === v) { + return Attribute.NO_QUOTE; + } else { + var pref = this.preferredQuoteMark(options); + if (pref === Attribute.NO_QUOTE) { + // pick a quote mark that isn't none and see if it's smaller + var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE; + var opts = CSSESC_QUOTE_OPTIONS[quote]; + var quoteValue = (0, _cssesc["default"])(v, opts); + if (quoteValue.length < escaped.length) { + return quote; + } + } + return pref; + } + } else if (numDoubleQuotes === numSingleQuotes) { + return this.preferredQuoteMark(options); + } else if (numDoubleQuotes < numSingleQuotes) { + return Attribute.DOUBLE_QUOTE; + } else { + return Attribute.SINGLE_QUOTE; + } + } + + /** + * Selects the preferred quote mark based on the options and the current quote mark value. + * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)` + * instead. + */; + _proto.preferredQuoteMark = function preferredQuoteMark(options) { + var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark; + if (quoteMark === undefined) { + quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark; + } + if (quoteMark === undefined) { + quoteMark = Attribute.DOUBLE_QUOTE; + } + return quoteMark; + }; + _proto._syncRawValue = function _syncRawValue() { + var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]); + if (rawValue === this._value) { + if (this.raws) { + delete this.raws.value; + } + } else { + this.raws.value = rawValue; + } + }; + _proto._handleEscapes = function _handleEscapes(prop, value) { + if (this._constructed) { + var escaped = (0, _cssesc["default"])(value, { + isIdentifier: true + }); + if (escaped !== value) { + this.raws[prop] = escaped; + } else { + delete this.raws[prop]; + } + } + }; + _proto._spacesFor = function _spacesFor(name) { + var attrSpaces = { + before: '', + after: '' + }; + var spaces = this.spaces[name] || {}; + var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {}; + return Object.assign(attrSpaces, spaces, rawSpaces); + }; + _proto._stringFor = function _stringFor(name, spaceName, concat) { + if (spaceName === void 0) { + spaceName = name; + } + if (concat === void 0) { + concat = defaultAttrConcat; + } + var attrSpaces = this._spacesFor(spaceName); + return concat(this.stringifyProperty(name), attrSpaces); + } + + /** + * returns the offset of the attribute part specified relative to the + * start of the node of the output string. + * + * * "ns" - alias for "namespace" + * * "namespace" - the namespace if it exists. + * * "attribute" - the attribute name + * * "attributeNS" - the start of the attribute or its namespace + * * "operator" - the match operator of the attribute + * * "value" - The value (string or identifier) + * * "insensitive" - the case insensitivity flag; + * @param part One of the possible values inside an attribute. + * @returns -1 if the name is invalid or the value doesn't exist in this attribute. + */; + _proto.offsetOf = function offsetOf(name) { + var count = 1; + var attributeSpaces = this._spacesFor("attribute"); + count += attributeSpaces.before.length; + if (name === "namespace" || name === "ns") { + return this.namespace ? count : -1; + } + if (name === "attributeNS") { + return count; + } + count += this.namespaceString.length; + if (this.namespace) { + count += 1; + } + if (name === "attribute") { + return count; + } + count += this.stringifyProperty("attribute").length; + count += attributeSpaces.after.length; + var operatorSpaces = this._spacesFor("operator"); + count += operatorSpaces.before.length; + var operator = this.stringifyProperty("operator"); + if (name === "operator") { + return operator ? count : -1; + } + count += operator.length; + count += operatorSpaces.after.length; + var valueSpaces = this._spacesFor("value"); + count += valueSpaces.before.length; + var value = this.stringifyProperty("value"); + if (name === "value") { + return value ? count : -1; + } + count += value.length; + count += valueSpaces.after.length; + var insensitiveSpaces = this._spacesFor("insensitive"); + count += insensitiveSpaces.before.length; + if (name === "insensitive") { + return this.insensitive ? count : -1; + } + return -1; + }; + _proto.toString = function toString() { + var _this2 = this; + var selector = [this.rawSpaceBefore, '[']; + selector.push(this._stringFor('qualifiedAttribute', 'attribute')); + if (this.operator && (this.value || this.value === '')) { + selector.push(this._stringFor('operator')); + selector.push(this._stringFor('value')); + selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) { + if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) { + attrSpaces.before = " "; + } + return defaultAttrConcat(attrValue, attrSpaces); + })); + } + selector.push(']'); + selector.push(this.rawSpaceAfter); + return selector.join(''); + }; + _createClass(Attribute, [{ + key: "quoted", + get: function get() { + var qm = this.quoteMark; + return qm === "'" || qm === '"'; + }, + set: function set(value) { + warnOfDeprecatedQuotedAssignment(); + } + + /** + * returns a single (`'`) or double (`"`) quote character if the value is quoted. + * returns `null` if the value is not quoted. + * returns `undefined` if the quotation state is unknown (this can happen when + * the attribute is constructed without specifying a quote mark.) + */ + }, { + key: "quoteMark", + get: function get() { + return this._quoteMark; + } + + /** + * Set the quote mark to be used by this attribute's value. + * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute + * value is updated accordingly. + * + * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted. + */, + set: function set(quoteMark) { + if (!this._constructed) { + this._quoteMark = quoteMark; + return; + } + if (this._quoteMark !== quoteMark) { + this._quoteMark = quoteMark; + this._syncRawValue(); + } + } + }, { + key: "qualifiedAttribute", + get: function get() { + return this.qualifiedName(this.raws.attribute || this.attribute); + } + }, { + key: "insensitiveFlag", + get: function get() { + return this.insensitive ? 'i' : ''; + } + }, { + key: "value", + get: function get() { + return this._value; + }, + set: + /** + * Before 3.0, the value had to be set to an escaped value including any wrapped + * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value + * is unescaped during parsing and any quote marks are removed. + * + * Because the ambiguity of this semantic change, if you set `attr.value = newValue`, + * a deprecation warning is raised when the new value contains any characters that would + * require escaping (including if it contains wrapped quotes). + * + * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe + * how the new value is quoted. + */ + function set(v) { + if (this._constructed) { + var _unescapeValue2 = unescapeValue(v), + deprecatedUsage = _unescapeValue2.deprecatedUsage, + unescaped = _unescapeValue2.unescaped, + quoteMark = _unescapeValue2.quoteMark; + if (deprecatedUsage) { + warnOfDeprecatedValueAssignment(); + } + if (unescaped === this._value && quoteMark === this._quoteMark) { + return; + } + this._value = unescaped; + this._quoteMark = quoteMark; + this._syncRawValue(); + } else { + this._value = v; + } + } + }, { + key: "insensitive", + get: function get() { + return this._insensitive; + } + + /** + * Set the case insensitive flag. + * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag` + * of the attribute is updated accordingly. + * + * @param {true | false} insensitive true if the attribute should match case-insensitively. + */, + set: function set(insensitive) { + if (!insensitive) { + this._insensitive = false; + + // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation. + // When setting `attr.insensitive = false` both should be erased to ensure correct serialization. + if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) { + this.raws.insensitiveFlag = undefined; + } + } + this._insensitive = insensitive; + } + }, { + key: "attribute", + get: function get() { + return this._attribute; + }, + set: function set(name) { + this._handleEscapes("attribute", name); + this._attribute = name; + } + }]); + return Attribute; + }(_namespace["default"]); + exports["default"] = Attribute; + Attribute.NO_QUOTE = null; + Attribute.SINGLE_QUOTE = "'"; + Attribute.DOUBLE_QUOTE = '"'; + var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = { + "'": { + quotes: 'single', + wrap: true + }, + '"': { + quotes: 'double', + wrap: true + } + }, _CSSESC_QUOTE_OPTIONS[null] = { + isIdentifier: true + }, _CSSESC_QUOTE_OPTIONS); + function defaultAttrConcat(attrValue, attrSpaces) { + return "" + attrSpaces.before + attrValue + attrSpaces.after; + } +} (attribute$1)); + +var universal$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _namespace = _interopRequireDefault(namespaceExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Universal = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Universal, _Namespace); + function Universal(opts) { + var _this; + _this = _Namespace.call(this, opts) || this; + _this.type = _types.UNIVERSAL; + _this.value = '*'; + return _this; + } + return Universal; + }(_namespace["default"]); + exports["default"] = Universal; + module.exports = exports.default; +} (universal$1, universal$1.exports)); + +var universalExports = universal$1.exports; + +var combinator$2 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _node = _interopRequireDefault(nodeExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Combinator = /*#__PURE__*/function (_Node) { + _inheritsLoose(Combinator, _Node); + function Combinator(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.COMBINATOR; + return _this; + } + return Combinator; + }(_node["default"]); + exports["default"] = Combinator; + module.exports = exports.default; +} (combinator$2, combinator$2.exports)); + +var combinatorExports = combinator$2.exports; + +var nesting$1 = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _node = _interopRequireDefault(nodeExports); + var _types = types; + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + var Nesting = /*#__PURE__*/function (_Node) { + _inheritsLoose(Nesting, _Node); + function Nesting(opts) { + var _this; + _this = _Node.call(this, opts) || this; + _this.type = _types.NESTING; + _this.value = '&'; + return _this; + } + return Nesting; + }(_node["default"]); + exports["default"] = Nesting; + module.exports = exports.default; +} (nesting$1, nesting$1.exports)); + +var nestingExports = nesting$1.exports; + +var sortAscending = {exports: {}}; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = sortAscending; + function sortAscending(list) { + return list.sort(function (a, b) { + return a - b; + }); + } + module.exports = exports.default; +} (sortAscending, sortAscending.exports)); + +var sortAscendingExports = sortAscending.exports; + +var tokenize = {}; + +var tokenTypes = {}; + +tokenTypes.__esModule = true; +tokenTypes.word = tokenTypes.tilde = tokenTypes.tab = tokenTypes.str = tokenTypes.space = tokenTypes.slash = tokenTypes.singleQuote = tokenTypes.semicolon = tokenTypes.plus = tokenTypes.pipe = tokenTypes.openSquare = tokenTypes.openParenthesis = tokenTypes.newline = tokenTypes.greaterThan = tokenTypes.feed = tokenTypes.equals = tokenTypes.doubleQuote = tokenTypes.dollar = tokenTypes.cr = tokenTypes.comment = tokenTypes.comma = tokenTypes.combinator = tokenTypes.colon = tokenTypes.closeSquare = tokenTypes.closeParenthesis = tokenTypes.caret = tokenTypes.bang = tokenTypes.backslash = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0; +var ampersand = 38; // `&`.charCodeAt(0); +tokenTypes.ampersand = ampersand; +var asterisk = 42; // `*`.charCodeAt(0); +tokenTypes.asterisk = asterisk; +var at = 64; // `@`.charCodeAt(0); +tokenTypes.at = at; +var comma$1 = 44; // `,`.charCodeAt(0); +tokenTypes.comma = comma$1; +var colon = 58; // `:`.charCodeAt(0); +tokenTypes.colon = colon; +var semicolon$1 = 59; // `;`.charCodeAt(0); +tokenTypes.semicolon = semicolon$1; +var openParenthesis = 40; // `(`.charCodeAt(0); +tokenTypes.openParenthesis = openParenthesis; +var closeParenthesis = 41; // `)`.charCodeAt(0); +tokenTypes.closeParenthesis = closeParenthesis; +var openSquare = 91; // `[`.charCodeAt(0); +tokenTypes.openSquare = openSquare; +var closeSquare = 93; // `]`.charCodeAt(0); +tokenTypes.closeSquare = closeSquare; +var dollar = 36; // `$`.charCodeAt(0); +tokenTypes.dollar = dollar; +var tilde = 126; // `~`.charCodeAt(0); +tokenTypes.tilde = tilde; +var caret = 94; // `^`.charCodeAt(0); +tokenTypes.caret = caret; +var plus = 43; // `+`.charCodeAt(0); +tokenTypes.plus = plus; +var equals = 61; // `=`.charCodeAt(0); +tokenTypes.equals = equals; +var pipe = 124; // `|`.charCodeAt(0); +tokenTypes.pipe = pipe; +var greaterThan = 62; // `>`.charCodeAt(0); +tokenTypes.greaterThan = greaterThan; +var space = 32; // ` `.charCodeAt(0); +tokenTypes.space = space; +var singleQuote = 39; // `'`.charCodeAt(0); +tokenTypes.singleQuote = singleQuote; +var doubleQuote = 34; // `"`.charCodeAt(0); +tokenTypes.doubleQuote = doubleQuote; +var slash = 47; // `/`.charCodeAt(0); +tokenTypes.slash = slash; +var bang = 33; // `!`.charCodeAt(0); +tokenTypes.bang = bang; +var backslash = 92; // '\\'.charCodeAt(0); +tokenTypes.backslash = backslash; +var cr = 13; // '\r'.charCodeAt(0); +tokenTypes.cr = cr; +var feed = 12; // '\f'.charCodeAt(0); +tokenTypes.feed = feed; +var newline = 10; // '\n'.charCodeAt(0); +tokenTypes.newline = newline; +var tab = 9; // '\t'.charCodeAt(0); + +// Expose aliases primarily for readability. +tokenTypes.tab = tab; +var str = singleQuote; + +// No good single character representation! +tokenTypes.str = str; +var comment$1 = -1; +tokenTypes.comment = comment$1; +var word = -2; +tokenTypes.word = word; +var combinator$1 = -3; +tokenTypes.combinator = combinator$1; + +(function (exports) { + + exports.__esModule = true; + exports.FIELDS = void 0; + exports["default"] = tokenize; + var t = _interopRequireWildcard(tokenTypes); + var _unescapable, _wordDelimiters; + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable); + var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters); + var hex = {}; + var hexChars = "0123456789abcdefABCDEF"; + for (var i = 0; i < hexChars.length; i++) { + hex[hexChars.charCodeAt(i)] = true; + } + + /** + * Returns the last index of the bar css word + * @param {string} css The string in which the word begins + * @param {number} start The index into the string where word's first letter occurs + */ + function consumeWord(css, start) { + var next = start; + var code; + do { + code = css.charCodeAt(next); + if (wordDelimiters[code]) { + return next - 1; + } else if (code === t.backslash) { + next = consumeEscape(css, next) + 1; + } else { + // All other characters are part of the word + next++; + } + } while (next < css.length); + return next - 1; + } + + /** + * Returns the last index of the escape sequence + * @param {string} css The string in which the sequence begins + * @param {number} start The index into the string where escape character (`\`) occurs. + */ + function consumeEscape(css, start) { + var next = start; + var code = css.charCodeAt(next + 1); + if (unescapable[code]) ; else if (hex[code]) { + var hexDigits = 0; + // consume up to 6 hex chars + do { + next++; + hexDigits++; + code = css.charCodeAt(next + 1); + } while (hex[code] && hexDigits < 6); + // if fewer than 6 hex chars, a trailing space ends the escape + if (hexDigits < 6 && code === t.space) { + next++; + } + } else { + // the next char is part of the current word + next++; + } + return next; + } + var FIELDS = { + TYPE: 0, + START_LINE: 1, + START_COL: 2, + END_LINE: 3, + END_COL: 4, + START_POS: 5, + END_POS: 6 + }; + exports.FIELDS = FIELDS; + function tokenize(input) { + var tokens = []; + var css = input.css.valueOf(); + var _css = css, + length = _css.length; + var offset = -1; + var line = 1; + var start = 0; + var end = 0; + var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType; + function unclosed(what, fix) { + if (input.safe) { + // fyi: this is never set to true. + css += fix; + next = css.length - 1; + } else { + throw input.error('Unclosed ' + what, line, start - offset, start); + } + } + while (start < length) { + code = css.charCodeAt(start); + if (code === t.newline) { + offset = start; + line += 1; + } + switch (code) { + case t.space: + case t.tab: + case t.newline: + case t.cr: + case t.feed: + next = start; + do { + next += 1; + code = css.charCodeAt(next); + if (code === t.newline) { + offset = next; + line += 1; + } + } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed); + tokenType = t.space; + endLine = line; + endColumn = next - offset - 1; + end = next; + break; + case t.plus: + case t.greaterThan: + case t.tilde: + case t.pipe: + next = start; + do { + next += 1; + code = css.charCodeAt(next); + } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe); + tokenType = t.combinator; + endLine = line; + endColumn = start - offset; + end = next; + break; + + // Consume these characters as single tokens. + case t.asterisk: + case t.ampersand: + case t.bang: + case t.comma: + case t.equals: + case t.dollar: + case t.caret: + case t.openSquare: + case t.closeSquare: + case t.colon: + case t.semicolon: + case t.openParenthesis: + case t.closeParenthesis: + next = start; + tokenType = code; + endLine = line; + endColumn = start - offset; + end = next + 1; + break; + case t.singleQuote: + case t.doubleQuote: + quote = code === t.singleQuote ? "'" : '"'; + next = start; + do { + escaped = false; + next = css.indexOf(quote, next + 1); + if (next === -1) { + unclosed('quote', quote); + } + escapePos = next; + while (css.charCodeAt(escapePos - 1) === t.backslash) { + escapePos -= 1; + escaped = !escaped; + } + } while (escaped); + tokenType = t.str; + endLine = line; + endColumn = start - offset; + end = next + 1; + break; + default: + if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) { + next = css.indexOf('*/', start + 2) + 1; + if (next === 0) { + unclosed('comment', '*/'); + } + content = css.slice(start, next + 1); + lines = content.split('\n'); + last = lines.length - 1; + if (last > 0) { + nextLine = line + last; + nextOffset = next - lines[last].length; + } else { + nextLine = line; + nextOffset = offset; + } + tokenType = t.comment; + line = nextLine; + endLine = nextLine; + endColumn = next - nextOffset; + } else if (code === t.slash) { + next = start; + tokenType = code; + endLine = line; + endColumn = start - offset; + end = next + 1; + } else { + next = consumeWord(css, start); + tokenType = t.word; + endLine = line; + endColumn = next - offset; + } + end = next + 1; + break; + } + + // Ensure that the token structure remains consistent + tokens.push([tokenType, + // [0] Token type + line, + // [1] Starting line + start - offset, + // [2] Starting column + endLine, + // [3] Ending line + endColumn, + // [4] Ending column + start, + // [5] Start position / Source index + end // [6] End position + ]); + + // Reset offset for the next token + if (nextOffset) { + offset = nextOffset; + nextOffset = null; + } + start = end; + } + return tokens; + } +} (tokenize)); + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _root = _interopRequireDefault(rootExports); + var _selector = _interopRequireDefault(selectorExports); + var _className = _interopRequireDefault(classNameExports); + var _comment = _interopRequireDefault(commentExports); + var _id = _interopRequireDefault(idExports); + var _tag = _interopRequireDefault(tagExports); + var _string = _interopRequireDefault(stringExports); + var _pseudo = _interopRequireDefault(pseudoExports); + var _attribute = _interopRequireWildcard(attribute$1); + var _universal = _interopRequireDefault(universalExports); + var _combinator = _interopRequireDefault(combinatorExports); + var _nesting = _interopRequireDefault(nestingExports); + var _sortAscending = _interopRequireDefault(sortAscendingExports); + var _tokenize = _interopRequireWildcard(tokenize); + var tokens = _interopRequireWildcard(tokenTypes); + var types$1 = _interopRequireWildcard(types); + var _util = util$6; + var _WHITESPACE_TOKENS, _Object$assign; + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS); + var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign)); + function tokenStart(token) { + return { + line: token[_tokenize.FIELDS.START_LINE], + column: token[_tokenize.FIELDS.START_COL] + }; + } + function tokenEnd(token) { + return { + line: token[_tokenize.FIELDS.END_LINE], + column: token[_tokenize.FIELDS.END_COL] + }; + } + function getSource(startLine, startColumn, endLine, endColumn) { + return { + start: { + line: startLine, + column: startColumn + }, + end: { + line: endLine, + column: endColumn + } + }; + } + function getTokenSource(token) { + return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]); + } + function getTokenSourceSpan(startToken, endToken) { + if (!startToken) { + return undefined; + } + return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]); + } + function unescapeProp(node, prop) { + var value = node[prop]; + if (typeof value !== "string") { + return; + } + if (value.indexOf("\\") !== -1) { + (0, _util.ensureObject)(node, 'raws'); + node[prop] = (0, _util.unesc)(value); + if (node.raws[prop] === undefined) { + node.raws[prop] = value; + } + } + return node; + } + function indexesOf(array, item) { + var i = -1; + var indexes = []; + while ((i = array.indexOf(item, i + 1)) !== -1) { + indexes.push(i); + } + return indexes; + } + function uniqs() { + var list = Array.prototype.concat.apply([], arguments); + return list.filter(function (item, i) { + return i === list.indexOf(item); + }); + } + var Parser = /*#__PURE__*/function () { + function Parser(rule, options) { + if (options === void 0) { + options = {}; + } + this.rule = rule; + this.options = Object.assign({ + lossy: false, + safe: false + }, options); + this.position = 0; + this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector; + this.tokens = (0, _tokenize["default"])({ + css: this.css, + error: this._errorGenerator(), + safe: this.options.safe + }); + var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]); + this.root = new _root["default"]({ + source: rootSource + }); + this.root.errorGenerator = this._errorGenerator(); + var selector = new _selector["default"]({ + source: { + start: { + line: 1, + column: 1 + } + } + }); + this.root.append(selector); + this.current = selector; + this.loop(); + } + var _proto = Parser.prototype; + _proto._errorGenerator = function _errorGenerator() { + var _this = this; + return function (message, errorOptions) { + if (typeof _this.rule === 'string') { + return new Error(message); + } + return _this.rule.error(message, errorOptions); + }; + }; + _proto.attribute = function attribute() { + var attr = []; + var startingToken = this.currToken; + this.position++; + while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { + attr.push(this.currToken); + this.position++; + } + if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { + return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]); + } + var len = attr.length; + var node = { + source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]), + sourceIndex: startingToken[_tokenize.FIELDS.START_POS] + }; + if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) { + return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]); + } + var pos = 0; + var spaceBefore = ''; + var commentBefore = ''; + var lastAdded = null; + var spaceAfterMeaningfulToken = false; + while (pos < len) { + var token = attr[pos]; + var content = this.content(token); + var next = attr[pos + 1]; + switch (token[_tokenize.FIELDS.TYPE]) { + case tokens.space: + // if ( + // len === 1 || + // pos === 0 && this.content(next) === '|' + // ) { + // return this.expected('attribute', token[TOKEN.START_POS], content); + // } + spaceAfterMeaningfulToken = true; + if (this.options.lossy) { + break; + } + if (lastAdded) { + (0, _util.ensureObject)(node, 'spaces', lastAdded); + var prevContent = node.spaces[lastAdded].after || ''; + node.spaces[lastAdded].after = prevContent + content; + var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null; + if (existingComment) { + node.raws.spaces[lastAdded].after = existingComment + content; + } + } else { + spaceBefore = spaceBefore + content; + commentBefore = commentBefore + content; + } + break; + case tokens.asterisk: + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) { + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'attribute'); + node.spaces.attribute.before = spaceBefore; + spaceBefore = ''; + } + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); + node.raws.spaces.attribute.before = spaceBefore; + commentBefore = ''; + } + node.namespace = (node.namespace || "") + content; + var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null; + if (rawValue) { + node.raws.namespace += content; + } + lastAdded = 'namespace'; + } + spaceAfterMeaningfulToken = false; + break; + case tokens.dollar: + if (lastAdded === "value") { + var oldRawValue = (0, _util.getProp)(node, 'raws', 'value'); + node.value += "$"; + if (oldRawValue) { + node.raws.value = oldRawValue + "$"; + } + break; + } + // Falls through + case tokens.caret: + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } + spaceAfterMeaningfulToken = false; + break; + case tokens.combinator: + if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } + if (content !== '|') { + spaceAfterMeaningfulToken = false; + break; + } + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } else if (!node.namespace && !node.attribute) { + node.namespace = true; + } + spaceAfterMeaningfulToken = false; + break; + case tokens.word: + if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && + // this look-ahead probably fails with comment nodes involved. + !node.operator && !node.namespace) { + node.namespace = content; + lastAdded = 'namespace'; + } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) { + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'attribute'); + node.spaces.attribute.before = spaceBefore; + spaceBefore = ''; + } + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); + node.raws.spaces.attribute.before = commentBefore; + commentBefore = ''; + } + node.attribute = (node.attribute || "") + content; + var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null; + if (_rawValue) { + node.raws.attribute += content; + } + lastAdded = 'attribute'; + } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) { + var _unescaped = (0, _util.unesc)(content); + var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || ''; + var oldValue = node.value || ''; + node.value = oldValue + _unescaped; + node.quoteMark = null; + if (_unescaped !== content || _oldRawValue) { + (0, _util.ensureObject)(node, 'raws'); + node.raws.value = (_oldRawValue || oldValue) + content; + } + lastAdded = 'value'; + } else { + var insensitive = content === 'i' || content === "I"; + if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) { + node.insensitive = insensitive; + if (!insensitive || content === "I") { + (0, _util.ensureObject)(node, 'raws'); + node.raws.insensitiveFlag = content; + } + lastAdded = 'insensitive'; + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'insensitive'); + node.spaces.insensitive.before = spaceBefore; + spaceBefore = ''; + } + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive'); + node.raws.spaces.insensitive.before = commentBefore; + commentBefore = ''; + } + } else if (node.value || node.value === '') { + lastAdded = 'value'; + node.value += content; + if (node.raws.value) { + node.raws.value += content; + } + } + } + spaceAfterMeaningfulToken = false; + break; + case tokens.str: + if (!node.attribute || !node.operator) { + return this.error("Expected an attribute followed by an operator preceding the string.", { + index: token[_tokenize.FIELDS.START_POS] + }); + } + var _unescapeValue = (0, _attribute.unescapeValue)(content), + unescaped = _unescapeValue.unescaped, + quoteMark = _unescapeValue.quoteMark; + node.value = unescaped; + node.quoteMark = quoteMark; + lastAdded = 'value'; + (0, _util.ensureObject)(node, 'raws'); + node.raws.value = content; + spaceAfterMeaningfulToken = false; + break; + case tokens.equals: + if (!node.attribute) { + return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content); + } + if (node.value) { + return this.error('Unexpected "=" found; an operator was already defined.', { + index: token[_tokenize.FIELDS.START_POS] + }); + } + node.operator = node.operator ? node.operator + content : content; + lastAdded = 'operator'; + spaceAfterMeaningfulToken = false; + break; + case tokens.comment: + if (lastAdded) { + if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') { + var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || ''; + var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment; + (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded); + node.raws.spaces[lastAdded].after = rawLastComment + content; + } else { + var lastValue = node[lastAdded] || ''; + var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue; + (0, _util.ensureObject)(node, 'raws'); + node.raws[lastAdded] = rawLastValue + content; + } + } else { + commentBefore = commentBefore + content; + } + break; + default: + return this.error("Unexpected \"" + content + "\" found.", { + index: token[_tokenize.FIELDS.START_POS] + }); + } + pos++; + } + unescapeProp(node, "attribute"); + unescapeProp(node, "namespace"); + this.newNode(new _attribute["default"](node)); + this.position++; + } + + /** + * return a node containing meaningless garbage up to (but not including) the specified token position. + * if the token position is negative, all remaining tokens are consumed. + * + * This returns an array containing a single string node if all whitespace, + * otherwise an array of comment nodes with space before and after. + * + * These tokens are not added to the current selector, the caller can add them or use them to amend + * a previous node's space metadata. + * + * In lossy mode, this returns only comments. + */; + _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) { + if (stopPosition < 0) { + stopPosition = this.tokens.length; + } + var startPosition = this.position; + var nodes = []; + var space = ""; + var lastComment = undefined; + do { + if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) { + if (!this.options.lossy) { + space += this.content(); + } + } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) { + var spaces = {}; + if (space) { + spaces.before = space; + space = ""; + } + lastComment = new _comment["default"]({ + value: this.content(), + source: getTokenSource(this.currToken), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], + spaces: spaces + }); + nodes.push(lastComment); + } + } while (++this.position < stopPosition); + if (space) { + if (lastComment) { + lastComment.spaces.after = space; + } else if (!this.options.lossy) { + var firstToken = this.tokens[startPosition]; + var lastToken = this.tokens[this.position - 1]; + nodes.push(new _string["default"]({ + value: '', + source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]), + sourceIndex: firstToken[_tokenize.FIELDS.START_POS], + spaces: { + before: space, + after: '' + } + })); + } + } + return nodes; + } + + /** + * + * @param {*} nodes + */; + _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) { + var _this2 = this; + if (requiredSpace === void 0) { + requiredSpace = false; + } + var space = ""; + var rawSpace = ""; + nodes.forEach(function (n) { + var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace); + var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace); + space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0); + rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0); + }); + if (rawSpace === space) { + rawSpace = undefined; + } + var result = { + space: space, + rawSpace: rawSpace + }; + return result; + }; + _proto.isNamedCombinator = function isNamedCombinator(position) { + if (position === void 0) { + position = this.position; + } + return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash; + }; + _proto.namedCombinator = function namedCombinator() { + if (this.isNamedCombinator()) { + var nameRaw = this.content(this.tokens[this.position + 1]); + var name = (0, _util.unesc)(nameRaw).toLowerCase(); + var raws = {}; + if (name !== nameRaw) { + raws.value = "/" + nameRaw + "/"; + } + var node = new _combinator["default"]({ + value: "/" + name + "/", + source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], + raws: raws + }); + this.position = this.position + 3; + return node; + } else { + this.unexpected(); + } + }; + _proto.combinator = function combinator() { + var _this3 = this; + if (this.content() === '|') { + return this.namespace(); + } + // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector. + var nextSigTokenPos = this.locateNextMeaningfulToken(this.position); + if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) { + var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); + if (nodes.length > 0) { + var last = this.current.last; + if (last) { + var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes), + space = _this$convertWhitespa.space, + rawSpace = _this$convertWhitespa.rawSpace; + if (rawSpace !== undefined) { + last.rawSpaceAfter += rawSpace; + } + last.spaces.after += space; + } else { + nodes.forEach(function (n) { + return _this3.newNode(n); + }); + } + } + return; + } + var firstToken = this.currToken; + var spaceOrDescendantSelectorNodes = undefined; + if (nextSigTokenPos > this.position) { + spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); + } + var node; + if (this.isNamedCombinator()) { + node = this.namedCombinator(); + } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) { + node = new _combinator["default"]({ + value: this.content(), + source: getTokenSource(this.currToken), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS] + }); + this.position++; + } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) { + this.unexpected(); + } + if (node) { + if (spaceOrDescendantSelectorNodes) { + var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), + _space = _this$convertWhitespa2.space, + _rawSpace = _this$convertWhitespa2.rawSpace; + node.spaces.before = _space; + node.rawSpaceBefore = _rawSpace; + } + } else { + // descendant combinator + var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), + _space2 = _this$convertWhitespa3.space, + _rawSpace2 = _this$convertWhitespa3.rawSpace; + if (!_rawSpace2) { + _rawSpace2 = _space2; + } + var spaces = {}; + var raws = { + spaces: {} + }; + if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) { + spaces.before = _space2.slice(0, _space2.length - 1); + raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1); + } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) { + spaces.after = _space2.slice(1); + raws.spaces.after = _rawSpace2.slice(1); + } else { + raws.value = _rawSpace2; + } + node = new _combinator["default"]({ + value: ' ', + source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]), + sourceIndex: firstToken[_tokenize.FIELDS.START_POS], + spaces: spaces, + raws: raws + }); + } + if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) { + node.spaces.after = this.optionalSpace(this.content()); + this.position++; + } + return this.newNode(node); + }; + _proto.comma = function comma() { + if (this.position === this.tokens.length - 1) { + this.root.trailingComma = true; + this.position++; + return; + } + this.current._inferEndPosition(); + var selector = new _selector["default"]({ + source: { + start: tokenStart(this.tokens[this.position + 1]) + } + }); + this.current.parent.append(selector); + this.current = selector; + this.position++; + }; + _proto.comment = function comment() { + var current = this.currToken; + this.newNode(new _comment["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + _proto.error = function error(message, opts) { + throw this.root.error(message, opts); + }; + _proto.missingBackslash = function missingBackslash() { + return this.error('Expected a backslash preceding the semicolon.', { + index: this.currToken[_tokenize.FIELDS.START_POS] + }); + }; + _proto.missingParenthesis = function missingParenthesis() { + return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.missingSquareBracket = function missingSquareBracket() { + return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.unexpected = function unexpected() { + return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.unexpectedPipe = function unexpectedPipe() { + return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]); + }; + _proto.namespace = function namespace() { + var before = this.prevToken && this.content(this.prevToken) || true; + if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) { + this.position++; + return this.word(before); + } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) { + this.position++; + return this.universal(before); + } + this.unexpectedPipe(); + }; + _proto.nesting = function nesting() { + if (this.nextToken) { + var nextContent = this.content(this.nextToken); + if (nextContent === "|") { + this.position++; + return; + } + } + var current = this.currToken; + this.newNode(new _nesting["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + _proto.parentheses = function parentheses() { + var last = this.current.last; + var unbalanced = 1; + this.position++; + if (last && last.type === types$1.PSEUDO) { + var selector = new _selector["default"]({ + source: { + start: tokenStart(this.tokens[this.position - 1]) + } + }); + var cache = this.current; + last.append(selector); + this.current = selector; + while (this.position < this.tokens.length && unbalanced) { + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + unbalanced++; + } + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + unbalanced--; + } + if (unbalanced) { + this.parse(); + } else { + this.current.source.end = tokenEnd(this.currToken); + this.current.parent.source.end = tokenEnd(this.currToken); + this.position++; + } + } + this.current = cache; + } else { + // I think this case should be an error. It's used to implement a basic parse of media queries + // but I don't think it's a good idea. + var parenStart = this.currToken; + var parenValue = "("; + var parenEnd; + while (this.position < this.tokens.length && unbalanced) { + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + unbalanced++; + } + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + unbalanced--; + } + parenEnd = this.currToken; + parenValue += this.parseParenthesisToken(this.currToken); + this.position++; + } + if (last) { + last.appendToPropertyAndEscape("value", parenValue, parenValue); + } else { + this.newNode(new _string["default"]({ + value: parenValue, + source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]), + sourceIndex: parenStart[_tokenize.FIELDS.START_POS] + })); + } + } + if (unbalanced) { + return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); + } + }; + _proto.pseudo = function pseudo() { + var _this4 = this; + var pseudoStr = ''; + var startingToken = this.currToken; + while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) { + pseudoStr += this.content(); + this.position++; + } + if (!this.currToken) { + return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1); + } + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) { + this.splitWord(false, function (first, length) { + pseudoStr += first; + _this4.newNode(new _pseudo["default"]({ + value: pseudoStr, + source: getTokenSourceSpan(startingToken, _this4.currToken), + sourceIndex: startingToken[_tokenize.FIELDS.START_POS] + })); + if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + _this4.error('Misplaced parenthesis.', { + index: _this4.nextToken[_tokenize.FIELDS.START_POS] + }); + } + }); + } else { + return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]); + } + }; + _proto.space = function space() { + var content = this.content(); + // Handle space before and after the selector + if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) { + return node.type === 'comment'; + })) { + this.spaces = this.optionalSpace(content); + this.position++; + } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + this.current.last.spaces.after = this.optionalSpace(content); + this.position++; + } else { + this.combinator(); + } + }; + _proto.string = function string() { + var current = this.currToken; + this.newNode(new _string["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + _proto.universal = function universal(namespace) { + var nextToken = this.nextToken; + if (nextToken && this.content(nextToken) === '|') { + this.position++; + return this.namespace(); + } + var current = this.currToken; + this.newNode(new _universal["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + }), namespace); + this.position++; + }; + _proto.splitWord = function splitWord(namespace, firstCallback) { + var _this5 = this; + var nextToken = this.nextToken; + var word = this.content(); + while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) { + this.position++; + var current = this.content(); + word += current; + if (current.lastIndexOf('\\') === current.length - 1) { + var next = this.nextToken; + if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) { + word += this.requiredSpace(this.content(next)); + this.position++; + } + } + nextToken = this.nextToken; + } + var hasClass = indexesOf(word, '.').filter(function (i) { + // Allow escaped dot within class name + var escapedDot = word[i - 1] === '\\'; + // Allow decimal numbers percent in @keyframes + var isKeyframesPercent = /^\d+\.\d+%$/.test(word); + return !escapedDot && !isKeyframesPercent; + }); + var hasId = indexesOf(word, '#').filter(function (i) { + return word[i - 1] !== '\\'; + }); + // Eliminate Sass interpolations from the list of id indexes + var interpolations = indexesOf(word, '#{'); + if (interpolations.length) { + hasId = hasId.filter(function (hashIndex) { + return !~interpolations.indexOf(hashIndex); + }); + } + var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId))); + indices.forEach(function (ind, i) { + var index = indices[i + 1] || word.length; + var value = word.slice(ind, index); + if (i === 0 && firstCallback) { + return firstCallback.call(_this5, value, indices.length); + } + var node; + var current = _this5.currToken; + var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i]; + var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1)); + if (~hasClass.indexOf(ind)) { + var classNameOpts = { + value: value.slice(1), + source: source, + sourceIndex: sourceIndex + }; + node = new _className["default"](unescapeProp(classNameOpts, "value")); + } else if (~hasId.indexOf(ind)) { + var idOpts = { + value: value.slice(1), + source: source, + sourceIndex: sourceIndex + }; + node = new _id["default"](unescapeProp(idOpts, "value")); + } else { + var tagOpts = { + value: value, + source: source, + sourceIndex: sourceIndex + }; + unescapeProp(tagOpts, "value"); + node = new _tag["default"](tagOpts); + } + _this5.newNode(node, namespace); + // Ensure that the namespace is used only once + namespace = null; + }); + this.position++; + }; + _proto.word = function word(namespace) { + var nextToken = this.nextToken; + if (nextToken && this.content(nextToken) === '|') { + this.position++; + return this.namespace(); + } + return this.splitWord(namespace); + }; + _proto.loop = function loop() { + while (this.position < this.tokens.length) { + this.parse(true); + } + this.current._inferEndPosition(); + return this.root; + }; + _proto.parse = function parse(throwOnParenthesis) { + switch (this.currToken[_tokenize.FIELDS.TYPE]) { + case tokens.space: + this.space(); + break; + case tokens.comment: + this.comment(); + break; + case tokens.openParenthesis: + this.parentheses(); + break; + case tokens.closeParenthesis: + if (throwOnParenthesis) { + this.missingParenthesis(); + } + break; + case tokens.openSquare: + this.attribute(); + break; + case tokens.dollar: + case tokens.caret: + case tokens.equals: + case tokens.word: + this.word(); + break; + case tokens.colon: + this.pseudo(); + break; + case tokens.comma: + this.comma(); + break; + case tokens.asterisk: + this.universal(); + break; + case tokens.ampersand: + this.nesting(); + break; + case tokens.slash: + case tokens.combinator: + this.combinator(); + break; + case tokens.str: + this.string(); + break; + // These cases throw; no break needed. + case tokens.closeSquare: + this.missingSquareBracket(); + case tokens.semicolon: + this.missingBackslash(); + default: + this.unexpected(); + } + } + + /** + * Helpers + */; + _proto.expected = function expected(description, index, found) { + if (Array.isArray(description)) { + var last = description.pop(); + description = description.join(', ') + " or " + last; + } + var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a'; + if (!found) { + return this.error("Expected " + an + " " + description + ".", { + index: index + }); + } + return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", { + index: index + }); + }; + _proto.requiredSpace = function requiredSpace(space) { + return this.options.lossy ? ' ' : space; + }; + _proto.optionalSpace = function optionalSpace(space) { + return this.options.lossy ? '' : space; + }; + _proto.lossySpace = function lossySpace(space, required) { + if (this.options.lossy) { + return required ? ' ' : ''; + } else { + return space; + } + }; + _proto.parseParenthesisToken = function parseParenthesisToken(token) { + var content = this.content(token); + if (token[_tokenize.FIELDS.TYPE] === tokens.space) { + return this.requiredSpace(content); + } else { + return content; + } + }; + _proto.newNode = function newNode(node, namespace) { + if (namespace) { + if (/^ +$/.test(namespace)) { + if (!this.options.lossy) { + this.spaces = (this.spaces || '') + namespace; + } + namespace = true; + } + node.namespace = namespace; + unescapeProp(node, "namespace"); + } + if (this.spaces) { + node.spaces.before = this.spaces; + this.spaces = ''; + } + return this.current.append(node); + }; + _proto.content = function content(token) { + if (token === void 0) { + token = this.currToken; + } + return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]); + }; + /** + * returns the index of the next non-whitespace, non-comment token. + * returns -1 if no meaningful token is found. + */ + _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) { + if (startPosition === void 0) { + startPosition = this.position + 1; + } + var searchPosition = startPosition; + while (searchPosition < this.tokens.length) { + if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) { + searchPosition++; + continue; + } else { + return searchPosition; + } + } + return -1; + }; + _createClass(Parser, [{ + key: "currToken", + get: function get() { + return this.tokens[this.position]; + } + }, { + key: "nextToken", + get: function get() { + return this.tokens[this.position + 1]; + } + }, { + key: "prevToken", + get: function get() { + return this.tokens[this.position - 1]; + } + }]); + return Parser; + }(); + exports["default"] = Parser; + module.exports = exports.default; +} (parser, parser.exports)); + +var parserExports = parser.exports; + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _parser = _interopRequireDefault(parserExports); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + var Processor = /*#__PURE__*/function () { + function Processor(func, options) { + this.func = func || function noop() {}; + this.funcRes = null; + this.options = options; + } + var _proto = Processor.prototype; + _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) { + if (options === void 0) { + options = {}; + } + var merged = Object.assign({}, this.options, options); + if (merged.updateSelector === false) { + return false; + } else { + return typeof rule !== "string"; + } + }; + _proto._isLossy = function _isLossy(options) { + if (options === void 0) { + options = {}; + } + var merged = Object.assign({}, this.options, options); + if (merged.lossless === false) { + return true; + } else { + return false; + } + }; + _proto._root = function _root(rule, options) { + if (options === void 0) { + options = {}; + } + var parser = new _parser["default"](rule, this._parseOptions(options)); + return parser.root; + }; + _proto._parseOptions = function _parseOptions(options) { + return { + lossy: this._isLossy(options) + }; + }; + _proto._run = function _run(rule, options) { + var _this = this; + if (options === void 0) { + options = {}; + } + return new Promise(function (resolve, reject) { + try { + var root = _this._root(rule, options); + Promise.resolve(_this.func(root)).then(function (transform) { + var string = undefined; + if (_this._shouldUpdateSelector(rule, options)) { + string = root.toString(); + rule.selector = string; + } + return { + transform: transform, + root: root, + string: string + }; + }).then(resolve, reject); + } catch (e) { + reject(e); + return; + } + }); + }; + _proto._runSync = function _runSync(rule, options) { + if (options === void 0) { + options = {}; + } + var root = this._root(rule, options); + var transform = this.func(root); + if (transform && typeof transform.then === "function") { + throw new Error("Selector processor returned a promise to a synchronous call."); + } + var string = undefined; + if (options.updateSelector && typeof rule !== "string") { + string = root.toString(); + rule.selector = string; + } + return { + transform: transform, + root: root, + string: string + }; + } + + /** + * Process rule into a selector AST. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {Promise<parser.Root>} The AST of the selector after processing it. + */; + _proto.ast = function ast(rule, options) { + return this._run(rule, options).then(function (result) { + return result.root; + }); + } + + /** + * Process rule into a selector AST synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {parser.Root} The AST of the selector after processing it. + */; + _proto.astSync = function astSync(rule, options) { + return this._runSync(rule, options).root; + } + + /** + * Process a selector into a transformed value asynchronously + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {Promise<any>} The value returned by the processor. + */; + _proto.transform = function transform(rule, options) { + return this._run(rule, options).then(function (result) { + return result.transform; + }); + } + + /** + * Process a selector into a transformed value synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {any} The value returned by the processor. + */; + _proto.transformSync = function transformSync(rule, options) { + return this._runSync(rule, options).transform; + } + + /** + * Process a selector into a new selector string asynchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {string} the selector after processing. + */; + _proto.process = function process(rule, options) { + return this._run(rule, options).then(function (result) { + return result.string || result.root.toString(); + }); + } + + /** + * Process a selector into a new selector string synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {string} the selector after processing. + */; + _proto.processSync = function processSync(rule, options) { + var result = this._runSync(rule, options); + return result.string || result.root.toString(); + }; + return Processor; + }(); + exports["default"] = Processor; + module.exports = exports.default; +} (processor, processor.exports)); + +var processorExports = processor.exports; + +var selectors = {}; + +var constructors = {}; + +constructors.__esModule = true; +constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0; +var _attribute = _interopRequireDefault(attribute$1); +var _className = _interopRequireDefault(classNameExports); +var _combinator = _interopRequireDefault(combinatorExports); +var _comment = _interopRequireDefault(commentExports); +var _id = _interopRequireDefault(idExports); +var _nesting = _interopRequireDefault(nestingExports); +var _pseudo = _interopRequireDefault(pseudoExports); +var _root = _interopRequireDefault(rootExports); +var _selector = _interopRequireDefault(selectorExports); +var _string = _interopRequireDefault(stringExports); +var _tag = _interopRequireDefault(tagExports); +var _universal = _interopRequireDefault(universalExports); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var attribute = function attribute(opts) { + return new _attribute["default"](opts); +}; +constructors.attribute = attribute; +var className = function className(opts) { + return new _className["default"](opts); +}; +constructors.className = className; +var combinator = function combinator(opts) { + return new _combinator["default"](opts); +}; +constructors.combinator = combinator; +var comment = function comment(opts) { + return new _comment["default"](opts); +}; +constructors.comment = comment; +var id = function id(opts) { + return new _id["default"](opts); +}; +constructors.id = id; +var nesting = function nesting(opts) { + return new _nesting["default"](opts); +}; +constructors.nesting = nesting; +var pseudo = function pseudo(opts) { + return new _pseudo["default"](opts); +}; +constructors.pseudo = pseudo; +var root = function root(opts) { + return new _root["default"](opts); +}; +constructors.root = root; +var selector = function selector(opts) { + return new _selector["default"](opts); +}; +constructors.selector = selector; +var string = function string(opts) { + return new _string["default"](opts); +}; +constructors.string = string; +var tag = function tag(opts) { + return new _tag["default"](opts); +}; +constructors.tag = tag; +var universal = function universal(opts) { + return new _universal["default"](opts); +}; +constructors.universal = universal; + +var guards = {}; + +guards.__esModule = true; +guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0; +guards.isContainer = isContainer; +guards.isIdentifier = void 0; +guards.isNamespace = isNamespace; +guards.isNesting = void 0; +guards.isNode = isNode; +guards.isPseudo = void 0; +guards.isPseudoClass = isPseudoClass; +guards.isPseudoElement = isPseudoElement; +guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0; +var _types = types; +var _IS_TYPE; +var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE); +function isNode(node) { + return typeof node === "object" && IS_TYPE[node.type]; +} +function isNodeType(type, node) { + return isNode(node) && node.type === type; +} +var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE); +guards.isAttribute = isAttribute; +var isClassName = isNodeType.bind(null, _types.CLASS); +guards.isClassName = isClassName; +var isCombinator = isNodeType.bind(null, _types.COMBINATOR); +guards.isCombinator = isCombinator; +var isComment = isNodeType.bind(null, _types.COMMENT); +guards.isComment = isComment; +var isIdentifier = isNodeType.bind(null, _types.ID); +guards.isIdentifier = isIdentifier; +var isNesting = isNodeType.bind(null, _types.NESTING); +guards.isNesting = isNesting; +var isPseudo = isNodeType.bind(null, _types.PSEUDO); +guards.isPseudo = isPseudo; +var isRoot = isNodeType.bind(null, _types.ROOT); +guards.isRoot = isRoot; +var isSelector = isNodeType.bind(null, _types.SELECTOR); +guards.isSelector = isSelector; +var isString = isNodeType.bind(null, _types.STRING); +guards.isString = isString; +var isTag = isNodeType.bind(null, _types.TAG); +guards.isTag = isTag; +var isUniversal = isNodeType.bind(null, _types.UNIVERSAL); +guards.isUniversal = isUniversal; +function isPseudoElement(node) { + return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line"); +} +function isPseudoClass(node) { + return isPseudo(node) && !isPseudoElement(node); +} +function isContainer(node) { + return !!(isNode(node) && node.walk); +} +function isNamespace(node) { + return isAttribute(node) || isTag(node); +} + +(function (exports) { + + exports.__esModule = true; + var _types = types; + Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + exports[key] = _types[key]; + }); + var _constructors = constructors; + Object.keys(_constructors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _constructors[key]) return; + exports[key] = _constructors[key]; + }); + var _guards = guards; + Object.keys(_guards).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _guards[key]) return; + exports[key] = _guards[key]; + }); +} (selectors)); + +(function (module, exports) { + + exports.__esModule = true; + exports["default"] = void 0; + var _processor = _interopRequireDefault(processorExports); + var selectors$1 = _interopRequireWildcard(selectors); + function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + var parser = function parser(processor) { + return new _processor["default"](processor); + }; + Object.assign(parser, selectors$1); + delete parser.__esModule; + var _default = parser; + exports["default"] = _default; + module.exports = exports.default; +} (dist, dist.exports)); + +var distExports = dist.exports; +var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports); + +const animationNameRE = /^(-\w+-)?animation-name$/; +const animationRE = /^(-\w+-)?animation$/; +const scopedPlugin = (id = "") => { + const keyframes = /* @__PURE__ */ Object.create(null); + const shortId = id.replace(/^data-v-/, ""); + return { + postcssPlugin: "vue-sfc-scoped", + Rule(rule) { + processRule(id, rule); + }, + AtRule(node) { + if (/-?keyframes$/.test(node.name) && !node.params.endsWith(`-${shortId}`)) { + keyframes[node.params] = node.params = node.params + "-" + shortId; + } + }, + OnceExit(root) { + if (Object.keys(keyframes).length) { + root.walkDecls((decl) => { + if (animationNameRE.test(decl.prop)) { + decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(","); + } + if (animationRE.test(decl.prop)) { + decl.value = decl.value.split(",").map((v) => { + const vals = v.trim().split(/\s+/); + const i = vals.findIndex((val) => keyframes[val]); + if (i !== -1) { + vals.splice(i, 1, keyframes[vals[i]]); + return vals.join(" "); + } else { + return v; + } + }).join(","); + } + }); + } + } + }; +}; +const processedRules = /* @__PURE__ */ new WeakSet(); +function processRule(id, rule) { + if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && /-?keyframes$/.test(rule.parent.name)) { + return; + } + processedRules.add(rule); + rule.selector = selectorParser((selectorRoot) => { + selectorRoot.each((selector) => { + rewriteSelector(id, selector, selectorRoot); + }); + }).processSync(rule.selector); +} +function rewriteSelector(id, selector, selectorRoot, slotted = false) { + let node = null; + let shouldInject = true; + selector.each((n) => { + if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) { + n.value = " "; + n.spaces.before = n.spaces.after = ""; + warn( + `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.` + ); + return false; + } + if (n.type === "pseudo") { + const { value } = n; + if (value === ":deep" || value === "::v-deep") { + if (n.nodes.length) { + let last = n; + n.nodes[0].each((ss) => { + selector.insertAfter(last, ss); + last = ss; + }); + const prev = selector.at(selector.index(n) - 1); + if (!prev || !isSpaceCombinator(prev)) { + selector.insertAfter( + n, + selectorParser.combinator({ + value: " " + }) + ); + } + selector.removeChild(n); + } else { + warn( + `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.` + ); + const prev = selector.at(selector.index(n) - 1); + if (prev && isSpaceCombinator(prev)) { + selector.removeChild(prev); + } + selector.removeChild(n); + } + return false; + } + if (value === ":slotted" || value === "::v-slotted") { + rewriteSelector( + id, + n.nodes[0], + selectorRoot, + true + /* slotted */ + ); + let last = n; + n.nodes[0].each((ss) => { + selector.insertAfter(last, ss); + last = ss; + }); + selector.removeChild(n); + shouldInject = false; + return false; + } + if (value === ":global" || value === "::v-global") { + selectorRoot.insertAfter(selector, n.nodes[0]); + selectorRoot.removeChild(selector); + return false; + } + } + if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where")) { + node = n; + } + }); + if (node) { + const { type, value } = node; + if (type === "pseudo" && (value === ":is" || value === ":where")) { + node.nodes.forEach( + (value2) => rewriteSelector(id, value2, selectorRoot, slotted) + ); + shouldInject = false; + } + } + if (node) { + node.spaces.after = ""; + } else { + selector.first.spaces.before = ""; + } + if (shouldInject) { + const idToAdd = slotted ? id + "-s" : id; + selector.insertAfter( + // If node is null it means we need to inject [id] at the start + // insertAfter can handle `null` here + node, + selectorParser.attribute({ + attribute: idToAdd, + value: idToAdd, + raws: {}, + quoteMark: `"` + }) + ); + } +} +function isSpaceCombinator(node) { + return node.type === "combinator" && /^\s+$/.test(node.value); +} +scopedPlugin.postcss = true; + +var sourceMap$1 = {}; + +var sourceMapGenerator = {}; + +var base64Vlq = {}; + +var base64$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +base64$1.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +base64$1.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = base64$1; + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +base64Vlq.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; + +var util$5 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '<dir>/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + /** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ + function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); + } + exports.parseSourceMapInput = parseSourceMapInput; + + /** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ + function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); + } + exports.computeSourceURL = computeSourceURL; +} (util$5)); + +var arraySet = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$4 = util$5; +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet$2() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet$2(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet$2.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet$2.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util$4.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util$4.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet$2.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet$2.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +arraySet.ArraySet = ArraySet$2; + +var mappingList = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$3 = util$5; + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList$1() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList$1.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList$1.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList$1.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util$3.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +mappingList.MappingList = MappingList$1; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ$1 = base64Vlq; +var util$2 = util$5; +var ArraySet$1 = arraySet.ArraySet; +var MappingList = mappingList.MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator$2(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util$2.getArg(aArgs, 'file', null); + this._sourceRoot = util$2.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util$2.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet$1(); + this._names = new ArraySet$1(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator$2.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator$2.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator$2({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util$2.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util$2.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator$2.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util$2.getArg(aArgs, 'generated'); + var original = util$2.getArg(aArgs, 'original', null); + var source = util$2.getArg(aArgs, 'source', null); + var name = util$2.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator$2.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util$2.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util$2.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util$2.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator$2.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util$2.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet$1(); + var newNames = new ArraySet$1(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util$2.join(aSourceMapPath, mapping.source); + } + if (sourceRoot != null) { + mapping.source = util$2.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util$2.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util$2.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator$2.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator$2.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = ''; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ$1.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ$1.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ$1.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ$1.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ$1.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator$2.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util$2.relative(aSourceRoot, source); + } + var key = util$2.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator$2.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator$2.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$2; + +var sourceMapConsumer = {}; + +var binarySearch$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +(function (exports) { + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; +} (binarySearch$1)); + +var quickSort$1 = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +quickSort$1.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util$1 = util$5; +var binarySearch = binarySearch$1; +var ArraySet = arraySet.ArraySet; +var base64VLQ = base64Vlq; +var quickSort = quickSort$1.quickSort; + +function SourceMapConsumer$1(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$1.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +}; + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer$1.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer$1.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer$1.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer$1.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer$1.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer$1.GENERATED_ORDER = 1; +SourceMapConsumer$1.ORIGINAL_ORDER = 2; + +SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer$1.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer$1.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer$1.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer$1.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL); + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer$1.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util$1.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util$1.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util$1.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$1.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util$1.getArg(mapping, 'generatedLine', null), + column: util$1.getArg(mapping, 'generatedColumn', null), + lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util$1.getArg(mapping, 'generatedLine', null), + column: util$1.getArg(mapping, 'generatedColumn', null), + lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$1; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$1.parseSourceMapInput(aSourceMap); + } + + var version = util$1.getArg(sourceMap, 'version'); + var sources = util$1.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util$1.getArg(sourceMap, 'names', []); + var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null); + var mappings = util$1.getArg(sourceMap, 'mappings'); + var file = util$1.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util$1.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util$1.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source) + ? util$1.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$1.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util$1.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util$1.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$1.getArg(aArgs, 'line'), + generatedColumn: util$1.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util$1.compareByGeneratedPositionsDeflated, + util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util$1.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util$1.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util$1.getArg(mapping, 'originalLine', null), + column: util$1.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util$1.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util$1.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util$1.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util$1.getArg(aArgs, 'line'), + originalColumn: util$1.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util$1.compareByOriginalPositions, + util$1.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util$1.getArg(mapping, 'generatedLine', null), + column: util$1.getArg(mapping, 'generatedColumn', null), + lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util$1.parseSourceMapInput(aSourceMap); + } + + var version = util$1.getArg(sourceMap, 'version'); + var sections = util$1.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util$1.getArg(s, 'offset'); + var offsetLine = util$1.getArg(offset, 'line'); + var offsetColumn = util$1.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer$1(util$1.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util$1.getArg(aArgs, 'line'), + generatedColumn: util$1.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util$1.compareByOriginalPositions); + }; + +sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + +var sourceNode = {}; + +/* -*- Mode: js; js-indent-level: 2; -*- */ + +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator; +var util = util$5; + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator$1(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +sourceNode.SourceNode = SourceNode; + +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator; +sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer; +sourceMap$1.SourceNode = sourceNode.SourceNode; + +var sourceMap = sourceMap$1; +var SourceMapConsumer = sourceMap.SourceMapConsumer; +var SourceMapGenerator = sourceMap.SourceMapGenerator; + +var mergeSourceMap = merge; + +/** + * Merge old source map and new source map and return merged. + * If old or new source map value is falsy, return another one as it is. + * + * @param {object|string} [oldMap] old source map object + * @param {object|string} [newmap] new source map object + * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined + */ +function merge(oldMap, newMap) { + if (!oldMap) return newMap + if (!newMap) return oldMap + + var oldMapConsumer = new SourceMapConsumer(oldMap); + var newMapConsumer = new SourceMapConsumer(newMap); + var mergedMapGenerator = new SourceMapGenerator(); + + // iterate on new map and overwrite original position of new map with one of old map + newMapConsumer.eachMapping(function(m) { + // pass when `originalLine` is null. + // It occurs in case that the node does not have origin in original code. + if (m.originalLine == null) return + + var origPosInOldMap = oldMapConsumer.originalPositionFor({ + line: m.originalLine, + column: m.originalColumn + }); + + if (origPosInOldMap.source == null) return + + mergedMapGenerator.addMapping({ + original: { + line: origPosInOldMap.line, + column: origPosInOldMap.column + }, + generated: { + line: m.generatedLine, + column: m.generatedColumn + }, + source: origPosInOldMap.source, + name: origPosInOldMap.name + }); + }); + + var consumers = [oldMapConsumer, newMapConsumer]; + consumers.forEach(function(consumer) { + consumer.sources.forEach(function(sourceFile) { + mergedMapGenerator._sources.add(sourceFile); + var sourceContent = consumer.sourceContentFor(sourceFile); + if (sourceContent != null) { + mergedMapGenerator.setSourceContent(sourceFile, sourceContent); + } + }); + }); + + mergedMapGenerator._sourceRoot = oldMap.sourceRoot; + mergedMapGenerator._file = oldMap.file; + + return JSON.parse(mergedMapGenerator.toString()) +} + +var merge$1 = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMap); + +var __defProp$5 = Object.defineProperty; +var __defProps$4 = Object.defineProperties; +var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols; +var __hasOwnProp$5 = Object.prototype.hasOwnProperty; +var __propIsEnum$5 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$5 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$5.call(b, prop)) + __defNormalProp$5(a, prop, b[prop]); + if (__getOwnPropSymbols$5) + for (var prop of __getOwnPropSymbols$5(b)) { + if (__propIsEnum$5.call(b, prop)) + __defNormalProp$5(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b)); +const scss = (source, map, options, load = require) => { + const nodeSass = load("sass"); + const finalOptions = __spreadProps$4(__spreadValues$5({}, options), { + data: getSource(source, options.filename, options.additionalData), + file: options.filename, + outFile: options.filename, + sourceMap: !!map + }); + try { + const result = nodeSass.renderSync(finalOptions); + const dependencies = result.stats.includedFiles; + if (map) { + return { + code: result.css.toString(), + map: merge$1(map, JSON.parse(result.map.toString())), + errors: [], + dependencies + }; + } + return { code: result.css.toString(), errors: [], dependencies }; + } catch (e) { + return { code: "", errors: [e], dependencies: [] }; + } +}; +const sass = (source, map, options, load) => scss( + source, + map, + __spreadProps$4(__spreadValues$5({}, options), { + indentedSyntax: true + }), + load +); +const less = (source, map, options, load = require) => { + const nodeLess = load("less"); + let result; + let error = null; + nodeLess.render( + getSource(source, options.filename, options.additionalData), + __spreadProps$4(__spreadValues$5({}, options), { syncImport: true }), + (err, output) => { + error = err; + result = output; + } + ); + if (error) + return { code: "", errors: [error], dependencies: [] }; + const dependencies = result.imports; + if (map) { + return { + code: result.css.toString(), + map: merge$1(map, result.map), + errors: [], + dependencies + }; + } + return { + code: result.css.toString(), + errors: [], + dependencies + }; +}; +const styl = (source, map, options, load = require) => { + const nodeStylus = load("stylus"); + try { + const ref = nodeStylus(source, options); + if (map) + ref.set("sourcemap", { inline: false, comment: false }); + const result = ref.render(); + const dependencies = ref.deps(); + if (map) { + return { + code: result, + map: merge$1(map, ref.sourcemap), + errors: [], + dependencies + }; + } + return { code: result, errors: [], dependencies }; + } catch (e) { + return { code: "", errors: [e], dependencies: [] }; + } +}; +function getSource(source, filename, additionalData) { + if (!additionalData) + return source; + if (isFunction$1(additionalData)) { + return additionalData(source, filename); + } + return additionalData + source; +} +const processors = { + less, + sass, + scss, + styl, + stylus: styl +}; + +var __defProp$4 = Object.defineProperty; +var __defProps$3 = Object.defineProperties; +var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols; +var __hasOwnProp$4 = Object.prototype.hasOwnProperty; +var __propIsEnum$4 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$4 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + if (__getOwnPropSymbols$4) + for (var prop of __getOwnPropSymbols$4(b)) { + if (__propIsEnum$4.call(b, prop)) + __defNormalProp$4(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b)); +function compileStyle(options) { + return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), { + isAsync: false + })); +} +function compileStyleAsync(options) { + return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), { + isAsync: true + })); +} +function doCompileStyle(options) { + const { + filename, + id, + scoped = false, + trim = true, + isProd = false, + modules = false, + modulesOptions = {}, + preprocessLang, + postcssOptions, + postcssPlugins + } = options; + const preprocessor = preprocessLang && processors[preprocessLang]; + const preProcessedSource = preprocessor && preprocess(options, preprocessor); + const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map; + const source = preProcessedSource ? preProcessedSource.code : options.source; + const shortId = id.replace(/^data-v-/, ""); + const longId = `data-v-${shortId}`; + const plugins = (postcssPlugins || []).slice(); + plugins.unshift(cssVarsPlugin({ id: shortId, isProd })); + if (trim) { + plugins.push(trimPlugin()); + } + if (scoped) { + plugins.push(scopedPlugin(longId)); + } + let cssModules; + if (modules) { + { + throw new Error( + "[@vue/compiler-sfc] `modules` option is not supported in the browser build." + ); + } + } + const postCSSOptions = __spreadProps$3(__spreadValues$4({}, postcssOptions), { + to: filename, + from: filename + }); + if (map) { + postCSSOptions.map = { + inline: false, + annotation: false, + prev: map + }; + } + let result; + let code; + let outMap; + const dependencies = new Set( + preProcessedSource ? preProcessedSource.dependencies : [] + ); + dependencies.delete(filename); + const errors = []; + if (preProcessedSource && preProcessedSource.errors.length) { + errors.push(...preProcessedSource.errors); + } + const recordPlainCssDependencies = (messages) => { + messages.forEach((msg) => { + if (msg.type === "dependency") { + dependencies.add(msg.file); + } + }); + return dependencies; + }; + try { + result = postcss$1(plugins).process(source, postCSSOptions); + if (options.isAsync) { + return result.then((result2) => ({ + code: result2.css || "", + map: result2.map && result2.map.toJSON(), + errors, + modules: cssModules, + rawResult: result2, + dependencies: recordPlainCssDependencies(result2.messages) + })).catch((error) => ({ + code: "", + map: void 0, + errors: [...errors, error], + rawResult: void 0, + dependencies + })); + } + recordPlainCssDependencies(result.messages); + code = result.css; + outMap = result.map; + } catch (e) { + errors.push(e); + } + return { + code: code || ``, + map: outMap && outMap.toJSON(), + errors, + rawResult: result, + dependencies + }; +} +function preprocess(options, preprocessor) { + if (!options.preprocessCustomRequire) { + throw new Error( + `[@vue/compiler-sfc] Style preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor.` + ); + } + return preprocessor( + options.source, + options.inMap || options.map, + __spreadValues$4({ + filename: options.filename + }, options.preprocessOptions), + options.preprocessCustomRequire + ); +} + +function analyzeScriptBindings(ast) { + for (const node of ast) { + if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") { + return analyzeBindingsFromOptions(node.declaration); + } + } + return {}; +} +function analyzeBindingsFromOptions(node) { + const bindings = {}; + Object.defineProperty(bindings, "__isScriptSetup", { + enumerable: false, + value: false + }); + for (const property of node.properties) { + if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") { + if (property.key.name === "props") { + for (const key of getObjectOrArrayExpressionKeys(property.value)) { + bindings[key] = "props"; + } + } else if (property.key.name === "inject") { + for (const key of getObjectOrArrayExpressionKeys(property.value)) { + bindings[key] = "options"; + } + } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) { + for (const key of getObjectExpressionKeys(property.value)) { + bindings[key] = "options"; + } + } + } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) { + for (const bodyItem of property.body.body) { + if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") { + for (const key of getObjectExpressionKeys(bodyItem.argument)) { + bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data"; + } + } + } + } + } + return bindings; +} +function getObjectExpressionKeys(node) { + const keys = []; + for (const prop of node.properties) { + if (prop.type === "SpreadElement") + continue; + const key = resolveObjectKey(prop.key, prop.computed); + if (key) + keys.push(String(key)); + } + return keys; +} +function getArrayExpressionKeys(node) { + const keys = []; + for (const element of node.elements) { + if (element && element.type === "StringLiteral") { + keys.push(element.value); + } + } + return keys; +} +function getObjectOrArrayExpressionKeys(value) { + if (value.type === "ArrayExpression") { + return getArrayExpressionKeys(value); + } + if (value.type === "ObjectExpression") { + return getObjectExpressionKeys(value); + } + return []; +} + +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + reset() { + this.intro = ''; + this.outro = ''; + if (this.edited) { + this.content = this.original; + this.storeName = false; + this.edited = false; + } + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa() { + if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') { + return (str) => globalThis.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa = /*#__PURE__*/ getBtoa(); + +class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); + } +} + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +const wordRegex = /\w/; + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + reset(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.reset(); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +var _a, _b; +class ScriptCompileContext { + constructor(descriptor, options) { + this.descriptor = descriptor; + this.options = options; + this.isCE = false; + this.source = this.descriptor.source; + this.filename = this.descriptor.filename; + this.s = new MagicString(this.source); + this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset; + this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset; + this.userImports = /* @__PURE__ */ Object.create(null); + // macros presence check + this.hasDefinePropsCall = false; + this.hasDefineEmitCall = false; + this.hasDefineExposeCall = false; + this.hasDefaultExportName = false; + this.hasDefaultExportRender = false; + this.hasDefineOptionsCall = false; + this.hasDefineSlotsCall = false; + this.hasDefineModelCall = false; + this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null); + // defineModel + this.modelDecls = /* @__PURE__ */ Object.create(null); + // codegen + this.bindingMetadata = {}; + this.helperImports = /* @__PURE__ */ new Set(); + const { script, scriptSetup } = descriptor; + const scriptLang = script && script.lang; + const scriptSetupLang = scriptSetup && scriptSetup.lang; + this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx"; + this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx"; + const customElement = options.customElement; + const filename = this.descriptor.filename; + if (customElement) { + this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename); + } + const plugins = resolveParserPlugins( + scriptLang || scriptSetupLang, + options.babelParserPlugins + ); + function parse(input, offset) { + try { + return parse_1$1(input, { + plugins, + sourceType: "module" + }).program; + } catch (e) { + e.message = `[vue/compiler-sfc] ${e.message} + +${descriptor.filename} +${generateCodeFrame( + descriptor.source, + e.pos + offset, + e.pos + offset + 1 + )}`; + throw e; + } + } + this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset); + this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset); + } + helper(key) { + this.helperImports.add(key); + return `_${key}`; + } + getString(node, scriptSetup = true) { + const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script; + return block.content.slice(node.start, node.end); + } + error(msg, node, scope) { + const offset = scope ? scope.offset : this.startOffset; + throw new Error( + `[@vue/compiler-sfc] ${msg} + +${(scope || this.descriptor).filename} +${generateCodeFrame( + (scope || this.descriptor).source, + node.start + offset, + node.end + offset + )}` + ); + } +} +function resolveParserPlugins(lang, userPlugins, dts = false) { + const plugins = []; + if (!userPlugins || !userPlugins.some( + (p) => p === "importAssertions" || p === "importAttributes" || isArray$3(p) && p[0] === "importAttributes" + )) { + plugins.push("importAttributes"); + } + if (lang === "jsx" || lang === "tsx") { + plugins.push("jsx"); + } else if (userPlugins) { + userPlugins = userPlugins.filter((p) => p !== "jsx"); + } + if (lang === "ts" || lang === "tsx") { + plugins.push(["typescript", { dts }], "explicitResourceManagement"); + if (!userPlugins || !userPlugins.includes("decorators")) { + plugins.push("decorators-legacy"); + } + } + if (userPlugins) { + plugins.push(...userPlugins); + } + return plugins; +} + +function rewriteDefault(input, as, parserPlugins) { + const ast = parse_1$1(input, { + sourceType: "module", + plugins: resolveParserPlugins("js", parserPlugins) + }).program.body; + const s = new MagicString(input); + rewriteDefaultAST(ast, s, as); + return s.toString(); +} +function rewriteDefaultAST(ast, s, as) { + if (!hasDefaultExport(ast)) { + s.append(` +const ${as} = {}`); + return; + } + ast.forEach((node) => { + if (node.type === "ExportDefaultDeclaration") { + if (node.declaration.type === "ClassDeclaration" && node.declaration.id) { + let start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start; + s.overwrite(start, node.declaration.id.start, ` class `); + s.append(` +const ${as} = ${node.declaration.id.name}`); + } else { + s.overwrite(node.start, node.declaration.start, `const ${as} = `); + } + } else if (node.type === "ExportNamedDeclaration") { + for (const specifier of node.specifiers) { + if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") { + if (node.source) { + if (specifier.local.name === "default") { + s.prepend( + `import { default as __VUE_DEFAULT__ } from '${node.source.value}' +` + ); + const end2 = specifierEnd(s, specifier.local.end, node.end); + s.remove(specifier.start, end2); + s.append(` +const ${as} = __VUE_DEFAULT__`); + continue; + } else { + s.prepend( + `import { ${s.slice( + specifier.local.start, + specifier.local.end + )} as __VUE_DEFAULT__ } from '${node.source.value}' +` + ); + const end2 = specifierEnd(s, specifier.exported.end, node.end); + s.remove(specifier.start, end2); + s.append(` +const ${as} = __VUE_DEFAULT__`); + continue; + } + } + const end = specifierEnd(s, specifier.end, node.end); + s.remove(specifier.start, end); + s.append(` +const ${as} = ${specifier.local.name}`); + } + } + } + }); +} +function hasDefaultExport(ast) { + for (const stmt of ast) { + if (stmt.type === "ExportDefaultDeclaration") { + return true; + } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some( + (spec) => spec.exported.name === "default" + )) { + return true; + } + } + return false; +} +function specifierEnd(s, end, nodeEnd) { + let hasCommas = false; + let oldEnd = end; + while (end < nodeEnd) { + if (/\s/.test(s.slice(end, end + 1))) { + end++; + } else if (s.slice(end, end + 1) === ",") { + end++; + hasCommas = true; + break; + } else if (s.slice(end, end + 1) === "}") { + break; + } + } + return hasCommas ? end : oldEnd; +} + +var __defProp$3 = Object.defineProperty; +var __defProps$2 = Object.defineProperties; +var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols; +var __hasOwnProp$3 = Object.prototype.hasOwnProperty; +var __propIsEnum$3 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$3 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + if (__getOwnPropSymbols$3) + for (var prop of __getOwnPropSymbols$3(b)) { + if (__propIsEnum$3.call(b, prop)) + __defNormalProp$3(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); +const normalScriptDefaultVar = `__default__`; +function processNormalScript(ctx, scopeId) { + var _a; + const script = ctx.descriptor.script; + if (script.lang && !ctx.isJS && !ctx.isTS) { + return script; + } + try { + let content = script.content; + let map = script.map; + const scriptAst = ctx.scriptAst; + const bindings = analyzeScriptBindings(scriptAst.body); + const { cssVars } = ctx.descriptor; + const { genDefaultAs, isProd } = ctx.options; + if (cssVars.length || genDefaultAs) { + const defaultVar = genDefaultAs || normalScriptDefaultVar; + const s = new MagicString(content); + rewriteDefaultAST(scriptAst.body, s, defaultVar); + content = s.toString(); + if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) { + content += genNormalScriptCssVarsCode( + cssVars, + bindings, + scopeId, + !!isProd, + defaultVar + ); + } + if (!genDefaultAs) { + content += ` +export default ${defaultVar}`; + } + } + return __spreadProps$2(__spreadValues$3({}, script), { + content, + map, + bindings, + scriptAst: scriptAst.body + }); + } catch (e) { + return script; + } +} + +var __defProp$2 = Object.defineProperty; +var __defProps$1 = Object.defineProperties; +var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; +var __hasOwnProp$2 = Object.prototype.hasOwnProperty; +var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$2 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + if (__getOwnPropSymbols$2) + for (var prop of __getOwnPropSymbols$2(b)) { + if (__propIsEnum$2.call(b, prop)) + __defNormalProp$2(a, prop, b[prop]); + } + return a; +}; +var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); +class TypeScope { + constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) { + this.filename = filename; + this.source = source; + this.offset = offset; + this.imports = imports; + this.types = types; + this.declares = declares; + this.isGenericScope = false; + this.resolvedImportSources = /* @__PURE__ */ Object.create(null); + this.exportedTypes = /* @__PURE__ */ Object.create(null); + this.exportedDeclares = /* @__PURE__ */ Object.create(null); + } +} +function resolveTypeElements(ctx, node, scope, typeParameters) { + const canCache = !typeParameters; + if (canCache && node._resolvedElements) { + return node._resolvedElements; + } + const resolved = innerResolveTypeElements( + ctx, + node, + node._ownerScope || scope || ctxToScope(ctx), + typeParameters + ); + return canCache ? node._resolvedElements = resolved : resolved; +} +function innerResolveTypeElements(ctx, node, scope, typeParameters) { + var _a, _b; + switch (node.type) { + case "TSTypeLiteral": + return typeElementsToMap(ctx, node.members, scope, typeParameters); + case "TSInterfaceDeclaration": + return resolveInterfaceMembers(ctx, node, scope, typeParameters); + case "TSTypeAliasDeclaration": + case "TSParenthesizedType": + return resolveTypeElements( + ctx, + node.typeAnnotation, + scope, + typeParameters + ); + case "TSFunctionType": { + return { props: {}, calls: [node] }; + } + case "TSUnionType": + case "TSIntersectionType": + return mergeElements( + node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)), + node.type + ); + case "TSMappedType": + return resolveMappedType(ctx, node, scope); + case "TSIndexedAccessType": { + const types = resolveIndexType(ctx, node, scope); + return mergeElements( + types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)), + "TSUnionType" + ); + } + case "TSExpressionWithTypeArguments": + case "TSTypeReference": { + const typeName = getReferenceName(node); + if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") { + return resolveExtractPropTypes( + resolveTypeElements( + ctx, + node.typeParameters.params[0], + scope, + typeParameters + ), + scope + ); + } + const resolved = resolveTypeReference(ctx, node, scope); + if (resolved) { + let typeParams; + if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) { + typeParams = /* @__PURE__ */ Object.create(null); + resolved.typeParameters.params.forEach((p, i) => { + let param = typeParameters && typeParameters[p.name]; + if (!param) + param = node.typeParameters.params[i]; + typeParams[p.name] = param; + }); + } + return resolveTypeElements( + ctx, + resolved, + resolved._ownerScope, + typeParams + ); + } else { + if (typeof typeName === "string") { + if (typeParameters && typeParameters[typeName]) { + return resolveTypeElements( + ctx, + typeParameters[typeName], + scope, + typeParameters + ); + } + if ( + // @ts-expect-error + SupportedBuiltinsSet.has(typeName) + ) { + return resolveBuiltin( + ctx, + node, + typeName, + scope, + typeParameters + ); + } else if (typeName === "ReturnType" && node.typeParameters) { + const ret = resolveReturnType( + ctx, + node.typeParameters.params[0], + scope + ); + if (ret) { + return resolveTypeElements(ctx, ret, scope); + } + } + } + return ctx.error( + `Unresolvable type reference or unsupported built-in utility type`, + node, + scope + ); + } + } + case "TSImportType": { + if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) { + return resolveExtractPropTypes( + resolveTypeElements(ctx, node.typeParameters.params[0], scope), + scope + ); + } + const sourceScope = importSourceToScope( + ctx, + node.argument, + scope, + node.argument.value + ); + const resolved = resolveTypeReference(ctx, node, sourceScope); + if (resolved) { + return resolveTypeElements(ctx, resolved, resolved._ownerScope); + } + break; + } + case "TSTypeQuery": + { + const resolved = resolveTypeReference(ctx, node, scope); + if (resolved) { + return resolveTypeElements(ctx, resolved, resolved._ownerScope); + } + } + break; + } + return ctx.error(`Unresolvable type: ${node.type}`, node, scope); +} +function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) { + const res = { props: {} }; + for (const e of elements) { + if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") { + if (typeParameters) { + scope = createChildScope(scope); + scope.isGenericScope = true; + Object.assign(scope.types, typeParameters); + } + e._ownerScope = scope; + const name = getId(e.key); + if (name && !e.computed) { + res.props[name] = e; + } else if (e.key.type === "TemplateLiteral") { + for (const key of resolveTemplateKeys(ctx, e.key, scope)) { + res.props[key] = e; + } + } else { + ctx.error( + `Unsupported computed key in type referenced by a macro`, + e.key, + scope + ); + } + } else if (e.type === "TSCallSignatureDeclaration") { + (res.calls || (res.calls = [])).push(e); + } + } + return res; +} +function mergeElements(maps, type) { + if (maps.length === 1) + return maps[0]; + const res = { props: {} }; + const { props: baseProps } = res; + for (const { props, calls } of maps) { + for (const key in props) { + if (!hasOwn(baseProps, key)) { + baseProps[key] = props[key]; + } else { + baseProps[key] = createProperty( + baseProps[key].key, + { + type, + // @ts-expect-error + types: [baseProps[key], props[key]] + }, + baseProps[key]._ownerScope, + baseProps[key].optional || props[key].optional + ); + } + } + if (calls) { + (res.calls || (res.calls = [])).push(...calls); + } + } + return res; +} +function createProperty(key, typeAnnotation, scope, optional) { + return { + type: "TSPropertySignature", + key, + kind: "get", + optional, + typeAnnotation: { + type: "TSTypeAnnotation", + typeAnnotation + }, + _ownerScope: scope + }; +} +function resolveInterfaceMembers(ctx, node, scope, typeParameters) { + const base = typeElementsToMap( + ctx, + node.body.body, + node._ownerScope, + typeParameters + ); + if (node.extends) { + for (const ext of node.extends) { + if (ext.leadingComments && ext.leadingComments.some((c) => c.value.includes("@vue-ignore"))) { + continue; + } + try { + const { props, calls } = resolveTypeElements(ctx, ext, scope); + for (const key in props) { + if (!hasOwn(base.props, key)) { + base.props[key] = props[key]; + } + } + if (calls) { + ; + (base.calls || (base.calls = [])).push(...calls); + } + } catch (e) { + ctx.error( + `Failed to resolve extends base type. +If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example: + +interface Props extends /* @vue-ignore */ Base {} + +Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`, + ext + ); + } + } + } + return base; +} +function resolveMappedType(ctx, node, scope) { + const res = { props: {} }; + const keys = resolveStringType(ctx, node.typeParameter.constraint, scope); + for (const key of keys) { + res.props[key] = createProperty( + { + type: "Identifier", + name: key + }, + node.typeAnnotation, + scope, + !!node.optional + ); + } + return res; +} +function resolveIndexType(ctx, node, scope) { + var _a, _b; + if (node.indexType.type === "TSNumberKeyword") { + return resolveArrayElementType(ctx, node.objectType, scope); + } + const { indexType, objectType } = node; + const types = []; + let keys; + let resolved; + if (indexType.type === "TSStringKeyword") { + resolved = resolveTypeElements(ctx, objectType, scope); + keys = Object.keys(resolved.props); + } else { + keys = resolveStringType(ctx, indexType, scope); + resolved = resolveTypeElements(ctx, objectType, scope); + } + for (const key of keys) { + const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation; + if (targetType) { + targetType._ownerScope = resolved.props[key]._ownerScope; + types.push(targetType); + } + } + return types; +} +function resolveArrayElementType(ctx, node, scope) { + if (node.type === "TSArrayType") { + return [node.elementType]; + } + if (node.type === "TSTupleType") { + return node.elementTypes.map( + (t) => t.type === "TSNamedTupleMember" ? t.elementType : t + ); + } + if (node.type === "TSTypeReference") { + if (getReferenceName(node) === "Array" && node.typeParameters) { + return node.typeParameters.params; + } else { + const resolved = resolveTypeReference(ctx, node, scope); + if (resolved) { + return resolveArrayElementType(ctx, resolved, scope); + } + } + } + return ctx.error( + "Failed to resolve element type from target type", + node, + scope + ); +} +function resolveStringType(ctx, node, scope) { + switch (node.type) { + case "StringLiteral": + return [node.value]; + case "TSLiteralType": + return resolveStringType(ctx, node.literal, scope); + case "TSUnionType": + return node.types.map((t) => resolveStringType(ctx, t, scope)).flat(); + case "TemplateLiteral": { + return resolveTemplateKeys(ctx, node, scope); + } + case "TSTypeReference": { + const resolved = resolveTypeReference(ctx, node, scope); + if (resolved) { + return resolveStringType(ctx, resolved, scope); + } + if (node.typeName.type === "Identifier") { + const getParam = (index = 0) => resolveStringType(ctx, node.typeParameters.params[index], scope); + switch (node.typeName.name) { + case "Extract": + return getParam(1); + case "Exclude": { + const excluded = getParam(1); + return getParam().filter((s) => !excluded.includes(s)); + } + case "Uppercase": + return getParam().map((s) => s.toUpperCase()); + case "Lowercase": + return getParam().map((s) => s.toLowerCase()); + case "Capitalize": + return getParam().map(capitalize$1); + case "Uncapitalize": + return getParam().map((s) => s[0].toLowerCase() + s.slice(1)); + default: + ctx.error( + "Unsupported type when resolving index type", + node.typeName, + scope + ); + } + } + } + } + return ctx.error("Failed to resolve index type into finite keys", node, scope); +} +function resolveTemplateKeys(ctx, node, scope) { + if (!node.expressions.length) { + return [node.quasis[0].value.raw]; + } + const res = []; + const e = node.expressions[0]; + const q = node.quasis[0]; + const leading = q ? q.value.raw : ``; + const resolved = resolveStringType(ctx, e, scope); + const restResolved = resolveTemplateKeys( + ctx, + __spreadProps$1(__spreadValues$2({}, node), { + expressions: node.expressions.slice(1), + quasis: q ? node.quasis.slice(1) : node.quasis + }), + scope + ); + for (const r of resolved) { + for (const rr of restResolved) { + res.push(leading + r + rr); + } + } + return res; +} +const SupportedBuiltinsSet = /* @__PURE__ */ new Set([ + "Partial", + "Required", + "Readonly", + "Pick", + "Omit" +]); +function resolveBuiltin(ctx, node, name, scope, typeParameters) { + const t = resolveTypeElements( + ctx, + node.typeParameters.params[0], + scope, + typeParameters + ); + switch (name) { + case "Partial": { + const res2 = { props: {}, calls: t.calls }; + Object.keys(t.props).forEach((key) => { + res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: true }); + }); + return res2; + } + case "Required": { + const res2 = { props: {}, calls: t.calls }; + Object.keys(t.props).forEach((key) => { + res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: false }); + }); + return res2; + } + case "Readonly": + return t; + case "Pick": { + const picked = resolveStringType( + ctx, + node.typeParameters.params[1], + scope + ); + const res2 = { props: {}, calls: t.calls }; + for (const key of picked) { + res2.props[key] = t.props[key]; + } + return res2; + } + case "Omit": + const omitted = resolveStringType( + ctx, + node.typeParameters.params[1], + scope + ); + const res = { props: {}, calls: t.calls }; + for (const key in t.props) { + if (!omitted.includes(key)) { + res.props[key] = t.props[key]; + } + } + return res; + } +} +function resolveTypeReference(ctx, node, scope, name, onlyExported = false) { + const canCache = !(scope == null ? void 0 : scope.isGenericScope); + if (canCache && node._resolvedReference) { + return node._resolvedReference; + } + const resolved = innerResolveTypeReference( + ctx, + scope || ctxToScope(ctx), + name || getReferenceName(node), + node, + onlyExported + ); + return canCache ? node._resolvedReference = resolved : resolved; +} +function innerResolveTypeReference(ctx, scope, name, node, onlyExported) { + if (typeof name === "string") { + if (scope.imports[name]) { + return resolveTypeFromImport(ctx, node, name, scope); + } else { + const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types; + if (lookupSource[name]) { + return lookupSource[name]; + } else { + const globalScopes = resolveGlobalScope(ctx); + if (globalScopes) { + for (const s of globalScopes) { + const src = node.type === "TSTypeQuery" ? s.declares : s.types; + if (src[name]) { + (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename); + return src[name]; + } + } + } + } + } + } else { + let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported); + if (ns) { + if (ns.type !== "TSModuleDeclaration") { + ns = ns._ns; + } + if (ns) { + const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope); + return innerResolveTypeReference( + ctx, + childScope, + name.length > 2 ? name.slice(1) : name[name.length - 1], + node, + !ns.declare + ); + } + } + } +} +function getReferenceName(node) { + const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName; + if ((ref == null ? void 0 : ref.type) === "Identifier") { + return ref.name; + } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") { + return qualifiedNameToPath(ref); + } else { + return "default"; + } +} +function qualifiedNameToPath(node) { + if (node.type === "Identifier") { + return [node.name]; + } else { + return [...qualifiedNameToPath(node.left), node.right.name]; + } +} +function resolveGlobalScope(ctx) { + if (ctx.options.globalTypeFiles) { + const fs = resolveFS(ctx); + if (!fs) { + throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access."); + } + return ctx.options.globalTypeFiles.map( + (file) => fileToScope(ctx, normalizePath(file), true) + ); + } +} +let ts; +let loadTS; +function registerTS(_loadTS) { + loadTS = () => { + try { + return _loadTS(); + } catch (err) { + if (typeof err.message === "string" && err.message.includes("Cannot find module")) { + throw new Error( + 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.' + ); + } else { + throw new Error( + "Failed to load TypeScript for resolving imported types." + ); + } + } + }; +} +function resolveFS(ctx) { + if (ctx.fs) { + return ctx.fs; + } + if (!ts && loadTS) { + ts = loadTS(); + } + const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys); + if (!fs) { + return; + } + return ctx.fs = { + fileExists(file) { + if (file.endsWith(".vue.ts")) { + file = file.replace(/\.ts$/, ""); + } + return fs.fileExists(file); + }, + readFile(file) { + if (file.endsWith(".vue.ts")) { + file = file.replace(/\.ts$/, ""); + } + return fs.readFile(file); + }, + realpath: fs.realpath + }; +} +function resolveTypeFromImport(ctx, node, name, scope) { + const { source, imported } = scope.imports[name]; + const sourceScope = importSourceToScope(ctx, node, scope, source); + return resolveTypeReference(ctx, node, sourceScope, imported, true); +} +function importSourceToScope(ctx, node, scope, source) { + let fs; + try { + fs = resolveFS(ctx); + } catch (err) { + return ctx.error(err.message, node, scope); + } + if (!fs) { + return ctx.error( + `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`, + node, + scope + ); + } + let resolved = scope.resolvedImportSources[source]; + if (!resolved) { + if (source.startsWith("..")) { + const osSpecificJoinFn = joinPaths; + const filename = osSpecificJoinFn(dirname$2(scope.filename), source); + resolved = resolveExt(filename, fs); + } else if (source.startsWith(".")) { + const filename = joinPaths(dirname$2(scope.filename), source); + resolved = resolveExt(filename, fs); + } else { + { + return ctx.error( + `Type import from non-relative sources is not supported in the browser build.`, + node, + scope + ); + } + } + if (resolved) { + resolved = scope.resolvedImportSources[source] = normalizePath(resolved); + } + } + if (resolved) { + (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved); + return fileToScope(ctx, resolved); + } else { + return ctx.error( + `Failed to resolve import source ${JSON.stringify(source)}.`, + node, + scope + ); + } +} +function resolveExt(filename, fs) { + filename = filename.replace(/\.js$/, ""); + const tryResolve = (filename2) => { + if (fs.fileExists(filename2)) + return filename2; + }; + return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.d.ts`)); +} +const tsConfigCache = createCache(); +const tsConfigRefMap = /* @__PURE__ */ new Map(); +const fileToScopeCache = createCache(); +function invalidateTypeCache(filename) { + filename = normalizePath(filename); + fileToScopeCache.delete(filename); + tsConfigCache.delete(filename); + const affectedConfig = tsConfigRefMap.get(filename); + if (affectedConfig) + tsConfigCache.delete(affectedConfig); +} +function fileToScope(ctx, filename, asGlobal = false) { + const cached = fileToScopeCache.get(filename); + if (cached) { + return cached; + } + const fs = resolveFS(ctx); + const source = fs.readFile(filename) || ""; + const body = parseFile(filename, source, ctx.options.babelParserPlugins); + const scope = new TypeScope(filename, source, 0, recordImports(body)); + recordTypes(ctx, body, scope, asGlobal); + fileToScopeCache.set(filename, scope); + return scope; +} +function parseFile(filename, content, parserPlugins) { + const ext = extname(filename); + if (ext === ".ts" || ext === ".tsx") { + return parse_1$1(content, { + plugins: resolveParserPlugins( + ext.slice(1), + parserPlugins, + filename.endsWith(".d.ts") + ), + sourceType: "module" + }).program.body; + } else if (ext === ".vue") { + const { + descriptor: { script, scriptSetup } + } = parse$7(content); + if (!script && !scriptSetup) { + return []; + } + const scriptOffset = script ? script.loc.start.offset : Infinity; + const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity; + const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup; + const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script; + let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content; + if (secondBlock) { + scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content; + } + const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang); + return parse_1$1(scriptContent, { + plugins: resolveParserPlugins(lang, parserPlugins), + sourceType: "module" + }).program.body; + } + return []; +} +function ctxToScope(ctx) { + if (ctx.scope) { + return ctx.scope; + } + const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body; + const scope = new TypeScope( + ctx.filename, + ctx.source, + "startOffset" in ctx ? ctx.startOffset : 0, + "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body) + ); + recordTypes(ctx, body, scope); + return ctx.scope = scope; +} +function moduleDeclToScope(ctx, node, parentScope) { + if (node._resolvedChildScope) { + return node._resolvedChildScope; + } + const scope = createChildScope(parentScope); + if (node.body.type === "TSModuleDeclaration") { + const decl = node.body; + decl._ownerScope = scope; + const id = getId(decl.id); + scope.types[id] = scope.exportedTypes[id] = decl; + } else { + recordTypes(ctx, node.body.body, scope); + } + return node._resolvedChildScope = scope; +} +function createChildScope(parentScope) { + return new TypeScope( + parentScope.filename, + parentScope.source, + parentScope.offset, + Object.create(parentScope.imports), + Object.create(parentScope.types), + Object.create(parentScope.declares) + ); +} +const importExportRE = /^Import|^Export/; +function recordTypes(ctx, body, scope, asGlobal = false) { + const { types, declares, exportedTypes, exportedDeclares, imports } = scope; + const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false; + for (const stmt of body) { + if (asGlobal) { + if (isAmbient) { + if (stmt.declare) { + recordType(stmt, types, declares); + } + } else if (stmt.type === "TSModuleDeclaration" && stmt.global) { + for (const s of stmt.body.body) { + recordType(s, types, declares); + } + } + } else { + recordType(stmt, types, declares); + } + } + if (!asGlobal) { + for (const stmt of body) { + if (stmt.type === "ExportNamedDeclaration") { + if (stmt.declaration) { + recordType(stmt.declaration, types, declares); + recordType(stmt.declaration, exportedTypes, exportedDeclares); + } else { + for (const spec of stmt.specifiers) { + if (spec.type === "ExportSpecifier") { + const local = spec.local.name; + const exported = getId(spec.exported); + if (stmt.source) { + imports[exported] = { + source: stmt.source.value, + imported: local + }; + exportedTypes[exported] = { + type: "TSTypeReference", + typeName: { + type: "Identifier", + name: local + }, + _ownerScope: scope + }; + } else if (types[local]) { + exportedTypes[exported] = types[local]; + } + } + } + } + } else if (stmt.type === "ExportAllDeclaration") { + const sourceScope = importSourceToScope( + ctx, + stmt.source, + scope, + stmt.source.value + ); + Object.assign(scope.exportedTypes, sourceScope.exportedTypes); + } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) { + if (stmt.declaration.type !== "Identifier") { + recordType(stmt.declaration, types, declares, "default"); + recordType( + stmt.declaration, + exportedTypes, + exportedDeclares, + "default" + ); + } else if (types[stmt.declaration.name]) { + exportedTypes["default"] = types[stmt.declaration.name]; + } + } + } + } + for (const key of Object.keys(types)) { + const node = types[key]; + node._ownerScope = scope; + if (node._ns) + node._ns._ownerScope = scope; + } + for (const key of Object.keys(declares)) { + declares[key]._ownerScope = scope; + } +} +function recordType(node, types, declares, overwriteId) { + switch (node.type) { + case "TSInterfaceDeclaration": + case "TSEnumDeclaration": + case "TSModuleDeclaration": { + const id = overwriteId || getId(node.id); + let existing = types[id]; + if (existing) { + if (node.type === "TSModuleDeclaration") { + if (existing.type === "TSModuleDeclaration") { + mergeNamespaces(existing, node); + } else { + attachNamespace(existing, node); + } + break; + } + if (existing.type === "TSModuleDeclaration") { + types[id] = node; + attachNamespace(node, existing); + break; + } + if (existing.type !== node.type) { + break; + } + if (node.type === "TSInterfaceDeclaration") { + existing.body.body.push(...node.body.body); + } else { + existing.members.push(...node.members); + } + } else { + types[id] = node; + } + break; + } + case "ClassDeclaration": + if (overwriteId || node.id) + types[overwriteId || getId(node.id)] = node; + break; + case "TSTypeAliasDeclaration": + types[node.id.name] = node.typeParameters ? node : node.typeAnnotation; + break; + case "TSDeclareFunction": + if (node.id) + declares[node.id.name] = node; + break; + case "VariableDeclaration": { + if (node.declare) { + for (const decl of node.declarations) { + if (decl.id.type === "Identifier" && decl.id.typeAnnotation) { + declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation; + } + } + } + break; + } + } +} +function mergeNamespaces(to, from) { + const toBody = to.body; + const fromBody = from.body; + if (toBody.type === "TSModuleDeclaration") { + if (fromBody.type === "TSModuleDeclaration") { + mergeNamespaces(toBody, fromBody); + } else { + fromBody.body.push({ + type: "ExportNamedDeclaration", + declaration: toBody, + exportKind: "type", + specifiers: [] + }); + } + } else if (fromBody.type === "TSModuleDeclaration") { + toBody.body.push({ + type: "ExportNamedDeclaration", + declaration: fromBody, + exportKind: "type", + specifiers: [] + }); + } else { + toBody.body.push(...fromBody.body); + } +} +function attachNamespace(to, ns) { + if (!to._ns) { + to._ns = ns; + } else { + mergeNamespaces(to._ns, ns); + } +} +function recordImports(body) { + const imports = /* @__PURE__ */ Object.create(null); + for (const s of body) { + recordImport(s, imports); + } + return imports; +} +function recordImport(node, imports) { + if (node.type !== "ImportDeclaration") { + return; + } + for (const s of node.specifiers) { + imports[s.local.name] = { + imported: getImportedName(s), + source: node.source.value + }; + } +} +function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx)) { + try { + switch (node.type) { + case "TSStringKeyword": + return ["String"]; + case "TSNumberKeyword": + return ["Number"]; + case "TSBooleanKeyword": + return ["Boolean"]; + case "TSObjectKeyword": + return ["Object"]; + case "TSNullKeyword": + return ["null"]; + case "TSTypeLiteral": + case "TSInterfaceDeclaration": { + const types = /* @__PURE__ */ new Set(); + const members = node.type === "TSTypeLiteral" ? node.members : node.body.body; + for (const m of members) { + if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") { + types.add("Function"); + } else { + types.add("Object"); + } + } + return types.size ? Array.from(types) : ["Object"]; + } + case "TSPropertySignature": + if (node.typeAnnotation) { + return inferRuntimeType( + ctx, + node.typeAnnotation.typeAnnotation, + scope + ); + } + break; + case "TSMethodSignature": + case "TSFunctionType": + return ["Function"]; + case "TSArrayType": + case "TSTupleType": + return ["Array"]; + case "TSLiteralType": + switch (node.literal.type) { + case "StringLiteral": + return ["String"]; + case "BooleanLiteral": + return ["Boolean"]; + case "NumericLiteral": + case "BigIntLiteral": + return ["Number"]; + default: + return [UNKNOWN_TYPE]; + } + case "TSTypeReference": { + const resolved = resolveTypeReference(ctx, node, scope); + if (resolved) { + return inferRuntimeType(ctx, resolved, resolved._ownerScope); + } + if (node.typeName.type === "Identifier") { + switch (node.typeName.name) { + case "Array": + case "Function": + case "Object": + case "Set": + case "Map": + case "WeakSet": + case "WeakMap": + case "Date": + case "Promise": + case "Error": + return [node.typeName.name]; + case "Partial": + case "Required": + case "Readonly": + case "Record": + case "Pick": + case "Omit": + case "InstanceType": + return ["Object"]; + case "Uppercase": + case "Lowercase": + case "Capitalize": + case "Uncapitalize": + return ["String"]; + case "Parameters": + case "ConstructorParameters": + return ["Array"]; + case "NonNullable": + if (node.typeParameters && node.typeParameters.params[0]) { + return inferRuntimeType( + ctx, + node.typeParameters.params[0], + scope + ).filter((t) => t !== "null"); + } + break; + case "Extract": + if (node.typeParameters && node.typeParameters.params[1]) { + return inferRuntimeType( + ctx, + node.typeParameters.params[1], + scope + ); + } + break; + case "Exclude": + case "OmitThisParameter": + if (node.typeParameters && node.typeParameters.params[0]) { + return inferRuntimeType( + ctx, + node.typeParameters.params[0], + scope + ); + } + break; + } + } + break; + } + case "TSParenthesizedType": + return inferRuntimeType(ctx, node.typeAnnotation, scope); + case "TSUnionType": + return flattenTypes(ctx, node.types, scope); + case "TSIntersectionType": { + return flattenTypes(ctx, node.types, scope).filter( + (t) => t !== UNKNOWN_TYPE + ); + } + case "TSEnumDeclaration": + return inferEnumType(node); + case "TSSymbolKeyword": + return ["Symbol"]; + case "TSIndexedAccessType": { + const types = resolveIndexType(ctx, node, scope); + return flattenTypes(ctx, types, scope); + } + case "ClassDeclaration": + return ["Object"]; + case "TSImportType": { + const sourceScope = importSourceToScope( + ctx, + node.argument, + scope, + node.argument.value + ); + const resolved = resolveTypeReference(ctx, node, sourceScope); + if (resolved) { + return inferRuntimeType(ctx, resolved, resolved._ownerScope); + } + break; + } + case "TSTypeQuery": { + const id = node.exprName; + if (id.type === "Identifier") { + const matched = scope.declares[id.name]; + if (matched) { + return inferRuntimeType(ctx, matched, matched._ownerScope); + } + } + break; + } + } + } catch (e) { + } + return [UNKNOWN_TYPE]; +} +function flattenTypes(ctx, types, scope) { + if (types.length === 1) { + return inferRuntimeType(ctx, types[0], scope); + } + return [ + ...new Set( + [].concat( + ...types.map((t) => inferRuntimeType(ctx, t, scope)) + ) + ) + ]; +} +function inferEnumType(node) { + const types = /* @__PURE__ */ new Set(); + for (const m of node.members) { + if (m.initializer) { + switch (m.initializer.type) { + case "StringLiteral": + types.add("String"); + break; + case "NumericLiteral": + types.add("Number"); + break; + } + } + } + return types.size ? [...types] : ["Number"]; +} +function resolveExtractPropTypes({ props }, scope) { + const res = { props: {} }; + for (const key in props) { + const raw = props[key]; + res.props[key] = reverseInferType( + raw.key, + raw.typeAnnotation.typeAnnotation, + scope + ); + } + return res; +} +function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) { + if (checkObjectSyntax && node.type === "TSTypeLiteral") { + const typeType = findStaticPropertyType(node, "type"); + if (typeType) { + const requiredType = findStaticPropertyType(node, "required"); + const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true; + return reverseInferType(key, typeType, scope, optional2, false); + } + } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") { + if (node.typeName.name.endsWith("Constructor")) { + return createProperty( + key, + ctorToType(node.typeName.name), + scope, + optional + ); + } else if (node.typeName.name === "PropType" && node.typeParameters) { + return createProperty(key, node.typeParameters.params[0], scope, optional); + } + } + if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) { + for (const t of node.typeParameters.params) { + const inferred = reverseInferType(key, t, scope, optional); + if (inferred) + return inferred; + } + } + return createProperty(key, { type: `TSNullKeyword` }, scope, optional); +} +function ctorToType(ctorType) { + const ctor = ctorType.slice(0, -11); + switch (ctor) { + case "String": + case "Number": + case "Boolean": + return { type: `TS${ctor}Keyword` }; + case "Array": + case "Function": + case "Object": + case "Set": + case "Map": + case "WeakSet": + case "WeakMap": + case "Date": + case "Promise": + return { + type: "TSTypeReference", + typeName: { type: "Identifier", name: ctor } + }; + } + return { type: `TSNullKeyword` }; +} +function findStaticPropertyType(node, key) { + const prop = node.members.find( + (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation + ); + return prop && prop.typeAnnotation.typeAnnotation; +} +function resolveReturnType(ctx, arg, scope) { + var _a; + let resolved = arg; + if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") { + resolved = resolveTypeReference(ctx, arg, scope); + } + if (!resolved) + return; + if (resolved.type === "TSFunctionType") { + return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation; + } + if (resolved.type === "TSDeclareFunction") { + return resolved.returnType; + } +} +function resolveUnionType(ctx, node, scope) { + if (node.type === "TSTypeReference") { + const resolved = resolveTypeReference(ctx, node, scope); + if (resolved) + node = resolved; + } + let types; + if (node.type === "TSUnionType") { + types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope)); + } else { + types = [node]; + } + return types; +} + +const DEFINE_MODEL = "defineModel"; +function processDefineModel(ctx, node, declId) { + if (!isCallOf(node, DEFINE_MODEL)) { + return false; + } + ctx.hasDefineModelCall = true; + const type = node.typeParameters && node.typeParameters.params[0] || void 0; + let modelName; + let options; + const arg0 = node.arguments[0] && unwrapTSNode(node.arguments[0]); + const hasName = arg0 && arg0.type === "StringLiteral"; + if (hasName) { + modelName = arg0.value; + options = node.arguments[1]; + } else { + modelName = "modelValue"; + options = arg0; + } + if (ctx.modelDecls[modelName]) { + ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node); + } + let optionsString = options && ctx.getString(options); + let optionsRemoved = !options; + const runtimeOptionNodes = []; + if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) { + let removed = 0; + for (let i = options.properties.length - 1; i >= 0; i--) { + const p = options.properties[i]; + const next = options.properties[i + 1]; + const start = p.start; + const end = next ? next.start : options.end - 1; + if ((p.type === "ObjectProperty" || p.type === "ObjectMethod") && (p.key.type === "Identifier" && (p.key.name === "get" || p.key.name === "set") || p.key.type === "StringLiteral" && (p.key.value === "get" || p.key.value === "set"))) { + optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start); + } else { + removed++; + ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end); + runtimeOptionNodes.push(p); + } + } + if (removed === options.properties.length) { + optionsRemoved = true; + ctx.s.remove( + ctx.startOffset + (hasName ? arg0.end : options.start), + ctx.startOffset + options.end + ); + } + } + ctx.modelDecls[modelName] = { + type, + options: optionsString, + runtimeOptionNodes, + identifier: declId && declId.type === "Identifier" ? declId.name : void 0 + }; + ctx.bindingMetadata[modelName] = "props"; + ctx.s.overwrite( + ctx.startOffset + node.callee.start, + ctx.startOffset + node.callee.end, + ctx.helper("useModel") + ); + ctx.s.appendLeft( + ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1), + `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`) + ); + return true; +} +function genModelProps(ctx) { + if (!ctx.hasDefineModelCall) + return; + const isProd = !!ctx.options.isProd; + let modelPropsDecl = ""; + for (const [name, { type, options }] of Object.entries(ctx.modelDecls)) { + let skipCheck = false; + let runtimeTypes = type && inferRuntimeType(ctx, type); + if (runtimeTypes) { + const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE); + runtimeTypes = runtimeTypes.filter((el) => { + if (el === UNKNOWN_TYPE) + return false; + return isProd ? el === "Boolean" || el === "Function" && options : true; + }); + skipCheck = !isProd && hasUnknownType && runtimeTypes.length > 0; + } + let runtimeType = runtimeTypes && runtimeTypes.length > 0 && toRuntimeTypeString(runtimeTypes) || void 0; + const codegenOptions = concatStrings([ + runtimeType && `type: ${runtimeType}`, + skipCheck && "skipCheck: true" + ]); + let decl; + if (runtimeType && options) { + decl = ctx.isTS ? `{ ${codegenOptions}, ...${options} }` : `Object.assign({ ${codegenOptions} }, ${options})`; + } else { + decl = options || (runtimeType ? `{ ${codegenOptions} }` : "{}"); + } + modelPropsDecl += ` + ${JSON.stringify(name)}: ${decl},`; + const modifierPropName = JSON.stringify( + name === "modelValue" ? `modelModifiers` : `${name}Modifiers` + ); + modelPropsDecl += ` + ${modifierPropName}: {},`; + } + return `{${modelPropsDecl} + }`; +} + +const DEFINE_PROPS = "defineProps"; +const WITH_DEFAULTS = "withDefaults"; +function processDefineProps(ctx, node, declId) { + if (!isCallOf(node, DEFINE_PROPS)) { + return processWithDefaults(ctx, node, declId); + } + if (ctx.hasDefinePropsCall) { + ctx.error(`duplicate ${DEFINE_PROPS}() call`, node); + } + ctx.hasDefinePropsCall = true; + ctx.propsRuntimeDecl = node.arguments[0]; + if (ctx.propsRuntimeDecl) { + for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) { + if (!(key in ctx.bindingMetadata)) { + ctx.bindingMetadata[key] = "props"; + } + } + } + if (node.typeParameters) { + if (ctx.propsRuntimeDecl) { + ctx.error( + `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`, + node + ); + } + ctx.propsTypeDecl = node.typeParameters.params[0]; + } + if (declId && declId.type === "ObjectPattern") { + processPropsDestructure(ctx, declId); + } + ctx.propsCall = node; + ctx.propsDecl = declId; + return true; +} +function processWithDefaults(ctx, node, declId) { + if (!isCallOf(node, WITH_DEFAULTS)) { + return false; + } + if (!processDefineProps(ctx, node.arguments[0], declId)) { + ctx.error( + `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, + node.arguments[0] || node + ); + } + if (ctx.propsRuntimeDecl) { + ctx.error( + `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`, + node + ); + } + if (ctx.propsDestructureDecl) { + ctx.error( + `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}(). +Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`, + node.callee + ); + } + ctx.propsRuntimeDefaults = node.arguments[1]; + if (!ctx.propsRuntimeDefaults) { + ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node); + } + ctx.propsCall = node; + return true; +} +function genRuntimeProps(ctx) { + let propsDecls; + if (ctx.propsRuntimeDecl) { + propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim(); + if (ctx.propsDestructureDecl) { + const defaults = []; + for (const key in ctx.propsDestructuredBindings) { + const d = genDestructuredDefaultValue(ctx, key); + const finalKey = getEscapedPropName(key); + if (d) + defaults.push( + `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}` + ); + } + if (defaults.length) { + propsDecls = `/*#__PURE__*/${ctx.helper( + `mergeDefaults` + )}(${propsDecls}, { + ${defaults.join(",\n ")} +})`; + } + } + } else if (ctx.propsTypeDecl) { + propsDecls = extractRuntimeProps(ctx); + } + const modelsDecls = genModelProps(ctx); + if (propsDecls && modelsDecls) { + return `/*#__PURE__*/${ctx.helper( + "mergeModels" + )}(${propsDecls}, ${modelsDecls})`; + } else { + return modelsDecls || propsDecls; + } +} +function extractRuntimeProps(ctx) { + const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl); + if (!props.length) { + return; + } + const propStrings = []; + const hasStaticDefaults = hasStaticWithDefaults(ctx); + for (const prop of props) { + propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults)); + if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) { + ctx.bindingMetadata[prop.key] = "props"; + } + } + let propsDecls = `{ + ${propStrings.join(",\n ")} + }`; + if (ctx.propsRuntimeDefaults && !hasStaticDefaults) { + propsDecls = `/*#__PURE__*/${ctx.helper( + "mergeDefaults" + )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`; + } + return propsDecls; +} +function resolveRuntimePropsFromType(ctx, node) { + const props = []; + const elements = resolveTypeElements(ctx, node); + for (const key in elements.props) { + const e = elements.props[key]; + let type = inferRuntimeType(ctx, e); + let skipCheck = false; + if (type.includes(UNKNOWN_TYPE)) { + if (type.includes("Boolean") || type.includes("Function")) { + type = type.filter((t) => t !== UNKNOWN_TYPE); + skipCheck = true; + } else { + type = ["null"]; + } + } + props.push({ + key, + required: !e.optional, + type: type || [`null`], + skipCheck + }); + } + return props; +} +function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) { + let defaultString; + const destructured = genDestructuredDefaultValue(ctx, key, type); + if (destructured) { + defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`; + } else if (hasStaticDefaults) { + const prop = ctx.propsRuntimeDefaults.properties.find( + (node) => { + if (node.type === "SpreadElement") + return false; + return resolveObjectKey(node.key, node.computed) === key; + } + ); + if (prop) { + if (prop.type === "ObjectProperty") { + defaultString = `default: ${ctx.getString(prop.value)}`; + } else { + defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`; + } + } + } + const finalKey = getEscapedPropName(key); + if (!ctx.options.isProd) { + return `${finalKey}: { ${concatStrings([ + `type: ${toRuntimeTypeString(type)}`, + `required: ${required}`, + skipCheck && "skipCheck: true", + defaultString + ])} }`; + } else if (type.some( + (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function" + )) { + return `${finalKey}: { ${concatStrings([ + `type: ${toRuntimeTypeString(type)}`, + defaultString + ])} }`; + } else { + if (ctx.isCE) { + if (defaultString) { + return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString( + type + )} }`}`; + } else { + return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`; + } + } + return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`; + } +} +function hasStaticWithDefaults(ctx) { + return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every( + (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal")) + )); +} +function genDestructuredDefaultValue(ctx, key, inferredType) { + const destructured = ctx.propsDestructuredBindings[key]; + const defaultVal = destructured && destructured.default; + if (defaultVal) { + const value = ctx.getString(defaultVal); + const unwrapped = unwrapTSNode(defaultVal); + if (inferredType && inferredType.length && !inferredType.includes("null")) { + const valueType = inferValueType(unwrapped); + if (valueType && !inferredType.includes(valueType)) { + ctx.error( + `Default value of prop "${key}" does not match declared type.`, + unwrapped + ); + } + } + const needSkipFactory = !inferredType && (isFunctionType(unwrapped) || unwrapped.type === "Identifier"); + const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function")); + return { + valueString: needFactoryWrap ? `() => (${value})` : value, + needSkipFactory + }; + } +} +function inferValueType(node) { + switch (node.type) { + case "StringLiteral": + return "String"; + case "NumericLiteral": + return "Number"; + case "BooleanLiteral": + return "Boolean"; + case "ObjectExpression": + return "Object"; + case "ArrayExpression": + return "Array"; + case "FunctionExpression": + case "ArrowFunctionExpression": + return "Function"; + } +} + +function processPropsDestructure(ctx, declId) { + if (!ctx.options.propsDestructure) { + return; + } + warnOnce$3( + `This project is using reactive props destructure, which is an experimental feature. It may receive breaking changes or be removed in the future, so use at your own risk. +To stay updated, follow the RFC at https://github.com/vuejs/rfcs/discussions/502.` + ); + ctx.propsDestructureDecl = declId; + const registerBinding = (key, local, defaultValue) => { + ctx.propsDestructuredBindings[key] = { local, default: defaultValue }; + if (local !== key) { + ctx.bindingMetadata[local] = "props-aliased"; + (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key; + } + }; + for (const prop of declId.properties) { + if (prop.type === "ObjectProperty") { + const propKey = resolveObjectKey(prop.key, prop.computed); + if (!propKey) { + ctx.error( + `${DEFINE_PROPS}() destructure cannot use computed key.`, + prop.key + ); + } + if (prop.value.type === "AssignmentPattern") { + const { left, right } = prop.value; + if (left.type !== "Identifier") { + ctx.error( + `${DEFINE_PROPS}() destructure does not support nested patterns.`, + left + ); + } + registerBinding(propKey, left.name, right); + } else if (prop.value.type === "Identifier") { + registerBinding(propKey, prop.value.name); + } else { + ctx.error( + `${DEFINE_PROPS}() destructure does not support nested patterns.`, + prop.value + ); + } + } else { + ctx.propsDestructureRestId = prop.argument.name; + ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const"; + } + } +} +function transformDestructuredProps(ctx, vueImportAliases) { + if (!ctx.options.propsDestructure) { + return; + } + const rootScope = {}; + const scopeStack = [rootScope]; + let currentScope = rootScope; + const excludedIds = /* @__PURE__ */ new WeakSet(); + const parentStack = []; + const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null); + for (const key in ctx.propsDestructuredBindings) { + const { local } = ctx.propsDestructuredBindings[key]; + rootScope[local] = true; + propsLocalToPublicMap[local] = key; + } + function pushScope() { + scopeStack.push(currentScope = Object.create(currentScope)); + } + function popScope() { + scopeStack.pop(); + currentScope = scopeStack[scopeStack.length - 1] || null; + } + function registerLocalBinding(id) { + excludedIds.add(id); + if (currentScope) { + currentScope[id.name] = false; + } else { + ctx.error( + "registerBinding called without active scope, something is wrong.", + id + ); + } + } + function walkScope(node, isRoot = false) { + for (const stmt of node.body) { + if (stmt.type === "VariableDeclaration") { + walkVariableDeclaration(stmt, isRoot); + } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") { + if (stmt.declare || !stmt.id) + continue; + registerLocalBinding(stmt.id); + } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") { + walkVariableDeclaration(stmt.left); + } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") { + walkVariableDeclaration(stmt.declaration, isRoot); + } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") { + walkVariableDeclaration(stmt.body, isRoot); + } + } + } + function walkVariableDeclaration(stmt, isRoot = false) { + if (stmt.declare) { + return; + } + for (const decl of stmt.declarations) { + const isDefineProps = isRoot && decl.init && isCallOf(unwrapTSNode(decl.init), "defineProps"); + for (const id of extractIdentifiers$1(decl.id)) { + if (isDefineProps) { + excludedIds.add(id); + } else { + registerLocalBinding(id); + } + } + } + } + function rewriteId(id, parent, parentStack2) { + if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") { + ctx.error(`Cannot assign to destructured props as they are readonly.`, id); + } + if (isStaticProperty(parent) && parent.shorthand) { + if (!parent.inPattern || isInDestructureAssignment(parent, parentStack2)) { + ctx.s.appendLeft( + id.end + ctx.startOffset, + `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}` + ); + } + } else { + ctx.s.overwrite( + id.start + ctx.startOffset, + id.end + ctx.startOffset, + genPropsAccessExp(propsLocalToPublicMap[id.name]) + ); + } + } + function checkUsage(node, method, alias = method) { + if (isCallOf(node, alias)) { + const arg = unwrapTSNode(node.arguments[0]); + if (arg.type === "Identifier" && currentScope[arg.name]) { + ctx.error( + `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`, + arg + ); + } + } + } + const ast = ctx.scriptSetupAst; + walkScope(ast, true); + walk$2(ast, { + enter(node, parent) { + parent && parentStack.push(parent); + if (parent && parent.type.startsWith("TS") && parent.type !== "TSAsExpression" && parent.type !== "TSNonNullExpression" && parent.type !== "TSTypeAssertion") { + return this.skip(); + } + checkUsage(node, "watch", vueImportAliases.watch); + checkUsage(node, "toRef", vueImportAliases.toRef); + if (isFunctionType(node)) { + pushScope(); + walkFunctionParams(node, registerLocalBinding); + if (node.body.type === "BlockStatement") { + walkScope(node.body); + } + return; + } + if (node.type === "CatchClause") { + pushScope(); + if (node.param && node.param.type === "Identifier") { + registerLocalBinding(node.param); + } + walkScope(node.body); + return; + } + if (node.type === "BlockStatement" && !isFunctionType(parent)) { + pushScope(); + walkScope(node); + return; + } + if (node.type === "Identifier") { + if (isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) { + if (currentScope[node.name]) { + rewriteId(node, parent, parentStack); + } + } + } + }, + leave(node, parent) { + parent && parentStack.pop(); + if (node.type === "BlockStatement" && !isFunctionType(parent) || isFunctionType(node)) { + popScope(); + } + } + }); +} + +const DEFINE_EMITS = "defineEmits"; +function processDefineEmits(ctx, node, declId) { + if (!isCallOf(node, DEFINE_EMITS)) { + return false; + } + if (ctx.hasDefineEmitCall) { + ctx.error(`duplicate ${DEFINE_EMITS}() call`, node); + } + ctx.hasDefineEmitCall = true; + ctx.emitsRuntimeDecl = node.arguments[0]; + if (node.typeParameters) { + if (ctx.emitsRuntimeDecl) { + ctx.error( + `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`, + node + ); + } + ctx.emitsTypeDecl = node.typeParameters.params[0]; + } + ctx.emitDecl = declId; + return true; +} +function genRuntimeEmits(ctx) { + let emitsDecl = ""; + if (ctx.emitsRuntimeDecl) { + emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim(); + } else if (ctx.emitsTypeDecl) { + const typeDeclaredEmits = extractRuntimeEmits(ctx); + emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``; + } + if (ctx.hasDefineModelCall) { + let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`; + emitsDecl = emitsDecl ? `/*#__PURE__*/${ctx.helper( + "mergeModels" + )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl; + } + return emitsDecl; +} +function extractRuntimeEmits(ctx) { + const emits = /* @__PURE__ */ new Set(); + const node = ctx.emitsTypeDecl; + if (node.type === "TSFunctionType") { + extractEventNames(ctx, node.parameters[0], emits); + return emits; + } + const { props, calls } = resolveTypeElements(ctx, node); + let hasProperty = false; + for (const key in props) { + emits.add(key); + hasProperty = true; + } + if (calls) { + if (hasProperty) { + ctx.error( + `defineEmits() type cannot mixed call signature and property syntax.`, + node + ); + } + for (const call of calls) { + extractEventNames(ctx, call.parameters[0], emits); + } + } + return emits; +} +function extractEventNames(ctx, eventName, emits) { + if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") { + const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation); + for (const type of types) { + if (type.type === "TSLiteralType") { + if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") { + emits.add(String(type.literal.value)); + } + } + } + } +} + +const DEFINE_EXPOSE = "defineExpose"; +function processDefineExpose(ctx, node) { + if (isCallOf(node, DEFINE_EXPOSE)) { + if (ctx.hasDefineExposeCall) { + ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node); + } + ctx.hasDefineExposeCall = true; + return true; + } + return false; +} + +const DEFINE_SLOTS = "defineSlots"; +function processDefineSlots(ctx, node, declId) { + if (!isCallOf(node, DEFINE_SLOTS)) { + return false; + } + if (ctx.hasDefineSlotsCall) { + ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node); + } + ctx.hasDefineSlotsCall = true; + if (node.arguments.length > 0) { + ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node); + } + if (declId) { + ctx.s.overwrite( + ctx.startOffset + node.start, + ctx.startOffset + node.end, + `${ctx.helper("useSlots")}()` + ); + } + return true; +} + +const DEFINE_OPTIONS = "defineOptions"; +function processDefineOptions(ctx, node) { + if (!isCallOf(node, DEFINE_OPTIONS)) { + return false; + } + if (ctx.hasDefineOptionsCall) { + ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node); + } + if (node.typeParameters) { + ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node); + } + if (!node.arguments[0]) + return true; + ctx.hasDefineOptionsCall = true; + ctx.optionsRuntimeDecl = unwrapTSNode(node.arguments[0]); + let propsOption = void 0; + let emitsOption = void 0; + let exposeOption = void 0; + let slotsOption = void 0; + if (ctx.optionsRuntimeDecl.type === "ObjectExpression") { + for (const prop of ctx.optionsRuntimeDecl.properties) { + if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") { + if (prop.key.name === "props") + propsOption = prop; + if (prop.key.name === "emits") + emitsOption = prop; + if (prop.key.name === "expose") + exposeOption = prop; + if (prop.key.name === "slots") + slotsOption = prop; + } + } + } + if (propsOption) { + ctx.error( + `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`, + propsOption + ); + } + if (emitsOption) { + ctx.error( + `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`, + emitsOption + ); + } + if (exposeOption) { + ctx.error( + `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`, + exposeOption + ); + } + if (slotsOption) { + ctx.error( + `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`, + slotsOption + ); + } + return true; +} + +function processAwait(ctx, node, needSemi, isStatement) { + const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start; + const startOffset = ctx.startOffset; + const argumentStr = ctx.descriptor.source.slice( + argumentStart + startOffset, + node.argument.end + startOffset + ); + const containsNestedAwait = /\bawait\b/.test(argumentStr); + ctx.s.overwrite( + node.start + startOffset, + argumentStart + startOffset, + `${needSemi ? `;` : ``}( + ([__temp,__restore] = ${ctx.helper( + `withAsyncContext` + )}(${containsNestedAwait ? `async ` : ``}() => ` + ); + ctx.s.appendLeft( + node.end + startOffset, + `)), + ${isStatement ? `` : `__temp = `}await __temp, + __restore()${isStatement ? `` : `, + __temp`} +)` + ); +} + +var __defProp$1 = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; +var __hasOwnProp$1 = Object.prototype.hasOwnProperty; +var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; +var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues$1 = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + if (__getOwnPropSymbols$1) + for (var prop of __getOwnPropSymbols$1(b)) { + if (__propIsEnum$1.call(b, prop)) + __defNormalProp$1(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +function compileScript(sfc, options) { + var _a; + if (!options.id) { + warnOnce$3( + `compileScript now requires passing the \`id\` option. +Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.` + ); + } + const ctx = new ScriptCompileContext(sfc, options); + const { script, scriptSetup, source, filename } = sfc; + const hoistStatic = options.hoistStatic !== false && !script; + const scopeId = options.id ? options.id.replace(/^data-v-/, "") : ""; + const scriptLang = script && script.lang; + const scriptSetupLang = scriptSetup && scriptSetup.lang; + if (!scriptSetup) { + if (!script) { + throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`); + } + return processNormalScript(ctx, scopeId); + } + if (script && scriptLang !== scriptSetupLang) { + throw new Error( + `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.` + ); + } + if (scriptSetupLang && !ctx.isJS && !ctx.isTS) { + return scriptSetup; + } + const scriptBindings = /* @__PURE__ */ Object.create(null); + const setupBindings = /* @__PURE__ */ Object.create(null); + let defaultExport; + let hasAwait = false; + let hasInlinedSsrRenderFn = false; + const startOffset = ctx.startOffset; + const endOffset = ctx.endOffset; + const scriptStartOffset = script && script.loc.start.offset; + const scriptEndOffset = script && script.loc.end.offset; + function hoistNode(node) { + const start = node.start + startOffset; + let end = node.end + startOffset; + if (node.trailingComments && node.trailingComments.length > 0) { + const lastCommentNode = node.trailingComments[node.trailingComments.length - 1]; + end = lastCommentNode.end + startOffset; + } + while (end <= source.length) { + if (!/\s/.test(source.charAt(end))) { + break; + } + end++; + } + ctx.s.move(start, end, 0); + } + function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) { + let isUsedInTemplate = needTemplateUsageCheck; + if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) { + isUsedInTemplate = isImportUsed(local, sfc); + } + ctx.userImports[local] = { + isType, + imported, + local, + source: source2, + isFromSetup, + isUsedInTemplate + }; + } + function checkInvalidScopeReference(node, method) { + if (!node) + return; + walkIdentifiers(node, (id) => { + const binding = setupBindings[id.name]; + if (binding && binding !== "literal-const") { + ctx.error( + `\`${method}()\` in <script setup> cannot reference locally declared variables because it will be hoisted outside of the setup() function. If your component options require initialization in the module scope, use a separate normal <script> to export the options instead.`, + id + ); + } + }); + } + const scriptAst = ctx.scriptAst; + const scriptSetupAst = ctx.scriptSetupAst; + if (scriptAst) { + for (const node of scriptAst.body) { + if (node.type === "ImportDeclaration") { + for (const specifier of node.specifiers) { + const imported = getImportedName(specifier); + registerUserImport( + node.source.value, + specifier.local.name, + imported, + node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type", + false, + !options.inlineTemplate + ); + } + } + } + } + for (const node of scriptSetupAst.body) { + if (node.type === "ImportDeclaration") { + hoistNode(node); + let removed = 0; + const removeSpecifier = (i) => { + const removeLeft = i > removed; + removed++; + const current = node.specifiers[i]; + const next = node.specifiers[i + 1]; + ctx.s.remove( + removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset, + next && !removeLeft ? next.start + startOffset : current.end + startOffset + ); + }; + for (let i = 0; i < node.specifiers.length; i++) { + const specifier = node.specifiers[i]; + const local = specifier.local.name; + const imported = getImportedName(specifier); + const source2 = node.source.value; + const existing = ctx.userImports[local]; + if (source2 === "vue" && (imported === DEFINE_PROPS || imported === DEFINE_EMITS || imported === DEFINE_EXPOSE)) { + warnOnce$3( + `\`${imported}\` is a compiler macro and no longer needs to be imported.` + ); + removeSpecifier(i); + } else if (existing) { + if (existing.source === source2 && existing.imported === imported) { + removeSpecifier(i); + } else { + ctx.error( + `different imports aliased to same local name.`, + specifier + ); + } + } else { + registerUserImport( + source2, + local, + imported, + node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type", + true, + !options.inlineTemplate + ); + } + } + if (node.specifiers.length && removed === node.specifiers.length) { + ctx.s.remove(node.start + startOffset, node.end + startOffset); + } + } + } + const vueImportAliases = {}; + for (const key in ctx.userImports) { + const { source: source2, imported, local } = ctx.userImports[key]; + if (source2 === "vue") + vueImportAliases[imported] = local; + } + if (script && scriptAst) { + for (const node of scriptAst.body) { + if (node.type === "ExportDefaultDeclaration") { + defaultExport = node; + let optionProperties; + if (defaultExport.declaration.type === "ObjectExpression") { + optionProperties = defaultExport.declaration.properties; + } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") { + optionProperties = defaultExport.declaration.arguments[0].properties; + } + if (optionProperties) { + for (const p of optionProperties) { + if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") { + ctx.hasDefaultExportName = true; + } + if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") { + ctx.hasDefaultExportRender = true; + } + } + } + const start = node.start + scriptStartOffset; + const end = node.declaration.start + scriptStartOffset; + ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `); + } else if (node.type === "ExportNamedDeclaration") { + const defaultSpecifier = node.specifiers.find( + (s) => s.exported.type === "Identifier" && s.exported.name === "default" + ); + if (defaultSpecifier) { + defaultExport = node; + if (node.specifiers.length > 1) { + ctx.s.remove( + defaultSpecifier.start + scriptStartOffset, + defaultSpecifier.end + scriptStartOffset + ); + } else { + ctx.s.remove( + node.start + scriptStartOffset, + node.end + scriptStartOffset + ); + } + if (node.source) { + ctx.s.prepend( + `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}' +` + ); + } else { + ctx.s.appendLeft( + scriptEndOffset, + ` +const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name} +` + ); + } + } + if (node.declaration) { + walkDeclaration( + "script", + node.declaration, + scriptBindings, + vueImportAliases, + hoistStatic + ); + } + } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) { + walkDeclaration( + "script", + node, + scriptBindings, + vueImportAliases, + hoistStatic + ); + } + } + if (scriptStartOffset > startOffset) { + if (!/\n$/.test(script.content.trim())) { + ctx.s.appendLeft(scriptEndOffset, ` +`); + } + ctx.s.move(scriptStartOffset, scriptEndOffset, 0); + } + } + for (const node of scriptSetupAst.body) { + if (node.type === "ExpressionStatement") { + const expr = unwrapTSNode(node.expression); + if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) { + ctx.s.remove(node.start + startOffset, node.end + startOffset); + } else if (processDefineExpose(ctx, expr)) { + const callee = expr.callee; + ctx.s.overwrite( + callee.start + startOffset, + callee.end + startOffset, + "__expose" + ); + } else { + processDefineModel(ctx, expr); + } + } + if (node.type === "VariableDeclaration" && !node.declare) { + const total = node.declarations.length; + let left = total; + let lastNonRemoved; + for (let i = 0; i < total; i++) { + const decl = node.declarations[i]; + const init = decl.init && unwrapTSNode(decl.init); + if (init) { + if (processDefineOptions(ctx, init)) { + ctx.error( + `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`, + node + ); + } + const isDefineProps = processDefineProps(ctx, init, decl.id); + const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id); + !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id)); + if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) { + if (left === 1) { + ctx.s.remove(node.start + startOffset, node.end + startOffset); + } else { + let start = decl.start + startOffset; + let end = decl.end + startOffset; + if (i === total - 1) { + start = node.declarations[lastNonRemoved].end + startOffset; + } else { + end = node.declarations[i + 1].start + startOffset; + } + ctx.s.remove(start, end); + left--; + } + } else if (isDefineEmits) { + ctx.s.overwrite( + startOffset + init.start, + startOffset + init.end, + "__emit" + ); + } else { + lastNonRemoved = i; + } + } + } + } + let isAllLiteral = false; + if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) { + isAllLiteral = walkDeclaration( + "scriptSetup", + node, + setupBindings, + vueImportAliases, + hoistStatic + ); + } + if (hoistStatic && isAllLiteral) { + hoistNode(node); + } + if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) { + const scope = [scriptSetupAst.body]; + walk$2(node, { + enter(child, parent) { + if (isFunctionType(child)) { + this.skip(); + } + if (child.type === "BlockStatement") { + scope.push(child.body); + } + if (child.type === "AwaitExpression") { + hasAwait = true; + const currentScope = scope[scope.length - 1]; + const needsSemi = currentScope.some((n, i) => { + return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start; + }); + processAwait( + ctx, + child, + needsSemi, + parent.type === "ExpressionStatement" + ); + } + }, + exit(node2) { + if (node2.type === "BlockStatement") + scope.pop(); + } + }); + } + if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") { + ctx.error( + `<script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, + node + ); + } + if (ctx.isTS) { + if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) { + if (node.type !== "TSEnumDeclaration") { + hoistNode(node); + } + } + } + } + if (ctx.propsDestructureDecl) { + transformDestructuredProps(ctx, vueImportAliases); + } + checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS); + checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS); + checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS); + checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS); + checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS); + for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) { + for (const node of runtimeOptionNodes) { + checkInvalidScopeReference(node, DEFINE_MODEL); + } + } + if (script) { + if (startOffset < scriptStartOffset) { + ctx.s.remove(0, startOffset); + ctx.s.remove(endOffset, scriptStartOffset); + ctx.s.remove(scriptEndOffset, source.length); + } else { + ctx.s.remove(0, scriptStartOffset); + ctx.s.remove(scriptEndOffset, startOffset); + ctx.s.remove(endOffset, source.length); + } + } else { + ctx.s.remove(0, startOffset); + ctx.s.remove(endOffset, source.length); + } + if (scriptAst) { + Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body)); + } + for (const [key, { isType, imported, source: source2 }] of Object.entries( + ctx.userImports + )) { + if (isType) + continue; + ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref"; + } + for (const key in scriptBindings) { + ctx.bindingMetadata[key] = scriptBindings[key]; + } + for (const key in setupBindings) { + ctx.bindingMetadata[key] = setupBindings[key]; + } + if (sfc.cssVars.length && // no need to do this when targeting SSR + !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) { + ctx.helperImports.add(CSS_VARS_HELPER); + ctx.helperImports.add("unref"); + ctx.s.prependLeft( + startOffset, + ` +${genCssVarsCode( + sfc.cssVars, + ctx.bindingMetadata, + scopeId, + !!options.isProd + )} +` + ); + } + let args = `__props`; + if (ctx.propsTypeDecl) { + args += `: any`; + } + if (ctx.propsDecl) { + if (ctx.propsDestructureRestId) { + ctx.s.overwrite( + startOffset + ctx.propsCall.start, + startOffset + ctx.propsCall.end, + `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify( + Object.keys(ctx.propsDestructuredBindings) + )})` + ); + ctx.s.overwrite( + startOffset + ctx.propsDestructureDecl.start, + startOffset + ctx.propsDestructureDecl.end, + ctx.propsDestructureRestId + ); + } else if (!ctx.propsDestructureDecl) { + ctx.s.overwrite( + startOffset + ctx.propsCall.start, + startOffset + ctx.propsCall.end, + "__props" + ); + } + } + if (hasAwait) { + const any = ctx.isTS ? `: any` : ``; + ctx.s.prependLeft(startOffset, ` +let __temp${any}, __restore${any} +`); + } + const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : []; + if (ctx.emitDecl) { + destructureElements.push(`emit: __emit`); + } + if (destructureElements.length) { + args += `, { ${destructureElements.join(", ")} }`; + } + let returned; + if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) { + const allBindings = __spreadValues$1(__spreadValues$1({}, scriptBindings), setupBindings); + for (const key in ctx.userImports) { + if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) { + allBindings[key] = true; + } + } + returned = `{ `; + for (const key in allBindings) { + if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) { + returned += `get ${key}() { return ${key} }, `; + } else if (ctx.bindingMetadata[key] === "setup-let") { + const setArg = key === "v" ? `_v` : `v`; + returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `; + } else { + returned += `${key}, `; + } + } + returned = returned.replace(/, $/, "") + ` }`; + } else { + if (sfc.template && !sfc.template.src) { + if (options.templateOptions && options.templateOptions.ssr) { + hasInlinedSsrRenderFn = true; + } + const { code, ast, preamble, tips, errors } = compileTemplate(__spreadProps(__spreadValues$1({ + filename, + ast: sfc.template.ast, + source: sfc.template.content, + inMap: sfc.template.map + }, options.templateOptions), { + id: scopeId, + scoped: sfc.styles.some((s) => s.scoped), + isProd: options.isProd, + ssrCssVars: sfc.cssVars, + compilerOptions: __spreadProps(__spreadValues$1({}, options.templateOptions && options.templateOptions.compilerOptions), { + inline: true, + isTS: ctx.isTS, + bindingMetadata: ctx.bindingMetadata + }) + })); + if (tips.length) { + tips.forEach(warnOnce$3); + } + const err = errors[0]; + if (typeof err === "string") { + throw new Error(err); + } else if (err) { + if (err.loc) { + err.message += ` + +` + sfc.filename + "\n" + generateCodeFrame( + source, + err.loc.start.offset, + err.loc.end.offset + ) + ` +`; + } + throw err; + } + if (preamble) { + ctx.s.prepend(preamble); + } + if (ast && ast.helpers.has(UNREF)) { + ctx.helperImports.delete("unref"); + } + returned = code; + } else { + returned = `() => {}`; + } + } + if (!options.inlineTemplate && true) { + ctx.s.appendRight( + endOffset, + ` +const __returned__ = ${returned} +Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true }) +return __returned__ +} + +` + ); + } else { + ctx.s.appendRight(endOffset, ` +return ${returned} +} + +`); + } + const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`; + let runtimeOptions = ``; + if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) { + const match = filename.match(/([^/\\]+)\.\w+$/); + if (match) { + runtimeOptions += ` + __name: '${match[1]}',`; + } + } + if (hasInlinedSsrRenderFn) { + runtimeOptions += ` + __ssrInlineRender: true,`; + } + const propsDecl = genRuntimeProps(ctx); + if (propsDecl) + runtimeOptions += ` + props: ${propsDecl},`; + const emitsDecl = genRuntimeEmits(ctx); + if (emitsDecl) + runtimeOptions += ` + emits: ${emitsDecl},`; + let definedOptions = ""; + if (ctx.optionsRuntimeDecl) { + definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim(); + } + const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose(); +`; + if (ctx.isTS) { + const def = (defaultExport ? ` + ...${normalScriptDefaultVar},` : ``) + (definedOptions ? ` + ...${definedOptions},` : ""); + ctx.s.prependLeft( + startOffset, + ` +${genDefaultAs} /*#__PURE__*/${ctx.helper( + `defineComponent` + )}({${def}${runtimeOptions} + ${hasAwait ? `async ` : ``}setup(${args}) { +${exposeCall}` + ); + ctx.s.appendRight(endOffset, `})`); + } else { + if (defaultExport || definedOptions) { + ctx.s.prependLeft( + startOffset, + ` +${genDefaultAs} /*#__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions} + ${hasAwait ? `async ` : ``}setup(${args}) { +${exposeCall}` + ); + ctx.s.appendRight(endOffset, `})`); + } else { + ctx.s.prependLeft( + startOffset, + ` +${genDefaultAs} {${runtimeOptions} + ${hasAwait ? `async ` : ``}setup(${args}) { +${exposeCall}` + ); + ctx.s.appendRight(endOffset, `}`); + } + } + if (ctx.helperImports.size > 0) { + ctx.s.prepend( + `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from 'vue' +` + ); + } + return __spreadProps(__spreadValues$1({}, scriptSetup), { + bindings: ctx.bindingMetadata, + imports: ctx.userImports, + content: ctx.s.toString(), + map: options.sourceMap !== false ? ctx.s.generateMap({ + source: filename, + hires: true, + includeContent: true + }) : void 0, + scriptAst: scriptAst == null ? void 0 : scriptAst.body, + scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body, + deps: ctx.deps ? [...ctx.deps] : void 0 + }); +} +function registerBinding(bindings, node, type) { + bindings[node.name] = type; +} +function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic) { + let isAllLiteral = false; + if (node.type === "VariableDeclaration") { + const isConst = node.kind === "const"; + isAllLiteral = isConst && node.declarations.every( + (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init) + ); + for (const { id, init: _init } of node.declarations) { + const init = _init && unwrapTSNode(_init); + const isDefineCall = !!(isConst && isCallOf( + init, + (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS + )); + if (id.type === "Identifier") { + let bindingType; + const userReactiveBinding = userImportAliases["reactive"]; + if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) { + bindingType = "literal-const"; + } else if (isCallOf(init, userReactiveBinding)) { + bindingType = isConst ? "setup-reactive-const" : "setup-let"; + } else if ( + // if a declaration is a const literal, we can mark it so that + // the generated render fn code doesn't need to unref() it + isDefineCall || isConst && canNeverBeRef(init, userReactiveBinding) + ) { + bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const"; + } else if (isConst) { + if (isCallOf( + init, + (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === DEFINE_MODEL + )) { + bindingType = "setup-ref"; + } else { + bindingType = "setup-maybe-ref"; + } + } else { + bindingType = "setup-let"; + } + registerBinding(bindings, id, bindingType); + } else { + if (isCallOf(init, DEFINE_PROPS)) { + continue; + } + if (id.type === "ObjectPattern") { + walkObjectPattern(id, bindings, isConst, isDefineCall); + } else if (id.type === "ArrayPattern") { + walkArrayPattern(id, bindings, isConst, isDefineCall); + } + } + } + } else if (node.type === "TSEnumDeclaration") { + isAllLiteral = node.members.every( + (member) => !member.initializer || isStaticNode(member.initializer) + ); + bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const"; + } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") { + bindings[node.id.name] = "setup-const"; + } + return isAllLiteral; +} +function walkObjectPattern(node, bindings, isConst, isDefineCall = false) { + for (const p of node.properties) { + if (p.type === "ObjectProperty") { + if (p.key.type === "Identifier" && p.key === p.value) { + const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let"; + registerBinding(bindings, p.key, type); + } else { + walkPattern(p.value, bindings, isConst, isDefineCall); + } + } else { + const type = isConst ? "setup-const" : "setup-let"; + registerBinding(bindings, p.argument, type); + } + } +} +function walkArrayPattern(node, bindings, isConst, isDefineCall = false) { + for (const e of node.elements) { + e && walkPattern(e, bindings, isConst, isDefineCall); + } +} +function walkPattern(node, bindings, isConst, isDefineCall = false) { + if (node.type === "Identifier") { + const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let"; + registerBinding(bindings, node, type); + } else if (node.type === "RestElement") { + const type = isConst ? "setup-const" : "setup-let"; + registerBinding(bindings, node.argument, type); + } else if (node.type === "ObjectPattern") { + walkObjectPattern(node, bindings, isConst); + } else if (node.type === "ArrayPattern") { + walkArrayPattern(node, bindings, isConst); + } else if (node.type === "AssignmentPattern") { + if (node.left.type === "Identifier") { + const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let"; + registerBinding(bindings, node.left, type); + } else { + walkPattern(node.left, bindings, isConst); + } + } +} +function canNeverBeRef(node, userReactiveImport) { + if (isCallOf(node, userReactiveImport)) { + return true; + } + switch (node.type) { + case "UnaryExpression": + case "BinaryExpression": + case "ArrayExpression": + case "ObjectExpression": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "UpdateExpression": + case "ClassExpression": + case "TaggedTemplateExpression": + return true; + case "SequenceExpression": + return canNeverBeRef( + node.expressions[node.expressions.length - 1], + userReactiveImport + ); + default: + if (isLiteralNode(node)) { + return true; + } + return false; + } +} +function isStaticNode(node) { + node = unwrapTSNode(node); + switch (node.type) { + case "UnaryExpression": + return isStaticNode(node.argument); + case "LogicalExpression": + case "BinaryExpression": + return isStaticNode(node.left) && isStaticNode(node.right); + case "ConditionalExpression": { + return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate); + } + case "SequenceExpression": + case "TemplateLiteral": + return node.expressions.every((expr) => isStaticNode(expr)); + case "ParenthesizedExpression": + return isStaticNode(node.expression); + case "StringLiteral": + case "NumericLiteral": + case "BooleanLiteral": + case "NullLiteral": + case "BigIntLiteral": + return true; + } + return false; +} + +var __defProp = Object.defineProperty; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +const version = "3.4.21"; +const parseCache = parseCache$1; +const errorMessages = __spreadValues(__spreadValues({}, errorMessages$1), DOMErrorMessages); +const walk = walk$2; +const shouldTransformRef = () => false; + +export { MagicString, parse_1$1 as babelParse, compileScript, compileStyle, compileStyleAsync, compileTemplate, errorMessages, extractIdentifiers$1 as extractIdentifiers, extractRuntimeEmits, extractRuntimeProps, generateCodeFrame, inferRuntimeType, invalidateTypeCache, isInDestructureAssignment, isStaticProperty, parse$7 as parse, parseCache, registerTS, resolveTypeElements, rewriteDefault, rewriteDefaultAST, shouldTransformRef, version, walk, walkIdentifiers }; diff --git a/game/entry.js b/game/entry.js index beeeb229c..6678ac740 100644 --- a/game/entry.js +++ b/game/entry.js @@ -4,6 +4,7 @@ import { userAgent } from "../noname/util/index.js"; const coreAndVersion = get.coreInfo(); const core = coreAndVersion[0], version = coreAndVersion[1]; +//@todo: 77 -> 80 if (core === 'chrome' && !isNaN(version) && version < 77) { const tip = '检测到您的浏览器内核版本小于77,请及时升级浏览器或手机webview内核!'; console.warn(tip); diff --git a/game/game.js b/game/game.js index 036a3096d..f071cb26e 100644 --- a/game/game.js +++ b/game/game.js @@ -166,6 +166,7 @@ new Promise(resolve => { // 使用ts compiler对ts文件进行编译 const result = ts.transpile(code, { module: ts.ModuleKind.CommonJS, + //@todo: ES2019 -> ES2020 target: ts.ScriptTarget.ES2019, inlineSourceMap: true, resolveJsonModule: true, @@ -203,15 +204,23 @@ new Promise(resolve => { }); try { const registration_1 = await navigator.serviceWorker.register(`${scope}service-worker.js`, { + type: 'module', updateViaCache: "all", scope, }); // 初次加载worker,需要重新启动一次 if (!findServiceWorker) location.reload(); + // 接收消息,暂时没用到 navigator.serviceWorker.addEventListener('message', e => { console.log(e); }); - registration_1.update().catch(console.error); + registration_1.update().catch(e => console.error('worker update失败', e)); + if (!sessionStorage.getItem('canUseTs')) { + await import('./canUse.ts').then(({ text }) => console.log(text)).catch(() => { + sessionStorage.setItem('canUseTs', '1'); + location.reload(); + }); + } } catch (e_1) { console.log('serviceWorker加载失败: ', e_1); } diff --git a/game/jszip.js b/game/jszip.js index 5d6af1655..84a63d2e3 100644 --- a/game/jszip.js +++ b/game/jszip.js @@ -1,3 +1,4 @@ +// @ts-nocheck /*! JSZip - A Javascript class for generating and reading zip files @@ -9,2418 +10,2493 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/master/LICENSE */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSZip=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ -'use strict'; -// private property -var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - - -// public method for encoding -exports.encode = function(input, utf8) { - var output = ""; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0; - - while (i < input.length) { - - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; - - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } - else if (isNaN(chr3)) { - enc4 = 64; - } - - output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); - - } - - return output; -}; - -// public method for decoding -exports.decode = function(input, utf8) { - var output = ""; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; - - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - - while (i < input.length) { - - enc1 = _keyStr.indexOf(input.charAt(i++)); - enc2 = _keyStr.indexOf(input.charAt(i++)); - enc3 = _keyStr.indexOf(input.charAt(i++)); - enc4 = _keyStr.indexOf(input.charAt(i++)); - - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; - - output = output + String.fromCharCode(chr1); - - if (enc3 != 64) { - output = output + String.fromCharCode(chr2); - } - if (enc4 != 64) { - output = output + String.fromCharCode(chr3); - } - - } - - return output; - -}; - -},{}],2:[function(_dereq_,module,exports){ -'use strict'; -function CompressedObject() { - this.compressedSize = 0; - this.uncompressedSize = 0; - this.crc32 = 0; - this.compressionMethod = null; - this.compressedContent = null; -} - -CompressedObject.prototype = { - /** - * Return the decompressed content in an unspecified format. - * The format will depend on the decompressor. - * @return {Object} the decompressed content. - */ - getContent: function() { - return null; // see implementation - }, - /** - * Return the compressed content in an unspecified format. - * The format will depend on the compressed conten source. - * @return {Object} the compressed content. - */ - getCompressedContent: function() { - return null; // see implementation - } -}; -module.exports = CompressedObject; - -},{}],3:[function(_dereq_,module,exports){ -'use strict'; -exports.STORE = { - magic: "\x00\x00", - compress: function(content, compressionOptions) { - return content; // no compression - }, - uncompress: function(content) { - return content; // no compression - }, - compressInputType: null, - uncompressInputType: null -}; -exports.DEFLATE = _dereq_('./flate'); - -},{"./flate":8}],4:[function(_dereq_,module,exports){ -'use strict'; - -var utils = _dereq_('./utils'); - -var table = [ - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, - 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, - 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, - 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, - 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, - 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, - 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, - 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, - 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, - 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, - 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, - 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, - 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, - 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, - 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, - 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, - 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, - 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, - 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, - 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, - 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, - 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, - 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, - 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, - 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, - 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, - 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D -]; - /** - * - * Javascript crc32 - * http://www.webtoolkit.info/ - * + * @type { typeof import('@types/jszip') } */ -module.exports = function crc32(input, crc) { - if (typeof input === "undefined" || !input.length) { - return 0; - } +(function (f) { if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f() } else if (typeof define === "function" && define.amd) { define([], f) } else { var g; if (typeof window !== "undefined") { g = window } else if (typeof global !== "undefined") { g = global } else if (typeof self !== "undefined") { g = self } else { g = this } g.JSZip = f() } })(function () { + var define, module, exports; return (function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof require == "function" && require; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw f.code = "MODULE_NOT_FOUND", f } var l = n[o] = { exports: {} }; t[o][0].call(l.exports, function (e) { var n = t[o][1][e]; return s(n ? n : e) }, l, l.exports, e, t, n, r) } return n[o].exports } var i = typeof require == "function" && require; for (var o = 0; o < r.length; o++)s(r[o]); return s })({ + 1: [function (require, module, exports) { + 'use strict'; + var DataReader = require('./dataReader'); - var isArray = utils.getTypeOf(input) !== "string"; + function ArrayReader(data) { + if (data) { + this.data = data; + this.length = this.data.length; + this.index = 0; + this.zero = 0; - if (typeof(crc) == "undefined") { - crc = 0; - } - var x = 0; - var y = 0; - var b = 0; - - crc = crc ^ (-1); - for (var i = 0, iTop = input.length; i < iTop; i++) { - b = isArray ? input[i] : input.charCodeAt(i); - y = (crc ^ b) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -}; -// vim: set shiftwidth=4 softtabstop=4: - -},{"./utils":21}],5:[function(_dereq_,module,exports){ -'use strict'; -var utils = _dereq_('./utils'); - -function DataReader(data) { - this.data = null; // type : see implementation - this.length = 0; - this.index = 0; -} -DataReader.prototype = { - /** - * Check that the offset will not go too far. - * @param {string} offset the additional offset to check. - * @throws {Error} an Error if the offset is out of bounds. - */ - checkOffset: function(offset) { - this.checkIndex(this.index + offset); - }, - /** - * Check that the specifed index will not be too far. - * @param {string} newIndex the index to check. - * @throws {Error} an Error if the index is out of bounds. - */ - checkIndex: function(newIndex) { - if (this.length < newIndex || newIndex < 0) { - throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?"); + for (var i = 0; i < this.data.length; i++) { + data[i] = data[i] & 0xFF; + } } - }, - /** - * Change the index. - * @param {number} newIndex The new index. - * @throws {Error} if the new index is out of the data. - */ - setIndex: function(newIndex) { - this.checkIndex(newIndex); - this.index = newIndex; - }, - /** - * Skip the next n bytes. - * @param {number} n the number of bytes to skip. - * @throws {Error} if the new index is out of the data. - */ - skip: function(n) { - this.setIndex(this.index + n); - }, - /** - * Get the byte at the specified index. - * @param {number} i the index to use. - * @return {number} a byte. - */ - byteAt: function(i) { - // see implementations - }, - /** - * Get the next number with a given byte size. - * @param {number} size the number of bytes to read. - * @return {number} the corresponding number. - */ - readInt: function(size) { - var result = 0, - i; + } + ArrayReader.prototype = new DataReader(); + /** + * @see DataReader.byteAt + */ + ArrayReader.prototype.byteAt = function (i) { + return this.data[this.zero + i]; + }; + /** + * @see DataReader.lastIndexOfSignature + */ + ArrayReader.prototype.lastIndexOfSignature = function (sig) { + var sig0 = sig.charCodeAt(0), + sig1 = sig.charCodeAt(1), + sig2 = sig.charCodeAt(2), + sig3 = sig.charCodeAt(3); + for (var i = this.length - 4; i >= 0; --i) { + if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { + return i - this.zero; + } + } + + return -1; + }; + /** + * @see DataReader.readData + */ + ArrayReader.prototype.readData = function (size) { this.checkOffset(size); - for (i = this.index + size - 1; i >= this.index; i--) { - result = (result << 8) + this.byteAt(i); + if (size === 0) { + return []; } + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); this.index += size; return result; - }, - /** - * Get the next string with a given byte size. - * @param {number} size the number of bytes to read. - * @return {string} the corresponding string. - */ - readString: function(size) { - return utils.transformTo("string", this.readData(size)); - }, - /** - * Get raw data without conversion, <size> bytes. - * @param {number} size the number of bytes to read. - * @return {Object} the raw data, implementation specific. - */ - readData: function(size) { - // see implementations - }, - /** - * Find the last occurence of a zip signature (4 bytes). - * @param {string} sig the signature to find. - * @return {number} the index of the last occurence, -1 if not found. - */ - lastIndexOfSignature: function(sig) { - // see implementations - }, - /** - * Get the next date. - * @return {Date} the date. - */ - readDate: function() { - var dostime = this.readInt(4); - return new Date( - ((dostime >> 25) & 0x7f) + 1980, // year - ((dostime >> 21) & 0x0f) - 1, // month - (dostime >> 16) & 0x1f, // day - (dostime >> 11) & 0x1f, // hour - (dostime >> 5) & 0x3f, // minute - (dostime & 0x1f) << 1); // second - } -}; -module.exports = DataReader; + }; + module.exports = ArrayReader; -},{"./utils":21}],6:[function(_dereq_,module,exports){ -'use strict'; -exports.base64 = false; -exports.binary = false; -exports.dir = false; -exports.createFolders = false; -exports.date = null; -exports.compression = null; -exports.compressionOptions = null; -exports.comment = null; -exports.unixPermissions = null; -exports.dosPermissions = null; - -},{}],7:[function(_dereq_,module,exports){ -'use strict'; -var utils = _dereq_('./utils'); - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.string2binary = function(str) { - return utils.string2binary(str); -}; - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.string2Uint8Array = function(str) { - return utils.transformTo("uint8array", str); -}; - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.uint8Array2String = function(array) { - return utils.transformTo("string", array); -}; - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.string2Blob = function(str) { - var buffer = utils.transformTo("arraybuffer", str); - return utils.arrayBuffer2Blob(buffer); -}; - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.arrayBuffer2Blob = function(buffer) { - return utils.arrayBuffer2Blob(buffer); -}; - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.transformTo = function(outputType, input) { - return utils.transformTo(outputType, input); -}; - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.getTypeOf = function(input) { - return utils.getTypeOf(input); -}; - -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.checkSupport = function(type) { - return utils.checkSupport(type); -}; - -/** - * @deprecated - * This value will be removed in a future version without replacement. - */ -exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS; - -/** - * @deprecated - * This value will be removed in a future version without replacement. - */ -exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS; + }, { "./dataReader": 6 }], 2: [function (require, module, exports) { + 'use strict'; + // private property + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.pretty = function(str) { - return utils.pretty(str); -}; + // public method for encoding + exports.encode = function (input, utf8) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.findCompression = function(compressionMethod) { - return utils.findCompression(compressionMethod); -}; + while (i < input.length) { -/** - * @deprecated - * This function will be removed in a future version without replacement. - */ -exports.isRegExp = function (object) { - return utils.isRegExp(object); -}; + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; -},{"./utils":21}],8:[function(_dereq_,module,exports){ -'use strict'; -var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } + else if (isNaN(chr3)) { + enc4 = 64; + } -var pako = _dereq_("pako"); -exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; -exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; + output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); -exports.magic = "\x08\x00"; -exports.compress = function(input, compressionOptions) { - return pako.deflateRaw(input, { - level : compressionOptions.level || -1 // default compression - }); -}; -exports.uncompress = function(input) { - return pako.inflateRaw(input); -}; - -},{"pako":24}],9:[function(_dereq_,module,exports){ -'use strict'; - -var base64 = _dereq_('./base64'); - -/** -Usage: - zip = new JSZip(); - zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing"); - zip.folder("images").file("smile.gif", base64Data, {base64: true}); - zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")}); - zip.remove("tempfile"); - - base64zip = zip.generate(); - -**/ - -/** - * Representation a of zip file in js - * @constructor - * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional). - * @param {Object=} options the options for creating this objects (optional). - */ -function JSZip(data, options) { - // if this constructor is used without `new`, it adds `new` before itself: - if(!(this instanceof JSZip)) return new JSZip(data, options); - - // object containing the files : - // { - // "folder/" : {...}, - // "folder/data.txt" : {...} - // } - this.files = {}; - - this.comment = null; - - // Where we are in the hierarchy - this.root = ""; - if (data) { - this.load(data, options); - } - this.clone = function() { - var newObj = new JSZip(); - for (var i in this) { - if (typeof this[i] !== "function") { - newObj[i] = this[i]; - } } - return newObj; - }; -} -JSZip.prototype = _dereq_('./object'); -JSZip.prototype.load = _dereq_('./load'); -JSZip.support = _dereq_('./support'); -JSZip.defaults = _dereq_('./defaults'); -/** - * @deprecated - * This namespace will be removed in a future version without replacement. - */ -JSZip.utils = _dereq_('./deprecatedPublicUtils'); + return output; + }; -JSZip.base64 = { - /** - * @deprecated - * This method will be removed in a future version without replacement. - */ - encode : function(input) { - return base64.encode(input); - }, - /** - * @deprecated - * This method will be removed in a future version without replacement. - */ - decode : function(input) { - return base64.decode(input); - } -}; -JSZip.compressions = _dereq_('./compressions'); -module.exports = JSZip; + // public method for decoding + exports.decode = function (input, utf8) { + var output = ""; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; -},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){ -'use strict'; -var base64 = _dereq_('./base64'); -var ZipEntries = _dereq_('./zipEntries'); -module.exports = function(data, options) { - var files, zipEntries, i, input; - options = options || {}; - if (options.base64) { - data = base64.decode(data); - } + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - zipEntries = new ZipEntries(data, options); - files = zipEntries.files; - for (i = 0; i < files.length; i++) { - input = files[i]; - this.file(input.fileName, input.decompressed, { + while (i < input.length) { + + enc1 = _keyStr.indexOf(input.charAt(i++)); + enc2 = _keyStr.indexOf(input.charAt(i++)); + enc3 = _keyStr.indexOf(input.charAt(i++)); + enc4 = _keyStr.indexOf(input.charAt(i++)); + + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; + + output = output + String.fromCharCode(chr1); + + if (enc3 != 64) { + output = output + String.fromCharCode(chr2); + } + if (enc4 != 64) { + output = output + String.fromCharCode(chr3); + } + + } + + return output; + + }; + + }, {}], 3: [function (require, module, exports) { + 'use strict'; + function CompressedObject() { + this.compressedSize = 0; + this.uncompressedSize = 0; + this.crc32 = 0; + this.compressionMethod = null; + this.compressedContent = null; + } + + CompressedObject.prototype = { + /** + * Return the decompressed content in an unspecified format. + * The format will depend on the decompressor. + * @return {Object} the decompressed content. + */ + getContent: function () { + return null; // see implementation + }, + /** + * Return the compressed content in an unspecified format. + * The format will depend on the compressed conten source. + * @return {Object} the compressed content. + */ + getCompressedContent: function () { + return null; // see implementation + } + }; + module.exports = CompressedObject; + + }, {}], 4: [function (require, module, exports) { + 'use strict'; + exports.STORE = { + magic: "\x00\x00", + compress: function (content, compressionOptions) { + return content; // no compression + }, + uncompress: function (content) { + return content; // no compression + }, + compressInputType: null, + uncompressInputType: null + }; + exports.DEFLATE = require('./flate'); + + }, { "./flate": 9 }], 5: [function (require, module, exports) { + 'use strict'; + + var utils = require('./utils'); + + var table = [ + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, + 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, + 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, + 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, + 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, + 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, + 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, + 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, + 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, + 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, + 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, + 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, + 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, + 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, + 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, + 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, + 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, + 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, + 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, + 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, + 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + ]; + + /** + * + * Javascript crc32 + * http://www.webtoolkit.info/ + * + */ + module.exports = function crc32(input, crc) { + if (typeof input === "undefined" || !input.length) { + return 0; + } + + var isArray = utils.getTypeOf(input) !== "string"; + + if (typeof (crc) == "undefined") { + crc = 0; + } + var x = 0; + var y = 0; + var b = 0; + + crc = crc ^ (-1); + for (var i = 0, iTop = input.length; i < iTop; i++) { + b = isArray ? input[i] : input.charCodeAt(i); + y = (crc ^ b) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); + }; + // vim: set shiftwidth=4 softtabstop=4: + + }, { "./utils": 22 }], 6: [function (require, module, exports) { + 'use strict'; + var utils = require('./utils'); + + function DataReader(data) { + this.data = null; // type : see implementation + this.length = 0; + this.index = 0; + this.zero = 0; + } + DataReader.prototype = { + /** + * Check that the offset will not go too far. + * @param {string} offset the additional offset to check. + * @throws {Error} an Error if the offset is out of bounds. + */ + checkOffset: function (offset) { + this.checkIndex(this.index + offset); + }, + /** + * Check that the specifed index will not be too far. + * @param {string} newIndex the index to check. + * @throws {Error} an Error if the index is out of bounds. + */ + checkIndex: function (newIndex) { + if (this.length < this.zero + newIndex || newIndex < 0) { + throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?"); + } + }, + /** + * Change the index. + * @param {number} newIndex The new index. + * @throws {Error} if the new index is out of the data. + */ + setIndex: function (newIndex) { + this.checkIndex(newIndex); + this.index = newIndex; + }, + /** + * Skip the next n bytes. + * @param {number} n the number of bytes to skip. + * @throws {Error} if the new index is out of the data. + */ + skip: function (n) { + this.setIndex(this.index + n); + }, + /** + * Get the byte at the specified index. + * @param {number} i the index to use. + * @return {number} a byte. + */ + byteAt: function (i) { + // see implementations + }, + /** + * Get the next number with a given byte size. + * @param {number} size the number of bytes to read. + * @return {number} the corresponding number. + */ + readInt: function (size) { + var result = 0, + i; + this.checkOffset(size); + for (i = this.index + size - 1; i >= this.index; i--) { + result = (result << 8) + this.byteAt(i); + } + this.index += size; + return result; + }, + /** + * Get the next string with a given byte size. + * @param {number} size the number of bytes to read. + * @return {string} the corresponding string. + */ + readString: function (size) { + return utils.transformTo("string", this.readData(size)); + }, + /** + * Get raw data without conversion, <size> bytes. + * @param {number} size the number of bytes to read. + * @return {Object} the raw data, implementation specific. + */ + readData: function (size) { + // see implementations + }, + /** + * Find the last occurence of a zip signature (4 bytes). + * @param {string} sig the signature to find. + * @return {number} the index of the last occurence, -1 if not found. + */ + lastIndexOfSignature: function (sig) { + // see implementations + }, + /** + * Get the next date. + * @return {Date} the date. + */ + readDate: function () { + var dostime = this.readInt(4); + return new Date( + ((dostime >> 25) & 0x7f) + 1980, // year + ((dostime >> 21) & 0x0f) - 1, // month + (dostime >> 16) & 0x1f, // day + (dostime >> 11) & 0x1f, // hour + (dostime >> 5) & 0x3f, // minute + (dostime & 0x1f) << 1); // second + } + }; + module.exports = DataReader; + + }, { "./utils": 22 }], 7: [function (require, module, exports) { + 'use strict'; + exports.base64 = false; + exports.binary = false; + exports.dir = false; + exports.createFolders = false; + exports.date = null; + exports.compression = null; + exports.compressionOptions = null; + exports.comment = null; + exports.unixPermissions = null; + exports.dosPermissions = null; + + }, {}], 8: [function (require, module, exports) { + 'use strict'; + var utils = require('./utils'); + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.string2binary = function (str) { + return utils.string2binary(str); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.string2Uint8Array = function (str) { + return utils.transformTo("uint8array", str); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.uint8Array2String = function (array) { + return utils.transformTo("string", array); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.string2Blob = function (str) { + var buffer = utils.transformTo("arraybuffer", str); + return utils.arrayBuffer2Blob(buffer); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.arrayBuffer2Blob = function (buffer) { + return utils.arrayBuffer2Blob(buffer); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.transformTo = function (outputType, input) { + return utils.transformTo(outputType, input); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.getTypeOf = function (input) { + return utils.getTypeOf(input); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.checkSupport = function (type) { + return utils.checkSupport(type); + }; + + /** + * @deprecated + * This value will be removed in a future version without replacement. + */ + exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS; + + /** + * @deprecated + * This value will be removed in a future version without replacement. + */ + exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS; + + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.pretty = function (str) { + return utils.pretty(str); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.findCompression = function (compressionMethod) { + return utils.findCompression(compressionMethod); + }; + + /** + * @deprecated + * This function will be removed in a future version without replacement. + */ + exports.isRegExp = function (object) { + return utils.isRegExp(object); + }; + + + }, { "./utils": 22 }], 9: [function (require, module, exports) { + 'use strict'; + var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); + + var pako = require("pako"); + exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; + exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array"; + + exports.magic = "\x08\x00"; + exports.compress = function (input, compressionOptions) { + return pako.deflateRaw(input, { + level: compressionOptions.level || -1 // default compression + }); + }; + exports.uncompress = function (input) { + return pako.inflateRaw(input); + }; + + }, { "pako": 25 }], 10: [function (require, module, exports) { + 'use strict'; + + var base64 = require('./base64'); + + /** + Usage: + zip = new JSZip(); + zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing"); + zip.folder("images").file("smile.gif", base64Data, {base64: true}); + zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")}); + zip.remove("tempfile"); + + base64zip = zip.generate(); + + **/ + + /** + * Representation a of zip file in js + * @constructor + * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional). + * @param {Object=} options the options for creating this objects (optional). + */ + function JSZip(data, options) { + // if this constructor is used without `new`, it adds `new` before itself: + if (!(this instanceof JSZip)) return new JSZip(data, options); + + // object containing the files : + // { + // "folder/" : {...}, + // "folder/data.txt" : {...} + // } + // NOTE: we use a null prototype because we do not + // want filenames like "toString" coming from a zip file + // to overwrite methods and attributes in a normal Object. + this.files = Object.create(null); + + this.comment = null; + + // Where we are in the hierarchy + this.root = ""; + if (data) { + this.load(data, options); + } + this.clone = function () { + var newObj = new JSZip(); + for (var i in this) { + if (typeof this[i] !== "function") { + newObj[i] = this[i]; + } + } + return newObj; + }; + } + JSZip.prototype = require('./object'); + JSZip.prototype.load = require('./load'); + JSZip.support = require('./support'); + JSZip.defaults = require('./defaults'); + + /** + * @deprecated + * This namespace will be removed in a future version without replacement. + */ + JSZip.utils = require('./deprecatedPublicUtils'); + + JSZip.base64 = { + /** + * @deprecated + * This method will be removed in a future version without replacement. + */ + encode: function (input) { + return base64.encode(input); + }, + /** + * @deprecated + * This method will be removed in a future version without replacement. + */ + decode: function (input) { + return base64.decode(input); + } + }; + JSZip.compressions = require('./compressions'); + module.exports = JSZip; + + }, { "./base64": 2, "./compressions": 4, "./defaults": 7, "./deprecatedPublicUtils": 8, "./load": 11, "./object": 14, "./support": 18 }], 11: [function (require, module, exports) { + 'use strict'; + var base64 = require('./base64'); + var utf8 = require('./utf8'); + var utils = require('./utils'); + var ZipEntries = require('./zipEntries'); + module.exports = function (data, options) { + var files, zipEntries, i, input; + options = utils.extend(options || {}, { + base64: false, + checkCRC32: false, + optimizedBinaryString: false, + createFolders: false, + decodeFileName: utf8.utf8decode + }); + if (options.base64) { + data = base64.decode(data); + } + + zipEntries = new ZipEntries(data, options); + files = zipEntries.files; + for (i = 0; i < files.length; i++) { + input = files[i]; + this.file(input.fileNameStr, input.decompressed, { binary: true, optimizedBinaryString: true, date: input.date, dir: input.dir, - comment : input.fileComment.length ? input.fileComment : null, - unixPermissions : input.unixPermissions, - dosPermissions : input.dosPermissions, + comment: input.fileCommentStr.length ? input.fileCommentStr : null, + unixPermissions: input.unixPermissions, + dosPermissions: input.dosPermissions, createFolders: options.createFolders - }); - } - if (zipEntries.zipComment.length) { - this.comment = zipEntries.zipComment; - } + }); + } + if (zipEntries.zipComment.length) { + this.comment = zipEntries.zipComment; + } - return this; -}; + return this; + }; -},{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; -module.exports = function(data, encoding){ - return new Buffer(data, encoding); -}; -module.exports.test = function(b){ - return Buffer.isBuffer(b); -}; + }, { "./base64": 2, "./utf8": 21, "./utils": 22, "./zipEntries": 23 }], 12: [function (require, module, exports) { + (function (Buffer) { + 'use strict'; + module.exports = function (data, encoding) { + return new Buffer(data, encoding); + }; + module.exports.test = function (b) { + return Buffer.isBuffer(b); + }; -}).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined)) -},{}],12:[function(_dereq_,module,exports){ -'use strict'; -var Uint8ArrayReader = _dereq_('./uint8ArrayReader'); + }).call(this, (typeof Buffer !== "undefined" ? Buffer : undefined)) + }, {}], 13: [function (require, module, exports) { + 'use strict'; + var Uint8ArrayReader = require('./uint8ArrayReader'); -function NodeBufferReader(data) { - this.data = data; - this.length = this.data.length; - this.index = 0; -} -NodeBufferReader.prototype = new Uint8ArrayReader(); + function NodeBufferReader(data) { + this.data = data; + this.length = this.data.length; + this.index = 0; + this.zero = 0; + } + NodeBufferReader.prototype = new Uint8ArrayReader(); -/** - * @see DataReader.readData - */ -NodeBufferReader.prototype.readData = function(size) { - this.checkOffset(size); - var result = this.data.slice(this.index, this.index + size); - this.index += size; - return result; -}; -module.exports = NodeBufferReader; + /** + * @see DataReader.readData + */ + NodeBufferReader.prototype.readData = function (size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = NodeBufferReader; -},{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){ -'use strict'; -var support = _dereq_('./support'); -var utils = _dereq_('./utils'); -var crc32 = _dereq_('./crc32'); -var signature = _dereq_('./signature'); -var defaults = _dereq_('./defaults'); -var base64 = _dereq_('./base64'); -var compressions = _dereq_('./compressions'); -var CompressedObject = _dereq_('./compressedObject'); -var nodeBuffer = _dereq_('./nodeBuffer'); -var utf8 = _dereq_('./utf8'); -var StringWriter = _dereq_('./stringWriter'); -var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter'); + }, { "./uint8ArrayReader": 19 }], 14: [function (require, module, exports) { + 'use strict'; + var support = require('./support'); + var utils = require('./utils'); + var crc32 = require('./crc32'); + var signature = require('./signature'); + var defaults = require('./defaults'); + var base64 = require('./base64'); + var compressions = require('./compressions'); + var CompressedObject = require('./compressedObject'); + var nodeBuffer = require('./nodeBuffer'); + var utf8 = require('./utf8'); + var StringWriter = require('./stringWriter'); + var Uint8ArrayWriter = require('./uint8ArrayWriter'); -/** - * Returns the raw data of a ZipObject, decompress the content if necessary. - * @param {ZipObject} file the file to use. - * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. - */ -var getRawData = function(file) { - if (file._data instanceof CompressedObject) { - file._data = file._data.getContent(); - file.options.binary = true; - file.options.base64 = false; + /** + * Returns the raw data of a ZipObject, decompress the content if necessary. + * @param {ZipObject} file the file to use. + * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. + */ + var getRawData = function (file) { + if (file._data instanceof CompressedObject) { + file._data = file._data.getContent(); + file.options.binary = true; + file.options.base64 = false; - if (utils.getTypeOf(file._data) === "uint8array") { + if (utils.getTypeOf(file._data) === "uint8array") { var copy = file._data; // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file). file._data = new Uint8Array(copy.length); // with an empty Uint8Array, Opera fails with a "Offset larger than array size" if (copy.length !== 0) { - file._data.set(copy, 0); + file._data.set(copy, 0); } + } } - } - return file._data; -}; + return file._data; + }; -/** - * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it. - * @param {ZipObject} file the file to use. - * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. - */ -var getBinaryData = function(file) { - var result = getRawData(file), - type = utils.getTypeOf(result); - if (type === "string") { - if (!file.options.binary) { + /** + * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it. + * @param {ZipObject} file the file to use. + * @return {String|ArrayBuffer|Uint8Array|Buffer} the data. + */ + var getBinaryData = function (file) { + var result = getRawData(file), + type = utils.getTypeOf(result); + if (type === "string") { + if (!file.options.binary) { // unicode text ! // unicode string => binary string is a painful process, check if we can avoid it. if (support.nodebuffer) { - return nodeBuffer(result, "utf-8"); + return nodeBuffer(result, "utf-8"); } + } + return file.asBinary(); } - return file.asBinary(); - } - return result; -}; + return result; + }; -/** - * Transform this._data into a string. - * @param {function} filter a function String -> String, applied if not null on the result. - * @return {String} the string representing this._data. - */ -var dataToString = function(asUTF8) { - var result = getRawData(this); - if (result === null || typeof result === "undefined") { - return ""; - } - // if the data is a base64 string, we decode it before checking the encoding ! - if (this.options.base64) { - result = base64.decode(result); - } - if (asUTF8 && this.options.binary) { - // JSZip.prototype.utf8decode supports arrays as input - // skip to array => string step, utf8decode will do it. - result = out.utf8decode(result); - } - else { - // no utf8 transformation, do the array => string step. - result = utils.transformTo("string", result); - } - - if (!asUTF8 && !this.options.binary) { - result = utils.transformTo("string", out.utf8encode(result)); - } - return result; -}; -/** - * A simple object representing a file in the zip file. - * @constructor - * @param {string} name the name of the file - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data - * @param {Object} options the options of the file - */ -var ZipObject = function(name, data, options) { - this.name = name; - this.dir = options.dir; - this.date = options.date; - this.comment = options.comment; - this.unixPermissions = options.unixPermissions; - this.dosPermissions = options.dosPermissions; - - this._data = data; - this.options = options; - - /* - * This object contains initial values for dir and date. - * With them, we can check if the user changed the deprecated metadata in - * `ZipObject#options` or not. - */ - this._initialMetadata = { - dir : options.dir, - date : options.date - }; -}; - -ZipObject.prototype = { - /** - * Return the content as UTF8 string. - * @return {string} the UTF8 string. - */ - asText: function() { - return dataToString.call(this, true); - }, - /** - * Returns the binary content. - * @return {string} the content as binary. - */ - asBinary: function() { - return dataToString.call(this, false); - }, - /** - * Returns the content as a nodejs Buffer. - * @return {Buffer} the content as a Buffer. - */ - asNodeBuffer: function() { - var result = getBinaryData(this); - return utils.transformTo("nodebuffer", result); - }, - /** - * Returns the content as an Uint8Array. - * @return {Uint8Array} the content as an Uint8Array. - */ - asUint8Array: function() { - var result = getBinaryData(this); - return utils.transformTo("uint8array", result); - }, - /** - * Returns the content as an ArrayBuffer. - * @return {ArrayBuffer} the content as an ArrayBufer. - */ - asArrayBuffer: function() { - return this.asUint8Array().buffer; - } -}; - -/** - * Transform an integer into a string in hexadecimal. - * @private - * @param {number} dec the number to convert. - * @param {number} bytes the number of bytes to generate. - * @returns {string} the result. - */ -var decToHex = function(dec, bytes) { - var hex = "", - i; - for (i = 0; i < bytes; i++) { - hex += String.fromCharCode(dec & 0xff); - dec = dec >>> 8; - } - return hex; -}; - -/** - * Merge the objects passed as parameters into a new one. - * @private - * @param {...Object} var_args All objects to merge. - * @return {Object} a new object with the data of the others. - */ -var extend = function() { - var result = {}, i, attr; - for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers - for (attr in arguments[i]) { - if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { - result[attr] = arguments[i][attr]; - } + /** + * Transform this._data into a string. + * @param {function} filter a function String -> String, applied if not null on the result. + * @return {String} the string representing this._data. + */ + var dataToString = function (asUTF8) { + var result = getRawData(this); + if (result === null || typeof result === "undefined") { + return ""; + } + // if the data is a base64 string, we decode it before checking the encoding ! + if (this.options.base64) { + result = base64.decode(result); + } + if (asUTF8 && this.options.binary) { + // JSZip.prototype.utf8decode supports arrays as input + // skip to array => string step, utf8decode will do it. + result = out.utf8decode(result); + } + else { + // no utf8 transformation, do the array => string step. + result = utils.transformTo("string", result); } - } - return result; -}; -/** - * Transforms the (incomplete) options from the user into the complete - * set of options to create a file. - * @private - * @param {Object} o the options from the user. - * @return {Object} the complete set of options. - */ -var prepareFileAttrs = function(o) { - o = o || {}; - if (o.base64 === true && (o.binary === null || o.binary === undefined)) { - o.binary = true; - } - o = extend(o, defaults); - o.date = o.date || new Date(); - if (o.compression !== null) o.compression = o.compression.toUpperCase(); + if (!asUTF8 && !this.options.binary) { + result = utils.transformTo("string", out.utf8encode(result)); + } + return result; + }; + /** + * A simple object representing a file in the zip file. + * @constructor + * @param {string} name the name of the file + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data + * @param {Object} options the options of the file + */ + var ZipObject = function (name, data, options) { + this.name = name; + this.dir = options.dir; + this.date = options.date; + this.comment = options.comment; + this.unixPermissions = options.unixPermissions; + this.dosPermissions = options.dosPermissions; - return o; -}; + this._data = data; + this.options = options; -/** - * Add a file in the current folder. - * @private - * @param {string} name the name of the file - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file - * @param {Object} o the options of the file - * @return {Object} the new file. - */ -var fileAdd = function(name, data, o) { - // be sure sub folders exist - var dataType = utils.getTypeOf(data), - parent; + /* + * This object contains initial values for dir and date. + * With them, we can check if the user changed the deprecated metadata in + * `ZipObject#options` or not. + */ + this._initialMetadata = { + dir: options.dir, + date: options.date + }; + }; - o = prepareFileAttrs(o); + ZipObject.prototype = { + /** + * Return the content as UTF8 string. + * @return {string} the UTF8 string. + */ + asText: function () { + return dataToString.call(this, true); + }, + /** + * Returns the binary content. + * @return {string} the content as binary. + */ + asBinary: function () { + return dataToString.call(this, false); + }, + /** + * Returns the content as a nodejs Buffer. + * @return {Buffer} the content as a Buffer. + */ + asNodeBuffer: function () { + var result = getBinaryData(this); + return utils.transformTo("nodebuffer", result); + }, + /** + * Returns the content as an Uint8Array. + * @return {Uint8Array} the content as an Uint8Array. + */ + asUint8Array: function () { + var result = getBinaryData(this); + return utils.transformTo("uint8array", result); + }, + /** + * Returns the content as an ArrayBuffer. + * @return {ArrayBuffer} the content as an ArrayBufer. + */ + asArrayBuffer: function () { + return this.asUint8Array().buffer; + } + }; - if (typeof o.unixPermissions === "string") { - o.unixPermissions = parseInt(o.unixPermissions, 8); - } + /** + * Transform an integer into a string in hexadecimal. + * @private + * @param {number} dec the number to convert. + * @param {number} bytes the number of bytes to generate. + * @returns {string} the result. + */ + var decToHex = function (dec, bytes) { + var hex = "", + i; + for (i = 0; i < bytes; i++) { + hex += String.fromCharCode(dec & 0xff); + dec = dec >>> 8; + } + return hex; + }; - // UNX_IFDIR 0040000 see zipinfo.c - if (o.unixPermissions && (o.unixPermissions & 0x4000)) { - o.dir = true; - } - // Bit 4 Directory - if (o.dosPermissions && (o.dosPermissions & 0x0010)) { - o.dir = true; - } + /** + * Transforms the (incomplete) options from the user into the complete + * set of options to create a file. + * @private + * @param {Object} o the options from the user. + * @return {Object} the complete set of options. + */ + var prepareFileAttrs = function (o) { + o = o || {}; + if (o.base64 === true && (o.binary === null || o.binary === undefined)) { + o.binary = true; + } + o = utils.extend(o, defaults); + o.date = o.date || new Date(); + if (o.compression !== null) o.compression = o.compression.toUpperCase(); - if (o.dir) { - name = forceTrailingSlash(name); - } + return o; + }; - if (o.createFolders && (parent = parentFolder(name))) { - folderAdd.call(this, parent, true); - } + /** + * Add a file in the current folder. + * @private + * @param {string} name the name of the file + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file + * @param {Object} o the options of the file + * @return {Object} the new file. + */ + var fileAdd = function (name, data, o) { + // be sure sub folders exist + var dataType = utils.getTypeOf(data), + parent; - if (o.dir || data === null || typeof data === "undefined") { - o.base64 = false; - o.binary = false; - data = null; - dataType = null; - } - else if (dataType === "string") { - if (o.binary && !o.base64) { + o = prepareFileAttrs(o); + + if (typeof o.unixPermissions === "string") { + o.unixPermissions = parseInt(o.unixPermissions, 8); + } + + // UNX_IFDIR 0040000 see zipinfo.c + if (o.unixPermissions && (o.unixPermissions & 0x4000)) { + o.dir = true; + } + // Bit 4 Directory + if (o.dosPermissions && (o.dosPermissions & 0x0010)) { + o.dir = true; + } + + if (o.dir) { + name = forceTrailingSlash(name); + } + + if (o.createFolders && (parent = parentFolder(name))) { + folderAdd.call(this, parent, true); + } + + if (o.dir || data === null || typeof data === "undefined") { + o.base64 = false; + o.binary = false; + data = null; + dataType = null; + } + else if (dataType === "string") { + if (o.binary && !o.base64) { // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask if (o.optimizedBinaryString !== true) { - // this is a string, not in a base64 format. - // Be sure that this is a correct "binary string" - data = utils.string2binary(data); + // this is a string, not in a base64 format. + // Be sure that this is a correct "binary string" + data = utils.string2binary(data); } + } } - } - else { // arraybuffer, uint8array, ... - o.base64 = false; - o.binary = true; + else { // arraybuffer, uint8array, ... + o.base64 = false; + o.binary = true; - if (!dataType && !(data instanceof CompressedObject)) { + if (!dataType && !(data instanceof CompressedObject)) { throw new Error("The data of '" + name + "' is in an unsupported format !"); - } + } - // special case : it's way easier to work with Uint8Array than with ArrayBuffer - if (dataType === "arraybuffer") { + // special case : it's way easier to work with Uint8Array than with ArrayBuffer + if (dataType === "arraybuffer") { data = utils.transformTo("uint8array", data); + } } - } - var object = new ZipObject(name, data, o); - this.files[name] = object; - return object; -}; + var object = new ZipObject(name, data, o); + this.files[name] = object; + return object; + }; -/** - * Find the parent folder of the path. - * @private - * @param {string} path the path to use - * @return {string} the parent folder, or "" - */ -var parentFolder = function (path) { - if (path.slice(-1) == '/') { - path = path.substring(0, path.length - 1); - } - var lastSlash = path.lastIndexOf('/'); - return (lastSlash > 0) ? path.substring(0, lastSlash) : ""; -}; + /** + * Find the parent folder of the path. + * @private + * @param {string} path the path to use + * @return {string} the parent folder, or "" + */ + var parentFolder = function (path) { + if (path.slice(-1) == '/') { + path = path.substring(0, path.length - 1); + } + var lastSlash = path.lastIndexOf('/'); + return (lastSlash > 0) ? path.substring(0, lastSlash) : ""; + }; -/** - * Returns the path with a slash at the end. - * @private - * @param {String} path the path to check. - * @return {String} the path with a trailing slash. - */ -var forceTrailingSlash = function(path) { - // Check the name ends with a / - if (path.slice(-1) != "/") { - path += "/"; // IE doesn't like substr(-1) - } - return path; -}; -/** - * Add a (sub) folder in the current folder. - * @private - * @param {string} name the folder's name - * @param {boolean=} [createFolders] If true, automatically create sub - * folders. Defaults to false. - * @return {Object} the new folder. - */ -var folderAdd = function(name, createFolders) { - createFolders = (typeof createFolders !== 'undefined') ? createFolders : false; + /** + * Returns the path with a slash at the end. + * @private + * @param {String} path the path to check. + * @return {String} the path with a trailing slash. + */ + var forceTrailingSlash = function (path) { + // Check the name ends with a / + if (path.slice(-1) != "/") { + path += "/"; // IE doesn't like substr(-1) + } + return path; + }; + /** + * Add a (sub) folder in the current folder. + * @private + * @param {string} name the folder's name + * @param {boolean=} [createFolders] If true, automatically create sub + * folders. Defaults to false. + * @return {Object} the new folder. + */ + var folderAdd = function (name, createFolders) { + createFolders = (typeof createFolders !== 'undefined') ? createFolders : false; - name = forceTrailingSlash(name); + name = forceTrailingSlash(name); - // Does this folder already exist? - if (!this.files[name]) { - fileAdd.call(this, name, null, { + // Does this folder already exist? + if (!this.files[name]) { + fileAdd.call(this, name, null, { dir: true, createFolders: createFolders - }); - } - return this.files[name]; -}; + }); + } + return this.files[name]; + }; -/** - * Generate a JSZip.CompressedObject for a given zipOject. - * @param {ZipObject} file the object to read. - * @param {JSZip.compression} compression the compression to use. - * @param {Object} compressionOptions the options to use when compressing. - * @return {JSZip.CompressedObject} the compressed result. - */ -var generateCompressedObjectFrom = function(file, compression, compressionOptions) { - var result = new CompressedObject(), - content; + /** + * Generate a JSZip.CompressedObject for a given zipOject. + * @param {ZipObject} file the object to read. + * @param {JSZip.compression} compression the compression to use. + * @param {Object} compressionOptions the options to use when compressing. + * @return {JSZip.CompressedObject} the compressed result. + */ + var generateCompressedObjectFrom = function (file, compression, compressionOptions) { + var result = new CompressedObject(), + content; - // the data has not been decompressed, we might reuse things ! - if (file._data instanceof CompressedObject) { - result.uncompressedSize = file._data.uncompressedSize; - result.crc32 = file._data.crc32; + // the data has not been decompressed, we might reuse things ! + if (file._data instanceof CompressedObject) { + result.uncompressedSize = file._data.uncompressedSize; + result.crc32 = file._data.crc32; - if (result.uncompressedSize === 0 || file.dir) { + if (result.uncompressedSize === 0 || file.dir) { compression = compressions['STORE']; result.compressedContent = ""; result.crc32 = 0; - } - else if (file._data.compressionMethod === compression.magic) { + } + else if (file._data.compressionMethod === compression.magic) { result.compressedContent = file._data.getCompressedContent(); - } - else { + } + else { content = file._data.getContent(); // need to decompress / recompress result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions); + } } - } - else { - // have uncompressed data - content = getBinaryData(file); - if (!content || content.length === 0 || file.dir) { + else { + // have uncompressed data + content = getBinaryData(file); + if (!content || content.length === 0 || file.dir) { compression = compressions['STORE']; content = ""; + } + result.uncompressedSize = content.length; + result.crc32 = crc32(content); + result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions); } - result.uncompressedSize = content.length; - result.crc32 = crc32(content); - result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions); - } - result.compressedSize = result.compressedContent.length; - result.compressionMethod = compression.magic; + result.compressedSize = result.compressedContent.length; + result.compressionMethod = compression.magic; - return result; -}; + return result; + }; -/** - * Generate the UNIX part of the external file attributes. - * @param {Object} unixPermissions the unix permissions or null. - * @param {Boolean} isDir true if the entry is a directory, false otherwise. - * @return {Number} a 32 bit integer. - * - * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : - * - * TTTTsstrwxrwxrwx0000000000ADVSHR - * ^^^^____________________________ file type, see zipinfo.c (UNX_*) - * ^^^_________________________ setuid, setgid, sticky - * ^^^^^^^^^________________ permissions - * ^^^^^^^^^^______ not used ? - * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only - */ -var generateUnixExternalFileAttr = function (unixPermissions, isDir) { + /** + * Generate the UNIX part of the external file attributes. + * @param {Object} unixPermissions the unix permissions or null. + * @param {Boolean} isDir true if the entry is a directory, false otherwise. + * @return {Number} a 32 bit integer. + * + * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : + * + * TTTTsstrwxrwxrwx0000000000ADVSHR + * ^^^^____________________________ file type, see zipinfo.c (UNX_*) + * ^^^_________________________ setuid, setgid, sticky + * ^^^^^^^^^________________ permissions + * ^^^^^^^^^^______ not used ? + * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only + */ + var generateUnixExternalFileAttr = function (unixPermissions, isDir) { - var result = unixPermissions; - if (!unixPermissions) { - // I can't use octal values in strict mode, hence the hexa. - // 040775 => 0x41fd - // 0100664 => 0x81b4 - result = isDir ? 0x41fd : 0x81b4; - } + var result = unixPermissions; + if (!unixPermissions) { + // I can't use octal values in strict mode, hence the hexa. + // 040775 => 0x41fd + // 0100664 => 0x81b4 + result = isDir ? 0x41fd : 0x81b4; + } - return (result & 0xFFFF) << 16; -}; + return (result & 0xFFFF) << 16; + }; -/** - * Generate the DOS part of the external file attributes. - * @param {Object} dosPermissions the dos permissions or null. - * @param {Boolean} isDir true if the entry is a directory, false otherwise. - * @return {Number} a 32 bit integer. - * - * Bit 0 Read-Only - * Bit 1 Hidden - * Bit 2 System - * Bit 3 Volume Label - * Bit 4 Directory - * Bit 5 Archive - */ -var generateDosExternalFileAttr = function (dosPermissions, isDir) { + /** + * Generate the DOS part of the external file attributes. + * @param {Object} dosPermissions the dos permissions or null. + * @param {Boolean} isDir true if the entry is a directory, false otherwise. + * @return {Number} a 32 bit integer. + * + * Bit 0 Read-Only + * Bit 1 Hidden + * Bit 2 System + * Bit 3 Volume Label + * Bit 4 Directory + * Bit 5 Archive + */ + var generateDosExternalFileAttr = function (dosPermissions, isDir) { - // the dir flag is already set for compatibility + // the dir flag is already set for compatibility - return (dosPermissions || 0) & 0x3F; -}; + return (dosPermissions || 0) & 0x3F; + }; -/** - * Generate the various parts used in the construction of the final zip file. - * @param {string} name the file name. - * @param {ZipObject} file the file content. - * @param {JSZip.CompressedObject} compressedObject the compressed object. - * @param {number} offset the current offset from the start of the zip file. - * @param {String} platform let's pretend we are this platform (change platform dependents fields) - * @return {object} the zip parts. - */ -var generateZipParts = function(name, file, compressedObject, offset, platform) { - var data = compressedObject.compressedContent, - utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), - comment = file.comment || "", - utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), - useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, - useUTF8ForComment = utfEncodedComment.length !== comment.length, - o = file.options, - dosTime, - dosDate, - extraFields = "", - unicodePathExtraField = "", - unicodeCommentExtraField = "", - dir, date; + /** + * Generate the various parts used in the construction of the final zip file. + * @param {string} name the file name. + * @param {ZipObject} file the file content. + * @param {JSZip.CompressedObject} compressedObject the compressed object. + * @param {number} offset the current offset from the start of the zip file. + * @param {String} platform let's pretend we are this platform (change platform dependents fields) + * @param {Function} encodeFileName the function to encode the file name / comment. + * @return {object} the zip parts. + */ + var generateZipParts = function (name, file, compressedObject, offset, platform, encodeFileName) { + var data = compressedObject.compressedContent, + useCustomEncoding = encodeFileName !== utf8.utf8encode, + encodedFileName = utils.transformTo("string", encodeFileName(file.name)), + utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), + comment = file.comment || "", + encodedComment = utils.transformTo("string", encodeFileName(comment)), + utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), + useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, + useUTF8ForComment = utfEncodedComment.length !== comment.length, + o = file.options, + dosTime, + dosDate, + extraFields = "", + unicodePathExtraField = "", + unicodeCommentExtraField = "", + dir, date; - // handle the deprecated options.dir - if (file._initialMetadata.dir !== file.dir) { - dir = file.dir; - } else { - dir = o.dir; - } + // handle the deprecated options.dir + if (file._initialMetadata.dir !== file.dir) { + dir = file.dir; + } else { + dir = o.dir; + } - // handle the deprecated options.date - if(file._initialMetadata.date !== file.date) { - date = file.date; - } else { - date = o.date; - } + // handle the deprecated options.date + if (file._initialMetadata.date !== file.date) { + date = file.date; + } else { + date = o.date; + } - var extFileAttr = 0; - var versionMadeBy = 0; - if (dir) { - // dos or unix, we set the dos dir flag - extFileAttr |= 0x00010; - } - if(platform === "UNIX") { - versionMadeBy = 0x031E; // UNIX, version 3.0 - extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); - } else { // DOS or other, fallback to DOS - versionMadeBy = 0x0014; // DOS, version 2.0 - extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); - } + var extFileAttr = 0; + var versionMadeBy = 0; + if (dir) { + // dos or unix, we set the dos dir flag + extFileAttr |= 0x00010; + } + if (platform === "UNIX") { + versionMadeBy = 0x031E; // UNIX, version 3.0 + extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); + } else { // DOS or other, fallback to DOS + versionMadeBy = 0x0014; // DOS, version 2.0 + extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); + } - // date - // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html - // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html - // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html + // date + // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html + // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html + // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html - dosTime = date.getHours(); - dosTime = dosTime << 6; - dosTime = dosTime | date.getMinutes(); - dosTime = dosTime << 5; - dosTime = dosTime | date.getSeconds() / 2; + dosTime = date.getHours(); + dosTime = dosTime << 6; + dosTime = dosTime | date.getMinutes(); + dosTime = dosTime << 5; + dosTime = dosTime | date.getSeconds() / 2; - dosDate = date.getFullYear() - 1980; - dosDate = dosDate << 4; - dosDate = dosDate | (date.getMonth() + 1); - dosDate = dosDate << 5; - dosDate = dosDate | date.getDate(); + dosDate = date.getFullYear() - 1980; + dosDate = dosDate << 4; + dosDate = dosDate | (date.getMonth() + 1); + dosDate = dosDate << 5; + dosDate = dosDate | date.getDate(); - if (useUTF8ForFileName) { - // set the unicode path extra field. unzip needs at least one extra - // field to correctly handle unicode path, so using the path is as good - // as any other information. This could improve the situation with - // other archive managers too. - // This field is usually used without the utf8 flag, with a non - // unicode path in the header (winrar, winzip). This helps (a bit) - // with the messy Windows' default compressed folders feature but - // breaks on p7zip which doesn't seek the unicode path extra field. - // So for now, UTF-8 everywhere ! - unicodePathExtraField = + if (useUTF8ForFileName) { + // set the unicode path extra field. unzip needs at least one extra + // field to correctly handle unicode path, so using the path is as good + // as any other information. This could improve the situation with + // other archive managers too. + // This field is usually used without the utf8 flag, with a non + // unicode path in the header (winrar, winzip). This helps (a bit) + // with the messy Windows' default compressed folders feature but + // breaks on p7zip which doesn't seek the unicode path extra field. + // So for now, UTF-8 everywhere ! + unicodePathExtraField = // Version decToHex(1, 1) + // NameCRC32 - decToHex(crc32(utfEncodedFileName), 4) + + decToHex(crc32(encodedFileName), 4) + // UnicodeName utfEncodedFileName; - extraFields += + extraFields += // Info-ZIP Unicode Path Extra Field "\x75\x70" + // size decToHex(unicodePathExtraField.length, 2) + // content unicodePathExtraField; - } + } - if(useUTF8ForComment) { + if (useUTF8ForComment) { - unicodeCommentExtraField = + unicodeCommentExtraField = // Version decToHex(1, 1) + // CommentCRC32 - decToHex(this.crc32(utfEncodedComment), 4) + + decToHex(this.crc32(encodedComment), 4) + // UnicodeName utfEncodedComment; - extraFields += + extraFields += // Info-ZIP Unicode Path Extra Field "\x75\x63" + // size decToHex(unicodeCommentExtraField.length, 2) + // content unicodeCommentExtraField; - } + } - var header = ""; + var header = ""; - // version needed to extract - header += "\x0A\x00"; - // general purpose bit flag - // set bit 11 if utf8 - header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00"; - // compression method - header += compressedObject.compressionMethod; - // last mod file time - header += decToHex(dosTime, 2); - // last mod file date - header += decToHex(dosDate, 2); - // crc-32 - header += decToHex(compressedObject.crc32, 4); - // compressed size - header += decToHex(compressedObject.compressedSize, 4); - // uncompressed size - header += decToHex(compressedObject.uncompressedSize, 4); - // file name length - header += decToHex(utfEncodedFileName.length, 2); - // extra field length - header += decToHex(extraFields.length, 2); + // version needed to extract + header += "\x0A\x00"; + // general purpose bit flag + // set bit 11 if utf8 + header += !useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00"; + // compression method + header += compressedObject.compressionMethod; + // last mod file time + header += decToHex(dosTime, 2); + // last mod file date + header += decToHex(dosDate, 2); + // crc-32 + header += decToHex(compressedObject.crc32, 4); + // compressed size + header += decToHex(compressedObject.compressedSize, 4); + // uncompressed size + header += decToHex(compressedObject.uncompressedSize, 4); + // file name length + header += decToHex(encodedFileName.length, 2); + // extra field length + header += decToHex(extraFields.length, 2); - var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields; + var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; - var dirRecord = signature.CENTRAL_FILE_HEADER + - // version made by (00: DOS) - decToHex(versionMadeBy, 2) + - // file header (common to file and central directory) - header + - // file comment length - decToHex(utfEncodedComment.length, 2) + - // disk number start - "\x00\x00" + - // internal file attributes TODO - "\x00\x00" + - // external file attributes - decToHex(extFileAttr, 4) + - // relative offset of local header - decToHex(offset, 4) + - // file name - utfEncodedFileName + - // extra field - extraFields + - // file comment - utfEncodedComment; + var dirRecord = signature.CENTRAL_FILE_HEADER + + // version made by (00: DOS) + decToHex(versionMadeBy, 2) + + // file header (common to file and central directory) + header + + // file comment length + decToHex(encodedComment.length, 2) + + // disk number start + "\x00\x00" + + // internal file attributes TODO + "\x00\x00" + + // external file attributes + decToHex(extFileAttr, 4) + + // relative offset of local header + decToHex(offset, 4) + + // file name + encodedFileName + + // extra field + extraFields + + // file comment + encodedComment; - return { - fileRecord: fileRecord, - dirRecord: dirRecord, - compressedObject: compressedObject - }; -}; + return { + fileRecord: fileRecord, + dirRecord: dirRecord, + compressedObject: compressedObject + }; + }; -// return the actual prototype of JSZip -var out = { - /** - * Read an existing zip and merge the data in the current JSZip object. - * The implementation is in jszip-load.js, don't forget to include it. - * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load - * @param {Object} options Options for loading the stream. - * options.base64 : is the stream in base64 ? default : false - * @return {JSZip} the current JSZip object - */ - load: function(stream, options) { - throw new Error("Load method is not defined. Is the file jszip-load.js included ?"); - }, + // return the actual prototype of JSZip + var out = { + /** + * Read an existing zip and merge the data in the current JSZip object. + * The implementation is in jszip-load.js, don't forget to include it. + * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load + * @param {Object} options Options for loading the stream. + * options.base64 : is the stream in base64 ? default : false + * @return {JSZip} the current JSZip object + */ + load: function (stream, options) { + throw new Error("Load method is not defined. Is the file jszip-load.js included ?"); + }, - /** - * Filter nested files/folders with the specified function. - * @param {Function} search the predicate to use : - * function (relativePath, file) {...} - * It takes 2 arguments : the relative path and the file. - * @return {Array} An array of matching elements. - */ - filter: function(search) { - var result = [], + /** + * Filter nested files/folders with the specified function. + * @param {Function} search the predicate to use : + * function (relativePath, file) {...} + * It takes 2 arguments : the relative path and the file. + * @return {Array} An array of matching elements. + */ + filter: function (search) { + var result = [], filename, relativePath, file, fileClone; - for (filename in this.files) { - if (!this.files.hasOwnProperty(filename)) { - continue; - } + for (filename in this.files) { file = this.files[filename]; // return a new object, don't let the user mess with our internal objects :) - fileClone = new ZipObject(file.name, file._data, extend(file.options)); + fileClone = new ZipObject(file.name, file._data, utils.extend(file.options)); relativePath = filename.slice(this.root.length, filename.length); if (filename.slice(0, this.root.length) === this.root && // the file is in the current root - search(relativePath, fileClone)) { // and the file matches the function - result.push(fileClone); + search(relativePath, fileClone)) { // and the file matches the function + result.push(fileClone); } - } - return result; - }, + } + return result; + }, - /** - * Add a file to the zip file, or search a file. - * @param {string|RegExp} name The name of the file to add (if data is defined), - * the name of the file to find (if no data) or a regex to match files. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded - * @param {Object} o File options - * @return {JSZip|Object|Array} this JSZip object (when adding a file), - * a file (when searching by string) or an array of files (when searching by regex). - */ - file: function(name, data, o) { - if (arguments.length === 1) { + /** + * Add a file to the zip file, or search a file. + * @param {string|RegExp} name The name of the file to add (if data is defined), + * the name of the file to find (if no data) or a regex to match files. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded + * @param {Object} o File options + * @return {JSZip|Object|Array} this JSZip object (when adding a file), + * a file (when searching by string) or an array of files (when searching by regex). + */ + file: function (name, data, o) { + if (arguments.length === 1) { if (utils.isRegExp(name)) { - var regexp = name; - return this.filter(function(relativePath, file) { - return !file.dir && regexp.test(relativePath); - }); + var regexp = name; + return this.filter(function (relativePath, file) { + return !file.dir && regexp.test(relativePath); + }); } else { // text - return this.filter(function(relativePath, file) { - return !file.dir && relativePath === name; - })[0] || null; + return this.filter(function (relativePath, file) { + return !file.dir && relativePath === name; + })[0] || null; } - } - else { // more than one argument : we have data ! + } + else { // more than one argument : we have data ! name = this.root + name; fileAdd.call(this, name, data, o); - } - return this; - }, + } + return this; + }, - /** - * Add a directory to the zip file, or search. - * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. - * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. - */ - folder: function(arg) { - if (!arg) { + /** + * Add a directory to the zip file, or search. + * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. + * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. + */ + folder: function (arg) { + if (!arg) { return this; - } + } - if (utils.isRegExp(arg)) { - return this.filter(function(relativePath, file) { - return file.dir && arg.test(relativePath); + if (utils.isRegExp(arg)) { + return this.filter(function (relativePath, file) { + return file.dir && arg.test(relativePath); }); - } + } - // else, name is a new folder - var name = this.root + arg; - var newFolder = folderAdd.call(this, name); + // else, name is a new folder + var name = this.root + arg; + var newFolder = folderAdd.call(this, name); - // Allow chaining by returning a new object with this folder as the root - var ret = this.clone(); - ret.root = newFolder.name; - return ret; - }, + // Allow chaining by returning a new object with this folder as the root + var ret = this.clone(); + ret.root = newFolder.name; + return ret; + }, - /** - * Delete a file, or a directory and all sub-files, from the zip - * @param {string} name the name of the file to delete - * @return {JSZip} this JSZip object - */ - remove: function(name) { - name = this.root + name; - var file = this.files[name]; - if (!file) { + /** + * Delete a file, or a directory and all sub-files, from the zip + * @param {string} name the name of the file to delete + * @return {JSZip} this JSZip object + */ + remove: function (name) { + name = this.root + name; + var file = this.files[name]; + if (!file) { // Look for any folders if (name.slice(-1) != "/") { - name += "/"; + name += "/"; } file = this.files[name]; - } + } - if (file && !file.dir) { + if (file && !file.dir) { // file delete this.files[name]; - } else { + } else { // maybe a folder, delete recursively - var kids = this.filter(function(relativePath, file) { - return file.name.slice(0, name.length) === name; + var kids = this.filter(function (relativePath, file) { + return file.name.slice(0, name.length) === name; }); for (var i = 0; i < kids.length; i++) { - delete this.files[kids[i].name]; + delete this.files[kids[i].name]; } - } + } - return this; - }, + return this; + }, - /** - * Generate the complete zip file - * @param {Object} options the options to generate the zip file : - * - base64, (deprecated, use type instead) true to generate base64. - * - compression, "STORE" by default. - * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. - * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file - */ - generate: function(options) { - options = extend(options || {}, { + /** + * Generate the complete zip file + * @param {Object} options the options to generate the zip file : + * - base64, (deprecated, use type instead) true to generate base64. + * - compression, "STORE" by default. + * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. + * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file + */ + generate: function (options) { + options = utils.extend(options || {}, { base64: true, compression: "STORE", - compressionOptions : null, + compressionOptions: null, type: "base64", platform: "DOS", comment: null, - mimeType: 'application/zip' - }); + mimeType: 'application/zip', + encodeFileName: utf8.utf8encode + }); - utils.checkSupport(options.type); + utils.checkSupport(options.type); - // accept nodejs `process.platform` - if( - options.platform === 'darwin' || - options.platform === 'freebsd' || - options.platform === 'linux' || - options.platform === 'sunos' - ) { - options.platform = "UNIX"; - } - if (options.platform === 'win32') { - options.platform = "DOS"; - } + // accept nodejs `process.platform` + if ( + options.platform === 'darwin' || + options.platform === 'freebsd' || + options.platform === 'linux' || + options.platform === 'sunos' + ) { + options.platform = "UNIX"; + } + if (options.platform === 'win32') { + options.platform = "DOS"; + } - var zipData = [], + var zipData = [], localDirLength = 0, centralDirLength = 0, writer, i, - utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || "")); + encodedComment = utils.transformTo("string", options.encodeFileName(options.comment || this.comment || "")); - // first, generate all the zip parts. - for (var name in this.files) { - if (!this.files.hasOwnProperty(name)) { - continue; - } + // first, generate all the zip parts. + for (var name in this.files) { var file = this.files[name]; var compressionName = file.options.compression || options.compression.toUpperCase(); var compression = compressions[compressionName]; if (!compression) { - throw new Error(compressionName + " is not a valid compression method !"); + throw new Error(compressionName + " is not a valid compression method !"); } var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions); - var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform); + var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform, options.encodeFileName); localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize; centralDirLength += zipPart.dirRecord.length; zipData.push(zipPart); - } + } - var dirEnd = ""; + var dirEnd = ""; - // end of central dir signature - dirEnd = signature.CENTRAL_DIRECTORY_END + - // number of this disk - "\x00\x00" + - // number of the disk with the start of the central directory - "\x00\x00" + - // total number of entries in the central directory on this disk - decToHex(zipData.length, 2) + - // total number of entries in the central directory - decToHex(zipData.length, 2) + - // size of the central directory 4 bytes - decToHex(centralDirLength, 4) + - // offset of start of central directory with respect to the starting disk number - decToHex(localDirLength, 4) + - // .ZIP file comment length - decToHex(utfEncodedComment.length, 2) + - // .ZIP file comment - utfEncodedComment; + // end of central dir signature + dirEnd = signature.CENTRAL_DIRECTORY_END + + // number of this disk + "\x00\x00" + + // number of the disk with the start of the central directory + "\x00\x00" + + // total number of entries in the central directory on this disk + decToHex(zipData.length, 2) + + // total number of entries in the central directory + decToHex(zipData.length, 2) + + // size of the central directory 4 bytes + decToHex(centralDirLength, 4) + + // offset of start of central directory with respect to the starting disk number + decToHex(localDirLength, 4) + + // .ZIP file comment length + decToHex(encodedComment.length, 2) + + // .ZIP file comment + encodedComment; - // we have all the parts (and the total length) - // time to create a writer ! - var typeName = options.type.toLowerCase(); - if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") { + // we have all the parts (and the total length) + // time to create a writer ! + var typeName = options.type.toLowerCase(); + if (typeName === "uint8array" || typeName === "arraybuffer" || typeName === "blob" || typeName === "nodebuffer") { writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length); - }else{ + } else { writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length); - } + } - for (i = 0; i < zipData.length; i++) { + for (i = 0; i < zipData.length; i++) { writer.append(zipData[i].fileRecord); writer.append(zipData[i].compressedObject.compressedContent); - } - for (i = 0; i < zipData.length; i++) { + } + for (i = 0; i < zipData.length; i++) { writer.append(zipData[i].dirRecord); - } + } - writer.append(dirEnd); + writer.append(dirEnd); - var zip = writer.finalize(); + var zip = writer.finalize(); - switch(options.type.toLowerCase()) { + switch (options.type.toLowerCase()) { // case "zip is an Uint8Array" - case "uint8array" : - case "arraybuffer" : - case "nodebuffer" : - return utils.transformTo(options.type.toLowerCase(), zip); - case "blob" : - return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType); + case "uint8array": + case "arraybuffer": + case "nodebuffer": + return utils.transformTo(options.type.toLowerCase(), zip); + case "blob": + return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType); // case "zip is a string" - case "base64" : - return (options.base64) ? base64.encode(zip) : zip; - default : // case "string" : - return zip; - } + case "base64": + return (options.base64) ? base64.encode(zip) : zip; + default: // case "string" : + return zip; + } - }, + }, - /** - * @deprecated - * This method will be removed in a future version without replacement. - */ - crc32: function (input, crc) { - return crc32(input, crc); - }, + /** + * @deprecated + * This method will be removed in a future version without replacement. + */ + crc32: function (input, crc) { + return crc32(input, crc); + }, - /** - * @deprecated - * This method will be removed in a future version without replacement. - */ - utf8encode: function (string) { - return utils.transformTo("string", utf8.utf8encode(string)); - }, + /** + * @deprecated + * This method will be removed in a future version without replacement. + */ + utf8encode: function (string) { + return utils.transformTo("string", utf8.utf8encode(string)); + }, - /** - * @deprecated - * This method will be removed in a future version without replacement. - */ - utf8decode: function (input) { - return utf8.utf8decode(input); - } -}; -module.exports = out; - -},{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(_dereq_,module,exports){ -'use strict'; -exports.LOCAL_FILE_HEADER = "PK\x03\x04"; -exports.CENTRAL_FILE_HEADER = "PK\x01\x02"; -exports.CENTRAL_DIRECTORY_END = "PK\x05\x06"; -exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; -exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; -exports.DATA_DESCRIPTOR = "PK\x07\x08"; - -},{}],15:[function(_dereq_,module,exports){ -'use strict'; -var DataReader = _dereq_('./dataReader'); -var utils = _dereq_('./utils'); - -function StringReader(data, optimizedBinaryString) { - this.data = data; - if (!optimizedBinaryString) { - this.data = utils.string2binary(this.data); - } - this.length = this.data.length; - this.index = 0; -} -StringReader.prototype = new DataReader(); -/** - * @see DataReader.byteAt - */ -StringReader.prototype.byteAt = function(i) { - return this.data.charCodeAt(i); -}; -/** - * @see DataReader.lastIndexOfSignature - */ -StringReader.prototype.lastIndexOfSignature = function(sig) { - return this.data.lastIndexOf(sig); -}; -/** - * @see DataReader.readData - */ -StringReader.prototype.readData = function(size) { - this.checkOffset(size); - // this will work because the constructor applied the "& 0xff" mask. - var result = this.data.slice(this.index, this.index + size); - this.index += size; - return result; -}; -module.exports = StringReader; - -},{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){ -'use strict'; - -var utils = _dereq_('./utils'); - -/** - * An object to write any content to a string. - * @constructor - */ -var StringWriter = function() { - this.data = []; -}; -StringWriter.prototype = { - /** - * Append any content to the current string. - * @param {Object} input the content to add. - */ - append: function(input) { - input = utils.transformTo("string", input); - this.data.push(input); - }, - /** - * Finalize the construction an return the result. - * @return {string} the generated string. - */ - finalize: function() { - return this.data.join(""); - } -}; - -module.exports = StringWriter; - -},{"./utils":21}],17:[function(_dereq_,module,exports){ -(function (Buffer){ -'use strict'; -exports.base64 = true; -exports.array = true; -exports.string = true; -exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; -// contains true if JSZip can read/generate nodejs Buffer, false otherwise. -// Browserify will provide a Buffer implementation for browsers, which is -// an augmented Uint8Array (i.e., can be used as either Buffer or U8). -exports.nodebuffer = typeof Buffer !== "undefined"; -// contains true if JSZip can read/generate Uint8Array, false otherwise. -exports.uint8array = typeof Uint8Array !== "undefined"; - -if (typeof ArrayBuffer === "undefined") { - exports.blob = false; -} -else { - var buffer = new ArrayBuffer(0); - try { - exports.blob = new Blob([buffer], { - type: "application/zip" - }).size === 0; - } - catch (e) { - try { - var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; - var builder = new Builder(); - builder.append(buffer); - exports.blob = builder.getBlob('application/zip').size === 0; + /** + * @deprecated + * This method will be removed in a future version without replacement. + */ + utf8decode: function (input) { + return utf8.utf8decode(input); } - catch (e) { - exports.blob = false; - } - } -} + }; + module.exports = out; -}).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined)) -},{}],18:[function(_dereq_,module,exports){ -'use strict'; -var DataReader = _dereq_('./dataReader'); + }, { "./base64": 2, "./compressedObject": 3, "./compressions": 4, "./crc32": 5, "./defaults": 7, "./nodeBuffer": 12, "./signature": 15, "./stringWriter": 17, "./support": 18, "./uint8ArrayWriter": 20, "./utf8": 21, "./utils": 22 }], 15: [function (require, module, exports) { + 'use strict'; + exports.LOCAL_FILE_HEADER = "PK\x03\x04"; + exports.CENTRAL_FILE_HEADER = "PK\x01\x02"; + exports.CENTRAL_DIRECTORY_END = "PK\x05\x06"; + exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; + exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; + exports.DATA_DESCRIPTOR = "PK\x07\x08"; -function Uint8ArrayReader(data) { - if (data) { + }, {}], 16: [function (require, module, exports) { + 'use strict'; + var DataReader = require('./dataReader'); + var utils = require('./utils'); + + function StringReader(data, optimizedBinaryString) { this.data = data; + if (!optimizedBinaryString) { + this.data = utils.string2binary(this.data); + } this.length = this.data.length; this.index = 0; - } -} -Uint8ArrayReader.prototype = new DataReader(); -/** - * @see DataReader.byteAt - */ -Uint8ArrayReader.prototype.byteAt = function(i) { - return this.data[i]; -}; -/** - * @see DataReader.lastIndexOfSignature - */ -Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) { - var sig0 = sig.charCodeAt(0), - sig1 = sig.charCodeAt(1), - sig2 = sig.charCodeAt(2), - sig3 = sig.charCodeAt(3); - for (var i = this.length - 4; i >= 0; --i) { - if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { - return i; + this.zero = 0; + } + StringReader.prototype = new DataReader(); + /** + * @see DataReader.byteAt + */ + StringReader.prototype.byteAt = function (i) { + return this.data.charCodeAt(this.zero + i); + }; + /** + * @see DataReader.lastIndexOfSignature + */ + StringReader.prototype.lastIndexOfSignature = function (sig) { + return this.data.lastIndexOf(sig) - this.zero; + }; + /** + * @see DataReader.readData + */ + StringReader.prototype.readData = function (size) { + this.checkOffset(size); + // this will work because the constructor applied the "& 0xff" mask. + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = StringReader; + + }, { "./dataReader": 6, "./utils": 22 }], 17: [function (require, module, exports) { + 'use strict'; + + var utils = require('./utils'); + + /** + * An object to write any content to a string. + * @constructor + */ + var StringWriter = function () { + this.data = []; + }; + StringWriter.prototype = { + /** + * Append any content to the current string. + * @param {Object} input the content to add. + */ + append: function (input) { + input = utils.transformTo("string", input); + this.data.push(input); + }, + /** + * Finalize the construction an return the result. + * @return {string} the generated string. + */ + finalize: function () { + return this.data.join(""); } - } + }; - return -1; -}; -/** - * @see DataReader.readData - */ -Uint8ArrayReader.prototype.readData = function(size) { - this.checkOffset(size); - if(size === 0) { - // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of []. - return new Uint8Array(0); - } - var result = this.data.subarray(this.index, this.index + size); - this.index += size; - return result; -}; -module.exports = Uint8ArrayReader; + module.exports = StringWriter; -},{"./dataReader":5}],19:[function(_dereq_,module,exports){ -'use strict'; + }, { "./utils": 22 }], 18: [function (require, module, exports) { + (function (Buffer) { + 'use strict'; + exports.base64 = true; + exports.array = true; + exports.string = true; + exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; + // contains true if JSZip can read/generate nodejs Buffer, false otherwise. + // Browserify will provide a Buffer implementation for browsers, which is + // an augmented Uint8Array (i.e., can be used as either Buffer or U8). + exports.nodebuffer = typeof Buffer !== "undefined"; + // contains true if JSZip can read/generate Uint8Array, false otherwise. + exports.uint8array = typeof Uint8Array !== "undefined"; -var utils = _dereq_('./utils'); + if (typeof ArrayBuffer === "undefined") { + exports.blob = false; + } + else { + var buffer = new ArrayBuffer(0); + try { + exports.blob = new Blob([buffer], { + type: "application/zip" + }).size === 0; + } + catch (e) { + try { + var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; + var builder = new Builder(); + builder.append(buffer); + exports.blob = builder.getBlob('application/zip').size === 0; + } + catch (e) { + exports.blob = false; + } + } + } -/** - * An object to write any content to an Uint8Array. - * @constructor - * @param {number} length The length of the array. - */ -var Uint8ArrayWriter = function(length) { - this.data = new Uint8Array(length); - this.index = 0; -}; -Uint8ArrayWriter.prototype = { - /** - * Append any content to the current array. - * @param {Object} input the content to add. - */ - append: function(input) { - if (input.length !== 0) { + }).call(this, (typeof Buffer !== "undefined" ? Buffer : undefined)) + }, {}], 19: [function (require, module, exports) { + 'use strict'; + var ArrayReader = require('./arrayReader'); + + function Uint8ArrayReader(data) { + if (data) { + this.data = data; + this.length = this.data.length; + this.index = 0; + this.zero = 0; + } + } + Uint8ArrayReader.prototype = new ArrayReader(); + /** + * @see DataReader.readData + */ + Uint8ArrayReader.prototype.readData = function (size) { + this.checkOffset(size); + if (size === 0) { + // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of []. + return new Uint8Array(0); + } + var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module.exports = Uint8ArrayReader; + + }, { "./arrayReader": 1 }], 20: [function (require, module, exports) { + 'use strict'; + + var utils = require('./utils'); + + /** + * An object to write any content to an Uint8Array. + * @constructor + * @param {number} length The length of the array. + */ + var Uint8ArrayWriter = function (length) { + this.data = new Uint8Array(length); + this.index = 0; + }; + Uint8ArrayWriter.prototype = { + /** + * Append any content to the current array. + * @param {Object} input the content to add. + */ + append: function (input) { + if (input.length !== 0) { // with an empty Uint8Array, Opera fails with a "Offset larger than array size" input = utils.transformTo("uint8array", input); this.data.set(input, this.index); this.index += input.length; + } + }, + /** + * Finalize the construction an return the result. + * @return {Uint8Array} the generated array. + */ + finalize: function () { + return this.data; } - }, - /** - * Finalize the construction an return the result. - * @return {Uint8Array} the generated array. - */ - finalize: function() { - return this.data; - } -}; + }; -module.exports = Uint8ArrayWriter; + module.exports = Uint8ArrayWriter; -},{"./utils":21}],20:[function(_dereq_,module,exports){ -'use strict'; + }, { "./utils": 22 }], 21: [function (require, module, exports) { + 'use strict'; -var utils = _dereq_('./utils'); -var support = _dereq_('./support'); -var nodeBuffer = _dereq_('./nodeBuffer'); + var utils = require('./utils'); + var support = require('./support'); + var nodeBuffer = require('./nodeBuffer'); -/** - * The following functions come from pako, from pako/lib/utils/strings - * released under the MIT license, see pako https://github.com/nodeca/pako/ - */ + /** + * The following functions come from pako, from pako/lib/utils/strings + * released under the MIT license, see pako https://github.com/nodeca/pako/ + */ -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -var _utf8len = new Array(256); -for (var i=0; i<256; i++) { - _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); -} -_utf8len[254]=_utf8len[254]=1; // Invalid sequence start + // Table with utf8 lengths (calculated by first byte of sequence) + // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, + // because max possible codepoint is 0x10ffff + var _utf8len = new Array(256); + for (var i = 0; i < 256; i++) { + _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); + } + _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start -// convert string to array (typed, when possible) -var string2buf = function (str) { - var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + // convert string to array (typed, when possible) + var string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { - c2 = str.charCodeAt(m_pos+1); + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - // allocate buffer - if (support.uint8array) { - buf = new Uint8Array(buf_len); - } else { - buf = new Array(buf_len); - } + // allocate buffer + if (support.uint8array) { + buf = new Uint8Array(buf_len); + } else { + buf = new Array(buf_len); + } - // convert - for (i=0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { - c2 = str.charCodeAt(m_pos+1); + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; } - } - if (c < 0x80) { + } + if (c < 0x80) { /* one byte */ buf[i++] = c; - } else if (c < 0x800) { + } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); - } else if (c < 0x10000) { + } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); - } else { + } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); + } } - } - return buf; -}; + return buf; + }; -// Calculate max possible position in utf8 buffer, -// that will not break sequence. If that's not possible -// - (very small limits) return max size as is. -// -// buf[] - utf8 bytes array -// max - length limit (mandatory); -var utf8border = function(buf, max) { - var pos; + // Calculate max possible position in utf8 buffer, + // that will not break sequence. If that's not possible + // - (very small limits) return max size as is. + // + // buf[] - utf8 bytes array + // max - length limit (mandatory); + var utf8border = function (buf, max) { + var pos; - max = max || buf.length; - if (max > buf.length) { max = buf.length; } + max = max || buf.length; + if (max > buf.length) { max = buf.length; } - // go back from last position, until start of sequence found - pos = max-1; - while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } - // Fuckup - very small and broken sequence, - // return max, because we should return something anyway. - if (pos < 0) { return max; } + // Fuckup - very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } - // If we came to start of buffer - that means vuffer is too small, - // return max too. - if (pos === 0) { return max; } + // If we came to start of buffer - that means vuffer is too small, + // return max too. + if (pos === 0) { return max; } - return (pos + _utf8len[buf[pos]] > max) ? pos : max; -}; + return (pos + _utf8len[buf[pos]] > max) ? pos : max; + }; -// convert array to string -var buf2string = function (buf) { - var str, i, out, c, c_len; - var len = buf.length; + // convert array to string + var buf2string = function (buf) { + var str, i, out, c, c_len; + var len = buf.length; - // Reserve max possible length (2 words per char) - // NB: by unknown reasons, Array is significantly faster for - // String.fromCharCode.apply than Uint16Array. - var utf16buf = new Array(len*2); + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); - for (out=0, i=0; i<len;) { - c = buf[i++]; - // quick process ascii - if (c < 0x80) { utf16buf[out++] = c; continue; } + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } - c_len = _utf8len[c]; - // skip 5 & 6 byte codes - if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } - // apply mask on first byte - c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; - // join the rest - while (c_len > 1 && i < len) { + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; - } + } - // terminated by end of string? - if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } - if (c < 0x10000) { + if (c < 0x10000) { utf16buf[out++] = c; - } else { + } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } } - } - // shrinkBuf(utf16buf, out) - if (utf16buf.length !== out) { - if(utf16buf.subarray) { + // shrinkBuf(utf16buf, out) + if (utf16buf.length !== out) { + if (utf16buf.subarray) { utf16buf = utf16buf.subarray(0, out); - } else { + } else { utf16buf.length = out; + } } - } - // return String.fromCharCode.apply(null, utf16buf); - return utils.applyFromCharCode(utf16buf); -}; + // return String.fromCharCode.apply(null, utf16buf); + return utils.applyFromCharCode(utf16buf); + }; -// That's all for the pako functions. + // That's all for the pako functions. -/** - * Transform a javascript string into an array (typed if possible) of bytes, - * UTF-8 encoded. - * @param {String} str the string to encode - * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string. - */ -exports.utf8encode = function utf8encode(str) { - if (support.nodebuffer) { - return nodeBuffer(str, "utf-8"); - } + /** + * Transform a javascript string into an array (typed if possible) of bytes, + * UTF-8 encoded. + * @param {String} str the string to encode + * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string. + */ + exports.utf8encode = function utf8encode(str) { + if (support.nodebuffer) { + return nodeBuffer(str, "utf-8"); + } - return string2buf(str); -}; + return string2buf(str); + }; -/** - * Transform a bytes array (or a representation) representing an UTF-8 encoded - * string into a javascript string. - * @param {Array|Uint8Array|Buffer} buf the data de decode - * @return {String} the decoded string. - */ -exports.utf8decode = function utf8decode(buf) { - if (support.nodebuffer) { - return utils.transformTo("nodebuffer", buf).toString("utf-8"); - } + /** + * Transform a bytes array (or a representation) representing an UTF-8 encoded + * string into a javascript string. + * @param {Array|Uint8Array|Buffer} buf the data de decode + * @return {String} the decoded string. + */ + exports.utf8decode = function utf8decode(buf) { + if (support.nodebuffer) { + return utils.transformTo("nodebuffer", buf).toString("utf-8"); + } - buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); + buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); - // return buf2string(buf); - // Chrome prefers to work with "small" chunks of data - // for the method buf2string. - // Firefox and Chrome has their own shortcut, IE doesn't seem to really care. - var result = [], k = 0, len = buf.length, chunk = 65536; - while (k < len) { - var nextBoundary = utf8border(buf, Math.min(k + chunk, len)); - if (support.uint8array) { + // return buf2string(buf); + // Chrome prefers to work with "small" chunks of data + // for the method buf2string. + // Firefox and Chrome has their own shortcut, IE doesn't seem to really care. + var result = [], k = 0, len = buf.length, chunk = 65536; + while (k < len) { + var nextBoundary = utf8border(buf, Math.min(k + chunk, len)); + if (support.uint8array) { result.push(buf2string(buf.subarray(k, nextBoundary))); - } else { + } else { result.push(buf2string(buf.slice(k, nextBoundary))); + } + k = nextBoundary; } - k = nextBoundary; - } - return result.join(""); + return result.join(""); -}; -// vim: set shiftwidth=4 softtabstop=4: + }; + // vim: set shiftwidth=4 softtabstop=4: -},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){ -'use strict'; -var support = _dereq_('./support'); -var compressions = _dereq_('./compressions'); -var nodeBuffer = _dereq_('./nodeBuffer'); -/** - * Convert a string to a "binary string" : a string containing only char codes between 0 and 255. - * @param {string} str the string to transform. - * @return {String} the binary string. - */ -exports.string2binary = function(str) { - var result = ""; - for (var i = 0; i < str.length; i++) { - result += String.fromCharCode(str.charCodeAt(i) & 0xff); - } - return result; -}; -exports.arrayBuffer2Blob = function(buffer, mimeType) { - exports.checkSupport("blob"); - mimeType = mimeType || 'application/zip'; - - try { - // Blob constructor - return new Blob([buffer], { - type: mimeType - }); - } - catch (e) { + }, { "./nodeBuffer": 12, "./support": 18, "./utils": 22 }], 22: [function (require, module, exports) { + 'use strict'; + var support = require('./support'); + var compressions = require('./compressions'); + var nodeBuffer = require('./nodeBuffer'); + /** + * Convert a string to a "binary string" : a string containing only char codes between 0 and 255. + * @param {string} str the string to transform. + * @return {String} the binary string. + */ + exports.string2binary = function (str) { + var result = ""; + for (var i = 0; i < str.length; i++) { + result += String.fromCharCode(str.charCodeAt(i) & 0xff); + } + return result; + }; + exports.arrayBuffer2Blob = function (buffer, mimeType) { + exports.checkSupport("blob"); + mimeType = mimeType || 'application/zip'; try { + // Blob constructor + return new Blob([buffer], { + type: mimeType + }); + } + catch (e) { + + try { // deprecated, browser only, old way var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; var builder = new Builder(); builder.append(buffer); return builder.getBlob(mimeType); - } - catch (e) { + } + catch (e) { // well, fuck ?! throw new Error("Bug : can't construct the Blob."); + } } - } -}; -/** - * The identity function. - * @param {Object} input the input. - * @return {Object} the same input. - */ -function identity(input) { - return input; -} - -/** - * Fill in an array with a string. - * @param {String} str the string to use. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). - * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. - */ -function stringToArrayLike(str, array) { - for (var i = 0; i < str.length; ++i) { - array[i] = str.charCodeAt(i) & 0xFF; - } - return array; -} - -/** - * Transform an array-like object to a string. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. - * @return {String} the result. - */ -function arrayLikeToString(array) { - // Performances notes : - // -------------------- - // String.fromCharCode.apply(null, array) is the fastest, see - // see http://jsperf.com/converting-a-uint8array-to-a-string/2 - // but the stack is limited (and we can get huge arrays !). - // - // result += String.fromCharCode(array[i]); generate too many strings ! - // - // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 - var chunk = 65536; - var result = [], - len = array.length, - type = exports.getTypeOf(array), - k = 0, - canUseApply = true; - try { - switch(type) { - case "uint8array": - String.fromCharCode.apply(null, new Uint8Array(0)); - break; - case "nodebuffer": - String.fromCharCode.apply(null, nodeBuffer(0)); - break; - } - } catch(e) { - canUseApply = false; + }; + /** + * The identity function. + * @param {Object} input the input. + * @return {Object} the same input. + */ + function identity(input) { + return input; } - // no apply : slow and painful algorithm - // default browser on android 4.* - if (!canUseApply) { - var resultStr = ""; - for(var i = 0; i < array.length;i++) { - resultStr += String.fromCharCode(array[i]); - } - return resultStr; - } - while (k < len && chunk > 1) { + /** + * Fill in an array with a string. + * @param {String} str the string to use. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). + * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. + */ + function stringToArrayLike(str, array) { + for (var i = 0; i < str.length; ++i) { + array[i] = str.charCodeAt(i) & 0xFF; + } + return array; + } + + /** + * Transform an array-like object to a string. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. + * @return {String} the result. + */ + function arrayLikeToString(array) { + // Performances notes : + // -------------------- + // String.fromCharCode.apply(null, array) is the fastest, see + // see http://jsperf.com/converting-a-uint8array-to-a-string/2 + // but the stack is limited (and we can get huge arrays !). + // + // result += String.fromCharCode(array[i]); generate too many strings ! + // + // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 + var chunk = 65536; + var result = [], + len = array.length, + type = exports.getTypeOf(array), + k = 0, + canUseApply = true; try { + switch (type) { + case "uint8array": + String.fromCharCode.apply(null, new Uint8Array(0)); + break; + case "nodebuffer": + String.fromCharCode.apply(null, nodeBuffer(0)); + break; + } + } catch (e) { + canUseApply = false; + } + + // no apply : slow and painful algorithm + // default browser on android 4.* + if (!canUseApply) { + var resultStr = ""; + for (var i = 0; i < array.length; i++) { + resultStr += String.fromCharCode(array[i]); + } + return resultStr; + } + while (k < len && chunk > 1) { + try { if (type === "array" || type === "nodebuffer") { - result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); + result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); } else { - result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); + result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); } k += chunk; - } - catch (e) { + } + catch (e) { chunk = Math.floor(chunk / 2); + } } - } - return result.join(""); -} + return result.join(""); + } -exports.applyFromCharCode = arrayLikeToString; + exports.applyFromCharCode = arrayLikeToString; -/** - * Copy the data from an array-like to an other array-like. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. - * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. - */ -function arrayLikeToArrayLike(arrayFrom, arrayTo) { - for (var i = 0; i < arrayFrom.length; i++) { - arrayTo[i] = arrayFrom[i]; - } - return arrayTo; -} + /** + * Copy the data from an array-like to an other array-like. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. + * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. + * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. + */ + function arrayLikeToArrayLike(arrayFrom, arrayTo) { + for (var i = 0; i < arrayFrom.length; i++) { + arrayTo[i] = arrayFrom[i]; + } + return arrayTo; + } -// a matrix containing functions to transform everything into everything. -var transform = {}; + // a matrix containing functions to transform everything into everything. + var transform = {}; -// string to ? -transform["string"] = { - "string": identity, - "array": function(input) { - return stringToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return transform["string"]["uint8array"](input).buffer; - }, - "uint8array": function(input) { - return stringToArrayLike(input, new Uint8Array(input.length)); - }, - "nodebuffer": function(input) { - return stringToArrayLike(input, nodeBuffer(input.length)); - } -}; + // string to ? + transform["string"] = { + "string": identity, + "array": function (input) { + return stringToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function (input) { + return transform["string"]["uint8array"](input).buffer; + }, + "uint8array": function (input) { + return stringToArrayLike(input, new Uint8Array(input.length)); + }, + "nodebuffer": function (input) { + return stringToArrayLike(input, nodeBuffer(input.length)); + } + }; -// array to ? -transform["array"] = { - "string": arrayLikeToString, - "array": identity, - "arraybuffer": function(input) { - return (new Uint8Array(input)).buffer; - }, - "uint8array": function(input) { - return new Uint8Array(input); - }, - "nodebuffer": function(input) { - return nodeBuffer(input); - } -}; + // array to ? + transform["array"] = { + "string": arrayLikeToString, + "array": identity, + "arraybuffer": function (input) { + return (new Uint8Array(input)).buffer; + }, + "uint8array": function (input) { + return new Uint8Array(input); + }, + "nodebuffer": function (input) { + return nodeBuffer(input); + } + }; -// arraybuffer to ? -transform["arraybuffer"] = { - "string": function(input) { - return arrayLikeToString(new Uint8Array(input)); - }, - "array": function(input) { - return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); - }, - "arraybuffer": identity, - "uint8array": function(input) { - return new Uint8Array(input); - }, - "nodebuffer": function(input) { - return nodeBuffer(new Uint8Array(input)); - } -}; + // arraybuffer to ? + transform["arraybuffer"] = { + "string": function (input) { + return arrayLikeToString(new Uint8Array(input)); + }, + "array": function (input) { + return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); + }, + "arraybuffer": identity, + "uint8array": function (input) { + return new Uint8Array(input); + }, + "nodebuffer": function (input) { + return nodeBuffer(new Uint8Array(input)); + } + }; -// uint8array to ? -transform["uint8array"] = { - "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return input.buffer; - }, - "uint8array": identity, - "nodebuffer": function(input) { - return nodeBuffer(input); - } -}; + // uint8array to ? + transform["uint8array"] = { + "string": arrayLikeToString, + "array": function (input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function (input) { + return input.buffer; + }, + "uint8array": identity, + "nodebuffer": function (input) { + return nodeBuffer(input); + } + }; -// nodebuffer to ? -transform["nodebuffer"] = { - "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return transform["nodebuffer"]["uint8array"](input).buffer; - }, - "uint8array": function(input) { - return arrayLikeToArrayLike(input, new Uint8Array(input.length)); - }, - "nodebuffer": identity -}; + // nodebuffer to ? + transform["nodebuffer"] = { + "string": arrayLikeToString, + "array": function (input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + "arraybuffer": function (input) { + return transform["nodebuffer"]["uint8array"](input).buffer; + }, + "uint8array": function (input) { + return arrayLikeToArrayLike(input, new Uint8Array(input.length)); + }, + "nodebuffer": identity + }; -/** - * Transform an input into any type. - * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. - * If no output type is specified, the unmodified input will be returned. - * @param {String} outputType the output type. - * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. - * @throws {Error} an Error if the browser doesn't support the requested output type. - */ -exports.transformTo = function(outputType, input) { - if (!input) { - // undefined, null, etc - // an empty string won't harm. - input = ""; - } - if (!outputType) { - return input; - } - exports.checkSupport(outputType); - var inputType = exports.getTypeOf(input); - var result = transform[inputType][outputType](input); - return result; -}; + /** + * Transform an input into any type. + * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. + * If no output type is specified, the unmodified input will be returned. + * @param {String} outputType the output type. + * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. + * @throws {Error} an Error if the browser doesn't support the requested output type. + */ + exports.transformTo = function (outputType, input) { + if (!input) { + // undefined, null, etc + // an empty string won't harm. + input = ""; + } + if (!outputType) { + return input; + } + exports.checkSupport(outputType); + var inputType = exports.getTypeOf(input); + var result = transform[inputType][outputType](input); + return result; + }; -/** - * Return the type of the input. - * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. - * @param {Object} input the input to identify. - * @return {String} the (lowercase) type of the input. - */ -exports.getTypeOf = function(input) { - if (typeof input === "string") { - return "string"; - } - if (Object.prototype.toString.call(input) === "[object Array]") { - return "array"; - } - if (support.nodebuffer && nodeBuffer.test(input)) { - return "nodebuffer"; - } - if (support.uint8array && input instanceof Uint8Array) { - return "uint8array"; - } - if (support.arraybuffer && input instanceof ArrayBuffer) { - return "arraybuffer"; - } -}; + /** + * Return the type of the input. + * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. + * @param {Object} input the input to identify. + * @return {String} the (lowercase) type of the input. + */ + exports.getTypeOf = function (input) { + if (typeof input === "string") { + return "string"; + } + if (Object.prototype.toString.call(input) === "[object Array]") { + return "array"; + } + if (support.nodebuffer && nodeBuffer.test(input)) { + return "nodebuffer"; + } + if (support.uint8array && input instanceof Uint8Array) { + return "uint8array"; + } + if (support.arraybuffer && input instanceof ArrayBuffer) { + return "arraybuffer"; + } + }; -/** - * Throw an exception if the type is not supported. - * @param {String} type the type to check. - * @throws {Error} an Error if the browser doesn't support the requested type. - */ -exports.checkSupport = function(type) { - var supported = support[type.toLowerCase()]; - if (!supported) { - throw new Error(type + " is not supported by this browser"); - } -}; -exports.MAX_VALUE_16BITS = 65535; -exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 + /** + * Throw an exception if the type is not supported. + * @param {String} type the type to check. + * @throws {Error} an Error if the browser doesn't support the requested type. + */ + exports.checkSupport = function (type) { + var supported = support[type.toLowerCase()]; + if (!supported) { + throw new Error(type + " is not supported by this browser"); + } + }; + exports.MAX_VALUE_16BITS = 65535; + exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 -/** - * Prettify a string read as binary. - * @param {string} str the string to prettify. - * @return {string} a pretty string. - */ -exports.pretty = function(str) { - var res = '', - code, i; - for (i = 0; i < (str || "").length; i++) { - code = str.charCodeAt(i); - res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); - } - return res; -}; + /** + * Prettify a string read as binary. + * @param {string} str the string to prettify. + * @return {string} a pretty string. + */ + exports.pretty = function (str) { + var res = '', + code, i; + for (i = 0; i < (str || "").length; i++) { + code = str.charCodeAt(i); + res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); + } + return res; + }; -/** - * Find a compression registered in JSZip. - * @param {string} compressionMethod the method magic to find. - * @return {Object|null} the JSZip compression object, null if none found. - */ -exports.findCompression = function(compressionMethod) { - for (var method in compressions) { - if (!compressions.hasOwnProperty(method)) { + /** + * Find a compression registered in JSZip. + * @param {string} compressionMethod the method magic to find. + * @return {Object|null} the JSZip compression object, null if none found. + */ + exports.findCompression = function (compressionMethod) { + for (var method in compressions) { + if (!compressions.hasOwnProperty(method)) { continue; - } - if (compressions[method].magic === compressionMethod) { + } + if (compressions[method].magic === compressionMethod) { return compressions[method]; + } } - } - return null; -}; -/** -* Cross-window, cross-Node-context regular expression detection -* @param {Object} object Anything -* @return {Boolean} true if the object is a regular expression, -* false otherwise -*/ -exports.isRegExp = function (object) { - return Object.prototype.toString.call(object) === "[object RegExp]"; -}; + return null; + }; + /** + * Cross-window, cross-Node-context regular expression detection + * @param {Object} object Anything + * @return {Boolean} true if the object is a regular expression, + * false otherwise + */ + exports.isRegExp = function (object) { + return Object.prototype.toString.call(object) === "[object RegExp]"; + }; + + /** + * Merge the objects passed as parameters into a new one. + * @private + * @param {...Object} var_args All objects to merge. + * @return {Object} a new object with the data of the others. + */ + exports.extend = function () { + var result = {}, i, attr; + for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers + for (attr in arguments[i]) { + if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { + result[attr] = arguments[i][attr]; + } + } + } + return result; + }; -},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){ -'use strict'; -var StringReader = _dereq_('./stringReader'); -var NodeBufferReader = _dereq_('./nodeBufferReader'); -var Uint8ArrayReader = _dereq_('./uint8ArrayReader'); -var utils = _dereq_('./utils'); -var sig = _dereq_('./signature'); -var ZipEntry = _dereq_('./zipEntry'); -var support = _dereq_('./support'); -var jszipProto = _dereq_('./object'); -// class ZipEntries {{{ -/** - * All the entries in the zip file. - * @constructor - * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load. - * @param {Object} loadOptions Options for loading the stream. - */ -function ZipEntries(data, loadOptions) { - this.files = []; - this.loadOptions = loadOptions; - if (data) { - this.load(data); - } -} -ZipEntries.prototype = { - /** - * Check that the reader is on the speficied signature. - * @param {string} expectedSignature the expected signature. - * @throws {Error} if it is an other signature. - */ - checkSignature: function(expectedSignature) { - var signature = this.reader.readString(4); - if (signature !== expectedSignature) { + }, { "./compressions": 4, "./nodeBuffer": 12, "./support": 18 }], 23: [function (require, module, exports) { + 'use strict'; + var StringReader = require('./stringReader'); + var NodeBufferReader = require('./nodeBufferReader'); + var Uint8ArrayReader = require('./uint8ArrayReader'); + var ArrayReader = require('./arrayReader'); + var utils = require('./utils'); + var sig = require('./signature'); + var ZipEntry = require('./zipEntry'); + var support = require('./support'); + var jszipProto = require('./object'); + // class ZipEntries {{{ + /** + * All the entries in the zip file. + * @constructor + * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load. + * @param {Object} loadOptions Options for loading the stream. + */ + function ZipEntries(data, loadOptions) { + this.files = []; + this.loadOptions = loadOptions; + if (data) { + this.load(data); + } + } + ZipEntries.prototype = { + /** + * Check that the reader is on the speficied signature. + * @param {string} expectedSignature the expected signature. + * @throws {Error} if it is an other signature. + */ + checkSignature: function (expectedSignature) { + var signature = this.reader.readString(4); + if (signature !== expectedSignature) { throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); - } - }, - /** - * Read the end of the central directory. - */ - readBlockEndOfCentral: function() { - this.diskNumber = this.reader.readInt(2); - this.diskWithCentralDirStart = this.reader.readInt(2); - this.centralDirRecordsOnThisDisk = this.reader.readInt(2); - this.centralDirRecords = this.reader.readInt(2); - this.centralDirSize = this.reader.readInt(4); - this.centralDirOffset = this.reader.readInt(4); + } + }, + /** + * Check if the given signature is at the given index. + * @param {number} askedIndex the index to check. + * @param {string} expectedSignature the signature to expect. + * @return {boolean} true if the signature is here, false otherwise. + */ + isSignature: function (askedIndex, expectedSignature) { + var currentIndex = this.reader.index; + this.reader.setIndex(askedIndex); + var signature = this.reader.readString(4); + var result = signature === expectedSignature; + this.reader.setIndex(currentIndex); + return result; + }, + /** + * Read the end of the central directory. + */ + readBlockEndOfCentral: function () { + this.diskNumber = this.reader.readInt(2); + this.diskWithCentralDirStart = this.reader.readInt(2); + this.centralDirRecordsOnThisDisk = this.reader.readInt(2); + this.centralDirRecords = this.reader.readInt(2); + this.centralDirSize = this.reader.readInt(4); + this.centralDirOffset = this.reader.readInt(4); - this.zipCommentLength = this.reader.readInt(2); - // warning : the encoding depends of the system locale - // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. - // On a windows machine, this field is encoded with the localized windows code page. - this.zipComment = this.reader.readString(this.zipCommentLength); - // To get consistent behavior with the generation part, we will assume that - // this is utf8 encoded. - this.zipComment = jszipProto.utf8decode(this.zipComment); - }, - /** - * Read the end of the Zip 64 central directory. - * Not merged with the method readEndOfCentral : - * The end of central can coexist with its Zip64 brother, - * I don't want to read the wrong number of bytes ! - */ - readBlockZip64EndOfCentral: function() { - this.zip64EndOfCentralSize = this.reader.readInt(8); - this.versionMadeBy = this.reader.readString(2); - this.versionNeeded = this.reader.readInt(2); - this.diskNumber = this.reader.readInt(4); - this.diskWithCentralDirStart = this.reader.readInt(4); - this.centralDirRecordsOnThisDisk = this.reader.readInt(8); - this.centralDirRecords = this.reader.readInt(8); - this.centralDirSize = this.reader.readInt(8); - this.centralDirOffset = this.reader.readInt(8); + this.zipCommentLength = this.reader.readInt(2); + // warning : the encoding depends of the system locale + // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. + // On a windows machine, this field is encoded with the localized windows code page. + var zipComment = this.reader.readData(this.zipCommentLength); + var decodeParamType = support.uint8array ? "uint8array" : "array"; + // To get consistent behavior with the generation part, we will assume that + // this is utf8 encoded unless specified otherwise. + var decodeContent = utils.transformTo(decodeParamType, zipComment); + this.zipComment = this.loadOptions.decodeFileName(decodeContent); + }, + /** + * Read the end of the Zip 64 central directory. + * Not merged with the method readEndOfCentral : + * The end of central can coexist with its Zip64 brother, + * I don't want to read the wrong number of bytes ! + */ + readBlockZip64EndOfCentral: function () { + this.zip64EndOfCentralSize = this.reader.readInt(8); + this.versionMadeBy = this.reader.readString(2); + this.versionNeeded = this.reader.readInt(2); + this.diskNumber = this.reader.readInt(4); + this.diskWithCentralDirStart = this.reader.readInt(4); + this.centralDirRecordsOnThisDisk = this.reader.readInt(8); + this.centralDirRecords = this.reader.readInt(8); + this.centralDirSize = this.reader.readInt(8); + this.centralDirOffset = this.reader.readInt(8); - this.zip64ExtensibleData = {}; - var extraDataSize = this.zip64EndOfCentralSize - 44, + this.zip64ExtensibleData = {}; + var extraDataSize = this.zip64EndOfCentralSize - 44, index = 0, extraFieldId, extraFieldLength, extraFieldValue; - while (index < extraDataSize) { + while (index < extraDataSize) { extraFieldId = this.reader.readInt(2); extraFieldLength = this.reader.readInt(4); extraFieldValue = this.reader.readString(extraFieldLength); this.zip64ExtensibleData[extraFieldId] = { - id: extraFieldId, - length: extraFieldLength, - value: extraFieldValue + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue }; - } - }, - /** - * Read the end of the Zip 64 central directory locator. - */ - readBlockZip64EndOfCentralLocator: function() { - this.diskWithZip64CentralDirStart = this.reader.readInt(4); - this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); - this.disksCount = this.reader.readInt(4); - if (this.disksCount > 1) { + } + }, + /** + * Read the end of the Zip 64 central directory locator. + */ + readBlockZip64EndOfCentralLocator: function () { + this.diskWithZip64CentralDirStart = this.reader.readInt(4); + this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); + this.disksCount = this.reader.readInt(4); + if (this.disksCount > 1) { throw new Error("Multi-volumes zip are not supported"); - } - }, - /** - * Read the local files, based on the offset read in the central part. - */ - readLocalFiles: function() { - var i, file; - for (i = 0; i < this.files.length; i++) { + } + }, + /** + * Read the local files, based on the offset read in the central part. + */ + readLocalFiles: function () { + var i, file; + for (i = 0; i < this.files.length; i++) { file = this.files[i]; this.reader.setIndex(file.localHeaderOffset); this.checkSignature(sig.LOCAL_FILE_HEADER); file.readLocalPart(this.reader); file.handleUTF8(); file.processAttributes(); - } - }, - /** - * Read the central directory. - */ - readCentralDir: function() { - var file; + } + }, + /** + * Read the central directory. + */ + readCentralDir: function () { + var file; - this.reader.setIndex(this.centralDirOffset); - while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) { + this.reader.setIndex(this.centralDirOffset); + while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) { file = new ZipEntry({ - zip64: this.zip64 + zip64: this.zip64 }, this.loadOptions); file.readCentralPart(this.reader); this.files.push(file); - } - }, - /** - * Read the end of central directory. - */ - readEndOfCentral: function() { - var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); - if (offset === -1) { + } + + if (this.centralDirRecords !== this.files.length) { + if (this.centralDirRecords !== 0 && this.files.length === 0) { + // We expected some records but couldn't find ANY. + // This is really suspicious, as if something went wrong. + throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + } else { + // We found some records but not all. + // Something is wrong but we got something for the user: no error here. + // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length); + } + } + }, + /** + * Read the end of central directory. + */ + readEndOfCentral: function () { + var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); + if (offset < 0) { // Check if the content is a truncated zip or complete garbage. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto // extractible zip for example) but it can give a good hint. // If an ajax request was used without responseType, we will also // get unreadable data. - var isGarbage = true; - try { - this.reader.setIndex(0); - this.checkSignature(sig.LOCAL_FILE_HEADER); - isGarbage = false; - } catch (e) {} + var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); if (isGarbage) { - throw new Error("Can't find end of central directory : is this a zip file ? " + - "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html"); + throw new Error("Can't find end of central directory : is this a zip file ? " + + "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html"); } else { - throw new Error("Corrupted zip : can't find end of central directory"); + throw new Error("Corrupted zip : can't find end of central directory"); } - } - this.reader.setIndex(offset); - this.checkSignature(sig.CENTRAL_DIRECTORY_END); - this.readBlockEndOfCentral(); + } + this.reader.setIndex(offset); + var endOfCentralDirOffset = offset; + this.checkSignature(sig.CENTRAL_DIRECTORY_END); + this.readBlockEndOfCentral(); - /* extract from the zip spec : - 4) If one of the fields in the end of central directory - record is too small to hold required data, the field - should be set to -1 (0xFFFF or 0xFFFFFFFF) and the - ZIP64 format record should be created. - 5) The end of central directory record and the - Zip64 end of central directory locator record must - reside on the same disk when splitting or spanning - an archive. - */ - if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { + /* extract from the zip spec : + 4) If one of the fields in the end of central directory + record is too small to hold required data, the field + should be set to -1 (0xFFFF or 0xFFFFFFFF) and the + ZIP64 format record should be created. + 5) The end of central directory record and the + Zip64 end of central directory locator record must + reside on the same disk when splitting or spanning + an archive. + */ + if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { this.zip64 = true; /* @@ -2434,4743 +2510,4421 @@ ZipEntries.prototype = { // should look for a zip64 EOCD locator offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); - if (offset === -1) { - throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator"); + if (offset < 0) { + throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator"); } this.reader.setIndex(offset); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); this.readBlockZip64EndOfCentralLocator(); // now the zip64 EOCD record + if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { + // console.warn("ZIP64 end of central directory not where expected."); + this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + if (this.relativeOffsetEndOfZip64CentralDir < 0) { + throw new Error("Corrupted zip : can't find the ZIP64 end of central directory"); + } + } this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); this.readBlockZip64EndOfCentral(); - } - }, - prepareReader: function(data) { - var type = utils.getTypeOf(data); - if (type === "string" && !support.uint8array) { + } + + var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; + if (this.zip64) { + expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator + expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize; + } + + var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; + + if (extraBytes > 0) { + // console.warn(extraBytes, "extra bytes at beginning or within zipfile"); + if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { + // The offsets seem wrong, but we have something at the specified offset. + // So… we keep it. + } else { + // the offset is wrong, update the "zero" of the reader + // this happens if data has been prepended (crx files for example) + this.reader.zero = extraBytes; + } + } else if (extraBytes < 0) { + throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); + } + }, + prepareReader: function (data) { + var type = utils.getTypeOf(data); + utils.checkSupport(type); + if (type === "string" && !support.uint8array) { this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString); - } - else if (type === "nodebuffer") { + } + else if (type === "nodebuffer") { this.reader = new NodeBufferReader(data); - } - else { + } + else if (support.uint8array) { this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data)); + } else if (support.array) { + this.reader = new ArrayReader(utils.transformTo("array", data)); + } else { + throw new Error("Unexpected error: unsupported type '" + type + "'"); + } + }, + /** + * Read a zip file and create ZipEntries. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. + */ + load: function (data) { + this.prepareReader(data); + this.readEndOfCentral(); + this.readCentralDir(); + this.readLocalFiles(); } - }, - /** - * Read a zip file and create ZipEntries. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. - */ - load: function(data) { - this.prepareReader(data); - this.readEndOfCentral(); - this.readCentralDir(); - this.readLocalFiles(); - } -}; -// }}} end of ZipEntries -module.exports = ZipEntries; + }; + // }}} end of ZipEntries + module.exports = ZipEntries; -},{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){ -'use strict'; -var StringReader = _dereq_('./stringReader'); -var utils = _dereq_('./utils'); -var CompressedObject = _dereq_('./compressedObject'); -var jszipProto = _dereq_('./object'); + }, { "./arrayReader": 1, "./nodeBufferReader": 13, "./object": 14, "./signature": 15, "./stringReader": 16, "./support": 18, "./uint8ArrayReader": 19, "./utils": 22, "./zipEntry": 24 }], 24: [function (require, module, exports) { + 'use strict'; + var StringReader = require('./stringReader'); + var utils = require('./utils'); + var CompressedObject = require('./compressedObject'); + var jszipProto = require('./object'); + var support = require('./support'); -var MADE_BY_DOS = 0x00; -var MADE_BY_UNIX = 0x03; + var MADE_BY_DOS = 0x00; + var MADE_BY_UNIX = 0x03; -// class ZipEntry {{{ -/** - * An entry in the zip file. - * @constructor - * @param {Object} options Options of the current file. - * @param {Object} loadOptions Options for loading the stream. - */ -function ZipEntry(options, loadOptions) { - this.options = options; - this.loadOptions = loadOptions; -} -ZipEntry.prototype = { - /** - * say if the file is encrypted. - * @return {boolean} true if the file is encrypted, false otherwise. - */ - isEncrypted: function() { - // bit 1 is set - return (this.bitFlag & 0x0001) === 0x0001; - }, - /** - * say if the file has utf-8 filename/comment. - * @return {boolean} true if the filename/comment is in utf-8, false otherwise. - */ - useUTF8: function() { - // bit 11 is set - return (this.bitFlag & 0x0800) === 0x0800; - }, - /** - * Prepare the function used to generate the compressed content from this ZipFile. - * @param {DataReader} reader the reader to use. - * @param {number} from the offset from where we should read the data. - * @param {number} length the length of the data to read. - * @return {Function} the callback to get the compressed content (the type depends of the DataReader class). - */ - prepareCompressedContent: function(reader, from, length) { - return function() { + // class ZipEntry {{{ + /** + * An entry in the zip file. + * @constructor + * @param {Object} options Options of the current file. + * @param {Object} loadOptions Options for loading the stream. + */ + function ZipEntry(options, loadOptions) { + this.options = options; + this.loadOptions = loadOptions; + } + ZipEntry.prototype = { + /** + * say if the file is encrypted. + * @return {boolean} true if the file is encrypted, false otherwise. + */ + isEncrypted: function () { + // bit 1 is set + return (this.bitFlag & 0x0001) === 0x0001; + }, + /** + * say if the file has utf-8 filename/comment. + * @return {boolean} true if the filename/comment is in utf-8, false otherwise. + */ + useUTF8: function () { + // bit 11 is set + return (this.bitFlag & 0x0800) === 0x0800; + }, + /** + * Prepare the function used to generate the compressed content from this ZipFile. + * @param {DataReader} reader the reader to use. + * @param {number} from the offset from where we should read the data. + * @param {number} length the length of the data to read. + * @return {Function} the callback to get the compressed content (the type depends of the DataReader class). + */ + prepareCompressedContent: function (reader, from, length) { + return function () { var previousIndex = reader.index; reader.setIndex(from); var compressedFileData = reader.readData(length); reader.setIndex(previousIndex); return compressedFileData; - }; - }, - /** - * Prepare the function used to generate the uncompressed content from this ZipFile. - * @param {DataReader} reader the reader to use. - * @param {number} from the offset from where we should read the data. - * @param {number} length the length of the data to read. - * @param {JSZip.compression} compression the compression used on this file. - * @param {number} uncompressedSize the uncompressed size to expect. - * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class). - */ - prepareContent: function(reader, from, length, compression, uncompressedSize) { - return function() { + }; + }, + /** + * Prepare the function used to generate the uncompressed content from this ZipFile. + * @param {DataReader} reader the reader to use. + * @param {number} from the offset from where we should read the data. + * @param {number} length the length of the data to read. + * @param {JSZip.compression} compression the compression used on this file. + * @param {number} uncompressedSize the uncompressed size to expect. + * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class). + */ + prepareContent: function (reader, from, length, compression, uncompressedSize) { + return function () { var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent()); var uncompressedFileData = compression.uncompress(compressedFileData); if (uncompressedFileData.length !== uncompressedSize) { - throw new Error("Bug : uncompressed data size mismatch"); + throw new Error("Bug : uncompressed data size mismatch"); } return uncompressedFileData; - }; - }, - /** - * Read the local part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readLocalPart: function(reader) { - var compression, localExtraFieldsLength; + }; + }, + /** + * Read the local part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readLocalPart: function (reader) { + var compression, localExtraFieldsLength; - // we already know everything from the central dir ! - // If the central dir data are false, we are doomed. - // On the bright side, the local part is scary : zip64, data descriptors, both, etc. - // The less data we get here, the more reliable this should be. - // Let's skip the whole header and dash to the data ! - reader.skip(22); - // in some zip created on windows, the filename stored in the central dir contains \ instead of /. - // Strangely, the filename here is OK. - // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes - // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... - // Search "unzip mismatching "local" filename continuing with "central" filename version" on - // the internet. - // - // I think I see the logic here : the central directory is used to display - // content and the local directory is used to extract the files. Mixing / and \ - // may be used to display \ to windows users and use / when extracting the files. - // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 - this.fileNameLength = reader.readInt(2); - localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir - this.fileName = reader.readString(this.fileNameLength); - reader.skip(localExtraFieldsLength); + // we already know everything from the central dir ! + // If the central dir data are false, we are doomed. + // On the bright side, the local part is scary : zip64, data descriptors, both, etc. + // The less data we get here, the more reliable this should be. + // Let's skip the whole header and dash to the data ! + reader.skip(22); + // in some zip created on windows, the filename stored in the central dir contains \ instead of /. + // Strangely, the filename here is OK. + // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes + // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... + // Search "unzip mismatching "local" filename continuing with "central" filename version" on + // the internet. + // + // I think I see the logic here : the central directory is used to display + // content and the local directory is used to extract the files. Mixing / and \ + // may be used to display \ to windows users and use / when extracting the files. + // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 + this.fileNameLength = reader.readInt(2); + localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir + this.fileName = reader.readData(this.fileNameLength); + reader.skip(localExtraFieldsLength); - if (this.compressedSize == -1 || this.uncompressedSize == -1) { + if (this.compressedSize == -1 || this.uncompressedSize == -1) { throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)"); - } + } - compression = utils.findCompression(this.compressionMethod); - if (compression === null) { // no compression found - throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")"); - } - this.decompressed = new CompressedObject(); - this.decompressed.compressedSize = this.compressedSize; - this.decompressed.uncompressedSize = this.uncompressedSize; - this.decompressed.crc32 = this.crc32; - this.decompressed.compressionMethod = this.compressionMethod; - this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression); - this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize); + compression = utils.findCompression(this.compressionMethod); + if (compression === null) { // no compression found + throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); + } + this.decompressed = new CompressedObject(); + this.decompressed.compressedSize = this.compressedSize; + this.decompressed.uncompressedSize = this.uncompressedSize; + this.decompressed.crc32 = this.crc32; + this.decompressed.compressionMethod = this.compressionMethod; + this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression); + this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize); - // we need to compute the crc32... - if (this.loadOptions.checkCRC32) { + // we need to compute the crc32... + if (this.loadOptions.checkCRC32) { this.decompressed = utils.transformTo("string", this.decompressed.getContent()); if (jszipProto.crc32(this.decompressed) !== this.crc32) { - throw new Error("Corrupted zip : CRC32 mismatch"); + throw new Error("Corrupted zip : CRC32 mismatch"); } - } - }, + } + }, - /** - * Read the central part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readCentralPart: function(reader) { - this.versionMadeBy = reader.readInt(2); - this.versionNeeded = reader.readInt(2); - this.bitFlag = reader.readInt(2); - this.compressionMethod = reader.readString(2); - this.date = reader.readDate(); - this.crc32 = reader.readInt(4); - this.compressedSize = reader.readInt(4); - this.uncompressedSize = reader.readInt(4); - this.fileNameLength = reader.readInt(2); - this.extraFieldsLength = reader.readInt(2); - this.fileCommentLength = reader.readInt(2); - this.diskNumberStart = reader.readInt(2); - this.internalFileAttributes = reader.readInt(2); - this.externalFileAttributes = reader.readInt(4); - this.localHeaderOffset = reader.readInt(4); + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readCentralPart: function (reader) { + this.versionMadeBy = reader.readInt(2); + this.versionNeeded = reader.readInt(2); + this.bitFlag = reader.readInt(2); + this.compressionMethod = reader.readString(2); + this.date = reader.readDate(); + this.crc32 = reader.readInt(4); + this.compressedSize = reader.readInt(4); + this.uncompressedSize = reader.readInt(4); + this.fileNameLength = reader.readInt(2); + this.extraFieldsLength = reader.readInt(2); + this.fileCommentLength = reader.readInt(2); + this.diskNumberStart = reader.readInt(2); + this.internalFileAttributes = reader.readInt(2); + this.externalFileAttributes = reader.readInt(4); + this.localHeaderOffset = reader.readInt(4); - if (this.isEncrypted()) { + if (this.isEncrypted()) { throw new Error("Encrypted zip are not supported"); - } + } - this.fileName = reader.readString(this.fileNameLength); - this.readExtraFields(reader); - this.parseZIP64ExtraField(reader); - this.fileComment = reader.readString(this.fileCommentLength); - }, + this.fileName = reader.readData(this.fileNameLength); + this.readExtraFields(reader); + this.parseZIP64ExtraField(reader); + this.fileComment = reader.readData(this.fileCommentLength); + }, - /** - * Parse the external file attributes and get the unix/dos permissions. - */ - processAttributes: function () { - this.unixPermissions = null; - this.dosPermissions = null; - var madeBy = this.versionMadeBy >> 8; + /** + * Parse the external file attributes and get the unix/dos permissions. + */ + processAttributes: function () { + this.unixPermissions = null; + this.dosPermissions = null; + var madeBy = this.versionMadeBy >> 8; - // Check if we have the DOS directory flag set. - // We look for it in the DOS and UNIX permissions - // but some unknown platform could set it as a compatibility flag. - this.dir = this.externalFileAttributes & 0x0010 ? true : false; + // Check if we have the DOS directory flag set. + // We look for it in the DOS and UNIX permissions + // but some unknown platform could set it as a compatibility flag. + this.dir = this.externalFileAttributes & 0x0010 ? true : false; - if(madeBy === MADE_BY_DOS) { + if (madeBy === MADE_BY_DOS) { // first 6 bits (0 to 5) this.dosPermissions = this.externalFileAttributes & 0x3F; - } + } - if(madeBy === MADE_BY_UNIX) { + if (madeBy === MADE_BY_UNIX) { this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF; // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8); - } + } - // fail safe : if the name ends with a / it probably means a folder - if (!this.dir && this.fileName.slice(-1) === '/') { + // fail safe : if the name ends with a / it probably means a folder + if (!this.dir && this.fileNameStr.slice(-1) === '/') { this.dir = true; - } - }, + } + }, - /** - * Parse the ZIP64 extra field and merge the info in the current ZipEntry. - * @param {DataReader} reader the reader to use. - */ - parseZIP64ExtraField: function(reader) { + /** + * Parse the ZIP64 extra field and merge the info in the current ZipEntry. + * @param {DataReader} reader the reader to use. + */ + parseZIP64ExtraField: function (reader) { - if (!this.extraFields[0x0001]) { + if (!this.extraFields[0x0001]) { return; - } + } - // should be something, preparing the extra reader - var extraReader = new StringReader(this.extraFields[0x0001].value); + // should be something, preparing the extra reader + var extraReader = new StringReader(this.extraFields[0x0001].value); - // I really hope that these 64bits integer can fit in 32 bits integer, because js - // won't let us have more. - if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { + // I really hope that these 64bits integer can fit in 32 bits integer, because js + // won't let us have more. + if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { this.uncompressedSize = extraReader.readInt(8); - } - if (this.compressedSize === utils.MAX_VALUE_32BITS) { + } + if (this.compressedSize === utils.MAX_VALUE_32BITS) { this.compressedSize = extraReader.readInt(8); - } - if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { + } + if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { this.localHeaderOffset = extraReader.readInt(8); - } - if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { + } + if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { this.diskNumberStart = extraReader.readInt(4); - } - }, - /** - * Read the central part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readExtraFields: function(reader) { - var start = reader.index, + } + }, + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readExtraFields: function (reader) { + var start = reader.index, extraFieldId, extraFieldLength, extraFieldValue; - this.extraFields = this.extraFields || {}; + this.extraFields = this.extraFields || {}; - while (reader.index < start + this.extraFieldsLength) { + while (reader.index < start + this.extraFieldsLength) { extraFieldId = reader.readInt(2); extraFieldLength = reader.readInt(2); extraFieldValue = reader.readString(extraFieldLength); this.extraFields[extraFieldId] = { - id: extraFieldId, - length: extraFieldLength, - value: extraFieldValue + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue }; - } - }, - /** - * Apply an UTF8 transformation if needed. - */ - handleUTF8: function() { - if (this.useUTF8()) { - this.fileName = jszipProto.utf8decode(this.fileName); - this.fileComment = jszipProto.utf8decode(this.fileComment); - } else { + } + }, + /** + * Apply an UTF8 transformation if needed. + */ + handleUTF8: function () { + var decodeParamType = support.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) { + this.fileNameStr = jszipProto.utf8decode(this.fileName); + this.fileCommentStr = jszipProto.utf8decode(this.fileComment); + } else { var upath = this.findExtraFieldUnicodePath(); if (upath !== null) { - this.fileName = upath; + this.fileNameStr = upath; + } else { + var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); } + var ucomment = this.findExtraFieldUnicodeComment(); if (ucomment !== null) { - this.fileComment = ucomment; + this.fileCommentStr = ucomment; + } else { + var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); } - } - }, + } + }, - /** - * Find the unicode path declared in the extra field, if any. - * @return {String} the unicode path, null otherwise. - */ - findExtraFieldUnicodePath: function() { - var upathField = this.extraFields[0x7075]; - if (upathField) { + /** + * Find the unicode path declared in the extra field, if any. + * @return {String} the unicode path, null otherwise. + */ + findExtraFieldUnicodePath: function () { + var upathField = this.extraFields[0x7075]; + if (upathField) { var extraReader = new StringReader(upathField.value); // wrong version if (extraReader.readInt(1) !== 1) { - return null; + return null; } // the crc of the filename changed, this field is out of date. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) { - return null; + return null; } return jszipProto.utf8decode(extraReader.readString(upathField.length - 5)); - } - return null; - }, + } + return null; + }, - /** - * Find the unicode comment declared in the extra field, if any. - * @return {String} the unicode comment, null otherwise. - */ - findExtraFieldUnicodeComment: function() { - var ucommentField = this.extraFields[0x6375]; - if (ucommentField) { + /** + * Find the unicode comment declared in the extra field, if any. + * @return {String} the unicode comment, null otherwise. + */ + findExtraFieldUnicodeComment: function () { + var ucommentField = this.extraFields[0x6375]; + if (ucommentField) { var extraReader = new StringReader(ucommentField.value); // wrong version if (extraReader.readInt(1) !== 1) { - return null; + return null; } // the crc of the comment changed, this field is out of date. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) { - return null; + return null; } return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5)); + } + return null; } - return null; - } -}; -module.exports = ZipEntry; + }; + module.exports = ZipEntry; -},{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){ -// Top level file is just a mixin of submodules & constants -'use strict'; + }, { "./compressedObject": 3, "./object": 14, "./stringReader": 16, "./support": 18, "./utils": 22 }], 25: [function (require, module, exports) { + // Top level file is just a mixin of submodules & constants + 'use strict'; -var assign = _dereq_('./lib/utils/common').assign; + var assign = require('./lib/utils/common').assign; -var deflate = _dereq_('./lib/deflate'); -var inflate = _dereq_('./lib/inflate'); -var constants = _dereq_('./lib/zlib/constants'); + var deflate = require('./lib/deflate'); + var inflate = require('./lib/inflate'); + var constants = require('./lib/zlib/constants'); -var pako = {}; + var pako = {}; -assign(pako, deflate, inflate, constants); + assign(pako, deflate, inflate, constants); -module.exports = pako; -},{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){ -'use strict'; + module.exports = pako; + + }, { "./lib/deflate": 26, "./lib/inflate": 27, "./lib/utils/common": 28, "./lib/zlib/constants": 31 }], 26: [function (require, module, exports) { + 'use strict'; -var zlib_deflate = _dereq_('./zlib/deflate.js'); -var utils = _dereq_('./utils/common'); -var strings = _dereq_('./utils/strings'); -var msg = _dereq_('./zlib/messages'); -var zstream = _dereq_('./zlib/zstream'); + var zlib_deflate = require('./zlib/deflate'); + var utils = require('./utils/common'); + var strings = require('./utils/strings'); + var msg = require('./zlib/messages'); + var ZStream = require('./zlib/zstream'); + + var toString = Object.prototype.toString; + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ + + var Z_NO_FLUSH = 0; + var Z_FINISH = 4; + + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_SYNC_FLUSH = 2; + + var Z_DEFAULT_COMPRESSION = -1; + + var Z_DEFAULT_STRATEGY = 0; + + var Z_DEFLATED = 8; + + /* ===========================================================================*/ -/* Public constants ==========================================================*/ -/* ===========================================================================*/ + /** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ -var Z_NO_FLUSH = 0; -var Z_FINISH = 4; + /* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ -var Z_OK = 0; -var Z_STREAM_END = 1; + /** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ -var Z_DEFAULT_COMPRESSION = -1; + /** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ -var Z_DEFAULT_STRATEGY = 0; - -var Z_DEFLATED = 8; - -/* ===========================================================================*/ + /** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ + /** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ + function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overriden. - **/ + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); -/** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param). - **/ + var opt = this.options; -/** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } -/** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data -/** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ -var Deflate = function(options) { + this.strm = new ZStream(); + this.strm.avail_out = 0; - this.options = utils.assign({ - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - to: '' - }, options || {}); + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); - var opt = this.options; + if (status !== Z_OK) { + throw new Error(msg[status]); + } - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; - } + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; - } + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data + status = zlib_deflate.deflateSetDictionary(this.strm, dict); - this.strm = new zstream(); - this.strm.avail_out = 0; + if (status !== Z_OK) { + throw new Error(msg[status]); + } - var status = zlib_deflate.deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - if (opt.header) { - zlib_deflate.deflateSetHeader(this.strm, opt.header); - } -}; - -/** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|String): input data. Strings will be converted to - * utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That flush internal pending buffers and call - * [[Deflate#onEnd]]. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ -Deflate.prototype.push = function(data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = strings.string2buf(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new utils.Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) { - if (this.options.to === 'string') { - this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); - } else { - this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + this._dict_set = true; + } } - } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = zlib_deflate.deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } + /** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ + Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; - return true; -}; + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); -/** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): ouput data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ -Deflate.prototype.onData = function(chunk) { - this.chunks.push(chunk); -}; - - -/** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that input stream complete - * or error happenned. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ -Deflate.prototype.onEnd = function(status) { - // On success - join - if (status === Z_OK) { - if (this.options.to === 'string') { - this.result = this.chunks.join(''); - } else { - this.result = utils.flattenChunks(this.chunks); - } - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; -}; - - -/** - * deflate(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * Compress `data` with deflate alrorythm and `options`. - * - * Supported options are: - * - * - level - * - windowBits - * - memLevel - * - strategy - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Sugar (options): - * - * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify - * negative windowBits implicitly. - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); - * - * console.log(pako.deflate(data)); - * ``` - **/ -function deflate(input, options) { - var deflator = new Deflate(options); - - deflator.push(input, true); - - // That will never happens, if you don't cheat with options :) - if (deflator.err) { throw deflator.msg; } - - return deflator.result; -} - - -/** - * deflateRaw(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * The same as [[deflate]], but creates raw data, without wrapper - * (header and adler32 crc). - **/ -function deflateRaw(input, options) { - options = options || {}; - options.raw = true; - return deflate(input, options); -} - - -/** - * gzip(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * The same as [[deflate]], but create gzip wrapper instead of - * deflate one. - **/ -function gzip(input, options) { - options = options || {}; - options.gzip = true; - return deflate(input, options); -} - - -exports.Deflate = Deflate; -exports.deflate = deflate; -exports.deflateRaw = deflateRaw; -exports.gzip = gzip; -},{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){ -'use strict'; - - -var zlib_inflate = _dereq_('./zlib/inflate.js'); -var utils = _dereq_('./utils/common'); -var strings = _dereq_('./utils/strings'); -var c = _dereq_('./zlib/constants'); -var msg = _dereq_('./zlib/messages'); -var zstream = _dereq_('./zlib/zstream'); -var gzheader = _dereq_('./zlib/gzheader'); - - -/** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - -/* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overriden. - **/ - -/** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param). - **/ - -/** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - -/** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - -/** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ -var Inflate = function(options) { - - this.options = utils.assign({ - chunkSize: 16384, - windowBits: 0, - to: '' - }, options || {}); - - var opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new zstream(); - this.strm.avail_out = 0; - - var status = zlib_inflate.inflateInit2( - this.strm, - opt.windowBits - ); - - if (status !== c.Z_OK) { - throw new Error(msg[status]); - } - - this.header = new gzheader(); - - zlib_inflate.inflateGetHeader(this.strm, this.header); -}; - -/** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That flush internal pending buffers and call - * [[Inflate#onEnd]]. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ -Inflate.prototype.push = function(data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var status, _mode; - var next_out_utf8, tail, utf8str; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = strings.binstring2buf(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new utils.Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ - - if (status !== c.Z_STREAM_END && status !== c.Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - - if (strm.next_out) { - if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) { - - if (this.options.to === 'string') { - - next_out_utf8 = strings.utf8border(strm.output, strm.next_out); - - tail = strm.next_out - next_out_utf8; - utf8str = strings.buf2string(strm.output, next_out_utf8); - - // move tail - strm.next_out = tail; - strm.avail_out = chunkSize - tail; - if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } - - this.onData(utf8str); - + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); } else { - this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + strm.input = data; } - } - } - } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END); - if (status === c.Z_STREAM_END) { - _mode = c.Z_FINISH; - } - // Finalize on the last chunk. - if (_mode === c.Z_FINISH) { - status = zlib_inflate.inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === c.Z_OK; - } + strm.next_in = 0; + strm.avail_in = strm.input.length; - return true; -}; - - -/** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): ouput data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ -Inflate.prototype.onData = function(chunk) { - this.chunks.push(chunk); -}; - - -/** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell inflate that input stream complete - * or error happenned. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ -Inflate.prototype.onEnd = function(status) { - // On success - join - if (status === c.Z_OK) { - if (this.options.to === 'string') { - // Glue & convert here, until we teach pako to send - // utf8 alligned strings to onData - this.result = this.chunks.join(''); - } else { - this.result = utils.flattenChunks(this.chunks); - } - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; -}; - - -/** - * inflate(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * Decompress `data` with inflate/ungzip and `options`. Autodetect - * format via wrapper header by default. That's why we don't provide - * separate `ungzip` method. - * - * Supported options are: - * - * - windowBits - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information. - * - * Sugar (options): - * - * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify - * negative windowBits implicitly. - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) - * , output; - * - * try { - * output = pako.inflate(input); - * } catch (err) - * console.log(err); - * } - * ``` - **/ -function inflate(input, options) { - var inflator = new Inflate(options); - - inflator.push(input, true); - - // That will never happens, if you don't cheat with options :) - if (inflator.err) { throw inflator.msg; } - - return inflator.result; -} - - -/** - * inflateRaw(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * The same as [[inflate]], but creates raw data, without wrapper - * (header and adler32 crc). - **/ -function inflateRaw(input, options) { - options = options || {}; - options.raw = true; - return inflate(input, options); -} - - -/** - * ungzip(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * Just shortcut to [[inflate]], because it autodetects format - * by header.content. Done for convenience. - **/ - - -exports.Inflate = Inflate; -exports.inflate = inflate; -exports.inflateRaw = inflateRaw; -exports.ungzip = inflate; - -},{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(_dereq_,module,exports){ -'use strict'; - - -var TYPED_OK = (typeof Uint8Array !== 'undefined') && - (typeof Uint16Array !== 'undefined') && - (typeof Int32Array !== 'undefined'); - - -exports.assign = function (obj /*from1, from2, from3, ...*/) { - var sources = Array.prototype.slice.call(arguments, 1); - while (sources.length) { - var source = sources.shift(); - if (!source) { continue; } - - if (typeof(source) !== 'object') { - throw new TypeError(source + 'must be non-object'); - } - - for (var p in source) { - if (source.hasOwnProperty(p)) { - obj[p] = source[p]; - } - } - } - - return obj; -}; - - -// reduce buffer size, avoiding mem copy -exports.shrinkBuf = function (buf, size) { - if (buf.length === size) { return buf; } - if (buf.subarray) { return buf.subarray(0, size); } - buf.length = size; - return buf; -}; - - -var fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs+len), dest_offs); - return; - } - // Fallback to ordinary array - for(var i=0; i<len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function(chunks) { - var i, l, len, pos, chunk, result; - - // calculate data length - len = 0; - for (i=0, l=chunks.length; i<l; i++) { - len += chunks[i].length; - } - - // join chunks - result = new Uint8Array(len); - pos = 0; - for (i=0, l=chunks.length; i<l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } - - return result; - } -}; - -var fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for(var i=0; i<len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function(chunks) { - return [].concat.apply([], chunks); - } -}; - - -// Enable/Disable typed arrays use, for testing -// -exports.setTyped = function (on) { - if (on) { - exports.Buf8 = Uint8Array; - exports.Buf16 = Uint16Array; - exports.Buf32 = Int32Array; - exports.assign(exports, fnTyped); - } else { - exports.Buf8 = Array; - exports.Buf16 = Array; - exports.Buf32 = Array; - exports.assign(exports, fnUntyped); - } -}; - -exports.setTyped(TYPED_OK); -},{}],28:[function(_dereq_,module,exports){ -// String encode/decode helpers -'use strict'; - - -var utils = _dereq_('./common'); - - -// Quick check if we can use fast array to bin string conversion -// -// - apply(Array) can fail on Android 2.2 -// - apply(Uint8Array) can fail on iOS 5.1 Safary -// -var STR_APPLY_OK = true; -var STR_APPLY_UIA_OK = true; - -try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } -try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } - - -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -var _utf8len = new utils.Buf8(256); -for (var i=0; i<256; i++) { - _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); -} -_utf8len[254]=_utf8len[254]=1; // Invalid sequence start - - -// convert string to array (typed, when possible) -exports.string2buf = function (str) { - var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { - c2 = str.charCodeAt(m_pos+1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - buf = new utils.Buf8(buf_len); - - // convert - for (i=0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { - c2 = str.charCodeAt(m_pos+1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | (c >>> 6); - buf[i++] = 0x80 | (c & 0x3f); - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | (c >>> 12); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } else { - /* four bytes */ - buf[i++] = 0xf0 | (c >>> 18); - buf[i++] = 0x80 | (c >>> 12 & 0x3f); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } - } - - return buf; -}; - -// Helper (used in 2 places) -function buf2binstring(buf, len) { - // use fallback for big arrays to avoid stack overflow - if (len < 65537) { - if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { - return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); - } - } - - var result = ''; - for(var i=0; i < len; i++) { - result += String.fromCharCode(buf[i]); - } - return result; -} - - -// Convert byte array to binary string -exports.buf2binstring = function(buf) { - return buf2binstring(buf, buf.length); -}; - - -// Convert binary string (typed, when possible) -exports.binstring2buf = function(str) { - var buf = new utils.Buf8(str.length); - for(var i=0, len=buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; -}; - - -// convert array to string -exports.buf2string = function (buf, max) { - var i, out, c, c_len; - var len = max || buf.length; - - // Reserve max possible length (2 words per char) - // NB: by unknown reasons, Array is significantly faster for - // String.fromCharCode.apply than Uint16Array. - var utf16buf = new Array(len*2); - - for (out=0, i=0; i<len;) { - c = buf[i++]; - // quick process ascii - if (c < 0x80) { utf16buf[out++] = c; continue; } - - c_len = _utf8len[c]; - // skip 5 & 6 byte codes - if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } - - // apply mask on first byte - c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; - // join the rest - while (c_len > 1 && i < len) { - c = (c << 6) | (buf[i++] & 0x3f); - c_len--; - } - - // terminated by end of string? - if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } - - if (c < 0x10000) { - utf16buf[out++] = c; - } else { - c -= 0x10000; - utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); - utf16buf[out++] = 0xdc00 | (c & 0x3ff); - } - } - - return buf2binstring(utf16buf, out); -}; - - -// Calculate max possible position in utf8 buffer, -// that will not break sequence. If that's not possible -// - (very small limits) return max size as is. -// -// buf[] - utf8 bytes array -// max - length limit (mandatory); -exports.utf8border = function(buf, max) { - var pos; - - max = max || buf.length; - if (max > buf.length) { max = buf.length; } - - // go back from last position, until start of sequence found - pos = max-1; - while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } - - // Fuckup - very small and broken sequence, - // return max, because we should return something anyway. - if (pos < 0) { return max; } - - // If we came to start of buffer - that means vuffer is too small, - // return max too. - if (pos === 0) { return max; } - - return (pos + _utf8len[buf[pos]] > max) ? pos : max; -}; - -},{"./common":27}],29:[function(_dereq_,module,exports){ -'use strict'; - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It doesn't worth to make additional optimizationa as in original. -// Small size is preferable. - -function adler32(adler, buf, len, pos) { - var s1 = (adler & 0xffff) |0 - , s2 = ((adler >>> 16) & 0xffff) |0 - , n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = (s1 + buf[pos++]) |0; - s2 = (s2 + s1) |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return (s1 | (s2 << 16)) |0; -} - - -module.exports = adler32; -},{}],30:[function(_dereq_,module,exports){ -module.exports = { - - /* Allowed flush values; see deflate() and inflate() below for details */ - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_TREES: 6, - - /* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - //Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - //Z_VERSION_ERROR: -6, - - /* compression levels */ - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - - - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - - /* Possible values of the data_type field (though see inflate()) */ - Z_BINARY: 0, - Z_TEXT: 1, - //Z_ASCII: 1, // = Z_TEXT (deprecated) - Z_UNKNOWN: 2, - - /* The deflate compression method */ - Z_DEFLATED: 8 - //Z_NULL: null // Use -1 or null inline, depending on var type -}; -},{}],31:[function(_dereq_,module,exports){ -'use strict'; - -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. - - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - var c, table = []; - - for(var n =0; n < 256; n++){ - c = n; - for(var k =0; k < 8; k++){ - c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -var crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - var t = crcTable - , end = pos + len; - - crc = crc ^ (-1); - - for (var i = pos; i < end; i++ ) { - crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return (crc ^ (-1)); // >>> 0; -} - - -module.exports = crc32; -},{}],32:[function(_dereq_,module,exports){ -'use strict'; - -var utils = _dereq_('../utils/common'); -var trees = _dereq_('./trees'); -var adler32 = _dereq_('./adler32'); -var crc32 = _dereq_('./crc32'); -var msg = _dereq_('./messages'); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -/* Allowed flush values; see deflate() and inflate() below for details */ -var Z_NO_FLUSH = 0; -var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -//var Z_TREES = 6; - - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -//var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -//var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - - -/* compression levels */ -//var Z_NO_COMPRESSION = 0; -//var Z_BEST_SPEED = 1; -//var Z_BEST_COMPRESSION = 9; -var Z_DEFAULT_COMPRESSION = -1; - - -var Z_FILTERED = 1; -var Z_HUFFMAN_ONLY = 2; -var Z_RLE = 3; -var Z_FIXED = 4; -var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -//var Z_BINARY = 0; -//var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - - -/* The deflate compression method */ -var Z_DEFLATED = 8; - -/*============================================================================*/ - - -var MAX_MEM_LEVEL = 9; -/* Maximum value for memLevel in deflateInit2 */ -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_MEM_LEVEL = 8; - - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ -var LITERALS = 256; -/* number of literal bytes 0..255 */ -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ -var D_CODES = 30; -/* number of distance codes */ -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ -var HEAP_SIZE = 2*L_CODES + 1; -/* maximum heap size */ -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); - -var PRESET_DICT = 0x20; - -var INIT_STATE = 42; -var EXTRA_STATE = 69; -var NAME_STATE = 73; -var COMMENT_STATE = 91; -var HCRC_STATE = 103; -var BUSY_STATE = 113; -var FINISH_STATE = 666; - -var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -var BS_BLOCK_DONE = 2; /* block flush performed */ -var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - -var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} - -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); -} - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ -function flush_pending(strm) { - var s = strm.state; - - //_tr_flush_bits(s); - var len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } -} - - -function flush_block_only (s, last) { - trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - - -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; -} - - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -function putShortMSB(s, b) { -// put_byte(s, (Byte)(b >> 8)); -// put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; -} - - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ -function read_buf(strm, buf, start, size) { - var len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - utils.arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; -} - - -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - var chain_length = s.max_chain_length; /* max hash chain length */ - var scan = s.strstart; /* current string */ - var match; /* matched string */ - var len; /* length of current match */ - var best_len = s.prev_length; /* best match length so far */ - var nice_match = s.nice_match; /* stop if match long enough */ - var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - var _win = s.window; // shortcut - - var wmask = s.w_mask; - var prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - var strend = s.strstart + MAX_MATCH; - var scan_end1 = _win[scan + best_len - 1]; - var scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (strend - scan); - scan = strend - MAX_MATCH; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - var _w_size = s.w_size; - var p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - utils.arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; -//#if MIN_MATCH != 3 -// Call update_hash() MIN_MATCH-3 more times -//#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ -// if (s.high_water < s.window_size) { -// var curr = s.strstart + s.lookahead; -// var init = 0; -// -// if (s.high_water < curr) { -// /* Previous high water mark below current data -- zero WIN_INIT -// * bytes or up to end of window, whichever is less. -// */ -// init = s.window_size - curr; -// if (init > WIN_INIT) -// init = WIN_INIT; -// zmemzero(s->window + curr, (unsigned)init); -// s->high_water = curr + init; -// } -// else if (s->high_water < (ulg)curr + WIN_INIT) { -// /* High water mark at or above current data, but below current data -// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up -// * to end of window, whichever is less. -// */ -// init = (ulg)curr + WIN_INIT - s->high_water; -// if (init > s->window_size - s->high_water) -// init = s->window_size - s->high_water; -// zmemzero(s->window + s->high_water, (unsigned)init); -// s->high_water += init; -// } -// } -// -// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -// "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - var max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); -// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || -// s.block_start >= s.w_size)) { -// throw new Error("slide too late"); -// } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); -// if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - var max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -function deflate_fast(s, flush) { - var hash_head; /* head of the hash chain */ - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { - s.match_length--; /* string at strstart already in table */ do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; + }; + + + /** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ + Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); + }; + + + /** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ + Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + + + /** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ + function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; + } + + + /** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); + } + + + /** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); + } + + + exports.Deflate = Deflate; + exports.deflate = deflate; + exports.deflateRaw = deflateRaw; + exports.gzip = gzip; + + }, { "./utils/common": 28, "./utils/strings": 29, "./zlib/deflate": 33, "./zlib/messages": 38, "./zlib/zstream": 40 }], 27: [function (require, module, exports) { + 'use strict'; + + + var zlib_inflate = require('./zlib/inflate'); + var utils = require('./utils/common'); + var strings = require('./utils/strings'); + var c = require('./zlib/constants'); + var msg = require('./zlib/messages'); + var ZStream = require('./zlib/zstream'); + var GZheader = require('./zlib/gzheader'); + + var toString = Object.prototype.toString; + + /** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + + /* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + + /** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + + /** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + + /** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + + /** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ + function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } + } + + /** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ + Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; + }; + + + /** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ + Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); + }; + + + /** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ + Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + + + /** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ + function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; + } + + + /** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ + function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); + } + + + /** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + + exports.Inflate = Inflate; + exports.inflate = inflate; + exports.inflateRaw = inflateRaw; + exports.ungzip = inflate; + + }, { "./utils/common": 28, "./utils/strings": 29, "./zlib/constants": 31, "./zlib/gzheader": 34, "./zlib/inflate": 36, "./zlib/messages": 38, "./zlib/zstream": 40 }], 28: [function (require, module, exports) { + 'use strict'; + + + var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + + function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + + exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; + }; + + + // reduce buffer size, avoiding mem copy + exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; + }; + + + var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } + }; + + var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } + }; + + + // Enable/Disable typed arrays use, for testing + // + exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } + }; + + exports.setTyped(TYPED_OK); + + }, {}], 29: [function (require, module, exports) { + // String encode/decode helpers + 'use strict'; + + + var utils = require('./common'); + + + // Quick check if we can use fast array to bin string conversion + // + // - apply(Array) can fail on Android 2.2 + // - apply(Uint8Array) can fail on iOS 5.1 Safari + // + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; + + try { String.fromCharCode.apply(null, [0]); } catch (__) { STR_APPLY_OK = false; } + try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } + + + // Table with utf8 lengths (calculated by first byte of sequence) + // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, + // because max possible codepoint is 0x10ffff + var _utf8len = new utils.Buf8(256); + for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); + } + _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + + // convert string to array (typed, when possible) + exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; + }; + + // Helper (used in 2 places) + function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; + } + + + // Convert byte array to binary string + exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); + }; + + + // Convert binary string (typed, when possible) + exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; + }; + + + // convert array to string + exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); + }; + + + // Calculate max possible position in utf8 buffer, + // that will not break sequence. If that's not possible + // - (very small limits) return max size as is. + // + // buf[] - utf8 bytes array + // max - length limit (mandatory); + exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; + }; + + }, { "./common": 28 }], 30: [function (require, module, exports) { + 'use strict'; + + // Note: adler32 takes 12% for level 0 and 2% for level 6. + // It isn't worth it to make additional optimizations as in original. + // Small size is preferable. + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) | 0, + s2 = ((adler >>> 16) & 0xffff) | 0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) | 0; + s2 = (s2 + s1) | 0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) | 0; + } + + + module.exports = adler32; + + }, {}], 31: [function (require, module, exports) { + 'use strict'; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type + }; + + }, {}], 32: [function (require, module, exports) { + 'use strict'; + + // Note: we can't get significant speed boost here. + // So write code to minimize size - no pregenerated tables + // and array tools dependencies. + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + // Use ordinary array, since untyped makes no boost here + function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; + } + + // Create table on load. Just 255 signed longs. Not a problem. + var crcTable = makeTable(); + + + function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; + } + + + module.exports = crc32; + + }, {}], 33: [function (require, module, exports) { + 'use strict'; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + var utils = require('../utils/common'); + var trees = require('./trees'); + var adler32 = require('./adler32'); + var crc32 = require('./crc32'); + var msg = require('./messages'); + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ + + + /* Allowed flush values; see deflate() and inflate() below for details */ + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + //var Z_SYNC_FLUSH = 2; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + //var Z_TREES = 6; + + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + var Z_OK = 0; + var Z_STREAM_END = 1; + //var Z_NEED_DICT = 2; + //var Z_ERRNO = -1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + //var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + //var Z_VERSION_ERROR = -6; + + + /* compression levels */ + //var Z_NO_COMPRESSION = 0; + //var Z_BEST_SPEED = 1; + //var Z_BEST_COMPRESSION = 9; + var Z_DEFAULT_COMPRESSION = -1; + + + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + + /* Possible values of the data_type field (though see inflate()) */ + //var Z_BINARY = 0; + //var Z_TEXT = 1; + //var Z_ASCII = 1; // = Z_TEXT + var Z_UNKNOWN = 2; + + + /* The deflate compression method */ + var Z_DEFLATED = 8; + + /*============================================================================*/ + + + var MAX_MEM_LEVEL = 9; + /* Maximum value for memLevel in deflateInit2 */ + var MAX_WBITS = 15; + /* 32K LZ77 window */ + var DEF_MEM_LEVEL = 8; + + + var LENGTH_CODES = 29; + /* number of length codes, not counting the special END_BLOCK code */ + var LITERALS = 256; + /* number of literal bytes 0..255 */ + var L_CODES = LITERALS + 1 + LENGTH_CODES; + /* number of Literal or Length codes, including the END_BLOCK code */ + var D_CODES = 30; + /* number of distance codes */ + var BL_CODES = 19; + /* number of codes used to transfer the bit lengths */ + var HEAP_SIZE = 2 * L_CODES + 1; + /* maximum heap size */ + var MAX_BITS = 15; + /* All codes must not exceed MAX_BITS bits */ + + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + + var PRESET_DICT = 0x20; + + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + + var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ + var BS_BLOCK_DONE = 2; /* block flush performed */ + var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ + var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + + var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + + function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); + } + + function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + + /* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ + function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + + + function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); + } + + + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + + + /* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ + function putShortMSB(s, b) { + // put_byte(s, (Byte)(b >> 8)); + // put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; + } + + + /* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; + } + + + /* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. */ - } while (--s.match_length !== 0); - s.strstart++; - } else - { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; -//#if MIN_MATCH != 3 -// Call UPDATE_HASH() MIN_MATCH-3 more times -//#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - var hash_head; /* head of hash chain */ - var bflush; /* set if current block must be flushed */ - - var max_insert; - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH-1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). + /* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; + //#if MIN_MATCH != 3 + // Call update_hash() MIN_MATCH-3 more times + //#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ - s.match_length = MIN_MATCH-1; + // if (s.high_water < s.window_size) { + // var curr = s.strstart + s.lookahead; + // var init = 0; + // + // if (s.high_water < curr) { + // /* Previous high water mark below current data -- zero WIN_INIT + // * bytes or up to end of window, whichever is less. + // */ + // init = s.window_size - curr; + // if (init > WIN_INIT) + // init = WIN_INIT; + // zmemzero(s->window + curr, (unsigned)init); + // s->high_water = curr + init; + // } + // else if (s->high_water < (ulg)curr + WIN_INIT) { + // /* High water mark at or above current data, but below current data + // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + // * to end of window, whichever is less. + // */ + // init = (ulg)curr + WIN_INIT - s->high_water; + // if (init > s->window_size - s->high_water) + // init = s->window_size - s->high_water; + // zmemzero(s->window + s->high_water, (unsigned)init); + // s->high_water += init; + // } + // } + // + // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + // "not enough room for search"); } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. + /* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. */ - s.lookahead -= s.prev_length-1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; + function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (; ;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); + // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || + // s.block_start >= s.w_size)) { + // throw new Error("slide too late"); + // } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); + // if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } /***/ } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH-1; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { return BS_NEED_MORE; } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. + + /* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; -} - - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - var bflush; /* set if current block must be flushed */ - var prev; /* byte at distance one to match */ - var scan, strend; /* scan goes up to strend for length of run */ - - var _win = s.window; - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH) { - fill_window(s); - if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -function deflate_huff(s, flush) { - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -var Config = function (good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; -}; - -var configuration_table; - -configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; - - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - s.ins_h = 0; -} - - -function DeflateState() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); - this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); - this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); - zero(this.dyn_ltree); - zero(this.dyn_dtree); - zero(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new utils.Buf16(MAX_BITS+1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ - zero(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; - zero(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ -} - - -function deflateResetKeep(strm) { - var s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - trees._tr_init(s); - return Z_OK; -} - - -function deflateReset(strm) { - var ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; -} - - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; -} - - -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - var wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - var s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); - - s.window = new utils.Buf8(s.w_size * 2); - s.head = new utils.Buf16(s.hash_size); - s.prev = new utils.Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - s.pending_buf = new utils.Buf8(s.pending_buf_size); - - s.d_buf = s.lit_bufsize >> 1; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); -} - -function deflateInit(strm, level) { - return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); -} - - -function deflate(strm, flush) { - var old_flush, s; - var beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - var level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - -//#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (; ;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + + //#if MIN_MATCH != 3 + // Call UPDATE_HASH() MIN_MATCH-3 more times + //#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ } } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; } + /***/ } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); + return BS_BLOCK_DONE; + } - if (s.gzhead.hcrc && s.pending > beg){ - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } -//#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: + /* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. */ - s.last_flush = -1; - return Z_OK; - } + function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } + var max_insert; - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } + /* Process the input block. */ + for (; ;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. + + + /* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - trees._tr_align(s); + function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (; ;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - trees._tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero(s.head); // Fill with NIL (= 0); + /* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ + function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + for (; ;) { + /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; + } + + /* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + + var configuration_table; + + configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ + ]; + + + /* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ + function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + + + function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + } + + + function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; + } + + + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; + } + + + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; + } + + + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); + } + + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + + + function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + + //#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } + //#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + + function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + + + /* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); s.strstart = 0; s.block_start = 0; s.insert = 0; } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; return Z_OK; } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else - { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - var status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} - -/* ========================================================================= - * Copy the source state to the destination state - */ -//function deflateCopy(dest, source) { -// -//} - -exports.deflateInit = deflateInit; -exports.deflateInit2 = deflateInit2; -exports.deflateReset = deflateReset; -exports.deflateResetKeep = deflateResetKeep; -exports.deflateSetHeader = deflateSetHeader; -exports.deflate = deflate; -exports.deflateEnd = deflateEnd; -exports.deflateInfo = 'pako deflate (from Nodeca project)'; - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateSetDictionary = deflateSetDictionary; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ -},{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){ -'use strict'; -function GZheader() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications + exports.deflateInit = deflateInit; + exports.deflateInit2 = deflateInit2; + exports.deflateReset = deflateReset; + exports.deflateResetKeep = deflateResetKeep; + exports.deflateSetHeader = deflateSetHeader; + exports.deflate = deflate; + exports.deflateEnd = deflateEnd; + exports.deflateSetDictionary = deflateSetDictionary; + exports.deflateInfo = 'pako deflate (from Nodeca project)'; - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // + /* Not implemented + exports.deflateBound = deflateBound; + exports.deflateCopy = deflateCopy; + exports.deflateParams = deflateParams; + exports.deflatePending = deflatePending; + exports.deflatePrime = deflatePrime; + exports.deflateTune = deflateTune; + */ - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; -} + }, { "../utils/common": 28, "./adler32": 30, "./crc32": 32, "./messages": 38, "./trees": 39 }], 34: [function (require, module, exports) { + 'use strict'; -module.exports = GZheader; -},{}],34:[function(_dereq_,module,exports){ -'use strict'; + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. -// See state defs from inflate.js -var BAD = 30; /* got a data error -- remain here until reset */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -module.exports = function inflate_fast(strm, start) { - var state; - var _in; /* local strm.input */ - var last; /* have enough input while in < last */ - var _out; /* local strm.output */ - var beg; /* inflate()'s initial strm.output */ - var end; /* while out < end, enough space available */ -//#ifdef INFLATE_STRICT - var dmax; /* maximum distance from zlib header */ -//#endif - var wsize; /* window size or zero if not using window */ - var whave; /* valid bytes in the window */ - var wnext; /* window write index */ - var window; /* allocated sliding window, if wsize != 0 */ - var hold; /* local strm.hold */ - var bits; /* local strm.bits */ - var lcode; /* local strm.lencode */ - var dcode; /* local strm.distcode */ - var lmask; /* mask for first level of length codes */ - var dmask; /* mask for first level of distance codes */ - var here; /* retrieved table entry */ - var op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - var len; /* match length, unused bytes */ - var dist; /* match distance */ - var from; /* where to copy match from */ - var from_source; - - - var input, output; // JS specific, because we have no pointers - - /* copy state to local variables */ - state = strm.state; - //here = state.here; - _in = strm.next_in; - input = strm.input; - last = _in + (strm.avail_in - 5); - _out = strm.next_out; - output = strm.output; - beg = _out - (start - strm.avail_out); - end = _out + (strm.avail_out - 257); -//#ifdef INFLATE_STRICT - dmax = state.dmax; -//#endif - wsize = state.wsize; - whave = state.whave; - wnext = state.wnext; - window = state.window; - hold = state.hold; - bits = state.bits; - lcode = state.lencode; - dcode = state.distcode; - lmask = (1 << state.lenbits) - 1; - dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; } - else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { + + module.exports = GZheader; + + }, {}], 35: [function (require, module, exports) { + 'use strict'; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + // See state defs from inflate.js + var BAD = 30; /* got a data error -- remain here until reset */ + var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + + /* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ + module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ + //#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ + //#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + //#ifdef INFLATE_STRICT + dmax = state.dmax; + //#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; hold += input[_in++] << bits; bits += 8; } - len += hold & ((1 << op) - 1); - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; + here = lcode[hold & lmask]; - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { + dolen: + for (; ;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; hold += input[_in++] << bits; bits += 8; } - } - dist += hold & ((1 << op) - 1); -//#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break top; - } -//#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; + here = dcode[hold & dmask]; + + dodist: + for (; ;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); + //#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + //#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + + // (!) This block is disabled in zlib defaults, + // don't enable it for binary compatibility + //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + // if (len <= op - whave) { + // do { + // output[_out++] = 0; + // } while (--len); + // continue top; + // } + // len -= op - whave; + // do { + // output[_out++] = 0; + // } while (--op > whave); + // if (op === 0) { + // from = _out - dist; + // do { + // output[_out++] = output[from++]; + // } while (--len); + // continue top; + // } + //#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; state.mode = BAD; break top; } -// (!) This block is disabled in zlib defailts, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// if (len <= op - whave) { -// do { -// output[_out++] = 0; -// } while (--len); -// continue top; -// } -// len -= op - whave; -// do { -// output[_out++] = 0; -// } while (--op > whave); -// if (op === 0) { -// from = _out - dist; -// do { -// output[_out++] = output[from++]; -// } while (--len); -// continue top; -// } -//#endif - } - from = 0; // window index - from_source = window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } - else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } + break; // need to emulate goto via "continue" } } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; } + + break; // need to emulate goto via "continue" } - else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dodist; - } - else { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break top; - } + } while (_in < last && _out < end); - break; // need to emulate goto via "continue" - } - } - else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dolen; - } - else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } - else { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break top; - } + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; + }; - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; + }, {}], 36: [function (require, module, exports) { + 'use strict'; - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); - strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); - state.hold = hold; - state.bits = bits; - return; -}; + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. -},{}],35:[function(_dereq_,module,exports){ -'use strict'; + var utils = require('../utils/common'); + var adler32 = require('./adler32'); + var crc32 = require('./crc32'); + var inflate_fast = require('./inffast'); + var inflate_table = require('./inftrees'); + + var CODES = 0; + var LENS = 1; + var DISTS = 2; + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ -var utils = _dereq_('../utils/common'); -var adler32 = _dereq_('./adler32'); -var crc32 = _dereq_('./crc32'); -var inflate_fast = _dereq_('./inffast'); -var inflate_table = _dereq_('./inftrees'); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ + /* Allowed flush values; see deflate() and inflate() below for details */ + //var Z_NO_FLUSH = 0; + //var Z_PARTIAL_FLUSH = 1; + //var Z_SYNC_FLUSH = 2; + //var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; -/* Allowed flush values; see deflate() and inflate() below for details */ -//var Z_NO_FLUSH = 0; -//var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -//var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -var Z_TREES = 6; + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + //var Z_ERRNO = -1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + //var Z_VERSION_ERROR = -6; + + /* The deflate compression method */ + var Z_DEFLATED = 8; -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - -/* The deflate compression method */ -var Z_DEFLATED = 8; + /* STATES ====================================================================*/ + /* ===========================================================================*/ -/* STATES ====================================================================*/ -/* ===========================================================================*/ + var HEAD = 1; /* i: waiting for magic header */ + var FLAGS = 2; /* i: waiting for method and flags (gzip) */ + var TIME = 3; /* i: waiting for modification time (gzip) */ + var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ + var EXLEN = 5; /* i: waiting for extra length (gzip) */ + var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ + var NAME = 7; /* i: waiting for end of file name (gzip) */ + var COMMENT = 8; /* i: waiting for end of comment (gzip) */ + var HCRC = 9; /* i: waiting for header crc (gzip) */ + var DICTID = 10; /* i: waiting for dictionary check value */ + var DICT = 11; /* waiting for inflateSetDictionary() call */ + var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ + var STORED = 14; /* i: waiting for stored size (length and complement) */ + var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ + var COPY = 16; /* i/o: waiting for input or output to copy stored block */ + var TABLE = 17; /* i: waiting for dynamic block table lengths */ + var LENLENS = 18; /* i: waiting for code length code lengths */ + var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ + var LEN_ = 20; /* i: same as LEN below, but only first time in */ + var LEN = 21; /* i: waiting for length/lit/eob code */ + var LENEXT = 22; /* i: waiting for length extra bits */ + var DIST = 23; /* i: waiting for distance code */ + var DISTEXT = 24; /* i: waiting for distance extra bits */ + var MATCH = 25; /* o: waiting for output space to copy string */ + var LIT = 26; /* o: waiting for output space to write literal */ + var CHECK = 27; /* i: waiting for 32-bit check value */ + var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ + var DONE = 29; /* finished check, done -- remain here until reset */ + var BAD = 30; /* got a data error -- remain here until reset */ + var MEM = 31; /* got an inflate() memory error -- remain here until reset */ + var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -var HEAD = 1; /* i: waiting for magic header */ -var FLAGS = 2; /* i: waiting for method and flags (gzip) */ -var TIME = 3; /* i: waiting for modification time (gzip) */ -var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -var EXLEN = 5; /* i: waiting for extra length (gzip) */ -var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -var NAME = 7; /* i: waiting for end of file name (gzip) */ -var COMMENT = 8; /* i: waiting for end of comment (gzip) */ -var HCRC = 9; /* i: waiting for header crc (gzip) */ -var DICTID = 10; /* i: waiting for dictionary check value */ -var DICT = 11; /* waiting for inflateSetDictionary() call */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ -var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -var STORED = 14; /* i: waiting for stored size (length and complement) */ -var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -var COPY = 16; /* i/o: waiting for input or output to copy stored block */ -var TABLE = 17; /* i: waiting for dynamic block table lengths */ -var LENLENS = 18; /* i: waiting for code length code lengths */ -var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -var LEN_ = 20; /* i: same as LEN below, but only first time in */ -var LEN = 21; /* i: waiting for length/lit/eob code */ -var LENEXT = 22; /* i: waiting for length extra bits */ -var DIST = 23; /* i: waiting for distance code */ -var DISTEXT = 24; /* i: waiting for distance extra bits */ -var MATCH = 25; /* o: waiting for output space to copy string */ -var LIT = 26; /* o: waiting for output space to write literal */ -var CHECK = 27; /* i: waiting for 32-bit check value */ -var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -var DONE = 29; /* finished check, done -- remain here until reset */ -var BAD = 30; /* got a data error -- remain here until reset */ -var MEM = 31; /* got an inflate() memory error -- remain here until reset */ -var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ + /* ===========================================================================*/ -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_WBITS = MAX_WBITS; + var MAX_WBITS = 15; + /* 32K LZ77 window */ + var DEF_WBITS = MAX_WBITS; -function ZSWAP32(q) { - return (((q >>> 24) & 0xff) + + function zswap32(q) { + return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); -} - - -function InflateState() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ - this.work = new utils.Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ -} - -function inflateResetKeep(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); - state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -function inflateReset(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - -} - -function inflateReset2(strm, windowBits) { - var wrap; - var state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); -} - -function inflateInit2(strm, windowBits) { - var ret; - var state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; -} - -function inflateInit(strm) { - return inflateInit2(strm, DEF_WBITS); -} - - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -var virgin = true; - -var lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - var sym; - - lenfix = new utils.Buf32(512); - distfix = new utils.Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; -} - - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - var dist; - var state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new utils.Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - utils.arraySet(state.window,src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - utils.arraySet(state.window,src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; -} - -function inflate(strm, flush) { - var state; - var input, output; // input/output buffers - var next; /* next input INDEX */ - var put; /* next output INDEX */ - var have, left; /* available input and output */ - var hold; /* bit buffer */ - var bits; /* bits in bit buffer */ - var _in, _out; /* save starting available input and output */ - var copy; /* number of stored or match bytes to copy */ - var from; /* where to copy match bytes from */ - var from_source; - var here = 0; /* current decoding table entry */ - var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - var len; /* length to copy for repeats, bits to drop */ - var ret; /* return code */ - var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ - var opts; - - var n; // temporary var for NEED_BITS - - var order = /* permutation of code lengths */ - [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; + + function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; + + function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more conveniend processing later - state.head.extra = new Array(state.head.extra_len); - } - utils.arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; - state.mode = TYPE; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = ZSWAP32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE; - /* falls through */ - case TYPE: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - utils.arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; + function inflateReset(strm) { + var state; - opts = {bits: state.lenbits}; - ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD; - break; } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; + function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; } else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - while (copy--) { - state.lens[state.have++] = len; + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; } } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); } - /* handle error breaks in while */ - if (state.mode === BAD) { break; } + function inflateInit2(strm, windowBits) { + var ret; + var state; - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD; - break; + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; } - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = {bits: state.lenbits}; - ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD; - break; + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); } - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = {bits: state.distbits}; - ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD; - break; + /* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ + var virgin = true; + + var lenfix, distfix; // We have no pointers in JS, so keep tables separate + + function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); + + + /* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; + } + + function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + //--- LOAD() --- put = strm.next_out; output = strm.output; @@ -7182,1974 +6936,2785 @@ function inflate(strm, flush) { bits = state.bits; //--- - if (state.mode === TYPE) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + _in = have; + _out = left; + ret = Z_OK; - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + inf_leave: // goto emulation + for (; ;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + //#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } + //#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (; ;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (; ;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (; ;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (; ;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } + //#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } + // (!) This block is disabled in zlib defaults, + // don't enable it for binary compatibility + //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + // Trace((stderr, "inflate.c too far\n")); + // copy -= state.whave; + // if (copy > state.length) { copy = state.length; } + // if (copy > left) { copy = left; } + // left -= copy; + // state.length -= copy; + // do { + // output[put++] = 0; + // } while (--copy); + // if (state.length === 0) { state.mode = LEN; } + // break; + //#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; } -// (!) This block is disabled in zlib defailts, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' insdead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; strm.total_out += _out; state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } - _out = left; - // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too - if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD; - break; + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); + return ret; } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; + + function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD; - break; + + var state = strm.state; + if (state.window) { + state.window = null; } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD: - ret = Z_DATA_ERROR; - break inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { - state.mode = MEM; - return Z_MEM_ERROR; - } - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; -} - -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - var state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; -} - -function inflateGetHeader(strm, head) { - var state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; -} - - -exports.inflateReset = inflateReset; -exports.inflateReset2 = inflateReset2; -exports.inflateResetKeep = inflateResetKeep; -exports.inflateInit = inflateInit; -exports.inflateInit2 = inflateInit2; -exports.inflate = inflate; -exports.inflateEnd = inflateEnd; -exports.inflateGetHeader = inflateGetHeader; -exports.inflateInfo = 'pako inflate (from Nodeca project)'; - -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSetDictionary = inflateSetDictionary; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ -},{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){ -'use strict'; - - -var utils = _dereq_('../utils/common'); - -var MAXBITS = 15; -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -var lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -var lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -var dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -var dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) -{ - var bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - var len = 0; /* a code's length in bits */ - var sym = 0; /* index of code symbols */ - var min = 0, max = 0; /* minimum and maximum code lengths */ - var root = 0; /* number of index bits for root table */ - var curr = 0; /* number of index bits for current table */ - var drop = 0; /* code bits to drop for sub-table */ - var left = 0; /* number of prefix codes available */ - var used = 0; /* code entries in table used */ - var huff = 0; /* Huffman code */ - var incr; /* for incrementing code, index */ - var fill; /* index for replicating entries */ - var low; /* low bits for current root entry */ - var mask; /* mask for low root bits */ - var next; /* next available space in table */ - var base = null; /* base value table to use */ - var base_index = 0; -// var shoextra; /* extra bits table to use */ - var end; /* use base and extra for symbol > end */ - var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ - var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ - var extra = null; - var extra_index = 0; - - var here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { break; } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { break; } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } - - var i=0; - /* process all codes and make table entries */ - for (;;) { - i++; - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } - else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } - else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << (len - drop); - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << (len - 1); - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { break; } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; + strm.state = null; + return Z_OK; } - /* increment past last table */ - next += min; /* here min is 1 << curr */ + function inflateGetHeader(strm, head) { + var state; - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { break; } - curr++; - left <<= 1; + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; } - /* check for enough space */ - used += 1 << curr; - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; - } - } + var state; + var dictid; + var ret; - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; - } + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -}; - -},{"../utils/common":27}],37:[function(_dereq_,module,exports){ -'use strict'; - -module.exports = { - '2': 'need dictionary', /* Z_NEED_DICT 2 */ - '1': 'stream end', /* Z_STREAM_END 1 */ - '0': '', /* Z_OK 0 */ - '-1': 'file error', /* Z_ERRNO (-1) */ - '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ - '-3': 'data error', /* Z_DATA_ERROR (-3) */ - '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ - '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ - '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ -}; -},{}],38:[function(_dereq_,module,exports){ -'use strict'; - - -var utils = _dereq_('../utils/common'); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -//var Z_FILTERED = 1; -//var Z_HUFFMAN_ONLY = 2; -//var Z_RLE = 3; -var Z_FIXED = 4; -//var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -var Z_BINARY = 0; -var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - -/*============================================================================*/ - - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - -// From zutil.h - -var STORED_BLOCK = 0; -var STATIC_TREES = 1; -var DYN_TREES = 2; -/* The three kinds of block type */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -/* The minimum and maximum match lengths */ - -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ - -var LITERALS = 256; -/* number of literal bytes 0..255 */ - -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ - -var D_CODES = 30; -/* number of distance codes */ - -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ - -var HEAP_SIZE = 2*L_CODES + 1; -/* maximum heap size */ - -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var Buf_size = 16; -/* size of bit buffer in bi_buf */ - - -/* =========================================================================== - * Constants - */ - -var MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -var END_BLOCK = 256; -/* end of block literal code */ - -var REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -var REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -var REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -var extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - -var extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - -var extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - -var bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -// We pre-fill arrays with 0 to avoid uninitialized gaps - -var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - -// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 -var static_ltree = new Array((L_CODES+2) * 2); -zero(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -var static_dtree = new Array(D_CODES * 2); -zero(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -var _dist_code = new Array(DIST_CODE_LEN); -zero(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); -zero(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -var base_length = new Array(LENGTH_CODES); -zero(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -var base_dist = new Array(D_CODES); -zero(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; -}; - - -var static_l_desc; -var static_d_desc; -var static_bl_desc; - - -var TreeDesc = function(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ -}; - - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; -} - - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -function put_short (s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = (w) & 0xff; - s.pending_buf[s.pending++] = (w >>> 8) & 0xff; -} - - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -function send_bits(s, value, length) { - if (s.bi_valid > (Buf_size - length)) { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> (Buf_size - s.bi_valid); - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); -} - - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -function bi_reverse(code, len) { - var res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var max_code = desc.max_code; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var extra = desc.stat_desc.extra_bits; - var base = desc.stat_desc.extra_base; - var max_length = desc.stat_desc.max_length; - var h; /* heap index */ - var n, m; /* iterate over the tree elements */ - var bits; /* bit length */ - var xbits; /* extra bits */ - var f; /* frequency */ - var overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max+1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n*2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { continue; } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n-base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { return; } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length-1; - while (s.bl_count[bits] === 0) { bits--; } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { continue; } - if (tree[m*2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; - tree[m*2 + 1]/*.Len*/ = bits; - } - n--; - } - } -} - - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ - var code = 0; /* running code value */ - var bits; /* bit index */ - var n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits-1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, - // "inconsistent bit counts"); - //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); - - for (n = 0; n <= max_code; n++) { - var len = tree[n*2 + 1]/*.Len*/; - if (len === 0) { continue; } - /* Now reverse the bits */ - tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); - - //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", - // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); - } -} - - -/* =========================================================================== - * Initialize the various 'constant' tables. - */ -function tr_static_init() { - var n; /* iterates over tree elements */ - var bits; /* bit counter */ - var length; /* length value */ - var code; /* code value */ - var dist; /* distance index */ - var bl_count = new Array(MAX_BITS+1); - /* number of codes at each bit length for an optimal tree */ - - // do check in _tr_init() - //if (static_init_done) return; - - /* For some embedded targets, global variables are not initialized: */ -/*#ifdef NO_INIT_GLOBAL_POINTERS - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; -#endif*/ - - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; - for (n = 0; n < (1<<extra_lbits[code]); n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length-1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1<<extra_dbits[code]); n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n*2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n*2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n*2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n*2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES+1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n*2 + 1]/*.Len*/ = 5; - static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - var n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } - for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } - for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } - - s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) -{ - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } -// while (len--) { -// put_byte(s, *buf++); -// } - utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - var _n2 = n*2; - var _m2 = m*2; - return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - var v = s.heap[k]; - var j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { break; } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; -} - - -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - var dist; /* distance of matched string */ - var lc; /* match length or unmatched char (if dist == 0) */ - var lx = 0; /* running index in l_buf */ - var code; /* the code to send */ - var extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code+LITERALS+1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); -} - - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var elems = desc.stat_desc.elems; - var n, m; /* iterate over heap elements */ - var max_code = -1; /* largest code with non zero frequency */ - var node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n*2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node*2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); -} - - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n+1)*2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } - s.bl_tree[REP_3_6*2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10*2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138*2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n+1)*2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count-3, 2); - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count-3, 3); + exports.inflateReset = inflateReset; + exports.inflateReset2 = inflateReset2; + exports.inflateResetKeep = inflateResetKeep; + exports.inflateInit = inflateInit; + exports.inflateInit2 = inflateInit2; + exports.inflate = inflate; + exports.inflateEnd = inflateEnd; + exports.inflateGetHeader = inflateGetHeader; + exports.inflateSetDictionary = inflateSetDictionary; + exports.inflateInfo = 'pako inflate (from Nodeca project)'; - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count-11, 7); - } + /* Not implemented + exports.inflateCopy = inflateCopy; + exports.inflateGetDictionary = inflateGetDictionary; + exports.inflateMark = inflateMark; + exports.inflatePrime = inflatePrime; + exports.inflateSync = inflateSync; + exports.inflateSyncPoint = inflateSyncPoint; + exports.inflateUndermine = inflateUndermine; + */ - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; + }, { "../utils/common": 28, "./adler32": 30, "./crc32": 32, "./inffast": 35, "./inftrees": 37 }], 37: [function (require, module, exports) { + 'use strict'; - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. - } else { - max_count = 7; - min_count = 4; - } - } -} + var utils = require('../utils/common'); + + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + + var CODES = 0; + var LENS = 1; + var DISTS = 2; + + var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 + ]; + + var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 + ]; + + var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 + ]; + + var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 + ]; + + module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; + // var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - var max_blindex; /* index of last bit length code of non zero freq */ + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3*(max_blindex+1) + 5+5+4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } - return max_blindex; -} + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (; ;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val | 0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) | 0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) | 0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; + }; + + }, { "../utils/common": 28 }], 38: [function (require, module, exports) { + 'use strict'; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ + }; + + }, {}], 39: [function (require, module, exports) { + 'use strict'; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + /* eslint-disable space-unary-ops */ + + var utils = require('../utils/common'); + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - var rank; /* index in bl_order */ + //var Z_FILTERED = 1; + //var Z_HUFFMAN_ONLY = 2; + //var Z_RLE = 3; + var Z_FIXED = 4; + //var Z_DEFAULT_STRATEGY = 0; - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes-1, 5); - send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + /* Possible values of the data_type field (though see inflate()) */ + var Z_BINARY = 0; + var Z_TEXT = 1; + //var Z_ASCII = 1; // = Z_TEXT + var Z_UNKNOWN = 2; - send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} + /*============================================================================*/ -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - var black_mask = 0xf3ffc07f; - var n; + function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { - return Z_BINARY; - } - } + // From zutil.h - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + /* The three kinds of block type */ - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} + var MIN_MATCH = 3; + var MAX_MATCH = 258; + /* The minimum and maximum match lengths */ + + // From deflate.h + /* =========================================================================== + * Internal compression state. + */ + + var LENGTH_CODES = 29; + /* number of length codes, not counting the special END_BLOCK code */ + + var LITERALS = 256; + /* number of literal bytes 0..255 */ + + var L_CODES = LITERALS + 1 + LENGTH_CODES; + /* number of Literal or Length codes, including the END_BLOCK code */ + + var D_CODES = 30; + /* number of distance codes */ + + var BL_CODES = 19; + /* number of codes used to transfer the bit lengths */ + + var HEAP_SIZE = 2 * L_CODES + 1; + /* maximum heap size */ + + var MAX_BITS = 15; + /* All codes must not exceed MAX_BITS bits */ + + var Buf_size = 16; + /* size of bit buffer in bi_buf */ -var static_init_done = false; + /* =========================================================================== + * Constants + */ -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -function _tr_init(s) -{ + var MAX_BL_BITS = 7; + /* Bit length codes must not exceed MAX_BL_BITS bits */ - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } + var END_BLOCK = 256; + /* end of block literal code */ - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + var REP_3_6 = 16; + /* repeat previous bit length 3-6 times (2 bits of repeat count) */ - s.bi_buf = 0; - s.bi_valid = 0; + var REPZ_3_10 = 17; + /* repeat a zero length 3-10 times (3 bits of repeat count) */ - /* Initialize the first block of the first file: */ - init_block(s); -} + var REPZ_11_138 = 18; + /* repeat a zero length 11-138 times (7 bits of repeat count) */ + + /* eslint-disable comma-spacing,array-bracket-spacing */ + var extra_lbits = /* extra bits for each length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]; + + var extra_dbits = /* extra bits for each distance code */ + [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]; + + var extra_blbits = /* extra bits for each bit length code */ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; + + var bl_order = + [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + /* eslint-enable comma-spacing,array-bracket-spacing */ + + /* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + + /* =========================================================================== + * Local data. These are initialized only once. + */ + + // We pre-fill arrays with 0 to avoid uninitialized gaps + + var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + + // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + /* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + /* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + /* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + /* length code for each normalized match length (0 == MIN_MATCH) */ + + var base_length = new Array(LENGTH_CODES); + zero(base_length); + /* First normalized length for each code (0 = MIN_MATCH) */ + + var base_dist = new Array(D_CODES); + zero(base_dist); + /* First normalized distance for each code (0 = distance of 1) */ -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; + } -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); -} + var static_l_desc; + var static_d_desc; + var static_bl_desc; -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - var max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s.opt_len+3+7) >>> 3; - static_lenb = (s.static_len+3+7) >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc*2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - -// (!) This block is disabled in zlib defailts, -// don't enable it for binary compatibility - -//#ifdef TRUNCATE_BLOCK -// /* Try to guess if it is profitable to stop the current block here */ -// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { -// /* Compute an upper bound for the compressed length */ -// out_length = s.last_lit*8; -// in_length = s.strstart - s.block_start; -// -// for (dcode = 0; dcode < D_CODES; dcode++) { -// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); -// } -// out_length >>>= 3; -// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", -// // s->last_lit, in_length, out_length, -// // 100L - out_length*100L/in_length)); -// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { -// return true; -// } -// } -//#endif - - return (s.last_lit === s.lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -exports._tr_init = _tr_init; -exports._tr_stored_block = _tr_stored_block; -exports._tr_flush_block = _tr_flush_block; -exports._tr_tally = _tr_tally; -exports._tr_align = _tr_align; -},{"../utils/common":27}],39:[function(_dereq_,module,exports){ -'use strict'; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ + } -function ZStream() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; -} -module.exports = ZStream; -},{}]},{},[9]) -(9) + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + + + /* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ + function put_short(s, w) { + // put_byte(s, (uch)((w) & 0xff)); + // put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; + } + + + /* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ + function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } + } + + + function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); + } + + + /* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + + + /* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + + + /* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ + function gen_bitlen(s, desc) + // deflate_state *s; + // tree_desc *desc; /* the tree descriptor */ + { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } + } + + + /* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ + function gen_codes(tree, max_code, bl_count) + // ct_data *tree; /* the tree to decorate */ + // int max_code; /* largest code with non zero frequency */ + // ushf *bl_count; /* number of codes at each bit length */ + { + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, + // "inconsistent bit counts"); + //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + var len = tree[n * 2 + 1]/*.Len*/; + if (len === 0) { continue; } + /* Now reverse the bits */ + tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); + + //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); + } + } + + + /* =========================================================================== + * Initialize the various 'constant' tables. + */ + function tr_static_init() { + var n; /* iterates over tree elements */ + var bits; /* bit counter */ + var length; /* length value */ + var code; /* code value */ + var dist; /* distance index */ + var bl_count = new Array(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + // do check in _tr_init() + //if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ + /*#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; + #endif*/ + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; + } + + + /* =========================================================================== + * Initialize a new block. + */ + function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + + + /* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + + /* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ + function copy_block(s, buf, len, header) + //DeflateState *s; + //charf *buf; /* the input data */ + //unsigned len; /* its length */ + //int header; /* true if block header must be written */ + { + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } + // while (len--) { + // put_byte(s, *buf++); + // } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + + /* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); + } + + /* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ + function pqdownheap(s, tree, k) + // deflate_state *s; + // ct_data *tree; /* the tree to restore */ + // int k; /* node to move down */ + { + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; + } + + + // inlined manually + // var SMALLEST = 1; + + /* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ + function compress_block(s, ltree, dtree) + // deflate_state *s; + // const ct_data *ltree; /* literal tree */ + // const ct_data *dtree; /* distance tree */ + { + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); + } + + + /* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ + function build_tree(s, desc) + // deflate_state *s; + // tree_desc *desc; /* the tree descriptor */ + { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); + } + + + /* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ + function scan_tree(s, tree, max_code) + // deflate_state *s; + // ct_data *tree; /* the tree to be scanned */ + // int max_code; /* and its largest code of non zero frequency */ + { + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } + } + + + /* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ + function send_tree(s, tree, max_code) + // deflate_state *s; + // ct_data *tree; /* the tree to be scanned */ + // int max_code; /* and its largest code of non zero frequency */ + { + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } + } + + + /* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ + function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; + } + + + /* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ + function send_all_trees(s, lcodes, dcodes, blcodes) + // deflate_state *s; + // int lcodes, dcodes, blcodes; /* number of codes for each tree */ + { + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); + } + + + /* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ + function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; + } + + + var static_init_done = false; + + /* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ + function _tr_init(s) { + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); + } + + + /* =========================================================================== + * Send a stored block + */ + function _tr_stored_block(s, buf, stored_len, last) + //DeflateState *s; + //charf *buf; /* input block */ + //ulg stored_len; /* length of input block */ + //int last; /* one if this is the last block for a file */ + { + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ + } + + + /* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + + + /* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ + function _tr_flush_block(s, buf, stored_len, last) + //DeflateState *s; + //charf *buf; /* input block, or NULL if too old */ + //ulg stored_len; /* length of input block */ + //int last; /* one if this is the last block for a file */ + { + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); + } + + /* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ + function _tr_tally(s, dist, lc) + // deflate_state *s; + // unsigned dist; /* distance of matched string */ + // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ + { + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + + // (!) This block is disabled in zlib defaults, + // don't enable it for binary compatibility + + //#ifdef TRUNCATE_BLOCK + // /* Try to guess if it is profitable to stop the current block here */ + // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { + // /* Compute an upper bound for the compressed length */ + // out_length = s.last_lit*8; + // in_length = s.strstart - s.block_start; + // + // for (dcode = 0; dcode < D_CODES; dcode++) { + // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); + // } + // out_length >>>= 3; + // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + // // s->last_lit, in_length, out_length, + // // 100L - out_length*100L/in_length)); + // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { + // return true; + // } + // } + //#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ + } + + exports._tr_init = _tr_init; + exports._tr_stored_block = _tr_stored_block; + exports._tr_flush_block = _tr_flush_block; + exports._tr_tally = _tr_tally; + exports._tr_align = _tr_align; + + }, { "../utils/common": 28 }], 40: [function (require, module, exports) { + 'use strict'; + + // (C) 1995-2013 Jean-loup Gailly and Mark Adler + // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; + } + + module.exports = ZStream; + + }, {}] + }, {}, [10])(10) }); diff --git a/game/pinyinjs.js b/game/pinyinjs.js index c65dbbe08..18071ddb5 100644 --- a/game/pinyinjs.js +++ b/game/pinyinjs.js @@ -41588,6 +41588,10 @@ var pinyin_dict_withtone = "yī,dīng zhēng,kǎo qiǎo yú,qī,shàng,xià,hǎn * @param splitter 返回结果拼接字符 */ function parsePolyphone(chinese, result, splitter, withtone) { + // 先删除中文字符之外的所有字符(包括英文字母、数字、标点符号、空格和其他非中文字符),然后再查找多音字 + chinese = chinese.replace(/[^\u4e00-\u9fa5]/g, ''); + if(chinese.length == 0) return result; + var poly = window.pinyin_dict_polyphone; var max = 7; // 最多只考虑7个汉字的多音字词,虽然词库里面有10个字的,但是数量非常少,为了整体效率暂时忽略之 var temp = poly[chinese]; @@ -41604,10 +41608,6 @@ var pinyin_dict_withtone = "yī,dīng zhēng,kǎo qiǎo yú,qī,shàng,xià,hǎn for (var i = 0; i < chinese.length;(i++,m++)) { temp = ''; for (var j = 0; j < max && (i + j) < chinese.length; j++) { - if (!dict.withtone[chinese[i]]) { - i+=(result[m].length-1); - break; - } // 如果碰到非汉字直接停止本次查找 temp += chinese[i + j]; var res = poly[temp]; if (res) // 如果找到了多音字词语 diff --git a/game/typescript.js b/game/typescript.js index 2d4d442e2..012c4cf1a 100644 --- a/game/typescript.js +++ b/game/typescript.js @@ -172279,4 +172279,7 @@ ${e.message}`; })(); if (typeof module !== "undefined" && module.exports) { module.exports = ts; +} +if (typeof globalThis !== "undefined") { + globalThis.ts = ts; } \ No newline at end of file diff --git a/image/character/caofang.jpg b/image/character/caofang.jpg new file mode 100644 index 000000000..85f2478f3 Binary files /dev/null and b/image/character/caofang.jpg differ diff --git a/image/character/clan_wangguang.jpg b/image/character/clan_wangguang.jpg new file mode 100644 index 000000000..234b93828 Binary files /dev/null and b/image/character/clan_wangguang.jpg differ diff --git a/image/character/clan_wanglun.jpg b/image/character/clan_wanglun.jpg index 201acdbd9..401986278 100644 Binary files a/image/character/clan_wanglun.jpg and b/image/character/clan_wanglun.jpg differ diff --git a/image/character/gz_gaoshun.jpg b/image/character/gz_gaoshun.jpg new file mode 100644 index 000000000..f929139c0 Binary files /dev/null and b/image/character/gz_gaoshun.jpg differ diff --git a/image/character/ol_wangyi.jpg b/image/character/ol_wangyi.jpg new file mode 100644 index 000000000..ae25c71a8 Binary files /dev/null and b/image/character/ol_wangyi.jpg differ diff --git a/index.html b/index.html index 26ccba872..4fa7ada28 100755 --- a/index.html +++ b/index.html @@ -7,6 +7,29 @@ <meta name="viewport" content="user-scalable=no, viewport-fit=cover"> <title>无名杀 +