diff --git a/.gitignore b/.gitignore index d614c80..09e96ef 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ server/data/ +tmp/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..ea4c2a2 --- /dev/null +++ b/README.md @@ -0,0 +1,91 @@ +# 实习工作日志(daywork) + +面向实习生的个人工作管理工具:考勤打卡、工作记录、周报总结、备忘录、加密密码库、差旅记账。多端(桌面 / 网页 / 安卓)使用同一云端账号,数据实时互通。 + +- 在线实例:https://daywk.linyux.cn (网页版即应用本体,可安装为 PWA) +- 代码仓库:https://gitea.linyux.cn/root/daywork +- 设计方案:[docs/实习工作日志系统-设计方案.md](docs/实习工作日志系统-设计方案.md) +- 发布记录:[docs/release-notes-v0.2.0.md](docs/release-notes-v0.2.0.md) + +## 架构 + +**服务器是唯一数据权威,各端只保留实时缓存。** + +``` +桌面(Electron) ─┐ +网页(PWA) ─┼─ 写:立即推送差异 → 服务器确认 → 返回权威快照 → 本地缓存重建 +安卓(Capacitor)─┘ 读:启动 / SSE 通知 / 60s 兜底 → 全量刷新缓存 + │ + ▼ + 同步服务器(零依赖 Node,JSON 文件存储,每日自动备份) + · 注册表:用户名 + PBKDF2 哈希(角色:xionglin 为管理员) + · 业务数据:按用户隔离的九张表(project / work_log / log_item / + attendance / weekly_note / setting / memo / credential / transaction) +``` + +要点: + +- **无合并逻辑**:本地缓存永远等于服务器快照,从结构上消灭双端分歧 +- **密码库端到端加密**:主密码 PBKDF2 派生 AES-256-GCM 密钥在本机加解密,服务器只见密文 +- **登录密码不上传明文**:服务端仅存 PBKDF2 哈希;本机存自动登录凭据(可清除) +- **用户管理**:管理员账号 xionglin 可在应用内新建 / 重置密码 / 删除用户(服务端鉴权) + +## 功能 + +打卡(上下班、自动改时、补卡、休假、地点预设)· 工作日志(结构化条目、里程碑、待跟进)· 日历视图 · 统计 · 周报与 AI 润色(可选配置)· 周记提醒 · 备忘录 · 加密密码库 · 记账(报销跟踪)· 全局搜索 · JSON/CSV 备份导入导出 · 用户管理(管理员) + +## 仓库结构 + +``` +├─ intern-log/ 客户端(Vue 3 + TS + Vite + Dexie) +│ ├─ src/ 业务源码(views / components / db / sync / domain / lib) +│ ├─ electron/ 桌面壳(Electron 主进程 + 预加载) +│ ├─ android/ Capacitor 安卓工程 +│ ├─ dist/ 网页构建产物(服务端容器直接托管,故随仓库提交) +│ ├─ release/ 打包产物(不入库,见 .gitignore) +│ └─ repro/ 开发验证脚本(同步引擎回归、协议审计、单测) +├─ server/ 同步服务端(零依赖 node:http + JSON 存储) +│ ├─ index.js 全部服务端逻辑(认证 / 同步 / SSE / 用户管理 / 备份) +│ ├─ Dockerfile / docker-compose.yml +│ └─ DEPLOY.md 部署手册(域名 / Caddy / 运维) +└─ docs/ 设计方案与发布记录 +``` + +## 开发 + +```bash +cd intern-log +pnpm install +pnpm dev # http://localhost:5173 +pnpm build # 产出 dist/(服务端容器托管的就是它) +``` + +桌面打包:`pnpm dist`(产物 release/InternLog-Setup-*.exe) +安卓打包:`pnpm build && npx cap sync android`,然后 `android/gradlew.bat assembleDebug` + +## 测试(本地验证脚本,位于 intern-log/repro/) + +```bash +# 起本地同步服务后运行: +node repro/protocol-audit.mjs # 服务端协议审计(认证/九表/LWW/墓碑/SSE/备份) +node repro/admin-audit.mjs # 用户管理审计 +# 引擎级测试需先 esbuild 打包(详见脚本头部注释): +# two-device.ts 双设备端到端回归 +# engine-realtime.ts 实时链路(写入自动推送 + SSE 自动拉取) +# unit-tests.ts 纯函数单测(日期/考勤/加密) +``` + +## 部署 + +见 [server/DEPLOY.md](server/DEPLOY.md)。更新流程: + +```bash +cd /opt/daywork && git pull && cd server && docker compose up -d --build +``` + +## 安全与隐私 + +- 登录密码、云端密码:仅 PBKDF2(15 万次迭代)哈希,任何一端不存明文 +- 密码库:AES-256-GCM,主密钥仅存在于解锁后的内存,主密码永不出机 +- 服务端每日自动备份到 server/data/backups/(保留 14 天),注册表变更即触发备份 +- 界面无表情符号,图标全部自绘 SVG diff --git a/RELEASE_NOTES_v0.1.0.md b/docs/release-notes-v0.1.0.md similarity index 100% rename from RELEASE_NOTES_v0.1.0.md rename to docs/release-notes-v0.1.0.md diff --git a/RELEASE_NOTES_v0.2.0.md b/docs/release-notes-v0.2.0.md similarity index 100% rename from RELEASE_NOTES_v0.2.0.md rename to docs/release-notes-v0.2.0.md diff --git a/实习工作日志系统-设计方案.md b/docs/实习工作日志系统-设计方案.md similarity index 100% rename from 实习工作日志系统-设计方案.md rename to docs/实习工作日志系统-设计方案.md diff --git a/intern-log/.gitignore b/intern-log/.gitignore index 133a48e..bd47215 100644 --- a/intern-log/.gitignore +++ b/intern-log/.gitignore @@ -1,5 +1,6 @@ node_modules/ release/ +repro/*.cjs *.local android/.gradle/ android/build/ diff --git a/intern-log/README.md b/intern-log/README.md index f993144..ac4ee0d 100644 --- a/intern-log/README.md +++ b/intern-log/README.md @@ -1,33 +1,42 @@ -# 实习工作日志 +# intern-log 客户端 -本地优先的实习工作记录工具:考勤打卡、月历、随手记、周记、一键生成总结。 +实习工作日志的多端客户端(网页 / Electron 桌面 / Capacitor 安卓共用同一套源码)。 -对应设计方案文档:实习工作日志系统-设计方案.md +整体架构、部署与安全设计见仓库根目录 [README](../README.md);设计方案见 [docs/实习工作日志系统-设计方案.md](../docs/实习工作日志系统-设计方案.md)。 ## 运行 pnpm install pnpm dev # 开发模式,默认 http://localhost:5173 - pnpm build # 构建产物到 dist/ + pnpm build # 构建产物到 dist/(服务端容器托管的就是它) pnpm preview # 预览构建产物,默认 http://localhost:4173 -## 说明 +## 数据模型(重要) -- 技术栈:Vue 3 + TypeScript + Vite + Dexie(IndexedDB),无后端、无外部图标库 -- 数据保存在浏览器 IndexedDB(数据库名 intern_worklog) -- 「设置」页可导出/导入 JSON 全量备份;「总结」页可导出 Markdown -- 支持上班地点记录(公司、客户现场、出差等),可直接输入自定义地点并自动记住,统计与总结含地点分布 -- 打卡时间支持行内直接修改(含补录下班时间),考勤状态自动重算 -- 表单带标签与必填校验;删除与备份覆盖导入使用统一确认弹窗;操作结果轻提示反馈 -- 工作记录支持弹窗完整信息编辑(全部字段),点击条目或编辑图标打开 -- 备忘录:双栏列表与编辑,未保存修改有守卫 -- 密码库:企业账号密码管理,主密码 PBKDF2 派生 AES-256-GCM 加密,支持解锁、锁定、搜索、复制、随机密码生成、修改主密码;备份文件中密码保持密文 -- 用户系统:每位用户独立 IndexedDB 数据库隔离存储;登录密码仅存 PBKDF2 哈希;30 分钟无操作自动退出;创建用户时可迁移升级前数据 -- 记账系统:支出/收入记录、报销跟踪(面向出差垫付)、月度汇总与分类分布 -- 多端同步:自建同步服务端(server 目录,Docker 部署见 server/DEPLOY.md),设置页配置后桌面、网页、手机 PWA 数据互通;密码库以密文同步 -- 安卓应用:Capacitor 脚手架已就绪,本机构建 APK 需 Android Studio:pnpm build && npx cap sync android,进入 android 目录执行 gradlew assembleDebug -- PWA:在 Edge/Chrome 中打开后,地址栏右侧点「安装」或菜单选择「将此站点作为应用安装」,即可获得独立窗口与桌面图标,离线可用 -- Electron 桌面版:pnpm dist 产出 release/InternLog-Setup-<版本>.exe(NSIS 安装包)与 release/win-unpacked/InternLog.exe(免安装版);数据存于系统用户目录,与浏览器数据互不影响 -- 全局搜索:Ctrl+K 唤起,覆盖工作记录与备忘录,点击结果跳转定位 -- 考勤支持休假标记;支持导出工作记录与考勤 CSV;总结草稿可复制、可 AI 润色(设置页配置 OpenAI 兼容接口);密码库 5 分钟无操作自动锁定 -- 图标为自绘 SVG(src/components/icons.ts),界面不含表情与特殊符号 +- **服务器是唯一数据权威**,本地 Dexie(IndexedDB)只是实时缓存: + 每次写操作立即推送差异到服务器,并以服务器返回的快照全量重建缓存 +- 同步引擎:`src/sync/engine.ts`(差异推送 + 快照重建 + SSE 实时通知 + 60s 兜底) +- 本地库按云端用户隔离:`intern_worklog_<云端userId>` + +## 目录速览 + + src/ + ├─ views/ 页面(日历/详情/统计/总结/记账/备忘录/密码库/设置/用户管理) + ├─ components/ 通用组件与自绘 SVG 图标(icons.ts) + ├─ db/ schema(Dexie)/ repo(数据仓库,写后即推)/ auth(云端登录)/ vault(加密密码库) + ├─ sync/ 同步引擎 + ├─ domain/ 考勤计算 / AI 润色 + └─ lib/ 日期、加密、下载、toast、错误浮层、服务器基址 + +## 打包 + +- 桌面:`pnpm dist` → release/InternLog-Setup-*.exe(NSIS)与 win-unpacked/ +- 安卓:`pnpm build && npx cap sync android` → android/gradlew.bat assembleDebug + (需 JDK 17:set JAVA_HOME=C:\Program Files\Java\jdk-17) + +## 验证脚本(repro/) + +开发期回归工具,不参与构建: + +- `protocol-audit.mjs` / `admin-audit.mjs`:对本地同步服务(127.0.0.1:3780)的协议级审计 +- `two-device.ts` / `engine-realtime.ts` / `unit-tests.ts`:引擎级与单元测试(用 esbuild 打包后 node 运行,命令见文件头注释) diff --git a/intern-log/repro/sync-repro.cjs b/intern-log/repro/sync-repro.cjs deleted file mode 100644 index 278a9da..0000000 --- a/intern-log/repro/sync-repro.cjs +++ /dev/null @@ -1,10070 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/dist/dexie.js -var require_dexie = __commonJS({ - "intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/dist/dexie.js"(exports2, module2) { - (function(global2, factory) { - typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.Dexie = factory()); - })(exports2, function() { - "use strict"; - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - var __assign = function() { - __assign = Object.assign || function __assign2(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - } - typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; - }; - var _global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; - var keys = Object.keys; - var isArray = Array.isArray; - if (typeof Promise !== "undefined" && !_global.Promise) { - _global.Promise = Promise; - } - function extend(obj, extension) { - if (typeof extension !== "object") - return obj; - keys(extension).forEach(function(key) { - obj[key] = extension[key]; - }); - return obj; - } - var getProto = Object.getPrototypeOf; - var _hasOwn = {}.hasOwnProperty; - function hasOwn(obj, prop) { - return _hasOwn.call(obj, prop); - } - function props(proto, extension) { - if (typeof extension === "function") - extension = extension(getProto(proto)); - (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(function(key) { - setProp(proto, key, extension[key]); - }); - } - var defineProperty = Object.defineProperty; - function setProp(obj, prop, functionOrGetSet, options) { - defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === "function" ? { - get: functionOrGetSet.get, - set: functionOrGetSet.set, - configurable: true - } : { value: functionOrGetSet, configurable: true, writable: true }, options)); - } - function derive(Child) { - return { - from: function(Parent) { - Child.prototype = Object.create(Parent.prototype); - setProp(Child.prototype, "constructor", Child); - return { - extend: props.bind(null, Child.prototype) - }; - } - }; - } - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - function getPropertyDescriptor(obj, prop) { - var pd = getOwnPropertyDescriptor(obj, prop); - var proto; - return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); - } - var _slice = [].slice; - function slice(args, start, end) { - return _slice.call(args, start, end); - } - function override(origFunc, overridedFactory) { - return overridedFactory(origFunc); - } - function assert(b) { - if (!b) - throw new Error("Assertion Failed"); - } - function asap$1(fn) { - if (_global.setImmediate) - setImmediate(fn); - else - setTimeout(fn, 0); - } - function arrayToObject(array, extractor) { - return array.reduce(function(result, item, i) { - var nameAndValue = extractor(item, i); - if (nameAndValue) - result[nameAndValue[0]] = nameAndValue[1]; - return result; - }, {}); - } - function getByKeyPath(obj, keyPath) { - if (typeof keyPath === "string" && hasOwn(obj, keyPath)) - return obj[keyPath]; - if (!keyPath) - return obj; - if (typeof keyPath !== "string") { - var rv = []; - for (var i = 0, l = keyPath.length; i < l; ++i) { - var val = getByKeyPath(obj, keyPath[i]); - rv.push(val); - } - return rv; - } - var period = keyPath.indexOf("."); - if (period !== -1) { - var innerObj = obj[keyPath.substr(0, period)]; - return innerObj == null ? void 0 : getByKeyPath(innerObj, keyPath.substr(period + 1)); - } - return void 0; - } - function setByKeyPath(obj, keyPath, value) { - if (!obj || keyPath === void 0) - return; - if ("isFrozen" in Object && Object.isFrozen(obj)) - return; - if (typeof keyPath !== "string" && "length" in keyPath) { - assert(typeof value !== "string" && "length" in value); - for (var i = 0, l = keyPath.length; i < l; ++i) { - setByKeyPath(obj, keyPath[i], value[i]); - } - } else { - var period = keyPath.indexOf("."); - if (period !== -1) { - var currentKeyPath = keyPath.substr(0, period); - var remainingKeyPath = keyPath.substr(period + 1); - if (remainingKeyPath === "") - if (value === void 0) { - if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) - obj.splice(currentKeyPath, 1); - else - delete obj[currentKeyPath]; - } else - obj[currentKeyPath] = value; - else { - var innerObj = obj[currentKeyPath]; - if (!innerObj || !hasOwn(obj, currentKeyPath)) { - if (value === void 0) - return; - innerObj = obj[currentKeyPath] = {}; - } - setByKeyPath(innerObj, remainingKeyPath, value); - } - } else { - if (value === void 0) { - if (isArray(obj) && !isNaN(parseInt(keyPath))) - obj.splice(keyPath, 1); - else - delete obj[keyPath]; - } else - obj[keyPath] = value; - } - } - } - function delByKeyPath(obj, keyPath) { - if (typeof keyPath === "string") - setByKeyPath(obj, keyPath, void 0); - else if ("length" in keyPath) - [].map.call(keyPath, function(kp) { - setByKeyPath(obj, kp, void 0); - }); - } - function shallowClone(obj) { - var rv = {}; - for (var m in obj) { - if (hasOwn(obj, m)) - rv[m] = obj[m]; - } - return rv; - } - var concat = [].concat; - function flatten(a) { - return concat.apply([], a); - } - var intrinsicTypeNames = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(flatten([8, 16, 32, 64].map(function(num) { - return ["Int", "Uint", "Float"].map(function(t) { - return t + num + "Array"; - }); - }))).filter(function(t) { - return _global[t]; - }); - var intrinsicTypes = new Set(intrinsicTypeNames.map(function(t) { - return _global[t]; - })); - function cloneSimpleObjectTree(o) { - var rv = {}; - for (var k in o) - if (hasOwn(o, k)) { - var v = o[k]; - rv[k] = !v || typeof v !== "object" || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v); - } - return rv; - } - var circularRefs = null; - function deepClone(any) { - circularRefs = /* @__PURE__ */ new WeakMap(); - var rv = innerDeepClone(any); - circularRefs = null; - return rv; - } - function innerDeepClone(x) { - if (!x || typeof x !== "object") - return x; - var rv = circularRefs.get(x); - if (rv) - return rv; - if (isArray(x)) { - rv = []; - circularRefs.set(x, rv); - for (var i = 0, l = x.length; i < l; ++i) { - rv.push(innerDeepClone(x[i])); - } - } else if (intrinsicTypes.has(x.constructor)) { - rv = x; - } else { - var proto = getProto(x); - rv = proto === Object.prototype ? {} : Object.create(proto); - circularRefs.set(x, rv); - for (var prop in x) { - if (hasOwn(x, prop)) { - rv[prop] = innerDeepClone(x[prop]); - } - } - } - return rv; - } - var toString = {}.toString; - function toStringTag(o) { - return toString.call(o).slice(8, -1); - } - var iteratorSymbol = typeof Symbol !== "undefined" ? Symbol.iterator : "@@iterator"; - var getIteratorOf = typeof iteratorSymbol === "symbol" ? function(x) { - var i; - return x != null && (i = x[iteratorSymbol]) && i.apply(x); - } : function() { - return null; - }; - function delArrayItem(a, x) { - var i = a.indexOf(x); - if (i >= 0) - a.splice(i, 1); - return i >= 0; - } - var NO_CHAR_ARRAY = {}; - function getArrayOf(arrayLike) { - var i, a, x, it; - if (arguments.length === 1) { - if (isArray(arrayLike)) - return arrayLike.slice(); - if (this === NO_CHAR_ARRAY && typeof arrayLike === "string") - return [arrayLike]; - if (it = getIteratorOf(arrayLike)) { - a = []; - while (x = it.next(), !x.done) - a.push(x.value); - return a; - } - if (arrayLike == null) - return [arrayLike]; - i = arrayLike.length; - if (typeof i === "number") { - a = new Array(i); - while (i--) - a[i] = arrayLike[i]; - return a; - } - return [arrayLike]; - } - i = arguments.length; - a = new Array(i); - while (i--) - a[i] = arguments[i]; - return a; - } - var isAsyncFunction = typeof Symbol !== "undefined" ? function(fn) { - return fn[Symbol.toStringTag] === "AsyncFunction"; - } : function() { - return false; - }; - var dexieErrorNames = [ - "Modify", - "Bulk", - "OpenFailed", - "VersionChange", - "Schema", - "Upgrade", - "InvalidTable", - "MissingAPI", - "NoSuchDatabase", - "InvalidArgument", - "SubTransaction", - "Unsupported", - "Internal", - "DatabaseClosed", - "PrematureCommit", - "ForeignAwait" - ]; - var idbDomErrorNames = [ - "Unknown", - "Constraint", - "Data", - "TransactionInactive", - "ReadOnly", - "Version", - "NotFound", - "InvalidState", - "InvalidAccess", - "Abort", - "Timeout", - "QuotaExceeded", - "Syntax", - "DataClone" - ]; - var errorList = dexieErrorNames.concat(idbDomErrorNames); - var defaultTexts = { - VersionChanged: "Database version changed by other database connection", - DatabaseClosed: "Database has been closed", - Abort: "Transaction aborted", - TransactionInactive: "Transaction has already completed or failed", - MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" - }; - function DexieError(name, msg) { - this.name = name; - this.message = msg; - } - derive(DexieError).from(Error).extend({ - toString: function() { - return this.name + ": " + this.message; - } - }); - function getMultiErrorMessage(msg, failures) { - return msg + ". Errors: " + Object.keys(failures).map(function(key) { - return failures[key].toString(); - }).filter(function(v, i, s) { - return s.indexOf(v) === i; - }).join("\n"); - } - function ModifyError(msg, failures, successCount, failedKeys) { - this.failures = failures; - this.failedKeys = failedKeys; - this.successCount = successCount; - this.message = getMultiErrorMessage(msg, failures); - } - derive(ModifyError).from(DexieError); - function BulkError(msg, failures) { - this.name = "BulkError"; - this.failures = Object.keys(failures).map(function(pos) { - return failures[pos]; - }); - this.failuresByPos = failures; - this.message = getMultiErrorMessage(msg, this.failures); - } - derive(BulkError).from(DexieError); - var errnames = errorList.reduce(function(obj, name) { - return obj[name] = name + "Error", obj; - }, {}); - var BaseException = DexieError; - var exceptions = errorList.reduce(function(obj, name) { - var fullName = name + "Error"; - function DexieError2(msgOrInner, inner) { - this.name = fullName; - if (!msgOrInner) { - this.message = defaultTexts[name] || fullName; - this.inner = null; - } else if (typeof msgOrInner === "string") { - this.message = "".concat(msgOrInner).concat(!inner ? "" : "\n " + inner); - this.inner = inner || null; - } else if (typeof msgOrInner === "object") { - this.message = "".concat(msgOrInner.name, " ").concat(msgOrInner.message); - this.inner = msgOrInner; - } - } - derive(DexieError2).from(BaseException); - obj[name] = DexieError2; - return obj; - }, {}); - exceptions.Syntax = SyntaxError; - exceptions.Type = TypeError; - exceptions.Range = RangeError; - var exceptionMap = idbDomErrorNames.reduce(function(obj, name) { - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - function mapError(domError, message) { - if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) - return domError; - var rv = new exceptionMap[domError.name](message || domError.message, domError); - if ("stack" in domError) { - setProp(rv, "stack", { - get: function() { - return this.inner.stack; - } - }); - } - return rv; - } - var fullNameExceptions = errorList.reduce(function(obj, name) { - if (["Syntax", "Type", "Range"].indexOf(name) === -1) - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - fullNameExceptions.ModifyError = ModifyError; - fullNameExceptions.DexieError = DexieError; - fullNameExceptions.BulkError = BulkError; - function nop() { - } - function mirror(val) { - return val; - } - function pureFunctionChain(f1, f2) { - if (f1 == null || f1 === mirror) - return f2; - return function(val) { - return f2(f1(val)); - }; - } - function callBoth(on1, on2) { - return function() { - on1.apply(this, arguments); - on2.apply(this, arguments); - }; - } - function hookCreatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - var res = f1.apply(this, arguments); - if (res !== void 0) - arguments[0] = res; - var onsuccess = this.onsuccess, onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res2 !== void 0 ? res2 : res; - }; - } - function hookDeletingChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - f1.apply(this, arguments); - var onsuccess = this.onsuccess, onerror = this.onerror; - this.onsuccess = this.onerror = null; - f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - }; - } - function hookUpdatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - var res = f1.apply(this, arguments); - var modifications = arguments[0]; - extend(modifications, res); - var onsuccess = this.onsuccess, onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res === void 0 ? res2 === void 0 ? void 0 : res2 : extend(res, res2); - }; - } - function reverseStoppableEventChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - if (f2.apply(this, arguments) === false) - return false; - return f1.apply(this, arguments); - }; - } - function promisableChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - var res = f1.apply(this, arguments); - if (res && typeof res.then === "function") { - var thiz = this, i = arguments.length, args = new Array(i); - while (i--) - args[i] = arguments[i]; - return res.then(function() { - return f2.apply(thiz, args); - }); - } - return f2.apply(this, arguments); - }; - } - var debug = typeof location !== "undefined" && /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); - function setDebug(value, filter) { - debug = value; - } - var INTERNAL = {}; - var ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === "undefined" ? [] : function() { - var globalP = Promise.resolve(); - if (typeof crypto === "undefined" || !crypto.subtle) - return [globalP, getProto(globalP), globalP]; - var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); - return [nativeP, getProto(nativeP), globalP]; - }(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; - var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; - var patchGlobalPromise = !!resolvedGlobalPromise; - function schedulePhysicalTick() { - queueMicrotask(physicalTick); - } - var asap = function(callback, args) { - microtickQueue.push([callback, args]); - if (needsNewPhysicalTick) { - schedulePhysicalTick(); - needsNewPhysicalTick = false; - } - }; - var isOutsideMicroTick = true, needsNewPhysicalTick = true, unhandledErrors = [], rejectingErrors = [], rejectionMapper = mirror; - var globalPSD = { - id: "global", - global: true, - ref: 0, - unhandleds: [], - onunhandled: nop, - pgp: false, - env: {}, - finalize: nop - }; - var PSD = globalPSD; - var microtickQueue = []; - var numScheduledCalls = 0; - var tickFinalizers = []; - function DexiePromise(fn) { - if (typeof this !== "object") - throw new TypeError("Promises must be constructed via new"); - this._listeners = []; - this._lib = false; - var psd = this._PSD = PSD; - if (typeof fn !== "function") { - if (fn !== INTERNAL) - throw new TypeError("Not a function"); - this._state = arguments[1]; - this._value = arguments[2]; - if (this._state === false) - handleRejection(this, this._value); - return; - } - this._state = null; - this._value = null; - ++psd.ref; - executePromiseTask(this, fn); - } - var thenProp = { - get: function() { - var psd = PSD, microTaskId = totalEchoes; - function then(onFulfilled, onRejected) { - var _this = this; - var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); - var cleanup = possibleAwait && !decrementExpectedAwaits(); - var rv = new DexiePromise(function(resolve, reject) { - propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); - }); - if (this._consoleTask) - rv._consoleTask = this._consoleTask; - return rv; - } - then.prototype = INTERNAL; - return then; - }, - set: function(value) { - setProp(this, "then", value && value.prototype === INTERNAL ? thenProp : { - get: function() { - return value; - }, - set: thenProp.set - }); - } - }; - props(DexiePromise.prototype, { - then: thenProp, - _then: function(onFulfilled, onRejected) { - propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); - }, - catch: function(onRejected) { - if (arguments.length === 1) - return this.then(null, onRejected); - var type2 = arguments[0], handler = arguments[1]; - return typeof type2 === "function" ? this.then(null, function(err) { - return err instanceof type2 ? handler(err) : PromiseReject(err); - }) : this.then(null, function(err) { - return err && err.name === type2 ? handler(err) : PromiseReject(err); - }); - }, - finally: function(onFinally) { - return this.then(function(value) { - return DexiePromise.resolve(onFinally()).then(function() { - return value; - }); - }, function(err) { - return DexiePromise.resolve(onFinally()).then(function() { - return PromiseReject(err); - }); - }); - }, - timeout: function(ms, msg) { - var _this = this; - return ms < Infinity ? new DexiePromise(function(resolve, reject) { - var handle = setTimeout(function() { - return reject(new exceptions.Timeout(msg)); - }, ms); - _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); - }) : this; - } - }); - if (typeof Symbol !== "undefined" && Symbol.toStringTag) - setProp(DexiePromise.prototype, Symbol.toStringTag, "Dexie.Promise"); - globalPSD.env = snapShot(); - function Listener(onFulfilled, onRejected, resolve, reject, zone) { - this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null; - this.onRejected = typeof onRejected === "function" ? onRejected : null; - this.resolve = resolve; - this.reject = reject; - this.psd = zone; - } - props(DexiePromise, { - all: function() { - var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve, reject) { - if (values.length === 0) - resolve([]); - var remaining = values.length; - values.forEach(function(a, i) { - return DexiePromise.resolve(a).then(function(x) { - values[i] = x; - if (!--remaining) - resolve(values); - }, reject); - }); - }); - }, - resolve: function(value) { - if (value instanceof DexiePromise) - return value; - if (value && typeof value.then === "function") - return new DexiePromise(function(resolve, reject) { - value.then(resolve, reject); - }); - var rv = new DexiePromise(INTERNAL, true, value); - return rv; - }, - reject: PromiseReject, - race: function() { - var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve, reject) { - values.map(function(value) { - return DexiePromise.resolve(value).then(resolve, reject); - }); - }); - }, - PSD: { - get: function() { - return PSD; - }, - set: function(value) { - return PSD = value; - } - }, - totalEchoes: { get: function() { - return totalEchoes; - } }, - newPSD: newScope, - usePSD, - scheduler: { - get: function() { - return asap; - }, - set: function(value) { - asap = value; - } - }, - rejectionMapper: { - get: function() { - return rejectionMapper; - }, - set: function(value) { - rejectionMapper = value; - } - }, - follow: function(fn, zoneProps) { - return new DexiePromise(function(resolve, reject) { - return newScope(function(resolve2, reject2) { - var psd = PSD; - psd.unhandleds = []; - psd.onunhandled = reject2; - psd.finalize = callBoth(function() { - var _this = this; - run_at_end_of_this_or_next_physical_tick(function() { - _this.unhandleds.length === 0 ? resolve2() : reject2(_this.unhandleds[0]); - }); - }, psd.finalize); - fn(); - }, zoneProps, resolve, reject); - }); - } - }); - if (NativePromise) { - if (NativePromise.allSettled) - setProp(DexiePromise, "allSettled", function() { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve) { - if (possiblePromises.length === 0) - resolve([]); - var remaining = possiblePromises.length; - var results = new Array(remaining); - possiblePromises.forEach(function(p, i) { - return DexiePromise.resolve(p).then(function(value) { - return results[i] = { status: "fulfilled", value }; - }, function(reason) { - return results[i] = { status: "rejected", reason }; - }).then(function() { - return --remaining || resolve(results); - }); - }); - }); - }); - if (NativePromise.any && typeof AggregateError !== "undefined") - setProp(DexiePromise, "any", function() { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve, reject) { - if (possiblePromises.length === 0) - reject(new AggregateError([])); - var remaining = possiblePromises.length; - var failures = new Array(remaining); - possiblePromises.forEach(function(p, i) { - return DexiePromise.resolve(p).then(function(value) { - return resolve(value); - }, function(failure) { - failures[i] = failure; - if (!--remaining) - reject(new AggregateError(failures)); - }); - }); - }); - }); - if (NativePromise.withResolvers) - DexiePromise.withResolvers = NativePromise.withResolvers; - } - function executePromiseTask(promise, fn) { - try { - fn(function(value) { - if (promise._state !== null) - return; - if (value === promise) - throw new TypeError("A promise cannot be resolved with itself."); - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - if (value && typeof value.then === "function") { - executePromiseTask(promise, function(resolve, reject) { - value instanceof DexiePromise ? value._then(resolve, reject) : value.then(resolve, reject); - }); - } else { - promise._state = true; - promise._value = value; - propagateAllListeners(promise); - } - if (shouldExecuteTick) - endMicroTickScope(); - }, handleRejection.bind(null, promise)); - } catch (ex) { - handleRejection(promise, ex); - } - } - function handleRejection(promise, reason) { - rejectingErrors.push(reason); - if (promise._state !== null) - return; - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - reason = rejectionMapper(reason); - promise._state = false; - promise._value = reason; - addPossiblyUnhandledError(promise); - propagateAllListeners(promise); - if (shouldExecuteTick) - endMicroTickScope(); - } - function propagateAllListeners(promise) { - var listeners = promise._listeners; - promise._listeners = []; - for (var i = 0, len = listeners.length; i < len; ++i) { - propagateToListener(promise, listeners[i]); - } - var psd = promise._PSD; - --psd.ref || psd.finalize(); - if (numScheduledCalls === 0) { - ++numScheduledCalls; - asap(function() { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - } - function propagateToListener(promise, listener) { - if (promise._state === null) { - promise._listeners.push(listener); - return; - } - var cb = promise._state ? listener.onFulfilled : listener.onRejected; - if (cb === null) { - return (promise._state ? listener.resolve : listener.reject)(promise._value); - } - ++listener.psd.ref; - ++numScheduledCalls; - asap(callListener, [cb, promise, listener]); - } - function callListener(cb, promise, listener) { - try { - var ret, value = promise._value; - if (!promise._state && rejectingErrors.length) - rejectingErrors = []; - ret = debug && promise._consoleTask ? promise._consoleTask.run(function() { - return cb(value); - }) : cb(value); - if (!promise._state && rejectingErrors.indexOf(value) === -1) { - markErrorAsHandled(promise); - } - listener.resolve(ret); - } catch (e) { - listener.reject(e); - } finally { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - --listener.psd.ref || listener.psd.finalize(); - } - } - function physicalTick() { - usePSD(globalPSD, function() { - beginMicroTickScope() && endMicroTickScope(); - }); - } - function beginMicroTickScope() { - var wasRootExec = isOutsideMicroTick; - isOutsideMicroTick = false; - needsNewPhysicalTick = false; - return wasRootExec; - } - function endMicroTickScope() { - var callbacks, i, l; - do { - while (microtickQueue.length > 0) { - callbacks = microtickQueue; - microtickQueue = []; - l = callbacks.length; - for (i = 0; i < l; ++i) { - var item = callbacks[i]; - item[0].apply(null, item[1]); - } - } - } while (microtickQueue.length > 0); - isOutsideMicroTick = true; - needsNewPhysicalTick = true; - } - function finalizePhysicalTick() { - var unhandledErrs = unhandledErrors; - unhandledErrors = []; - unhandledErrs.forEach(function(p) { - p._PSD.onunhandled.call(null, p._value, p); - }); - var finalizers = tickFinalizers.slice(0); - var i = finalizers.length; - while (i) - finalizers[--i](); - } - function run_at_end_of_this_or_next_physical_tick(fn) { - function finalizer() { - fn(); - tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); - } - tickFinalizers.push(finalizer); - ++numScheduledCalls; - asap(function() { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - function addPossiblyUnhandledError(promise) { - if (!unhandledErrors.some(function(p) { - return p._value === promise._value; - })) - unhandledErrors.push(promise); - } - function markErrorAsHandled(promise) { - var i = unhandledErrors.length; - while (i) - if (unhandledErrors[--i]._value === promise._value) { - unhandledErrors.splice(i, 1); - return; - } - } - function PromiseReject(reason) { - return new DexiePromise(INTERNAL, false, reason); - } - function wrap(fn, errorCatcher) { - var psd = PSD; - return function() { - var wasRootExec = beginMicroTickScope(), outerScope = PSD; - try { - switchToZone(psd, true); - return fn.apply(this, arguments); - } catch (e) { - errorCatcher && errorCatcher(e); - } finally { - switchToZone(outerScope, false); - if (wasRootExec) - endMicroTickScope(); - } - }; - } - var task = { awaits: 0, echoes: 0, id: 0 }; - var taskCounter = 0; - var zoneStack = []; - var zoneEchoes = 0; - var totalEchoes = 0; - var zone_id_counter = 0; - function newScope(fn, props2, a1, a2) { - var parent = PSD, psd = Object.create(parent); - psd.parent = parent; - psd.ref = 0; - psd.global = false; - psd.id = ++zone_id_counter; - globalPSD.env; - psd.env = patchGlobalPromise ? { - Promise: DexiePromise, - PromiseProp: { - value: DexiePromise, - configurable: true, - writable: true - }, - all: DexiePromise.all, - race: DexiePromise.race, - allSettled: DexiePromise.allSettled, - any: DexiePromise.any, - resolve: DexiePromise.resolve, - reject: DexiePromise.reject - } : {}; - if (props2) - extend(psd, props2); - ++parent.ref; - psd.finalize = function() { - --this.parent.ref || this.parent.finalize(); - }; - var rv = usePSD(psd, fn, a1, a2); - if (psd.ref === 0) - psd.finalize(); - return rv; - } - function incrementExpectedAwaits() { - if (!task.id) - task.id = ++taskCounter; - ++task.awaits; - task.echoes += ZONE_ECHO_LIMIT; - return task.id; - } - function decrementExpectedAwaits() { - if (!task.awaits) - return false; - if (--task.awaits === 0) - task.id = 0; - task.echoes = task.awaits * ZONE_ECHO_LIMIT; - return true; - } - if (("" + nativePromiseThen).indexOf("[native code]") === -1) { - incrementExpectedAwaits = decrementExpectedAwaits = nop; - } - function onPossibleParallellAsync(possiblePromise) { - if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { - incrementExpectedAwaits(); - return possiblePromise.then(function(x) { - decrementExpectedAwaits(); - return x; - }, function(e) { - decrementExpectedAwaits(); - return rejection(e); - }); - } - return possiblePromise; - } - function zoneEnterEcho(targetZone) { - ++totalEchoes; - if (!task.echoes || --task.echoes === 0) { - task.echoes = task.awaits = task.id = 0; - } - zoneStack.push(PSD); - switchToZone(targetZone, true); - } - function zoneLeaveEcho() { - var zone = zoneStack[zoneStack.length - 1]; - zoneStack.pop(); - switchToZone(zone, false); - } - function switchToZone(targetZone, bEnteringZone) { - var currentZone = PSD; - if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { - queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); - } - if (targetZone === PSD) - return; - PSD = targetZone; - if (currentZone === globalPSD) - globalPSD.env = snapShot(); - if (patchGlobalPromise) { - var GlobalPromise = globalPSD.env.Promise; - var targetEnv = targetZone.env; - if (currentZone.global || targetZone.global) { - Object.defineProperty(_global, "Promise", targetEnv.PromiseProp); - GlobalPromise.all = targetEnv.all; - GlobalPromise.race = targetEnv.race; - GlobalPromise.resolve = targetEnv.resolve; - GlobalPromise.reject = targetEnv.reject; - if (targetEnv.allSettled) - GlobalPromise.allSettled = targetEnv.allSettled; - if (targetEnv.any) - GlobalPromise.any = targetEnv.any; - } - } - } - function snapShot() { - var GlobalPromise = _global.Promise; - return patchGlobalPromise ? { - Promise: GlobalPromise, - PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), - all: GlobalPromise.all, - race: GlobalPromise.race, - allSettled: GlobalPromise.allSettled, - any: GlobalPromise.any, - resolve: GlobalPromise.resolve, - reject: GlobalPromise.reject - } : {}; - } - function usePSD(psd, fn, a1, a2, a3) { - var outerScope = PSD; - try { - switchToZone(psd, true); - return fn(a1, a2, a3); - } finally { - switchToZone(outerScope, false); - } - } - function nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { - return typeof fn !== "function" ? fn : function() { - var outerZone = PSD; - if (possibleAwait) - incrementExpectedAwaits(); - switchToZone(zone, true); - try { - return fn.apply(this, arguments); - } finally { - switchToZone(outerZone, false); - if (cleanup) - queueMicrotask(decrementExpectedAwaits); - } - }; - } - function execInGlobalContext(cb) { - if (Promise === NativePromise && task.echoes === 0) { - if (zoneEchoes === 0) { - cb(); - } else { - enqueueNativeMicroTask(cb); - } - } else { - setTimeout(cb, 0); - } - } - var rejection = DexiePromise.reject; - function tempTransaction(db2, mode, storeNames, fn) { - if (!db2.idbdb || !db2._state.openComplete && !PSD.letThrough && !db2._vip) { - if (db2._state.openComplete) { - return rejection(new exceptions.DatabaseClosed(db2._state.dbOpenError)); - } - if (!db2._state.isBeingOpened) { - if (!db2._state.autoOpen) - return rejection(new exceptions.DatabaseClosed()); - db2.open().catch(nop); - } - return db2._state.dbReadyPromise.then(function() { - return tempTransaction(db2, mode, storeNames, fn); - }); - } else { - var trans = db2._createTransaction(mode, storeNames, db2._dbSchema); - try { - trans.create(); - db2._state.PR1398_maxLoop = 3; - } catch (ex) { - if (ex.name === errnames.InvalidState && db2.isOpen() && --db2._state.PR1398_maxLoop > 0) { - console.warn("Dexie: Need to reopen db"); - db2.close({ disableAutoOpen: false }); - return db2.open().then(function() { - return tempTransaction(db2, mode, storeNames, fn); - }); - } - return rejection(ex); - } - return trans._promise(mode, function(resolve, reject) { - return newScope(function() { - PSD.trans = trans; - return fn(resolve, reject, trans); - }); - }).then(function(result) { - if (mode === "readwrite") - try { - trans.idbtrans.commit(); - } catch (_a2) { - } - return mode === "readonly" ? result : trans._completion.then(function() { - return result; - }); - }); - } - } - var DEXIE_VERSION = "4.4.6"; - var maxString = String.fromCharCode(65535); - var minKey = -Infinity; - var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; - var STRING_EXPECTED = "String expected."; - var DEFAULT_MAX_CONNECTIONS = 1e3; - var DBNAMES_DB = "__dbnames"; - var READONLY = "readonly"; - var READWRITE = "readwrite"; - function combine(filter1, filter2) { - return filter1 ? filter2 ? function() { - return filter1.apply(this, arguments) && filter2.apply(this, arguments); - } : filter1 : filter2; - } - var AnyRange = { - type: 3, - lower: -Infinity, - lowerOpen: false, - upper: [[]], - upperOpen: false - }; - function workaroundForUndefinedPrimKey(keyPath) { - return typeof keyPath === "string" && !/\./.test(keyPath) ? function(obj) { - if (obj[keyPath] === void 0 && keyPath in obj) { - obj = deepClone(obj); - delete obj[keyPath]; - } - return obj; - } : function(obj) { - return obj; - }; - } - function Entity2() { - throw exceptions.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor."); - } - function cmp3(a, b) { - try { - var ta = type(a); - var tb = type(b); - if (ta !== tb) { - if (ta === "Array") - return 1; - if (tb === "Array") - return -1; - if (ta === "binary") - return 1; - if (tb === "binary") - return -1; - if (ta === "string") - return 1; - if (tb === "string") - return -1; - if (ta === "Date") - return 1; - if (tb !== "Date") - return NaN; - return -1; - } - switch (ta) { - case "number": - case "Date": - case "string": - return a > b ? 1 : a < b ? -1 : 0; - case "binary": { - return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); - } - case "Array": - return compareArrays(a, b); - } - } catch (_a2) { - } - return NaN; - } - function compareArrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - var res = cmp3(a[i], b[i]); - if (res !== 0) - return res; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function compareUint8Arrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - if (a[i] !== b[i]) - return a[i] < b[i] ? -1 : 1; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function type(x) { - var t = typeof x; - if (t !== "object") - return t; - if (ArrayBuffer.isView(x)) - return "binary"; - var tsTag = toStringTag(x); - return tsTag === "ArrayBuffer" ? "binary" : tsTag; - } - function getUint8Array(a) { - if (a instanceof Uint8Array) - return a; - if (ArrayBuffer.isView(a)) - return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); - return new Uint8Array(a); - } - function builtInDeletionTrigger(table, keys2, res) { - var yProps = table.schema.yProps; - if (!yProps) - return res; - if (keys2 && res.numFailures > 0) - keys2 = keys2.filter(function(_, i) { - return !res.failures[i]; - }); - return Promise.all(yProps.map(function(_a2) { - var updatesTable = _a2.updatesTable; - return keys2 ? table.db.table(updatesTable).where("k").anyOf(keys2).delete() : table.db.table(updatesTable).clear(); - })).then(function() { - return res; - }); - } - var PropModification2 = function() { - function PropModification3(spec) { - this["@@propmod"] = spec; - } - PropModification3.prototype.execute = function(value) { - var _a2; - var spec = this["@@propmod"]; - if (spec.add !== void 0) { - var term = spec.add; - if (isArray(term)) { - return __spreadArray(__spreadArray([], isArray(value) ? value : [], true), term, true).sort(); - } - if (typeof term === "number") - return (Number(value) || 0) + term; - if (typeof term === "bigint") { - try { - return BigInt(value) + term; - } catch (_b) { - return BigInt(0) + term; - } - } - throw new TypeError("Invalid term ".concat(term)); - } - if (spec.remove !== void 0) { - var subtrahend_1 = spec.remove; - if (isArray(subtrahend_1)) { - return isArray(value) ? value.filter(function(item) { - return !subtrahend_1.includes(item); - }).sort() : []; - } - if (typeof subtrahend_1 === "number") - return Number(value) - subtrahend_1; - if (typeof subtrahend_1 === "bigint") { - try { - return BigInt(value) - subtrahend_1; - } catch (_c) { - return BigInt(0) - subtrahend_1; - } - } - throw new TypeError("Invalid subtrahend ".concat(subtrahend_1)); - } - var prefixToReplace = (_a2 = spec.replacePrefix) === null || _a2 === void 0 ? void 0 : _a2[0]; - if (prefixToReplace && typeof value === "string" && value.startsWith(prefixToReplace)) { - return spec.replacePrefix[1] + value.substring(prefixToReplace.length); - } - return value; - }; - return PropModification3; - }(); - function applyUpdateSpec(obj, changes) { - var keyPaths = keys(changes); - var numKeys = keyPaths.length; - var anythingModified = false; - for (var i = 0; i < numKeys; ++i) { - var keyPath = keyPaths[i]; - var value = changes[keyPath]; - var origValue = getByKeyPath(obj, keyPath); - if (value instanceof PropModification2) { - setByKeyPath(obj, keyPath, value.execute(origValue)); - anythingModified = true; - } else if (origValue !== value) { - setByKeyPath(obj, keyPath, value); - anythingModified = true; - } - } - return anythingModified; - } - var Table = function() { - function Table2() { - } - Table2.prototype._trans = function(mode, fn, writeLocked) { - var trans = this._tx || PSD.trans; - var tableName = this.name; - var task2 = debug && typeof console !== "undefined" && console.createTask && console.createTask("Dexie: ".concat(mode === "readonly" ? "read" : "write", " ").concat(this.name)); - function checkTableInTransaction(resolve, reject, trans2) { - if (!trans2.schema[tableName]) - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - return fn(trans2.idbtrans, trans2); - } - var wasRootExec = beginMicroTickScope(); - try { - var p = trans && trans.db._novip === this.db._novip ? trans === PSD.trans ? trans._promise(mode, checkTableInTransaction, writeLocked) : newScope(function() { - return trans._promise(mode, checkTableInTransaction, writeLocked); - }, { trans, transless: PSD.transless || PSD }) : tempTransaction(this.db, mode, [this.name], checkTableInTransaction); - if (task2) { - p._consoleTask = task2; - p = p.catch(function(err) { - console.trace(err); - return rejection(err); - }); - } - return p; - } finally { - if (wasRootExec) - endMicroTickScope(); - } - }; - Table2.prototype.get = function(keyOrCrit, cb) { - var _this = this; - if (keyOrCrit && keyOrCrit.constructor === Object) - return this.where(keyOrCrit).first(cb); - if (keyOrCrit == null) - return rejection(new exceptions.Type("Invalid argument to Table.get()")); - return this._trans("readonly", function(trans) { - return _this.core.get({ trans, key: keyOrCrit }).then(function(res) { - return _this.hook.reading.fire(res); - }); - }).then(cb); - }; - Table2.prototype.where = function(indexOrCrit) { - if (typeof indexOrCrit === "string") - return new this.db.WhereClause(this, indexOrCrit); - if (isArray(indexOrCrit)) - return new this.db.WhereClause(this, "[".concat(indexOrCrit.join("+"), "]")); - var keyPaths = keys(indexOrCrit); - if (keyPaths.length === 1) - return this.where(keyPaths[0]).equals(indexOrCrit[keyPaths[0]]); - var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function(ix) { - if (ix.compound && keyPaths.every(function(keyPath) { - return ix.keyPath.indexOf(keyPath) >= 0; - })) { - for (var i = 0; i < keyPaths.length; ++i) { - if (keyPaths.indexOf(ix.keyPath[i]) === -1) - return false; - } - return true; - } - return false; - }).sort(function(a, b) { - return a.keyPath.length - b.keyPath.length; - })[0]; - if (compoundIndex && this.db._maxKey !== maxString) { - var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); - return this.where(keyPathsInValidOrder).equals(keyPathsInValidOrder.map(function(kp) { - return indexOrCrit[kp]; - })); - } - if (!compoundIndex && debug) - console.warn("The query ".concat(JSON.stringify(indexOrCrit), " on ").concat(this.name, " would benefit from a ") + "compound index [".concat(keyPaths.join("+"), "]")); - var idxByName = this.schema.idxByName; - function equals(a, b) { - return cmp3(a, b) === 0; - } - var _a2 = keyPaths.reduce(function(_a3, keyPath) { - var prevIndex = _a3[0], prevFilterFn = _a3[1]; - var index = idxByName[keyPath]; - var value = indexOrCrit[keyPath]; - return [ - prevIndex || index, - prevIndex || !index ? combine(prevFilterFn, index && index.multi ? function(x) { - var prop = getByKeyPath(x, keyPath); - return isArray(prop) && prop.some(function(item) { - return equals(value, item); - }); - } : function(x) { - return equals(value, getByKeyPath(x, keyPath)); - }) : prevFilterFn - ]; - }, [null, null]), idx = _a2[0], filterFunction = _a2[1]; - return idx ? this.where(idx.name).equals(indexOrCrit[idx.keyPath]).filter(filterFunction) : compoundIndex ? this.filter(filterFunction) : this.where(keyPaths).equals(""); - }; - Table2.prototype.filter = function(filterFunction) { - return this.toCollection().and(filterFunction); - }; - Table2.prototype.count = function(thenShortcut) { - return this.toCollection().count(thenShortcut); - }; - Table2.prototype.offset = function(offset) { - return this.toCollection().offset(offset); - }; - Table2.prototype.limit = function(numRows) { - return this.toCollection().limit(numRows); - }; - Table2.prototype.each = function(callback) { - return this.toCollection().each(callback); - }; - Table2.prototype.toArray = function(thenShortcut) { - return this.toCollection().toArray(thenShortcut); - }; - Table2.prototype.toCollection = function() { - return new this.db.Collection(new this.db.WhereClause(this)); - }; - Table2.prototype.orderBy = function(index) { - return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? "[".concat(index.join("+"), "]") : index)); - }; - Table2.prototype.reverse = function() { - return this.toCollection().reverse(); - }; - Table2.prototype.mapToClass = function(constructor) { - var _a2 = this, db2 = _a2.db, tableName = _a2.name; - this.schema.mappedClass = constructor; - if (constructor.prototype instanceof Entity2) { - constructor = function(_super) { - __extends(class_1, _super); - function class_1() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(class_1.prototype, "db", { - get: function() { - return db2; - }, - enumerable: false, - configurable: true - }); - class_1.prototype.table = function() { - return tableName; - }; - return class_1; - }(constructor); - } - var inheritedProps = /* @__PURE__ */ new Set(); - for (var proto = constructor.prototype; proto; proto = getProto(proto)) { - Object.getOwnPropertyNames(proto).forEach(function(propName) { - return inheritedProps.add(propName); - }); - } - var readHook = function(obj) { - if (!obj) - return obj; - var res = Object.create(constructor.prototype); - for (var m in obj) - if (!inheritedProps.has(m)) - try { - res[m] = obj[m]; - } catch (_) { - } - return res; - }; - if (this.schema.readHook) { - this.hook.reading.unsubscribe(this.schema.readHook); - } - this.schema.readHook = readHook; - this.hook("reading", readHook); - return constructor; - }; - Table2.prototype.defineClass = function() { - function Class(content) { - extend(this, content); - } - return this.mapToClass(Class); - }; - Table2.prototype.add = function(obj, key) { - var _this = this; - var _a2 = this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ - trans, - type: "add", - keys: key != null ? [key] : null, - values: [objToAdd] - }); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; - }).then(function(lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } catch (_) { - } - } - return lastResult; - }); - }; - Table2.prototype.upsert = function(key, modifications) { - var _this = this; - var keyPath = this.schema.primKey.keyPath; - return this._trans("readwrite", function(trans) { - return _this.core.get({ trans, key }).then(function(existing) { - var obj = existing !== null && existing !== void 0 ? existing : {}; - applyUpdateSpec(obj, modifications); - if (keyPath) - setByKeyPath(obj, keyPath, key); - return _this.core.mutate({ - trans, - type: "put", - values: [obj], - keys: [key], - upsert: true, - updates: { keys: [key], changeSpecs: [modifications] } - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : !!existing; - }); - }); - }); - }; - Table2.prototype.update = function(keyOrObject, modifications) { - if (typeof keyOrObject === "object" && !isArray(keyOrObject)) { - var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); - if (key === void 0) - return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); - return this.where(":id").equals(key).modify(modifications); - } else { - return this.where(":id").equals(keyOrObject).modify(modifications); - } - }; - Table2.prototype.put = function(obj, key) { - var _this = this; - var _a2 = this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ - trans, - type: "put", - values: [objToAdd], - keys: key != null ? [key] : null - }); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; - }).then(function(lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } catch (_) { - } - } - return lastResult; - }); - }; - Table2.prototype.delete = function(key) { - var _this = this; - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ trans, type: "delete", keys: [key] }).then(function(res) { - return builtInDeletionTrigger(_this, [key], res); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : void 0; - }); - }); - }; - Table2.prototype.clear = function() { - var _this = this; - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ trans, type: "deleteRange", range: AnyRange }).then(function(res) { - return builtInDeletionTrigger(_this, null, res); - }); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : void 0; - }); - }; - Table2.prototype.bulkGet = function(keys2) { - var _this = this; - return this._trans("readonly", function(trans) { - return _this.core.getMany({ - keys: keys2, - trans - }).then(function(result) { - return result.map(function(res) { - return _this.hook.reading.fire(res); - }); - }); - }); - }; - Table2.prototype.bulkAdd = function(objects, keysOrOptions, options) { - var _this = this; - var keys2 = Array.isArray(keysOrOptions) ? keysOrOptions : void 0; - options = options || (keys2 ? void 0 : keysOrOptions); - var wantResults = options ? options.allKeys : void 0; - return this._trans("readwrite", function(trans) { - var _a2 = _this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - if (keyPath && keys2) - throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); - if (keys2 && keys2.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToAdd = keyPath && auto ? objects.map(workaroundForUndefinedPrimKey(keyPath)) : objects; - return _this.core.mutate({ - trans, - type: "add", - keys: keys2, - values: objectsToAdd, - wantResults - }).then(function(_a3) { - var numFailures = _a3.numFailures, results = _a3.results, lastResult = _a3.lastResult, failures = _a3.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkAdd(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table2.prototype.bulkPut = function(objects, keysOrOptions, options) { - var _this = this; - var keys2 = Array.isArray(keysOrOptions) ? keysOrOptions : void 0; - options = options || (keys2 ? void 0 : keysOrOptions); - var wantResults = options ? options.allKeys : void 0; - return this._trans("readwrite", function(trans) { - var _a2 = _this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - if (keyPath && keys2) - throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); - if (keys2 && keys2.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToPut = keyPath && auto ? objects.map(workaroundForUndefinedPrimKey(keyPath)) : objects; - return _this.core.mutate({ - trans, - type: "put", - keys: keys2, - values: objectsToPut, - wantResults - }).then(function(_a3) { - var numFailures = _a3.numFailures, results = _a3.results, lastResult = _a3.lastResult, failures = _a3.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkPut(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table2.prototype.bulkUpdate = function(keysAndChanges) { - var _this = this; - var coreTable = this.core; - var keys2 = keysAndChanges.map(function(entry) { - return entry.key; - }); - var changeSpecs = keysAndChanges.map(function(entry) { - return entry.changes; - }); - var offsetMap = []; - return this._trans("readwrite", function(trans) { - return coreTable.getMany({ trans, keys: keys2, cache: "clone" }).then(function(objs) { - var resultKeys = []; - var resultObjs = []; - keysAndChanges.forEach(function(_a2, idx) { - var key = _a2.key, changes = _a2.changes; - var obj = objs[idx]; - if (obj) { - for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) { - var keyPath = _b[_i]; - var value = changes[keyPath]; - if (keyPath === _this.schema.primKey.keyPath) { - if (cmp3(value, key) !== 0) { - throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()"); - } - } else { - setByKeyPath(obj, keyPath, value); - } - } - offsetMap.push(idx); - resultKeys.push(key); - resultObjs.push(obj); - } - }); - var numEntries = resultKeys.length; - return coreTable.mutate({ - trans, - type: "put", - keys: resultKeys, - values: resultObjs, - updates: { - keys: keys2, - changeSpecs - } - }).then(function(_a2) { - var numFailures = _a2.numFailures, failures = _a2.failures; - if (numFailures === 0) - return numEntries; - for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) { - var offset = _b[_i]; - var mappedOffset = offsetMap[Number(offset)]; - if (mappedOffset != null) { - var failure = failures[offset]; - delete failures[offset]; - failures[mappedOffset] = failure; - } - } - throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures); - }); - }); - }); - }; - Table2.prototype.bulkDelete = function(keys2) { - var _this = this; - var numKeys = keys2.length; - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ trans, type: "delete", keys: keys2 }).then(function(res) { - return builtInDeletionTrigger(_this, keys2, res); - }); - }).then(function(_a2) { - var numFailures = _a2.numFailures, lastResult = _a2.lastResult, failures = _a2.failures; - if (numFailures === 0) - return lastResult; - throw new BulkError("".concat(_this.name, ".bulkDelete(): ").concat(numFailures, " of ").concat(numKeys, " operations failed"), failures); - }); - }; - return Table2; - }(); - function Events(ctx) { - var evs = {}; - var rv = function(eventName, subscriber) { - if (subscriber) { - var i2 = arguments.length, args = new Array(i2 - 1); - while (--i2) - args[i2 - 1] = arguments[i2]; - evs[eventName].subscribe.apply(null, args); - return ctx; - } else if (typeof eventName === "string") { - return evs[eventName]; - } - }; - rv.addEventType = add3; - for (var i = 1, l = arguments.length; i < l; ++i) { - add3(arguments[i]); - } - return rv; - function add3(eventName, chainFunction, defaultFunction) { - if (typeof eventName === "object") - return addConfiguredEvents(eventName); - if (!chainFunction) - chainFunction = reverseStoppableEventChain; - if (!defaultFunction) - defaultFunction = nop; - var context = { - subscribers: [], - fire: defaultFunction, - subscribe: function(cb) { - if (context.subscribers.indexOf(cb) === -1) { - context.subscribers.push(cb); - context.fire = chainFunction(context.fire, cb); - } - }, - unsubscribe: function(cb) { - context.subscribers = context.subscribers.filter(function(fn) { - return fn !== cb; - }); - context.fire = context.subscribers.reduce(chainFunction, defaultFunction); - } - }; - evs[eventName] = rv[eventName] = context; - return context; - } - function addConfiguredEvents(cfg) { - keys(cfg).forEach(function(eventName) { - var args = cfg[eventName]; - if (isArray(args)) { - add3(eventName, cfg[eventName][0], cfg[eventName][1]); - } else if (args === "asap") { - var context = add3(eventName, mirror, function fire() { - var i2 = arguments.length, args2 = new Array(i2); - while (i2--) - args2[i2] = arguments[i2]; - context.subscribers.forEach(function(fn) { - asap$1(function fireEvent() { - fn.apply(null, args2); - }); - }); - }); - } else - throw new exceptions.InvalidArgument("Invalid event config"); - }); - } - } - function makeClassConstructor(prototype, constructor) { - derive(constructor).from({ prototype }); - return constructor; - } - function createTableConstructor(db2) { - return makeClassConstructor(Table.prototype, function Table2(name, tableSchema, trans) { - this.db = db2; - this._tx = trans; - this.name = name; - this.schema = tableSchema; - this.hook = db2._allTables[name] ? db2._allTables[name].hook : Events(null, { - creating: [hookCreatingChain, nop], - reading: [pureFunctionChain, mirror], - updating: [hookUpdatingChain, nop], - deleting: [hookDeletingChain, nop] - }); - }); - } - function isPlainKeyRange(ctx, ignoreLimitFilter) { - return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); - } - function addFilter(ctx, fn) { - ctx.filter = combine(ctx.filter, fn); - } - function addReplayFilter(ctx, factory, isLimitFilter) { - var curr = ctx.replayFilter; - ctx.replayFilter = curr ? function() { - return combine(curr(), factory()); - } : factory; - ctx.justLimit = isLimitFilter && !curr; - } - function addMatchFilter(ctx, fn) { - ctx.isMatch = combine(ctx.isMatch, fn); - } - function getIndexOrStore(ctx, coreSchema) { - if (ctx.isPrimKey) - return coreSchema.primaryKey; - var index = coreSchema.getIndexByKeyPath(ctx.index); - if (!index) - throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); - return index; - } - function openCursor(ctx, coreTable, trans) { - var index = getIndexOrStore(ctx, coreTable.schema); - return coreTable.openCursor({ - trans, - values: !ctx.keysOnly, - reverse: ctx.dir === "prev", - unique: !!ctx.unique, - query: { - index, - range: ctx.range - } - }); - } - function iter(ctx, fn, coreTrans, coreTable) { - var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; - if (!ctx.or) { - return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); - } else { - var set_1 = {}; - var union = function(item, cursor, advance) { - if (!filter || filter(cursor, advance, function(result) { - return cursor.stop(result); - }, function(err) { - return cursor.fail(err); - })) { - var primaryKey = cursor.primaryKey; - var key = "" + primaryKey; - if (key === "[object ArrayBuffer]") - key = "" + new Uint8Array(primaryKey); - if (!hasOwn(set_1, key)) { - set_1[key] = true; - fn(item, cursor, advance); - } - } - }; - return Promise.all([ - ctx.or._iterate(union, coreTrans), - iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) - ]); - } - } - function iterate(cursorPromise, filter, fn, valueMapper) { - var mappedFn = valueMapper ? function(x, c, a) { - return fn(valueMapper(x), c, a); - } : fn; - var wrappedFn = wrap(mappedFn); - return cursorPromise.then(function(cursor) { - if (cursor) { - return cursor.start(function() { - var c = function() { - return cursor.continue(); - }; - if (!filter || filter(cursor, function(advancer) { - return c = advancer; - }, function(val) { - cursor.stop(val); - c = nop; - }, function(e) { - cursor.fail(e); - c = nop; - })) - wrappedFn(cursor.value, cursor, function(advancer) { - return c = advancer; - }); - c(); - }); - } - }); - } - var Collection = function() { - function Collection2() { - } - Collection2.prototype._read = function(fn, cb) { - var ctx = this._ctx; - return ctx.error ? ctx.table._trans(null, rejection.bind(null, ctx.error)) : ctx.table._trans("readonly", fn).then(cb); - }; - Collection2.prototype._write = function(fn) { - var ctx = this._ctx; - return ctx.error ? ctx.table._trans(null, rejection.bind(null, ctx.error)) : ctx.table._trans("readwrite", fn, "locked"); - }; - Collection2.prototype._addAlgorithm = function(fn) { - var ctx = this._ctx; - ctx.algorithm = combine(ctx.algorithm, fn); - }; - Collection2.prototype._iterate = function(fn, coreTrans) { - return iter(this._ctx, fn, coreTrans, this._ctx.table.core); - }; - Collection2.prototype.clone = function(props2) { - var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); - if (props2) - extend(ctx, props2); - rv._ctx = ctx; - return rv; - }; - Collection2.prototype.raw = function() { - this._ctx.valueMapper = null; - return this; - }; - Collection2.prototype.each = function(fn) { - var ctx = this._ctx; - return this._read(function(trans) { - return iter(ctx, fn, trans, ctx.table.core); - }); - }; - Collection2.prototype.count = function(cb) { - var _this = this; - return this._read(function(trans) { - var ctx = _this._ctx; - var coreTable = ctx.table.core; - if (isPlainKeyRange(ctx, true)) { - return coreTable.count({ - trans, - query: { - index: getIndexOrStore(ctx, coreTable.schema), - range: ctx.range - } - }).then(function(count2) { - return Math.min(count2, ctx.limit); - }); - } else { - var count = 0; - return iter(ctx, function() { - ++count; - return false; - }, trans, coreTable).then(function() { - return count; - }); - } - }).then(cb); - }; - Collection2.prototype.sortBy = function(keyPath, cb) { - var parts = keyPath.split(".").reverse(), lastPart = parts[0], lastIndex = parts.length - 1; - function getval(obj, i) { - if (i) - return getval(obj[parts[i]], i - 1); - return obj[lastPart]; - } - var order = this._ctx.dir === "next" ? 1 : -1; - function sorter(a, b) { - var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); - return cmp3(aVal, bVal) * order; - } - return this.toArray(function(a) { - return a.slice().sort(sorter); - }).then(cb); - }; - Collection2.prototype.toArray = function(cb) { - var _this = this; - return this._read(function(trans) { - var ctx = _this._ctx; - if (isPlainKeyRange(ctx, true) && ctx.limit > 0) { - var valueMapper_1 = ctx.valueMapper; - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans, - limit: ctx.limit, - values: true, - direction: ctx.dir === "prev" ? "prev" : void 0, - query: { - index, - range: ctx.range - } - }).then(function(_a2) { - var result = _a2.result; - return valueMapper_1 ? result.map(valueMapper_1) : result; - }); - } else { - var a_1 = []; - return iter(ctx, function(item) { - return a_1.push(item); - }, trans, ctx.table.core).then(function() { - return a_1; - }); - } - }, cb); - }; - Collection2.prototype.offset = function(offset) { - var ctx = this._ctx; - if (offset <= 0) - return this; - ctx.offset += offset; - if (isPlainKeyRange(ctx)) { - addReplayFilter(ctx, function() { - var offsetLeft = offset; - return function(cursor, advance) { - if (offsetLeft === 0) - return true; - if (offsetLeft === 1) { - --offsetLeft; - return false; - } - advance(function() { - cursor.advance(offsetLeft); - offsetLeft = 0; - }); - return false; - }; - }); - } else { - addReplayFilter(ctx, function() { - var offsetLeft = offset; - return function() { - return --offsetLeft < 0; - }; - }); - } - return this; - }; - Collection2.prototype.limit = function(numRows) { - this._ctx.limit = Math.min(this._ctx.limit, numRows); - addReplayFilter(this._ctx, function() { - var rowsLeft = numRows; - return function(cursor, advance, resolve) { - if (--rowsLeft <= 0) - advance(resolve); - return rowsLeft >= 0; - }; - }, true); - return this; - }; - Collection2.prototype.until = function(filterFunction, bIncludeStopEntry) { - addFilter(this._ctx, function(cursor, advance, resolve) { - if (filterFunction(cursor.value)) { - advance(resolve); - return bIncludeStopEntry; - } else { - return true; - } - }); - return this; - }; - Collection2.prototype.first = function(cb) { - return this.limit(1).toArray(function(a) { - return a[0]; - }).then(cb); - }; - Collection2.prototype.last = function(cb) { - return this.reverse().first(cb); - }; - Collection2.prototype.filter = function(filterFunction) { - addFilter(this._ctx, function(cursor) { - return filterFunction(cursor.value); - }); - addMatchFilter(this._ctx, filterFunction); - return this; - }; - Collection2.prototype.and = function(filter) { - return this.filter(filter); - }; - Collection2.prototype.or = function(indexName) { - return new this.db.WhereClause(this._ctx.table, indexName, this); - }; - Collection2.prototype.reverse = function() { - this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev"; - if (this._ondirectionchange) - this._ondirectionchange(this._ctx.dir); - return this; - }; - Collection2.prototype.desc = function() { - return this.reverse(); - }; - Collection2.prototype.eachKey = function(cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function(val, cursor) { - cb(cursor.key, cursor); - }); - }; - Collection2.prototype.eachUniqueKey = function(cb) { - this._ctx.unique = "unique"; - return this.eachKey(cb); - }; - Collection2.prototype.eachPrimaryKey = function(cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function(val, cursor) { - cb(cursor.primaryKey, cursor); - }); - }; - Collection2.prototype.keys = function(cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function(item, cursor) { - a.push(cursor.key); - }).then(function() { - return a; - }).then(cb); - }; - Collection2.prototype.primaryKeys = function(cb) { - var ctx = this._ctx; - if (isPlainKeyRange(ctx, true) && ctx.limit > 0) { - return this._read(function(trans) { - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans, - values: false, - limit: ctx.limit, - direction: ctx.dir === "prev" ? "prev" : void 0, - query: { - index, - range: ctx.range - } - }); - }).then(function(_a2) { - var result = _a2.result; - return result; - }).then(cb); - } - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function(item, cursor) { - a.push(cursor.primaryKey); - }).then(function() { - return a; - }).then(cb); - }; - Collection2.prototype.uniqueKeys = function(cb) { - this._ctx.unique = "unique"; - return this.keys(cb); - }; - Collection2.prototype.firstKey = function(cb) { - return this.limit(1).keys(function(a) { - return a[0]; - }).then(cb); - }; - Collection2.prototype.lastKey = function(cb) { - return this.reverse().firstKey(cb); - }; - Collection2.prototype.distinct = function() { - var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; - if (!idx || !idx.multi) - return this; - var set = {}; - addFilter(this._ctx, function(cursor) { - var strKey = cursor.primaryKey.toString(); - var found = hasOwn(set, strKey); - set[strKey] = true; - return !found; - }); - return this; - }; - Collection2.prototype.modify = function(changes) { - var _this = this; - var ctx = this._ctx; - return this._write(function(trans) { - var modifyer; - if (typeof changes === "function") { - modifyer = changes; - } else { - modifyer = function(item) { - return applyUpdateSpec(item, changes); - }; - } - var coreTable = ctx.table.core; - var _a2 = coreTable.schema.primaryKey, outbound = _a2.outbound, extractKey2 = _a2.extractKey; - var limit = 200; - var modifyChunkSize = _this.db._options.modifyChunkSize; - if (modifyChunkSize) { - if (typeof modifyChunkSize == "object") { - limit = modifyChunkSize[coreTable.name] || modifyChunkSize["*"] || 200; - } else { - limit = modifyChunkSize; - } - } - var totalFailures = []; - var successCount = 0; - var failedKeys = []; - var applyMutateResult = function(expectedCount, res) { - var failures = res.failures, numFailures = res.numFailures; - successCount += expectedCount - numFailures; - for (var _i = 0, _a3 = keys(failures); _i < _a3.length; _i++) { - var pos = _a3[_i]; - totalFailures.push(failures[pos]); - } - }; - var isUnconditionalDelete = changes === deleteCallback; - return _this.clone().primaryKeys().then(function(keys2) { - var criteria = isPlainKeyRange(ctx) && ctx.limit === Infinity && (typeof changes !== "function" || isUnconditionalDelete) && { - index: ctx.index, - range: ctx.range - }; - var nextChunk = function(offset) { - var count = Math.min(limit, keys2.length - offset); - var keysInChunk = keys2.slice(offset, offset + count); - return (isUnconditionalDelete ? Promise.resolve([]) : coreTable.getMany({ - trans, - keys: keysInChunk, - cache: "immutable" - })).then(function(values) { - var addValues = []; - var putValues = []; - var putKeys = outbound ? [] : null; - var deleteKeys = isUnconditionalDelete ? keysInChunk : []; - if (!isUnconditionalDelete) - for (var i = 0; i < count; ++i) { - var origValue = values[i]; - var ctx_1 = { - value: deepClone(origValue), - primKey: keys2[offset + i] - }; - if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { - if (ctx_1.value == null) { - deleteKeys.push(keys2[offset + i]); - } else if (!outbound && cmp3(extractKey2(origValue), extractKey2(ctx_1.value)) !== 0) { - deleteKeys.push(keys2[offset + i]); - addValues.push(ctx_1.value); - } else { - putValues.push(ctx_1.value); - if (outbound) - putKeys.push(keys2[offset + i]); - } - } - } - return Promise.resolve(addValues.length > 0 && coreTable.mutate({ trans, type: "add", values: addValues }).then(function(res) { - for (var pos in res.failures) { - deleteKeys.splice(parseInt(pos), 1); - } - applyMutateResult(addValues.length, res); - })).then(function() { - return (putValues.length > 0 || criteria && typeof changes === "object") && coreTable.mutate({ - trans, - type: "put", - keys: putKeys, - values: putValues, - criteria, - changeSpec: typeof changes !== "function" && changes, - isAdditionalChunk: offset > 0 - }).then(function(res) { - return applyMutateResult(putValues.length, res); - }); - }).then(function() { - return (deleteKeys.length > 0 || criteria && isUnconditionalDelete) && coreTable.mutate({ - trans, - type: "delete", - keys: deleteKeys, - criteria, - isAdditionalChunk: offset > 0 - }).then(function(res) { - return builtInDeletionTrigger(ctx.table, deleteKeys, res); - }).then(function(res) { - return applyMutateResult(deleteKeys.length, res); - }); - }).then(function() { - return keys2.length > offset + count && nextChunk(offset + limit); - }); - }); - }; - return nextChunk(0).then(function() { - if (totalFailures.length > 0) - throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); - return keys2.length; - }); - }); - }); - }; - Collection2.prototype.delete = function() { - var ctx = this._ctx, range = ctx.range; - if (isPlainKeyRange(ctx) && !ctx.table.schema.yProps && (ctx.isPrimKey || range.type === 3)) { - return this._write(function(trans) { - var primaryKey = ctx.table.core.schema.primaryKey; - var coreRange = range; - return ctx.table.core.count({ trans, query: { index: primaryKey, range: coreRange } }).then(function(count) { - return ctx.table.core.mutate({ trans, type: "deleteRange", range: coreRange }).then(function(_a2) { - var failures = _a2.failures, numFailures = _a2.numFailures; - if (numFailures) - throw new ModifyError("Could not delete some values", Object.keys(failures).map(function(pos) { - return failures[pos]; - }), count - numFailures); - return count - numFailures; - }); - }); - }); - } - return this.modify(deleteCallback); - }; - return Collection2; - }(); - var deleteCallback = function(value, ctx) { - return ctx.value = null; - }; - function createCollectionConstructor(db2) { - return makeClassConstructor(Collection.prototype, function Collection2(whereClause, keyRangeGenerator) { - this.db = db2; - var keyRange = AnyRange, error = null; - if (keyRangeGenerator) - try { - keyRange = keyRangeGenerator(); - } catch (ex) { - error = ex; - } - var whereCtx = whereClause._ctx; - var table = whereCtx.table; - var readingHook = table.hook.reading.fire; - this._ctx = { - table, - index: whereCtx.index, - isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name, - range: keyRange, - keysOnly: false, - dir: "next", - unique: "", - algorithm: null, - filter: null, - replayFilter: null, - justLimit: true, - isMatch: null, - offset: 0, - limit: Infinity, - error, - or: whereCtx.or, - valueMapper: readingHook !== mirror ? readingHook : null - }; - }); - } - function simpleCompare(a, b) { - return a < b ? -1 : a === b ? 0 : 1; - } - function simpleCompareReverse(a, b) { - return a > b ? -1 : a === b ? 0 : 1; - } - function fail(collectionOrWhereClause, err, T) { - var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause.Collection(collectionOrWhereClause) : collectionOrWhereClause; - collection._ctx.error = T ? new T(err) : new TypeError(err); - return collection; - } - function emptyCollection(whereClause) { - return new whereClause.Collection(whereClause, function() { - return rangeEqual(""); - }).limit(0); - } - function upperFactory(dir) { - return dir === "next" ? function(s) { - return s.toUpperCase(); - } : function(s) { - return s.toLowerCase(); - }; - } - function lowerFactory(dir) { - return dir === "next" ? function(s) { - return s.toLowerCase(); - } : function(s) { - return s.toUpperCase(); - }; - } - function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp4, dir) { - var length = Math.min(key.length, lowerNeedle.length); - var llp = -1; - for (var i = 0; i < length; ++i) { - var lwrKeyChar = lowerKey[i]; - if (lwrKeyChar !== lowerNeedle[i]) { - if (cmp4(key[i], upperNeedle[i]) < 0) - return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); - if (cmp4(key[i], lowerNeedle[i]) < 0) - return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); - if (llp >= 0) - return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); - return null; - } - if (cmp4(key[i], lwrKeyChar) < 0) - llp = i; - } - if (length < lowerNeedle.length && dir === "next") - return key + upperNeedle.substr(key.length); - if (length < key.length && dir === "prev") - return key.substr(0, upperNeedle.length); - return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1); - } - function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { - var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; - if (!needles.every(function(s) { - return typeof s === "string"; - })) { - return fail(whereClause, STRING_EXPECTED); - } - function initDirection(dir) { - upper = upperFactory(dir); - lower = lowerFactory(dir); - compare = dir === "next" ? simpleCompare : simpleCompareReverse; - var needleBounds = needles.map(function(needle) { - return { lower: lower(needle), upper: upper(needle) }; - }).sort(function(a, b) { - return compare(a.lower, b.lower); - }); - upperNeedles = needleBounds.map(function(nb) { - return nb.upper; - }); - lowerNeedles = needleBounds.map(function(nb) { - return nb.lower; - }); - direction = dir; - nextKeySuffix = dir === "next" ? "" : suffix; - } - initDirection("next"); - var c = new whereClause.Collection(whereClause, function() { - return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); - }); - c._ondirectionchange = function(direction2) { - initDirection(direction2); - }; - var firstPossibleNeedle = 0; - c._addAlgorithm(function(cursor, advance, resolve) { - var key = cursor.key; - if (typeof key !== "string") - return false; - var lowerKey = lower(key); - if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { - return true; - } else { - var lowestPossibleCasing = null; - for (var i = firstPossibleNeedle; i < needlesLen; ++i) { - var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); - if (casing === null && lowestPossibleCasing === null) - firstPossibleNeedle = i + 1; - else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { - lowestPossibleCasing = casing; - } - } - if (lowestPossibleCasing !== null) { - advance(function() { - cursor.continue(lowestPossibleCasing + nextKeySuffix); - }); - } else { - advance(resolve); - } - return false; - } - }); - return c; - } - function createRange(lower, upper, lowerOpen, upperOpen) { - return { - type: 2, - lower, - upper, - lowerOpen, - upperOpen - }; - } - function rangeEqual(value) { - return { - type: 1, - lower: value, - upper: value - }; - } - var WhereClause = function() { - function WhereClause2() { - } - Object.defineProperty(WhereClause2.prototype, "Collection", { - get: function() { - return this._ctx.table.db.Collection; - }, - enumerable: false, - configurable: true - }); - WhereClause2.prototype.between = function(lower, upper, includeLower, includeUpper) { - includeLower = includeLower !== false; - includeUpper = includeUpper === true; - try { - if (this._cmp(lower, upper) > 0 || this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) - return emptyCollection(this); - return new this.Collection(this, function() { - return createRange(lower, upper, !includeLower, !includeUpper); - }); - } catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - }; - WhereClause2.prototype.equals = function(value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return rangeEqual(value); - }); - }; - WhereClause2.prototype.above = function(value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(value, void 0, true); - }); - }; - WhereClause2.prototype.aboveOrEqual = function(value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(value, void 0, false); - }); - }; - WhereClause2.prototype.below = function(value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(void 0, value, false, true); - }); - }; - WhereClause2.prototype.belowOrEqual = function(value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(void 0, value); - }); - }; - WhereClause2.prototype.startsWith = function(str) { - if (typeof str !== "string") - return fail(this, STRING_EXPECTED); - return this.between(str, str + maxString, true, true); - }; - WhereClause2.prototype.startsWithIgnoreCase = function(str) { - if (str === "") - return this.startsWith(str); - return addIgnoreCaseAlgorithm(this, function(x, a) { - return x.indexOf(a[0]) === 0; - }, [str], maxString); - }; - WhereClause2.prototype.equalsIgnoreCase = function(str) { - return addIgnoreCaseAlgorithm(this, function(x, a) { - return x === a[0]; - }, [str], ""); - }; - WhereClause2.prototype.anyOfIgnoreCase = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function(x, a) { - return a.indexOf(x) !== -1; - }, set, ""); - }; - WhereClause2.prototype.startsWithAnyOfIgnoreCase = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function(x, a) { - return a.some(function(n) { - return x.indexOf(n) === 0; - }); - }, set, maxString); - }; - WhereClause2.prototype.anyOf = function() { - var _this = this; - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - var compare = this._cmp; - try { - set.sort(compare); - } catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - if (set.length === 0) - return emptyCollection(this); - var c = new this.Collection(this, function() { - return createRange(set[0], set[set.length - 1]); - }); - c._ondirectionchange = function(direction) { - compare = direction === "next" ? _this._ascending : _this._descending; - set.sort(compare); - }; - var i = 0; - c._addAlgorithm(function(cursor, advance, resolve) { - var key = cursor.key; - while (compare(key, set[i]) > 0) { - ++i; - if (i === set.length) { - advance(resolve); - return false; - } - } - if (compare(key, set[i]) === 0) { - return true; - } else { - advance(function() { - cursor.continue(set[i]); - }); - return false; - } - }); - return c; - }; - WhereClause2.prototype.notEqual = function(value) { - return this.inAnyRange([ - [minKey, value], - [value, this.db._maxKey] - ], { includeLowers: false, includeUppers: false }); - }; - WhereClause2.prototype.noneOf = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return new this.Collection(this); - try { - set.sort(this._ascending); - } catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - var ranges = set.reduce(function(res, val) { - return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; - }, null); - ranges.push([set[set.length - 1], this.db._maxKey]); - return this.inAnyRange(ranges, { - includeLowers: false, - includeUppers: false - }); - }; - WhereClause2.prototype.inAnyRange = function(ranges, options) { - var _this = this; - var cmp4 = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; - if (ranges.length === 0) - return emptyCollection(this); - if (!ranges.every(function(range) { - return range[0] !== void 0 && range[1] !== void 0 && ascending(range[0], range[1]) <= 0; - })) { - return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); - } - var includeLowers = !options || options.includeLowers !== false; - var includeUppers = options && options.includeUppers === true; - function addRange2(ranges2, newRange) { - var i = 0, l = ranges2.length; - for (; i < l; ++i) { - var range = ranges2[i]; - if (cmp4(newRange[0], range[1]) < 0 && cmp4(newRange[1], range[0]) > 0) { - range[0] = min(range[0], newRange[0]); - range[1] = max(range[1], newRange[1]); - break; - } - } - if (i === l) - ranges2.push(newRange); - return ranges2; - } - var sortDirection = ascending; - function rangeSorter(a, b) { - return sortDirection(a[0], b[0]); - } - var set; - try { - set = ranges.reduce(addRange2, []); - set.sort(rangeSorter); - } catch (ex) { - return fail(this, INVALID_KEY_ARGUMENT); - } - var rangePos = 0; - var keyIsBeyondCurrentEntry = includeUppers ? function(key) { - return ascending(key, set[rangePos][1]) > 0; - } : function(key) { - return ascending(key, set[rangePos][1]) >= 0; - }; - var keyIsBeforeCurrentEntry = includeLowers ? function(key) { - return descending(key, set[rangePos][0]) > 0; - } : function(key) { - return descending(key, set[rangePos][0]) >= 0; - }; - function keyWithinCurrentRange(key) { - return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); - } - var checkKey = keyIsBeyondCurrentEntry; - var c = new this.Collection(this, function() { - return createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); - }); - c._ondirectionchange = function(direction) { - if (direction === "next") { - checkKey = keyIsBeyondCurrentEntry; - sortDirection = ascending; - } else { - checkKey = keyIsBeforeCurrentEntry; - sortDirection = descending; - } - set.sort(rangeSorter); - }; - c._addAlgorithm(function(cursor, advance, resolve) { - var key = cursor.key; - while (checkKey(key)) { - ++rangePos; - if (rangePos === set.length) { - advance(resolve); - return false; - } - } - if (keyWithinCurrentRange(key)) { - return true; - } else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { - return false; - } else { - advance(function() { - if (sortDirection === ascending) - cursor.continue(set[rangePos][0]); - else - cursor.continue(set[rangePos][1]); - }); - return false; - } - }); - return c; - }; - WhereClause2.prototype.startsWithAnyOf = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (!set.every(function(s) { - return typeof s === "string"; - })) { - return fail(this, "startsWithAnyOf() only works with strings"); - } - if (set.length === 0) - return emptyCollection(this); - return this.inAnyRange(set.map(function(str) { - return [str, str + maxString]; - })); - }; - return WhereClause2; - }(); - function createWhereClauseConstructor(db2) { - return makeClassConstructor(WhereClause.prototype, function WhereClause2(table, index, orCollection) { - this.db = db2; - this._ctx = { - table, - index: index === ":id" ? null : index, - or: orCollection - }; - this._cmp = this._ascending = cmp3; - this._descending = function(a, b) { - return cmp3(b, a); - }; - this._max = function(a, b) { - return cmp3(a, b) > 0 ? a : b; - }; - this._min = function(a, b) { - return cmp3(a, b) < 0 ? a : b; - }; - this._IDBKeyRange = db2._deps.IDBKeyRange; - if (!this._IDBKeyRange) - throw new exceptions.MissingAPI(); - }); - } - function eventRejectHandler(reject) { - return wrap(function(event) { - preventDefault(event); - reject(event.target.error); - return false; - }); - } - function preventDefault(event) { - if (event.stopPropagation) - event.stopPropagation(); - if (event.preventDefault) - event.preventDefault(); - } - var DEXIE_STORAGE_MUTATED_EVENT_NAME = "storagemutated"; - var STORAGE_MUTATED_DOM_EVENT_NAME = "x-storagemutated-1"; - var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); - var Transaction = function() { - function Transaction2() { - } - Transaction2.prototype._lock = function() { - assert(!PSD.global); - ++this._reculock; - if (this._reculock === 1 && !PSD.global) - PSD.lockOwnerFor = this; - return this; - }; - Transaction2.prototype._unlock = function() { - assert(!PSD.global); - if (--this._reculock === 0) { - if (!PSD.global) - PSD.lockOwnerFor = null; - while (this._blockedFuncs.length > 0 && !this._locked()) { - var fnAndPSD = this._blockedFuncs.shift(); - try { - usePSD(fnAndPSD[1], fnAndPSD[0]); - } catch (e) { - } - } - } - return this; - }; - Transaction2.prototype._locked = function() { - return this._reculock && PSD.lockOwnerFor !== this; - }; - Transaction2.prototype.create = function(idbtrans) { - var _this = this; - if (!this.mode) - return this; - var idbdb = this.db.idbdb; - var dbOpenError = this.db._state.dbOpenError; - assert(!this.idbtrans); - if (!idbtrans && !idbdb) { - switch (dbOpenError && dbOpenError.name) { - case "DatabaseClosedError": - throw new exceptions.DatabaseClosed(dbOpenError); - case "MissingAPIError": - throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); - default: - throw new exceptions.OpenFailed(dbOpenError); - } - } - if (!this.active) - throw new exceptions.TransactionInactive(); - assert(this._completion._state === null); - idbtrans = this.idbtrans = idbtrans || (this.db.core ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) : idbdb.transaction(this.storeNames, this.mode, { - durability: this.chromeTransactionDurability - })); - idbtrans.onerror = wrap(function(ev) { - preventDefault(ev); - _this._reject(idbtrans.error); - }); - idbtrans.onabort = wrap(function(ev) { - preventDefault(ev); - _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); - _this.active = false; - _this.on("abort").fire(ev); - }); - idbtrans.oncomplete = wrap(function() { - _this.active = false; - _this._resolve(); - if ("mutatedParts" in idbtrans) { - globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); - } - }); - return this; - }; - Transaction2.prototype._promise = function(mode, fn, bWriteLock) { - var _this = this; - if (mode === "readwrite" && this.mode !== "readwrite") - return rejection(new exceptions.ReadOnly("Transaction is readonly")); - if (!this.active) - return rejection(new exceptions.TransactionInactive()); - if (this._locked()) { - return new DexiePromise(function(resolve, reject) { - _this._blockedFuncs.push([ - function() { - _this._promise(mode, fn, bWriteLock).then(resolve, reject); - }, - PSD - ]); - }); - } else if (bWriteLock) { - return newScope(function() { - var p2 = new DexiePromise(function(resolve, reject) { - _this._lock(); - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p2.finally(function() { - return _this._unlock(); - }); - p2._lib = true; - return p2; - }); - } else { - var p = new DexiePromise(function(resolve, reject) { - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p._lib = true; - return p; - } - }; - Transaction2.prototype._root = function() { - return this.parent ? this.parent._root() : this; - }; - Transaction2.prototype.waitFor = function(promiseLike) { - var root = this._root(); - var promise = DexiePromise.resolve(promiseLike); - if (root._waitingFor) { - root._waitingFor = root._waitingFor.then(function() { - return promise; - }); - } else { - root._waitingFor = promise; - root._waitingQueue = []; - var store = root.idbtrans.objectStore(root.storeNames[0]); - (function spin() { - ++root._spinCount; - while (root._waitingQueue.length) - root._waitingQueue.shift()(); - if (root._waitingFor) - store.get(-Infinity).onsuccess = spin; - })(); - } - var currentWaitPromise = root._waitingFor; - return new DexiePromise(function(resolve, reject) { - promise.then(function(res) { - return root._waitingQueue.push(wrap(resolve.bind(null, res))); - }, function(err) { - return root._waitingQueue.push(wrap(reject.bind(null, err))); - }).finally(function() { - if (root._waitingFor === currentWaitPromise) { - root._waitingFor = null; - } - }); - }); - }; - Transaction2.prototype.abort = function() { - if (this.active) { - this.active = false; - if (this.idbtrans) - this.idbtrans.abort(); - this._reject(new exceptions.Abort()); - } - }; - Transaction2.prototype.table = function(tableName) { - var memoizedTables = this._memoizedTables || (this._memoizedTables = {}); - if (hasOwn(memoizedTables, tableName)) - return memoizedTables[tableName]; - var tableSchema = this.schema[tableName]; - if (!tableSchema) { - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - } - var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); - transactionBoundTable.core = this.db.core.table(tableName); - memoizedTables[tableName] = transactionBoundTable; - return transactionBoundTable; - }; - return Transaction2; - }(); - function createTransactionConstructor(db2) { - return makeClassConstructor(Transaction.prototype, function Transaction2(mode, storeNames, dbschema, chromeTransactionDurability, parent) { - var _this = this; - if (mode !== "readonly") - storeNames.forEach(function(storeName) { - var _a2; - var yProps = (_a2 = dbschema[storeName]) === null || _a2 === void 0 ? void 0 : _a2.yProps; - if (yProps) - storeNames = storeNames.concat(yProps.map(function(p) { - return p.updatesTable; - })); - }); - this.db = db2; - this.mode = mode; - this.storeNames = storeNames; - this.schema = dbschema; - this.chromeTransactionDurability = chromeTransactionDurability; - this.idbtrans = null; - this.on = Events(this, "complete", "error", "abort"); - this.parent = parent || null; - this.active = true; - this._reculock = 0; - this._blockedFuncs = []; - this._resolve = null; - this._reject = null; - this._waitingFor = null; - this._waitingQueue = null; - this._spinCount = 0; - this._completion = new DexiePromise(function(resolve, reject) { - _this._resolve = resolve; - _this._reject = reject; - }); - this._completion.then(function() { - _this.active = false; - _this.on.complete.fire(); - }, function(e) { - var wasActive = _this.active; - _this.active = false; - _this.on.error.fire(e); - _this.parent ? _this.parent._reject(e) : wasActive && _this.idbtrans && _this.idbtrans.abort(); - return rejection(e); - }); - }); - } - function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey, type2) { - return { - name, - keyPath, - unique, - multi, - auto, - compound, - src: (unique && !isPrimKey ? "&" : "") + (multi ? "*" : "") + (auto ? "++" : "") + nameFromKeyPath(keyPath), - type: type2 - }; - } - function nameFromKeyPath(keyPath) { - return typeof keyPath === "string" ? keyPath : keyPath ? "[" + [].join.call(keyPath, "+") + "]" : ""; - } - function createTableSchema(name, primKey, indexes) { - return { - name, - primKey, - indexes, - mappedClass: null, - idxByName: arrayToObject(indexes, function(index) { - return [index.name, index]; - }) - }; - } - function safariMultiStoreFix(storeNames) { - return storeNames.length === 1 ? storeNames[0] : storeNames; - } - var getMaxKey = function(IdbKeyRange) { - try { - IdbKeyRange.only([[]]); - getMaxKey = function() { - return [[]]; - }; - return [[]]; - } catch (e) { - getMaxKey = function() { - return maxString; - }; - return maxString; - } - }; - function getKeyExtractor(keyPath) { - if (keyPath == null) { - return function() { - return void 0; - }; - } else if (typeof keyPath === "string") { - return getSinglePathKeyExtractor(keyPath); - } else { - return function(obj) { - return getByKeyPath(obj, keyPath); - }; - } - } - function getSinglePathKeyExtractor(keyPath) { - var split = keyPath.split("."); - if (split.length === 1) { - return function(obj) { - return obj[keyPath]; - }; - } else { - return function(obj) { - return getByKeyPath(obj, keyPath); - }; - } - } - function arrayify(arrayLike) { - return [].slice.call(arrayLike); - } - var _id_counter = 0; - function getKeyPathAlias(keyPath) { - return keyPath == null ? ":id" : typeof keyPath === "string" ? keyPath : "[".concat(keyPath.join("+"), "]"); - } - function createDBCore(db2, IdbKeyRange, tmpTrans) { - function extractSchema(db3, trans) { - var tables2 = arrayify(db3.objectStoreNames); - var tempStore = tables2.length > 0 ? trans.objectStore(tables2[0]) : {}; - return { - schema: { - name: db3.name, - tables: tables2.map(function(table) { - return trans.objectStore(table); - }).map(function(store) { - var keyPath = store.keyPath, autoIncrement = store.autoIncrement; - var compound = isArray(keyPath); - var outbound = keyPath == null; - var indexByKeyPath = {}; - var result = { - name: store.name, - primaryKey: { - name: null, - isPrimaryKey: true, - outbound, - compound, - keyPath, - autoIncrement, - unique: true, - extractKey: getKeyExtractor(keyPath) - }, - indexes: arrayify(store.indexNames).map(function(indexName) { - return store.index(indexName); - }).map(function(index) { - var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath2 = index.keyPath; - var compound2 = isArray(keyPath2); - var result2 = { - name, - compound: compound2, - keyPath: keyPath2, - unique, - multiEntry, - extractKey: getKeyExtractor(keyPath2) - }; - indexByKeyPath[getKeyPathAlias(keyPath2)] = result2; - return result2; - }), - getIndexByKeyPath: function(keyPath2) { - return indexByKeyPath[getKeyPathAlias(keyPath2)]; - } - }; - indexByKeyPath[":id"] = result.primaryKey; - if (keyPath != null) { - indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; - } - return result; - }) - }, - hasGetAll: tables2.length > 0 && "getAll" in tempStore && !(typeof navigator !== "undefined" && /Safari/.test(navigator.userAgent) && !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604), - hasIdb3Features: "getAllRecords" in tempStore - }; - } - function makeIDBKeyRange(range) { - if (range.type === 3) - return null; - if (range.type === 4) - throw new Error("Cannot convert never type to IDBKeyRange"); - var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; - var idbRange = lower === void 0 ? upper === void 0 ? null : IdbKeyRange.upperBound(upper, !!upperOpen) : upper === void 0 ? IdbKeyRange.lowerBound(lower, !!lowerOpen) : IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); - return idbRange; - } - function createDbCoreTable(tableSchema) { - var tableName = tableSchema.name; - function mutate(_a3) { - var trans = _a3.trans, type2 = _a3.type, keys2 = _a3.keys, values = _a3.values, range = _a3.range; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var outbound = store.keyPath == null; - var isAddOrPut = type2 === "put" || type2 === "add"; - if (!isAddOrPut && type2 !== "delete" && type2 !== "deleteRange") - throw new Error("Invalid operation type: " + type2); - var length = (keys2 || values || { length: 1 }).length; - if (keys2 && values && keys2.length !== values.length) { - throw new Error("Given keys array must have same length as given values array."); - } - if (length === 0) - return resolve({ - numFailures: 0, - failures: {}, - results: [], - lastResult: void 0 - }); - var req; - var reqs = []; - var failures = []; - var numFailures = 0; - var errorHandler = function(event) { - ++numFailures; - preventDefault(event); - }; - if (type2 === "deleteRange") { - if (range.type === 4) - return resolve({ - numFailures, - failures, - results: [], - lastResult: void 0 - }); - if (range.type === 3) - reqs.push(req = store.clear()); - else - reqs.push(req = store.delete(makeIDBKeyRange(range))); - } else { - var _a4 = isAddOrPut ? outbound ? [values, keys2] : [values, null] : [keys2, null], args1 = _a4[0], args2 = _a4[1]; - if (isAddOrPut) { - for (var i = 0; i < length; ++i) { - reqs.push(req = args2 && args2[i] !== void 0 ? store[type2](args1[i], args2[i]) : store[type2](args1[i])); - req.onerror = errorHandler; - } - } else { - for (var i = 0; i < length; ++i) { - reqs.push(req = store[type2](args1[i])); - req.onerror = errorHandler; - } - } - } - var done = function(event) { - var lastResult = event.target.result; - reqs.forEach(function(req2, i2) { - return req2.error != null && (failures[i2] = req2.error); - }); - resolve({ - numFailures, - failures, - results: type2 === "delete" ? keys2 : reqs.map(function(req2) { - return req2.result; - }), - lastResult - }); - }; - req.onerror = function(event) { - errorHandler(event); - done(event); - }; - req.onsuccess = done; - }); - } - function openCursor2(_a3) { - var trans = _a3.trans, values = _a3.values, query2 = _a3.query, reverse = _a3.reverse, unique = _a3.unique; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var index = query2.index, range = query2.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var direction = reverse ? unique ? "prevunique" : "prev" : unique ? "nextunique" : "next"; - var req = values || !("openKeyCursor" in source) ? source.openCursor(makeIDBKeyRange(range), direction) : source.openKeyCursor(makeIDBKeyRange(range), direction); - req.onerror = eventRejectHandler(reject); - req.onsuccess = wrap(function(ev) { - var cursor = req.result; - if (!cursor) { - resolve(null); - return; - } - cursor.___id = ++_id_counter; - cursor.done = false; - var _cursorContinue = cursor.continue.bind(cursor); - var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; - if (_cursorContinuePrimaryKey) - _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); - var _cursorAdvance = cursor.advance.bind(cursor); - var doThrowCursorIsNotStarted = function() { - throw new Error("Cursor not started"); - }; - var doThrowCursorIsStopped = function() { - throw new Error("Cursor not stopped"); - }; - cursor.trans = trans; - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; - cursor.fail = wrap(reject); - cursor.next = function() { - var _this = this; - var gotOne = 1; - return this.start(function() { - return gotOne-- ? _this.continue() : _this.stop(); - }).then(function() { - return _this; - }); - }; - cursor.start = function(callback) { - var iterationPromise = new Promise(function(resolveIteration, rejectIteration) { - resolveIteration = wrap(resolveIteration); - req.onerror = eventRejectHandler(rejectIteration); - cursor.fail = rejectIteration; - cursor.stop = function(value) { - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; - resolveIteration(value); - }; - }); - var guardedCallback = function() { - if (req.result) { - try { - callback(); - } catch (err) { - cursor.fail(err); - } - } else { - cursor.done = true; - cursor.start = function() { - throw new Error("Cursor behind last entry"); - }; - cursor.stop(); - } - }; - req.onsuccess = wrap(function(ev2) { - req.onsuccess = guardedCallback; - guardedCallback(); - }); - cursor.continue = _cursorContinue; - cursor.continuePrimaryKey = _cursorContinuePrimaryKey; - cursor.advance = _cursorAdvance; - guardedCallback(); - return iterationPromise; - }; - resolve(cursor); - }, reject); - }); - } - function query(hasGetAll2, hasIdb3Features2) { - return function(request) { - return new Promise(function(resolve, reject) { - var _a3; - resolve = wrap(resolve); - var trans = request.trans, values = request.values, limit = request.limit, query2 = request.query; - var direction = (_a3 = request.direction) !== null && _a3 !== void 0 ? _a3 : "next"; - var nonInfinitLimit = limit === Infinity ? void 0 : limit; - var index = query2.index, range = query2.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - if (limit === 0) - return resolve({ result: [] }); - if (hasIdb3Features2) { - var options = { - query: idbKeyRange, - count: nonInfinitLimit, - direction - }; - var req = values ? source.getAll(options) : source.getAllKeys(options); - req.onsuccess = function(event) { - return resolve({ result: event.target.result }); - }; - req.onerror = eventRejectHandler(reject); - } else if (hasGetAll2 && direction === "next") { - var req = values ? source.getAll(idbKeyRange, nonInfinitLimit) : source.getAllKeys(idbKeyRange, nonInfinitLimit); - req.onsuccess = function(event) { - return resolve({ result: event.target.result }); - }; - req.onerror = eventRejectHandler(reject); - } else { - var count_1 = 0; - var req_1 = values || !("openKeyCursor" in source) ? source.openCursor(idbKeyRange, direction) : source.openKeyCursor(idbKeyRange, direction); - var result_1 = []; - req_1.onsuccess = function() { - var cursor = req_1.result; - if (!cursor) - return resolve({ result: result_1 }); - result_1.push(values ? cursor.value : cursor.primaryKey); - if (++count_1 === limit) - return resolve({ result: result_1 }); - cursor.continue(); - }; - req_1.onerror = eventRejectHandler(reject); - } - }); - }; - } - return { - name: tableName, - schema: tableSchema, - mutate, - getMany: function(_a3) { - var trans = _a3.trans, keys2 = _a3.keys; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var length = keys2.length; - var result = new Array(length); - var keyCount = 0; - var callbackCount = 0; - var req; - var successHandler = function(event) { - var req2 = event.target; - if ((result[req2._pos] = req2.result) != null) - ; - if (++callbackCount === keyCount) - resolve(result); - }; - var errorHandler = eventRejectHandler(reject); - for (var i = 0; i < length; ++i) { - var key = keys2[i]; - if (key != null) { - req = store.get(keys2[i]); - req._pos = i; - req.onsuccess = successHandler; - req.onerror = errorHandler; - ++keyCount; - } - } - if (keyCount === 0) - resolve(result); - }); - }, - get: function(_a3) { - var trans = _a3.trans, key = _a3.key; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var req = store.get(key); - req.onsuccess = function(event) { - return resolve(event.target.result); - }; - req.onerror = eventRejectHandler(reject); - }); - }, - query: query(hasGetAll, hasIdb3Features), - openCursor: openCursor2, - count: function(_a3) { - var query2 = _a3.query, trans = _a3.trans; - var index = query2.index, range = query2.range; - return new Promise(function(resolve, reject) { - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); - req.onsuccess = wrap(function(ev) { - return resolve(ev.target.result); - }); - req.onerror = eventRejectHandler(reject); - }); - } - }; - } - var _a2 = extractSchema(db2, tmpTrans), schema = _a2.schema, hasGetAll = _a2.hasGetAll, hasIdb3Features = _a2.hasIdb3Features; - var tables = schema.tables.map(function(tableSchema) { - return createDbCoreTable(tableSchema); - }); - var tableMap = {}; - tables.forEach(function(table) { - return tableMap[table.name] = table; - }); - return { - stack: "dbcore", - transaction: db2.transaction.bind(db2), - table: function(name) { - var result = tableMap[name]; - if (!result) - throw new Error("Table '".concat(name, "' not found")); - return tableMap[name]; - }, - MIN_KEY: -Infinity, - MAX_KEY: getMaxKey(IdbKeyRange), - schema - }; - } - function createMiddlewareStack(stackImpl, middlewares) { - return middlewares.reduce(function(down, _a2) { - var create = _a2.create; - return __assign(__assign({}, down), create(down)); - }, stackImpl); - } - function createMiddlewareStacks(middlewares, idbdb, _a2, tmpTrans) { - var IDBKeyRange = _a2.IDBKeyRange; - _a2.indexedDB; - var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); - return { - dbcore - }; - } - function generateMiddlewareStacks(db2, tmpTrans) { - var idbdb = tmpTrans.db; - var stacks = createMiddlewareStacks(db2._middlewares, idbdb, db2._deps, tmpTrans); - db2.core = stacks.dbcore; - db2.tables.forEach(function(table) { - var tableName = table.name; - if (db2.core.schema.tables.some(function(tbl) { - return tbl.name === tableName; - })) { - table.core = db2.core.table(tableName); - if (db2[tableName] instanceof db2.Table) { - db2[tableName].core = table.core; - } - } - }); - } - function setApiOnPlace(db2, objs, tableNames, dbschema) { - tableNames.forEach(function(tableName) { - var schema = dbschema[tableName]; - objs.forEach(function(obj) { - var propDesc = getPropertyDescriptor(obj, tableName); - if (!propDesc || "value" in propDesc && propDesc.value === void 0) { - if (obj === db2.Transaction.prototype || obj instanceof db2.Transaction) { - setProp(obj, tableName, { - get: function() { - return this.table(tableName); - }, - set: function(value) { - defineProperty(this, tableName, { - value, - writable: true, - configurable: true, - enumerable: true - }); - } - }); - } else { - obj[tableName] = new db2.Table(tableName, schema); - } - } - }); - }); - } - function removeTablesApi(db2, objs) { - objs.forEach(function(obj) { - for (var key in obj) { - if (obj[key] instanceof db2.Table) - delete obj[key]; - } - }); - } - function lowerVersionFirst(a, b) { - return a._cfg.version - b._cfg.version; - } - function runUpgraders(db2, oldVersion, idbUpgradeTrans, reject) { - var globalSchema = db2._dbSchema; - if (idbUpgradeTrans.objectStoreNames.contains("$meta") && !globalSchema.$meta) { - globalSchema.$meta = createTableSchema("$meta", parseIndexSyntax("")[0], []); - db2._storeNames.push("$meta"); - } - var trans = db2._createTransaction("readwrite", db2._storeNames, globalSchema); - trans.create(idbUpgradeTrans); - trans._completion.catch(reject); - var rejectTransaction = trans._reject.bind(trans); - var transless = PSD.transless || PSD; - newScope(function() { - PSD.trans = trans; - PSD.transless = transless; - if (oldVersion === 0) { - keys(globalSchema).forEach(function(tableName) { - createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); - }); - generateMiddlewareStacks(db2, idbUpgradeTrans); - DexiePromise.follow(function() { - return db2.on.populate.fire(trans); - }).catch(rejectTransaction); - } else { - generateMiddlewareStacks(db2, idbUpgradeTrans); - return getExistingVersion(db2, trans, oldVersion).then(function(oldVersion2) { - return updateTablesAndIndexes(db2, oldVersion2, trans, idbUpgradeTrans); - }).catch(rejectTransaction); - } - }); - } - function patchCurrentVersion(db2, idbUpgradeTrans) { - createMissingTables(db2._dbSchema, idbUpgradeTrans); - if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains("$meta")) { - idbUpgradeTrans.db.createObjectStore("$meta").add(Math.ceil(idbUpgradeTrans.db.version / 10 - 1), "version"); - } - var globalSchema = buildGlobalSchema(db2, db2.idbdb, idbUpgradeTrans); - adjustToExistingIndexNames(db2, db2._dbSchema, idbUpgradeTrans); - var diff = getSchemaDiff(globalSchema, db2._dbSchema); - var _loop_1 = function(tableChange2) { - if (tableChange2.change.length || tableChange2.recreate) { - console.warn("Unable to patch indexes of table ".concat(tableChange2.name, " because it has changes on the type of index or primary key.")); - return { value: void 0 }; - } - var store = idbUpgradeTrans.objectStore(tableChange2.name); - tableChange2.add.forEach(function(idx) { - if (debug) - console.debug("Dexie upgrade patch: Creating missing index ".concat(tableChange2.name, ".").concat(idx.src)); - addIndex(store, idx); - }); - }; - for (var _i = 0, _a2 = diff.change; _i < _a2.length; _i++) { - var tableChange = _a2[_i]; - var state_1 = _loop_1(tableChange); - if (typeof state_1 === "object") - return state_1.value; - } - } - function getExistingVersion(db2, trans, oldVersion) { - if (trans.storeNames.includes("$meta")) { - return trans.table("$meta").get("version").then(function(metaVersion) { - return metaVersion != null ? metaVersion : oldVersion; - }); - } else { - return DexiePromise.resolve(oldVersion); - } - } - function updateTablesAndIndexes(db2, oldVersion, trans, idbUpgradeTrans) { - var queue = []; - var versions = db2._versions; - var globalSchema = db2._dbSchema = buildGlobalSchema(db2, db2.idbdb, idbUpgradeTrans); - var versToRun = versions.filter(function(v) { - return v._cfg.version >= oldVersion; - }); - if (versToRun.length === 0) { - return DexiePromise.resolve(); - } - versToRun.forEach(function(version) { - queue.push(function() { - var oldSchema = globalSchema; - var newSchema = version._cfg.dbschema; - adjustToExistingIndexNames(db2, oldSchema, idbUpgradeTrans); - adjustToExistingIndexNames(db2, newSchema, idbUpgradeTrans); - globalSchema = db2._dbSchema = newSchema; - var diff = getSchemaDiff(oldSchema, newSchema); - diff.add.forEach(function(tuple) { - createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); - }); - diff.change.forEach(function(change) { - if (change.recreate) { - throw new exceptions.Upgrade("Not yet support for changing primary key"); - } else { - var store_1 = idbUpgradeTrans.objectStore(change.name); - change.add.forEach(function(idx) { - return addIndex(store_1, idx); - }); - change.change.forEach(function(idx) { - store_1.deleteIndex(idx.name); - addIndex(store_1, idx); - }); - change.del.forEach(function(idxName) { - return store_1.deleteIndex(idxName); - }); - } - }); - var contentUpgrade = version._cfg.contentUpgrade; - if (contentUpgrade && version._cfg.version > oldVersion) { - generateMiddlewareStacks(db2, idbUpgradeTrans); - trans._memoizedTables = {}; - var upgradeSchema_1 = shallowClone(newSchema); - diff.del.forEach(function(table) { - upgradeSchema_1[table] = oldSchema[table]; - }); - removeTablesApi(db2, [db2.Transaction.prototype]); - setApiOnPlace(db2, [db2.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); - trans.schema = upgradeSchema_1; - var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); - if (contentUpgradeIsAsync_1) { - incrementExpectedAwaits(); - } - var returnValue_1; - var promiseFollowed = DexiePromise.follow(function() { - returnValue_1 = contentUpgrade(trans); - if (returnValue_1) { - if (contentUpgradeIsAsync_1) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue_1.then(decrementor, decrementor); - } - } - }); - return returnValue_1 && typeof returnValue_1.then === "function" ? DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function() { - return returnValue_1; - }); - } - }); - queue.push(function(idbtrans) { - var newSchema = version._cfg.dbschema; - deleteRemovedTables(newSchema, idbtrans); - removeTablesApi(db2, [db2.Transaction.prototype]); - setApiOnPlace(db2, [db2.Transaction.prototype], db2._storeNames, db2._dbSchema); - trans.schema = db2._dbSchema; - }); - queue.push(function(idbtrans) { - if (db2.idbdb.objectStoreNames.contains("$meta")) { - if (Math.ceil(db2.idbdb.version / 10) === version._cfg.version) { - db2.idbdb.deleteObjectStore("$meta"); - delete db2._dbSchema.$meta; - db2._storeNames = db2._storeNames.filter(function(name) { - return name !== "$meta"; - }); - } else { - idbtrans.objectStore("$meta").put(version._cfg.version, "version"); - } - } - }); - }); - function runQueue() { - return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : DexiePromise.resolve(); - } - return runQueue().then(function() { - createMissingTables(globalSchema, idbUpgradeTrans); - }); - } - function getSchemaDiff(oldSchema, newSchema) { - var diff = { - del: [], - add: [], - change: [] - }; - var table; - for (table in oldSchema) { - if (!newSchema[table]) - diff.del.push(table); - } - for (table in newSchema) { - var oldDef = oldSchema[table], newDef = newSchema[table]; - if (!oldDef) { - diff.add.push([table, newDef]); - } else { - var change = { - name: table, - def: newDef, - recreate: false, - del: [], - add: [], - change: [] - }; - if ("" + (oldDef.primKey.keyPath || "") !== "" + (newDef.primKey.keyPath || "") || oldDef.primKey.auto !== newDef.primKey.auto) { - change.recreate = true; - diff.change.push(change); - } else { - var oldIndexes = oldDef.idxByName; - var newIndexes = newDef.idxByName; - var idxName = void 0; - for (idxName in oldIndexes) { - if (!newIndexes[idxName]) - change.del.push(idxName); - } - for (idxName in newIndexes) { - var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; - if (!oldIdx) - change.add.push(newIdx); - else if (oldIdx.src !== newIdx.src) - change.change.push(newIdx); - } - if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { - diff.change.push(change); - } - } - } - } - return diff; - } - function createTable(idbtrans, tableName, primKey, indexes) { - var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); - indexes.forEach(function(idx) { - return addIndex(store, idx); - }); - return store; - } - function createMissingTables(newSchema, idbtrans) { - keys(newSchema).forEach(function(tableName) { - if (!idbtrans.db.objectStoreNames.contains(tableName)) { - if (debug) - console.debug("Dexie: Creating missing table", tableName); - createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); - } - }); - } - function deleteRemovedTables(newSchema, idbtrans) { - [].slice.call(idbtrans.db.objectStoreNames).forEach(function(storeName) { - return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName); - }); - } - function addIndex(store, idx) { - store.createIndex(idx.name, idx.keyPath, { - unique: idx.unique, - multiEntry: idx.multi - }); - } - function buildGlobalSchema(db2, idbdb, tmpTrans) { - var globalSchema = {}; - var dbStoreNames = slice(idbdb.objectStoreNames, 0); - dbStoreNames.forEach(function(storeName) { - var store = tmpTrans.objectStore(storeName); - var keyPath = store.keyPath; - var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", true, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); - var indexes = []; - for (var j = 0; j < store.indexNames.length; ++j) { - var idbindex = store.index(store.indexNames[j]); - keyPath = idbindex.keyPath; - var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); - indexes.push(index); - } - globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); - }); - return globalSchema; - } - function readGlobalSchema(db2, idbdb, tmpTrans) { - db2.verno = idbdb.version / 10; - var globalSchema = db2._dbSchema = buildGlobalSchema(db2, idbdb, tmpTrans); - db2._storeNames = slice(idbdb.objectStoreNames, 0); - setApiOnPlace(db2, [db2._allTables], keys(globalSchema), globalSchema); - } - function verifyInstalledSchema(db2, tmpTrans) { - var installedSchema = buildGlobalSchema(db2, db2.idbdb, tmpTrans); - var diff = getSchemaDiff(installedSchema, db2._dbSchema); - return !(diff.add.length || diff.change.some(function(ch) { - return ch.add.length || ch.change.length; - })); - } - function adjustToExistingIndexNames(db2, schema, idbtrans) { - var storeNames = idbtrans.db.objectStoreNames; - for (var i = 0; i < storeNames.length; ++i) { - var storeName = storeNames[i]; - var store = idbtrans.objectStore(storeName); - db2._hasGetAll = "getAll" in store; - for (var j = 0; j < store.indexNames.length; ++j) { - var indexName = store.indexNames[j]; - var keyPath = store.index(indexName).keyPath; - var dexieName = typeof keyPath === "string" ? keyPath : "[" + slice(keyPath).join("+") + "]"; - if (schema[storeName]) { - var indexSpec = schema[storeName].idxByName[dexieName]; - if (indexSpec) { - indexSpec.name = indexName; - delete schema[storeName].idxByName[dexieName]; - schema[storeName].idxByName[indexName] = indexSpec; - } - } - } - } - if (typeof navigator !== "undefined" && /Safari/.test(navigator.userAgent) && !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { - db2._hasGetAll = false; - } - } - function parseIndexSyntax(primKeyAndIndexes) { - return primKeyAndIndexes.split(",").map(function(index, indexNum) { - var _a2; - var typeSplit = index.split(":"); - var type2 = (_a2 = typeSplit[1]) === null || _a2 === void 0 ? void 0 : _a2.trim(); - index = typeSplit[0].trim(); - var name = index.replace(/([&*]|\+\+)/g, ""); - var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split("+") : name; - return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0, type2); - }); - } - var Version = function() { - function Version2() { - } - Version2.prototype._createTableSchema = function(name, primKey, indexes) { - return createTableSchema(name, primKey, indexes); - }; - Version2.prototype._parseIndexSyntax = function(primKeyAndIndexes) { - return parseIndexSyntax(primKeyAndIndexes); - }; - Version2.prototype._parseStoresSpec = function(stores, outSchema) { - var _this = this; - keys(stores).forEach(function(tableName) { - if (stores[tableName] !== null) { - var indexes = _this._parseIndexSyntax(stores[tableName]); - var primKey = indexes.shift(); - if (!primKey) { - throw new exceptions.Schema("Invalid schema for table " + tableName + ": " + stores[tableName]); - } - primKey.unique = true; - if (primKey.multi) - throw new exceptions.Schema("Primary key cannot be multiEntry*"); - indexes.forEach(function(idx) { - if (idx.auto) - throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); - if (!idx.keyPath) - throw new exceptions.Schema("Index must have a name and cannot be an empty string"); - }); - var tblSchema = _this._createTableSchema(tableName, primKey, indexes); - outSchema[tableName] = tblSchema; - } - }); - }; - Version2.prototype.stores = function(stores) { - var db2 = this.db; - this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; - var versions = db2._versions; - var storesSpec = {}; - var dbschema = {}; - versions.forEach(function(version) { - extend(storesSpec, version._cfg.storesSource); - dbschema = version._cfg.dbschema = {}; - version._parseStoresSpec(storesSpec, dbschema); - }); - db2._dbSchema = dbschema; - removeTablesApi(db2, [db2._allTables, db2, db2.Transaction.prototype]); - setApiOnPlace(db2, [db2._allTables, db2, db2.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); - db2._storeNames = keys(dbschema); - return this; - }; - Version2.prototype.upgrade = function(upgradeFunction) { - this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); - return this; - }; - return Version2; - }(); - function createVersionConstructor(db2) { - return makeClassConstructor(Version.prototype, function Version2(versionNumber) { - this.db = db2; - this._cfg = { - version: versionNumber, - storesSource: null, - dbschema: {}, - tables: {}, - contentUpgrade: null - }; - }); - } - var connections = createConnectionsManager(); - function createConnectionsManager() { - if (typeof FinalizationRegistry !== "undefined" && typeof WeakRef !== "undefined") { - var _refs_1 = /* @__PURE__ */ new Set(); - var _registry_1 = new FinalizationRegistry(function(ref) { - _refs_1.delete(ref); - }); - var toArray = function() { - return Array.from(_refs_1).map(function(ref) { - return ref.deref(); - }).filter(function(db2) { - return db2 !== void 0; - }); - }; - var add3 = function(db2) { - var ref = new WeakRef(db2._novip); - _refs_1.add(ref); - _registry_1.register(db2._novip, ref, ref); - if (_refs_1.size > db2._options.maxConnections) { - var oldestRef = _refs_1.values().next().value; - _refs_1.delete(oldestRef); - _registry_1.unregister(oldestRef); - } - }; - var remove3 = function(db2) { - if (!db2) - return; - var iterator = _refs_1.values(); - var result = iterator.next(); - while (!result.done) { - var ref = result.value; - if (ref.deref() === db2._novip) { - _refs_1.delete(ref); - _registry_1.unregister(ref); - return; - } - result = iterator.next(); - } - }; - return { toArray, add: add3, remove: remove3 }; - } else { - var connections_1 = []; - var toArray = function() { - return connections_1; - }; - var add3 = function(db2) { - connections_1.push(db2._novip); - }; - var remove3 = function(db2) { - if (!db2) - return; - var index = connections_1.indexOf(db2._novip); - if (index !== -1) { - connections_1.splice(index, 1); - } - }; - return { toArray, add: add3, remove: remove3 }; - } - } - function getDbNamesTable(indexedDB2, IDBKeyRange) { - var dbNamesDB = indexedDB2["_dbNamesDB"]; - if (!dbNamesDB) { - dbNamesDB = indexedDB2["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { - addons: [], - indexedDB: indexedDB2, - IDBKeyRange - }); - dbNamesDB.version(1).stores({ dbnames: "name" }); - } - return dbNamesDB.table("dbnames"); - } - function hasDatabasesNative(indexedDB2) { - return indexedDB2 && typeof indexedDB2.databases === "function"; - } - function getDatabaseNames(_a2) { - var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; - return hasDatabasesNative(indexedDB2) ? Promise.resolve(indexedDB2.databases()).then(function(infos) { - return infos.map(function(info) { - return info.name; - }).filter(function(name) { - return name !== DBNAMES_DB; - }); - }) : getDbNamesTable(indexedDB2, IDBKeyRange).toCollection().primaryKeys(); - } - function _onDatabaseCreated(_a2, name) { - var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; - !hasDatabasesNative(indexedDB2) && name !== DBNAMES_DB && getDbNamesTable(indexedDB2, IDBKeyRange).put({ name }).catch(nop); - } - function _onDatabaseDeleted(_a2, name) { - var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; - !hasDatabasesNative(indexedDB2) && name !== DBNAMES_DB && getDbNamesTable(indexedDB2, IDBKeyRange).delete(name).catch(nop); - } - function vip(fn) { - return newScope(function() { - PSD.letThrough = true; - return fn(); - }); - } - function idbReady() { - var isSafari = !navigator.userAgentData && /Safari\//.test(navigator.userAgent) && !/Chrom(e|ium)\//.test(navigator.userAgent); - if (!isSafari || !indexedDB.databases) - return Promise.resolve(); - var intervalId; - return new Promise(function(resolve) { - var tryIdb = function() { - return indexedDB.databases().finally(resolve); - }; - intervalId = setInterval(tryIdb, 100); - tryIdb(); - }).finally(function() { - return clearInterval(intervalId); - }); - } - var _a; - function isEmptyRange(node) { - return !("from" in node); - } - var RangeSet2 = function(fromOrTree, to) { - if (this) { - extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); - } else { - var rv = new RangeSet2(); - if (fromOrTree && "d" in fromOrTree) { - extend(rv, fromOrTree); - } - return rv; - } - }; - props(RangeSet2.prototype, (_a = { - add: function(rangeSet) { - mergeRanges2(this, rangeSet); - return this; - }, - addKey: function(key) { - addRange(this, key, key); - return this; - }, - addKeys: function(keys2) { - var _this = this; - keys2.forEach(function(key) { - return addRange(_this, key, key); - }); - return this; - }, - hasKey: function(key) { - var node = getRangeSetIterator(this).next(key).value; - return node && cmp3(node.from, key) <= 0 && cmp3(node.to, key) >= 0; - } - }, _a[iteratorSymbol] = function() { - return getRangeSetIterator(this); - }, _a)); - function addRange(target, from, to) { - var diff = cmp3(from, to); - if (isNaN(diff)) - return; - if (diff > 0) - throw RangeError(); - if (isEmptyRange(target)) - return extend(target, { from, to, d: 1 }); - var left = target.l; - var right = target.r; - if (cmp3(to, target.from) < 0) { - left ? addRange(left, from, to) : target.l = { from, to, d: 1, l: null, r: null }; - return rebalance(target); - } - if (cmp3(from, target.to) > 0) { - right ? addRange(right, from, to) : target.r = { from, to, d: 1, l: null, r: null }; - return rebalance(target); - } - if (cmp3(from, target.from) < 0) { - target.from = from; - target.l = null; - target.d = right ? right.d + 1 : 1; - } - if (cmp3(to, target.to) > 0) { - target.to = to; - target.r = null; - target.d = target.l ? target.l.d + 1 : 1; - } - var rightWasCutOff = !target.r; - if (left && !target.l) { - mergeRanges2(target, left); - } - if (right && rightWasCutOff) { - mergeRanges2(target, right); - } - } - function mergeRanges2(target, newSet) { - function _addRangeSet(target2, _a2) { - var from = _a2.from, to = _a2.to, l = _a2.l, r = _a2.r; - addRange(target2, from, to); - if (l) - _addRangeSet(target2, l); - if (r) - _addRangeSet(target2, r); - } - if (!isEmptyRange(newSet)) - _addRangeSet(target, newSet); - } - function rangesOverlap2(rangeSet1, rangeSet2) { - var i1 = getRangeSetIterator(rangeSet2); - var nextResult1 = i1.next(); - if (nextResult1.done) - return false; - var a = nextResult1.value; - var i2 = getRangeSetIterator(rangeSet1); - var nextResult2 = i2.next(a.from); - var b = nextResult2.value; - while (!nextResult1.done && !nextResult2.done) { - if (cmp3(b.from, a.to) <= 0 && cmp3(b.to, a.from) >= 0) - return true; - cmp3(a.from, b.from) < 0 ? a = (nextResult1 = i1.next(b.from)).value : b = (nextResult2 = i2.next(a.from)).value; - } - return false; - } - function getRangeSetIterator(node) { - var state = isEmptyRange(node) ? null : { s: 0, n: node }; - return { - next: function(key) { - var keyProvided = arguments.length > 0; - while (state) { - switch (state.s) { - case 0: - state.s = 1; - if (keyProvided) { - while (state.n.l && cmp3(key, state.n.from) < 0) - state = { up: state, n: state.n.l, s: 1 }; - } else { - while (state.n.l) - state = { up: state, n: state.n.l, s: 1 }; - } - case 1: - state.s = 2; - if (!keyProvided || cmp3(key, state.n.to) <= 0) - return { value: state.n, done: false }; - case 2: - if (state.n.r) { - state.s = 3; - state = { up: state, n: state.n.r, s: 0 }; - continue; - } - case 3: - state = state.up; - } - } - return { done: true }; - } - }; - } - function rebalance(target) { - var _a2, _b; - var diff = (((_a2 = target.r) === null || _a2 === void 0 ? void 0 : _a2.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); - var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; - if (r) { - var l = r === "r" ? "l" : "r"; - var rootClone = __assign({}, target); - var oldRootRight = target[r]; - target.from = oldRootRight.from; - target.to = oldRootRight.to; - target[r] = oldRootRight[r]; - rootClone[r] = oldRootRight[l]; - target[l] = rootClone; - rootClone.d = computeDepth(rootClone); - } - target.d = computeDepth(target); - } - function computeDepth(_a2) { - var r = _a2.r, l = _a2.l; - return (r ? l ? Math.max(r.d, l.d) : r.d : l ? l.d : 0) + 1; - } - function extendObservabilitySet(target, newSet) { - keys(newSet).forEach(function(part) { - if (target[part]) - mergeRanges2(target[part], newSet[part]); - else - target[part] = cloneSimpleObjectTree(newSet[part]); - }); - return target; - } - function obsSetsOverlap(os1, os2) { - return os1.all || os2.all || Object.keys(os1).some(function(key) { - return os2[key] && rangesOverlap2(os2[key], os1[key]); - }); - } - var cache = {}; - var unsignaledParts = {}; - var isTaskEnqueued = false; - function signalSubscribersLazily(part, optimistic) { - extendObservabilitySet(unsignaledParts, part); - if (!isTaskEnqueued) { - isTaskEnqueued = true; - setTimeout(function() { - isTaskEnqueued = false; - var parts = unsignaledParts; - unsignaledParts = {}; - signalSubscribersNow(parts, false); - }, 0); - } - } - function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) { - if (deleteAffectedCacheEntries === void 0) { - deleteAffectedCacheEntries = false; - } - var queriesToSignal = /* @__PURE__ */ new Set(); - if (updatedParts.all) { - for (var _i = 0, _a2 = Object.values(cache); _i < _a2.length; _i++) { - var tblCache = _a2[_i]; - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } else { - for (var key in updatedParts) { - var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); - if (parts) { - var dbName = parts[1], tableName = parts[2]; - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (tblCache) - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } - } - queriesToSignal.forEach(function(requery) { - return requery(); - }); - } - function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { - var updatedEntryLists = []; - for (var _i = 0, _a2 = Object.entries(tblCache.queries.query); _i < _a2.length; _i++) { - var _b = _a2[_i], indexName = _b[0], entries = _b[1]; - var filteredEntries = []; - for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) { - var entry = entries_1[_c]; - if (obsSetsOverlap(updatedParts, entry.obsSet)) { - entry.subscribers.forEach(function(requery) { - return outQueriesToSignal.add(requery); - }); - } else if (deleteAffectedCacheEntries) { - filteredEntries.push(entry); - } - } - if (deleteAffectedCacheEntries) - updatedEntryLists.push([indexName, filteredEntries]); - } - if (deleteAffectedCacheEntries) { - for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) { - var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1]; - tblCache.queries.query[indexName] = filteredEntries; - } - } - } - function dexieOpen(db2) { - var state = db2._state; - var indexedDB2 = db2._deps.indexedDB; - if (state.isBeingOpened || db2.idbdb) - return state.dbReadyPromise.then(function() { - return state.dbOpenError ? rejection(state.dbOpenError) : db2; - }); - state.isBeingOpened = true; - state.dbOpenError = null; - state.openComplete = false; - var openCanceller = state.openCanceller; - var nativeVerToOpen = Math.round(db2.verno * 10); - var schemaPatchMode = false; - function throwIfCancelled() { - if (state.openCanceller !== openCanceller) - throw new exceptions.DatabaseClosed("db.open() was cancelled"); - } - var resolveDbReady = state.dbReadyResolve, upgradeTransaction = null, wasCreated = false; - var tryOpenDB = function() { - return new DexiePromise(function(resolve, reject) { - throwIfCancelled(); - if (!indexedDB2) - throw new exceptions.MissingAPI(); - var dbName = db2.name; - var req = state.autoSchema || !nativeVerToOpen ? indexedDB2.open(dbName) : indexedDB2.open(dbName, nativeVerToOpen); - if (!req) - throw new exceptions.MissingAPI(); - req.onerror = eventRejectHandler(reject); - req.onblocked = wrap(db2._fireOnBlocked); - req.onupgradeneeded = wrap(function(e) { - upgradeTransaction = req.transaction; - if (state.autoSchema && !db2._options.allowEmptyDB) { - req.onerror = preventDefault; - upgradeTransaction.abort(); - req.result.close(); - var delreq = indexedDB2.deleteDatabase(dbName); - delreq.onsuccess = delreq.onerror = wrap(function() { - reject(new exceptions.NoSuchDatabase("Database ".concat(dbName, " doesnt exist"))); - }); - } else { - upgradeTransaction.onerror = eventRejectHandler(reject); - var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; - wasCreated = oldVer < 1; - db2.idbdb = req.result; - if (schemaPatchMode) { - patchCurrentVersion(db2, upgradeTransaction); - } - runUpgraders(db2, oldVer / 10, upgradeTransaction, reject); - } - }, reject); - req.onsuccess = wrap(function() { - upgradeTransaction = null; - var idbdb = db2.idbdb = req.result; - var objectStoreNames = slice(idbdb.objectStoreNames); - if (objectStoreNames.length > 0) - try { - var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), "readonly"); - if (state.autoSchema) - readGlobalSchema(db2, idbdb, tmpTrans); - else { - adjustToExistingIndexNames(db2, db2._dbSchema, tmpTrans); - if (!verifyInstalledSchema(db2, tmpTrans) && !schemaPatchMode) { - console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."); - idbdb.close(); - nativeVerToOpen = idbdb.version + 1; - schemaPatchMode = true; - return resolve(tryOpenDB()); - } - } - generateMiddlewareStacks(db2, tmpTrans); - } catch (e) { - } - connections.add(db2); - idbdb.onversionchange = wrap(function(ev) { - state.vcFired = true; - db2.on("versionchange").fire(ev); - }); - idbdb.onclose = wrap(function() { - db2.close({ disableAutoOpen: false }); - }); - if (wasCreated) - _onDatabaseCreated(db2._deps, dbName); - resolve(); - }, reject); - }).catch(function(err) { - switch (err === null || err === void 0 ? void 0 : err.name) { - case "UnknownError": - if (state.PR1398_maxLoop > 0) { - state.PR1398_maxLoop--; - console.warn("Dexie: Workaround for Chrome UnknownError on open()"); - return tryOpenDB(); - } - break; - case "VersionError": - if (nativeVerToOpen > 0) { - nativeVerToOpen = 0; - return tryOpenDB(); - } - break; - } - return DexiePromise.reject(err); - }); - }; - return DexiePromise.race([ - openCanceller, - (typeof navigator === "undefined" ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) - ]).then(function() { - throwIfCancelled(); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function() { - return db2.on.ready.fire(db2.vip); - })).then(function fireRemainders() { - if (state.onReadyBeingFired.length > 0) { - var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function() { - return remainders_1(db2.vip); - })).then(fireRemainders); - } - }); - }).finally(function() { - if (state.openCanceller === openCanceller) { - state.onReadyBeingFired = null; - state.isBeingOpened = false; - } - }).catch(function(err) { - state.dbOpenError = err; - try { - upgradeTransaction && upgradeTransaction.abort(); - } catch (_a2) { - } - if (openCanceller === state.openCanceller) { - db2._close(); - } - return rejection(err); - }).finally(function() { - state.openComplete = true; - resolveDbReady(); - }).then(function() { - if (wasCreated) { - var everything_1 = {}; - db2.tables.forEach(function(table) { - table.schema.indexes.forEach(function(idx) { - if (idx.name) - everything_1["idb://".concat(db2.name, "/").concat(table.name, "/").concat(idx.name)] = new RangeSet2(-Infinity, [[[]]]); - }); - everything_1["idb://".concat(db2.name, "/").concat(table.name, "/")] = everything_1["idb://".concat(db2.name, "/").concat(table.name, "/:dels")] = new RangeSet2(-Infinity, [[[]]]); - }); - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1); - signalSubscribersNow(everything_1, true); - } - return db2; - }); - } - function awaitIterator(iterator) { - var callNext = function(result) { - return iterator.next(result); - }, doThrow = function(error) { - return iterator.throw(error); - }, onSuccess = step(callNext), onError = step(doThrow); - function step(getNext) { - return function(val) { - var next = getNext(val), value = next.value; - return next.done ? value : !value || typeof value.then !== "function" ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError); - }; - } - return step(callNext)(); - } - function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { - var i = arguments.length; - if (i < 2) - throw new exceptions.InvalidArgument("Too few arguments"); - var args = new Array(i - 1); - while (--i) - args[i - 1] = arguments[i]; - scopeFunc = args.pop(); - var tables = flatten(args); - return [mode, tables, scopeFunc]; - } - function enterTransactionScope(db2, mode, storeNames, parentTransaction, scopeFunc) { - return DexiePromise.resolve().then(function() { - var transless = PSD.transless || PSD; - var trans = db2._createTransaction(mode, storeNames, db2._dbSchema, parentTransaction); - trans.explicit = true; - var zoneProps = { - trans, - transless - }; - if (parentTransaction) { - trans.idbtrans = parentTransaction.idbtrans; - } else { - try { - trans.create(); - trans.idbtrans._explicit = true; - db2._state.PR1398_maxLoop = 3; - } catch (ex) { - if (ex.name === errnames.InvalidState && db2.isOpen() && --db2._state.PR1398_maxLoop > 0) { - console.warn("Dexie: Need to reopen db"); - db2.close({ disableAutoOpen: false }); - return db2.open().then(function() { - return enterTransactionScope(db2, mode, storeNames, null, scopeFunc); - }); - } - return rejection(ex); - } - } - var scopeFuncIsAsync = isAsyncFunction(scopeFunc); - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var returnValue; - var promiseFollowed = DexiePromise.follow(function() { - returnValue = scopeFunc.call(trans, trans); - if (returnValue) { - if (scopeFuncIsAsync) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue.then(decrementor, decrementor); - } else if (typeof returnValue.next === "function" && typeof returnValue.throw === "function") { - returnValue = awaitIterator(returnValue); - } - } - }, zoneProps); - return (returnValue && typeof returnValue.then === "function" ? DexiePromise.resolve(returnValue).then(function(x) { - return trans.active ? x : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); - }) : promiseFollowed.then(function() { - return returnValue; - })).then(function(x) { - if (parentTransaction) - trans._resolve(); - return trans._completion.then(function() { - return x; - }); - }).catch(function(e) { - trans._reject(e); - return rejection(e); - }); - }); - } - function pad2(a, value, count) { - var result = isArray(a) ? a.slice() : [a]; - for (var i = 0; i < count; ++i) - result.push(value); - return result; - } - function createVirtualIndexMiddleware(down) { - return __assign(__assign({}, down), { table: function(tableName) { - var table = down.table(tableName); - var schema = table.schema; - var indexLookup = /* @__PURE__ */ Object.create(null); - var allVirtualIndexes = []; - function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { - var keyPathAlias = getKeyPathAlias(keyPath); - var indexList = indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []; - var keyLength = keyPath == null ? 0 : typeof keyPath === "string" ? 1 : keyPath.length; - var isVirtual = keyTail > 0; - var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual ? "".concat(keyPathAlias, "(virtual-from:").concat(lowLevelIndex.name, ")") : lowLevelIndex.name, lowLevelIndex, isVirtual, keyTail, keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); - indexList.push(virtualIndex); - if (!virtualIndex.isPrimaryKey) { - allVirtualIndexes.push(virtualIndex); - } - if (keyLength > 1) { - var virtualKeyPath = keyLength === 2 ? keyPath[0] : keyPath.slice(0, keyLength - 1); - addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); - } - indexList.sort(function(a, b) { - return a.keyTail - b.keyTail; - }); - return virtualIndex; - } - var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); - indexLookup[":id"] = [primaryKey]; - for (var _i = 0, _a2 = schema.indexes; _i < _a2.length; _i++) { - var index = _a2[_i]; - addVirtualIndexes(index.keyPath, 0, index); - } - function findBestIndex(keyPath) { - var result2 = indexLookup[getKeyPathAlias(keyPath)]; - return result2 && result2[0]; - } - function translateRange(range, keyTail) { - return { - type: range.type === 1 ? 2 : range.type, - lower: pad2(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), - lowerOpen: true, - upper: pad2(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), - upperOpen: true - }; - } - function translateRequest(req) { - var index2 = req.query.index; - return index2.isVirtual ? __assign(__assign({}, req), { query: { - index: index2.lowLevelIndex, - range: translateRange(req.query.range, index2.keyTail) - } }) : req; - } - var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function(req) { - return table.count(translateRequest(req)); - }, query: function(req) { - return table.query(translateRequest(req)); - }, openCursor: function(req) { - var _a3 = req.query.index, keyTail = _a3.keyTail, isVirtual = _a3.isVirtual, keyLength = _a3.keyLength; - if (!isVirtual) - return table.openCursor(req); - function createVirtualCursor(cursor) { - function _continue(key) { - key != null ? cursor.continue(pad2(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : req.unique ? cursor.continue(cursor.key.slice(0, keyLength).concat(req.reverse ? down.MIN_KEY : down.MAX_KEY, keyTail)) : cursor.continue(); - } - var virtualCursor = Object.create(cursor, { - continue: { value: _continue }, - continuePrimaryKey: { - value: function(key, primaryKey2) { - cursor.continuePrimaryKey(pad2(key, down.MAX_KEY, keyTail), primaryKey2); - } - }, - primaryKey: { - get: function() { - return cursor.primaryKey; - } - }, - key: { - get: function() { - var key = cursor.key; - return keyLength === 1 ? key[0] : key.slice(0, keyLength); - } - }, - value: { - get: function() { - return cursor.value; - } - } - }); - return virtualCursor; - } - return table.openCursor(translateRequest(req)).then(function(cursor) { - return cursor && createVirtualCursor(cursor); - }); - } }); - return result; - } }); - } - var virtualIndexMiddleware = { - stack: "dbcore", - name: "VirtualIndexMiddleware", - level: 1, - create: createVirtualIndexMiddleware - }; - function getObjectDiff(a, b, rv, prfx) { - rv = rv || {}; - prfx = prfx || ""; - keys(a).forEach(function(prop) { - if (!hasOwn(b, prop)) { - rv[prfx + prop] = void 0; - } else { - var ap = a[prop], bp = b[prop]; - if (typeof ap === "object" && typeof bp === "object" && ap && bp) { - var apTypeName = toStringTag(ap); - var bpTypeName = toStringTag(bp); - if (apTypeName !== bpTypeName) { - rv[prfx + prop] = b[prop]; - } else if (apTypeName === "Object") { - getObjectDiff(ap, bp, rv, prfx + prop + "."); - } else if (ap !== bp) { - rv[prfx + prop] = b[prop]; - } - } else if (ap !== bp) - rv[prfx + prop] = b[prop]; - } - }); - keys(b).forEach(function(prop) { - if (!hasOwn(a, prop)) { - rv[prfx + prop] = b[prop]; - } - }); - return rv; - } - function getEffectiveKeys(primaryKey, req) { - if (req.type === "delete") - return req.keys; - return req.keys || req.values.map(primaryKey.extractKey); - } - var hooksMiddleware = { - stack: "dbcore", - name: "HooksMiddleware", - level: 2, - create: function(downCore) { - return __assign(__assign({}, downCore), { table: function(tableName) { - var downTable = downCore.table(tableName); - var primaryKey = downTable.schema.primaryKey; - var tableMiddleware = __assign(__assign({}, downTable), { mutate: function(req) { - var dxTrans = PSD.trans; - var _a2 = dxTrans.table(tableName).hook, deleting = _a2.deleting, creating = _a2.creating, updating = _a2.updating; - switch (req.type) { - case "add": - if (creating.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return addPutOrDelete(req); - }, true); - case "put": - if (creating.fire === nop && updating.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return addPutOrDelete(req); - }, true); - case "delete": - if (deleting.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return addPutOrDelete(req); - }, true); - case "deleteRange": - if (deleting.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return deleteRange(req); - }, true); - } - return downTable.mutate(req); - function addPutOrDelete(req2) { - var dxTrans2 = PSD.trans; - var keys2 = req2.keys || getEffectiveKeys(primaryKey, req2); - if (!keys2) - throw new Error("Keys missing"); - req2 = req2.type === "add" || req2.type === "put" ? __assign(__assign({}, req2), { keys: keys2 }) : __assign({}, req2); - if (req2.type !== "delete") - req2.values = __spreadArray([], req2.values, true); - if (req2.keys) - req2.keys = __spreadArray([], req2.keys, true); - return getExistingValues(downTable, req2, keys2).then(function(existingValues) { - var contexts = keys2.map(function(key, i) { - var existingValue = existingValues[i]; - var ctx = { onerror: null, onsuccess: null }; - if (req2.type === "delete") { - deleting.fire.call(ctx, key, existingValue, dxTrans2); - } else if (req2.type === "add" || existingValue === void 0) { - var generatedPrimaryKey = creating.fire.call(ctx, key, req2.values[i], dxTrans2); - if (key == null && generatedPrimaryKey != null) { - key = generatedPrimaryKey; - req2.keys[i] = key; - if (!primaryKey.outbound) { - setByKeyPath(req2.values[i], primaryKey.keyPath, key); - } - } - } else { - var objectDiff = getObjectDiff(existingValue, req2.values[i]); - var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans2); - if (additionalChanges_1) { - var requestedValue_1 = req2.values[i]; - Object.keys(additionalChanges_1).forEach(function(keyPath) { - if (hasOwn(requestedValue_1, keyPath)) { - requestedValue_1[keyPath] = additionalChanges_1[keyPath]; - } else { - setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); - } - }); - } - } - return ctx; - }); - return downTable.mutate(req2).then(function(_a3) { - var failures = _a3.failures, results = _a3.results, numFailures = _a3.numFailures, lastResult = _a3.lastResult; - for (var i = 0; i < keys2.length; ++i) { - var primKey = results ? results[i] : keys2[i]; - var ctx = contexts[i]; - if (primKey == null) { - ctx.onerror && ctx.onerror(failures[i]); - } else { - ctx.onsuccess && ctx.onsuccess( - req2.type === "put" && existingValues[i] ? req2.values[i] : primKey - ); - } - } - return { failures, results, numFailures, lastResult }; - }).catch(function(error) { - contexts.forEach(function(ctx) { - return ctx.onerror && ctx.onerror(error); - }); - return Promise.reject(error); - }); - }); - } - function deleteRange(req2) { - return deleteNextChunk(req2.trans, req2.range, 1e4); - } - function deleteNextChunk(trans, range, limit) { - return downTable.query({ - trans, - values: false, - query: { index: primaryKey, range }, - limit - }).then(function(_a3) { - var result = _a3.result; - return addPutOrDelete({ - type: "delete", - keys: result, - trans - }).then(function(res) { - if (res.numFailures > 0) - return Promise.reject(res.failures[0]); - if (result.length < limit) { - return { - failures: [], - numFailures: 0, - lastResult: void 0 - }; - } else { - return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); - } - }); - }); - } - } }); - return tableMiddleware; - } }); - } - }; - function getExistingValues(table, req, effectiveKeys) { - return req.type === "add" ? Promise.resolve([]) : table.getMany({ - trans: req.trans, - keys: effectiveKeys, - cache: "immutable" - }); - } - function getFromTransactionCache(keys2, cache2, clone) { - try { - if (!cache2) - return null; - if (cache2.keys.length < keys2.length) - return null; - var result = []; - for (var i = 0, j = 0; i < cache2.keys.length && j < keys2.length; ++i) { - if (cmp3(cache2.keys[i], keys2[j]) !== 0) - continue; - result.push(clone ? deepClone(cache2.values[i]) : cache2.values[i]); - ++j; - } - return result.length === keys2.length ? result : null; - } catch (_a2) { - return null; - } - } - var cacheExistingValuesMiddleware = { - stack: "dbcore", - level: -1, - create: function(core) { - return { - table: function(tableName) { - var table = core.table(tableName); - return __assign(__assign({}, table), { getMany: function(req) { - if (!req.cache) { - return table.getMany(req); - } - var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); - if (cachedResult) { - return DexiePromise.resolve(cachedResult); - } - return table.getMany(req).then(function(res) { - req.trans["_cache"] = { - keys: req.keys, - values: req.cache === "clone" ? deepClone(res) : res - }; - return res; - }); - }, mutate: function(req) { - if (req.type !== "add") - req.trans["_cache"] = null; - return table.mutate(req); - } }); - } - }; - } - }; - function isCachableContext(ctx, table) { - return ctx.trans.mode === "readonly" && !!ctx.subscr && !ctx.trans.explicit && ctx.trans.db._options.cache !== "disabled" && !table.schema.primaryKey.outbound; - } - function isCachableRequest(type2, req) { - switch (type2) { - case "query": - return req.values && !req.unique; - case "get": - return false; - case "getMany": - return false; - case "count": - return false; - case "openCursor": - return false; - } - } - var observabilityMiddleware = { - stack: "dbcore", - level: 0, - name: "Observability", - create: function(core) { - var dbName = core.schema.name; - var FULL_RANGE = new RangeSet2(core.MIN_KEY, core.MAX_KEY); - return __assign(__assign({}, core), { transaction: function(stores, mode, options) { - if (PSD.subscr && mode !== "readonly") { - throw new exceptions.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(PSD.querier)); - } - return core.transaction(stores, mode, options); - }, table: function(tableName) { - var table = core.table(tableName); - var schema = table.schema; - var primaryKey = schema.primaryKey, indexes = schema.indexes; - var extractKey2 = primaryKey.extractKey, outbound = primaryKey.outbound; - var indexesWithAutoIncPK = primaryKey.autoIncrement && indexes.filter(function(index) { - return index.compound && index.keyPath.includes(primaryKey.keyPath); - }); - var tableClone = __assign(__assign({}, table), { mutate: function(req) { - var _a2, _b; - var trans = req.trans; - var mutatedParts = req.mutatedParts || (req.mutatedParts = {}); - var getRangeSet = function(indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return mutatedParts[part] || (mutatedParts[part] = new RangeSet2()); - }; - var pkRangeSet = getRangeSet(""); - var delsRangeSet = getRangeSet(":dels"); - var type2 = req.type; - var _c = req.type === "deleteRange" ? [req.range] : req.type === "delete" ? [req.keys] : req.values.length < 50 ? [ - getEffectiveKeys(primaryKey, req).filter(function(id) { - return id; - }), - req.values - ] : [], keys2 = _c[0], newObjs = _c[1]; - var oldCache = req.trans["_cache"]; - if (isArray(keys2)) { - pkRangeSet.addKeys(keys2); - var oldObjs = type2 === "delete" || keys2.length === newObjs.length ? getFromTransactionCache(keys2, oldCache) : null; - if (!oldObjs) { - delsRangeSet.addKeys(keys2); - } - if (oldObjs || newObjs) { - trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); - } - } else if (keys2) { - var range = { - from: (_a2 = keys2.lower) !== null && _a2 !== void 0 ? _a2 : core.MIN_KEY, - to: (_b = keys2.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY - }; - delsRangeSet.add(range); - pkRangeSet.add(range); - } else { - pkRangeSet.add(FULL_RANGE); - delsRangeSet.add(FULL_RANGE); - schema.indexes.forEach(function(idx) { - return getRangeSet(idx.name).add(FULL_RANGE); - }); - } - return table.mutate(req).then(function(res) { - if (keys2 && (req.type === "add" || req.type === "put")) { - pkRangeSet.addKeys(res.results); - if (indexesWithAutoIncPK) { - indexesWithAutoIncPK.forEach(function(idx) { - var idxVals = req.values.map(function(v) { - return idx.extractKey(v); - }); - var pkPos = idx.keyPath.findIndex(function(prop) { - return prop === primaryKey.keyPath; - }); - for (var i = 0, len = res.results.length; i < len; ++i) { - idxVals[i][pkPos] = res.results[i]; - } - getRangeSet(idx.name).addKeys(idxVals); - }); - } - } - trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); - return res; - }); - } }); - var getRange = function(_a2) { - var _b, _c; - var _d = _a2.query, index = _d.index, range = _d.range; - return [ - index, - new RangeSet2((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY) - ]; - }; - var readSubscribers = { - get: function(req) { - return [primaryKey, new RangeSet2(req.key)]; - }, - getMany: function(req) { - return [primaryKey, new RangeSet2().addKeys(req.keys)]; - }, - count: getRange, - query: getRange, - openCursor: getRange - }; - keys(readSubscribers).forEach(function(method) { - tableClone[method] = function(req) { - var subscr = PSD.subscr; - var isLiveQuery = !!subscr; - var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); - var obsSet = cachable ? req.obsSet = {} : subscr; - if (isLiveQuery) { - var getRangeSet = function(indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return obsSet[part] || (obsSet[part] = new RangeSet2()); - }; - var pkRangeSet_1 = getRangeSet(""); - var delsRangeSet_1 = getRangeSet(":dels"); - var _a2 = readSubscribers[method](req), queriedIndex = _a2[0], queriedRanges = _a2[1]; - if (method === "query" && queriedIndex.isPrimaryKey && !req.values) { - delsRangeSet_1.add(queriedRanges); - } else { - getRangeSet(queriedIndex.name || "").add(queriedRanges); - } - if (!queriedIndex.isPrimaryKey) { - if (method === "count") { - delsRangeSet_1.add(FULL_RANGE); - } else { - var keysPromise_1 = method === "query" && outbound && req.values && table.query(__assign(__assign({}, req), { values: false })); - return table[method].apply(this, arguments).then(function(res) { - if (method === "query") { - if (outbound && req.values) { - return keysPromise_1.then(function(_a3) { - var resultingKeys = _a3.result; - pkRangeSet_1.addKeys(resultingKeys); - return res; - }); - } - var pKeys = req.values ? res.result.map(extractKey2) : res.result; - if (req.values) { - pkRangeSet_1.addKeys(pKeys); - } else { - delsRangeSet_1.addKeys(pKeys); - } - } else if (method === "openCursor") { - var cursor_1 = res; - var wantValues_1 = req.values; - return cursor_1 && Object.create(cursor_1, { - key: { - get: function() { - delsRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.key; - } - }, - primaryKey: { - get: function() { - var pkey = cursor_1.primaryKey; - delsRangeSet_1.addKey(pkey); - return pkey; - } - }, - value: { - get: function() { - wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.value; - } - } - }); - } - return res; - }); - } - } - } - return table[method].apply(this, arguments); - }; - }); - return tableClone; - } }); - } - }; - function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { - function addAffectedIndex(ix) { - var rangeSet = getRangeSet(ix.name || ""); - function extractKey2(obj) { - return obj != null ? ix.extractKey(obj) : null; - } - var addKeyOrKeys = function(key) { - return ix.multiEntry && isArray(key) ? key.forEach(function(key2) { - return rangeSet.addKey(key2); - }) : rangeSet.addKey(key); - }; - (oldObjs || newObjs).forEach(function(_, i) { - var oldKey = oldObjs && extractKey2(oldObjs[i]); - var newKey = newObjs && extractKey2(newObjs[i]); - if (cmp3(oldKey, newKey) !== 0) { - if (oldKey != null) - addKeyOrKeys(oldKey); - if (newKey != null) - addKeyOrKeys(newKey); - } - }); - } - schema.indexes.forEach(addAffectedIndex); - } - function adjustOptimisticFromFailures(tblCache, req, res) { - if (res.numFailures === 0) - return req; - if (req.type === "deleteRange") { - return null; - } - var numBulkOps = req.keys ? req.keys.length : "values" in req && req.values ? req.values.length : 1; - if (res.numFailures === numBulkOps) { - return null; - } - var clone = __assign({}, req); - if (isArray(clone.keys)) { - clone.keys = clone.keys.filter(function(_, i) { - return !(i in res.failures); - }); - } - if ("values" in clone && isArray(clone.values)) { - clone.values = clone.values.filter(function(_, i) { - return !(i in res.failures); - }); - } - return clone; - } - function isAboveLower(key, range) { - return range.lower === void 0 ? true : range.lowerOpen ? cmp3(key, range.lower) > 0 : cmp3(key, range.lower) >= 0; - } - function isBelowUpper(key, range) { - return range.upper === void 0 ? true : range.upperOpen ? cmp3(key, range.upper) < 0 : cmp3(key, range.upper) <= 0; - } - function isWithinRange(key, range) { - return isAboveLower(key, range) && isBelowUpper(key, range); - } - function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { - if (!ops || ops.length === 0) - return result; - var index = req.query.index; - var multiEntry = index.multiEntry; - var queryRange = req.query.range; - var primaryKey = table.schema.primaryKey; - var extractPrimKey = primaryKey.extractKey; - var extractIndex = index.extractKey; - var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; - var finalResult = ops.reduce(function(result2, op) { - var modifedResult = result2; - var includedValues = []; - if (op.type === "add" || op.type === "put") { - var includedPKs = new RangeSet2(); - for (var i = op.values.length - 1; i >= 0; --i) { - var value = op.values[i]; - var pk = extractPrimKey(value); - if (includedPKs.hasKey(pk)) - continue; - var key = extractIndex(value); - if (multiEntry && isArray(key) ? key.some(function(k) { - return isWithinRange(k, queryRange); - }) : isWithinRange(key, queryRange)) { - includedPKs.addKey(pk); - includedValues.push(value); - } - } - } - switch (op.type) { - case "add": { - var existingKeys_1 = new RangeSet2().addKeys(req.values ? result2.map(function(v) { - return extractPrimKey(v); - }) : result2); - modifedResult = result2.concat(req.values ? includedValues.filter(function(v) { - var key2 = extractPrimKey(v); - if (existingKeys_1.hasKey(key2)) - return false; - existingKeys_1.addKey(key2); - return true; - }) : includedValues.map(function(v) { - return extractPrimKey(v); - }).filter(function(k) { - if (existingKeys_1.hasKey(k)) - return false; - existingKeys_1.addKey(k); - return true; - })); - break; - } - case "put": { - var keySet_1 = new RangeSet2().addKeys(op.values.map(function(v) { - return extractPrimKey(v); - })); - modifedResult = result2.filter( - function(item) { - return !keySet_1.hasKey(req.values ? extractPrimKey(item) : item); - } - ).concat( - req.values ? includedValues : includedValues.map(function(v) { - return extractPrimKey(v); - }) - ); - break; - } - case "delete": - var keysToDelete_1 = new RangeSet2().addKeys(op.keys); - modifedResult = result2.filter(function(item) { - return !keysToDelete_1.hasKey(req.values ? extractPrimKey(item) : item); - }); - break; - case "deleteRange": - var range_1 = op.range; - modifedResult = result2.filter(function(item) { - return !isWithinRange(extractPrimKey(item), range_1); - }); - break; - } - return modifedResult; - }, result); - if (finalResult === result) - return result; - var sorter = function(a, b) { - return cmp3(extractLowLevelIndex(a), extractLowLevelIndex(b)) || cmp3(extractPrimKey(a), extractPrimKey(b)); - }; - finalResult.sort(req.direction === "prev" || req.direction === "prevunique" ? function(a, b) { - return sorter(b, a); - } : sorter); - if (req.limit && req.limit < Infinity) { - if (finalResult.length > req.limit) { - finalResult.length = req.limit; - } else if (result.length === req.limit && finalResult.length < req.limit) { - cacheEntry.dirty = true; - } - } - return immutable ? Object.freeze(finalResult) : finalResult; - } - function areRangesEqual(r1, r2) { - return cmp3(r1.lower, r2.lower) === 0 && cmp3(r1.upper, r2.upper) === 0 && !!r1.lowerOpen === !!r2.lowerOpen && !!r1.upperOpen === !!r2.upperOpen; - } - function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { - if (lower1 === void 0) - return lower2 !== void 0 ? -1 : 0; - if (lower2 === void 0) - return 1; - var c = cmp3(lower1, lower2); - if (c === 0) { - if (lowerOpen1 && lowerOpen2) - return 0; - if (lowerOpen1) - return 1; - if (lowerOpen2) - return -1; - } - return c; - } - function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { - if (upper1 === void 0) - return upper2 !== void 0 ? 1 : 0; - if (upper2 === void 0) - return -1; - var c = cmp3(upper1, upper2); - if (c === 0) { - if (upperOpen1 && upperOpen2) - return 0; - if (upperOpen1) - return -1; - if (upperOpen2) - return 1; - } - return c; - } - function isSuperRange(r1, r2) { - return compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0; - } - function findCompatibleQuery(dbName, tableName, type2, req) { - var _a2; - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return []; - var queries = tblCache.queries[type2]; - if (!queries) - return [null, false, tblCache, null]; - var indexName = req.query ? req.query.index.name : null; - var entries = queries[indexName || ""]; - if (!entries) - return [null, false, tblCache, null]; - switch (type2) { - case "query": - var reqDirection_1 = (_a2 = req.direction) !== null && _a2 !== void 0 ? _a2 : "next"; - var equalEntry = entries.find(function(entry) { - var _a3; - return entry.req.limit === req.limit && entry.req.values === req.values && ((_a3 = entry.req.direction) !== null && _a3 !== void 0 ? _a3 : "next") === reqDirection_1 && areRangesEqual(entry.req.query.range, req.query.range); - }); - if (equalEntry) - return [ - equalEntry, - true, - tblCache, - entries - ]; - var superEntry = entries.find(function(entry) { - var _a3; - var limit = "limit" in entry.req ? entry.req.limit : Infinity; - return limit >= req.limit && ((_a3 = entry.req.direction) !== null && _a3 !== void 0 ? _a3 : "next") === reqDirection_1 && (req.values ? entry.req.values : true) && isSuperRange(entry.req.query.range, req.query.range); - }); - return [superEntry, false, tblCache, entries]; - case "count": - var countQuery = entries.find(function(entry) { - return areRangesEqual(entry.req.query.range, req.query.range); - }); - return [countQuery, !!countQuery, tblCache, entries]; - } - } - function subscribeToCacheEntry(cacheEntry, container, requery, signal) { - cacheEntry.subscribers.add(requery); - signal.addEventListener("abort", function() { - cacheEntry.subscribers.delete(requery); - if (cacheEntry.subscribers.size === 0) { - enqueForDeletion(cacheEntry, container); - } - }); - } - function enqueForDeletion(cacheEntry, container) { - setTimeout(function() { - if (cacheEntry.subscribers.size === 0) { - delArrayItem(container, cacheEntry); - } - }, 3e3); - } - var cacheMiddleware = { - stack: "dbcore", - level: 0, - name: "Cache", - create: function(core) { - var dbName = core.schema.name; - var coreMW = __assign(__assign({}, core), { transaction: function(stores, mode, options) { - var idbtrans = core.transaction(stores, mode, options); - if (mode === "readwrite") { - var ac_1 = new AbortController(); - var signal = ac_1.signal; - var endTransaction = function(wasCommitted) { - return function() { - ac_1.abort(); - if (mode === "readwrite") { - var affectedSubscribers_1 = /* @__PURE__ */ new Set(); - for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) { - var storeName = stores_1[_i]; - var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)]; - if (tblCache) { - var table = core.table(storeName); - var ops = tblCache.optimisticOps.filter(function(op) { - return op.trans === idbtrans; - }); - if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) { - for (var _a2 = 0, _b = Object.values(tblCache.queries.query); _a2 < _b.length; _a2++) { - var entries = _b[_a2]; - for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) { - var entry = _d[_c]; - if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function(requery) { - return affectedSubscribers_1.add(requery); - }); - } - } - } - } else if (ops.length > 0) { - tblCache.optimisticOps = tblCache.optimisticOps.filter(function(op) { - return op.trans !== idbtrans; - }); - for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) { - var entries = _f[_e]; - for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) { - var entry = _h[_g]; - if (entry.res != null && idbtrans.mutatedParts) { - if (wasCommitted && !entry.dirty) { - var freezeResults = Object.isFrozen(entry.res); - var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); - if (entry.dirty) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function(requery) { - return affectedSubscribers_1.add(requery); - }); - } else if (modRes !== entry.res) { - entry.res = modRes; - entry.promise = DexiePromise.resolve({ - result: modRes - }); - } - } else { - if (entry.dirty) { - delArrayItem(entries, entry); - } - entry.subscribers.forEach(function(requery) { - return affectedSubscribers_1.add(requery); - }); - } - } - } - } - } - } - } - affectedSubscribers_1.forEach(function(requery) { - return requery(); - }); - } - }; - }; - idbtrans.addEventListener("abort", endTransaction(false), { - signal - }); - idbtrans.addEventListener("error", endTransaction(false), { - signal - }); - idbtrans.addEventListener("complete", endTransaction(true), { - signal - }); - } - return idbtrans; - }, table: function(tableName) { - var downTable = core.table(tableName); - var primKey = downTable.schema.primaryKey; - var tableMW = __assign(__assign({}, downTable), { mutate: function(req) { - var trans = PSD.trans; - if (primKey.outbound || trans.db._options.cache === "disabled" || trans.explicit || trans.idbtrans.mode !== "readwrite") { - return downTable.mutate(req); - } - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return downTable.mutate(req); - var promise = downTable.mutate(req); - if ((req.type === "add" || req.type === "put") && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function(key) { - return key == null; - }))) { - promise.then(function(res) { - var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function(value, i) { - var _a2; - if (res.failures[i]) - return value; - var valueWithKey = ((_a2 = primKey.keyPath) === null || _a2 === void 0 ? void 0 : _a2.includes(".")) ? deepClone(value) : __assign({}, value); - setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); - return valueWithKey; - }) }); - var adjustedReq = adjustOptimisticFromFailures(tblCache, reqWithResolvedKeys, res); - tblCache.optimisticOps.push(adjustedReq); - queueMicrotask(function() { - return req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - }); - }); - } else { - tblCache.optimisticOps.push(req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - promise.then(function(res) { - if (res.numFailures > 0) { - delArrayItem(tblCache.optimisticOps, req); - var adjustedReq = adjustOptimisticFromFailures(tblCache, req, res); - if (adjustedReq) { - tblCache.optimisticOps.push(adjustedReq); - } - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - } - }); - promise.catch(function() { - delArrayItem(tblCache.optimisticOps, req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - }); - } - return promise; - }, query: function(req) { - var _a2; - if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) - return downTable.query(req); - var freezeResults = ((_a2 = PSD.trans) === null || _a2 === void 0 ? void 0 : _a2.db._options.cache) === "immutable"; - var _b = PSD, requery = _b.requery, signal = _b.signal; - var _c = findCompatibleQuery(dbName, tableName, "query", req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3]; - if (cacheEntry && exactMatch) { - cacheEntry.obsSet = req.obsSet; - } else { - var promise = downTable.query(req).then(function(res) { - var result = res.result; - if (cacheEntry) - cacheEntry.res = result; - if (freezeResults) { - for (var i = 0, l = result.length; i < l; ++i) { - Object.freeze(result[i]); - } - Object.freeze(result); - } - return res; - }).catch(function(error) { - if (container && cacheEntry) - delArrayItem(container, cacheEntry); - return Promise.reject(error); - }); - cacheEntry = { - obsSet: req.obsSet, - promise, - subscribers: /* @__PURE__ */ new Set(), - type: "query", - req, - dirty: false - }; - if (container) { - container.push(cacheEntry); - } else { - container = [cacheEntry]; - if (!tblCache) { - tblCache = cache["idb://".concat(dbName, "/").concat(tableName)] = { - queries: { - query: {}, - count: {} - }, - objs: /* @__PURE__ */ new Map(), - optimisticOps: [], - unsignaledParts: {} - }; - } - tblCache.queries.query[req.query.index.name || ""] = container; - } - } - subscribeToCacheEntry(cacheEntry, container, requery, signal); - return cacheEntry.promise.then(function(res) { - var result = applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults); - return { - result: freezeResults ? result : deepClone(result) - }; - }); - } }); - return tableMW; - } }); - return coreMW; - } - }; - function vipify(target, vipDb) { - return new Proxy(target, { - get: function(target2, prop, receiver) { - if (prop === "db") - return vipDb; - return Reflect.get(target2, prop, receiver); - } - }); - } - var Dexie$1 = function() { - function Dexie4(name, options) { - var _this = this; - this._middlewares = {}; - this.verno = 0; - var deps = Dexie4.dependencies; - this._options = options = __assign({ - addons: Dexie4.addons, - autoOpen: true, - indexedDB: deps.indexedDB, - IDBKeyRange: deps.IDBKeyRange, - cache: "cloned", - maxConnections: DEFAULT_MAX_CONNECTIONS - }, options); - this._deps = { - indexedDB: options.indexedDB, - IDBKeyRange: options.IDBKeyRange - }; - var addons = options.addons; - this._dbSchema = {}; - this._versions = []; - this._storeNames = []; - this._allTables = {}; - this.idbdb = null; - this._novip = this; - var state = { - dbOpenError: null, - isBeingOpened: false, - onReadyBeingFired: null, - openComplete: false, - dbReadyResolve: nop, - dbReadyPromise: null, - cancelOpen: nop, - openCanceller: null, - autoSchema: true, - PR1398_maxLoop: 3, - autoOpen: options.autoOpen - }; - state.dbReadyPromise = new DexiePromise(function(resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function(_, reject) { - state.cancelOpen = reject; - }); - this._state = state; - this.name = name; - this.on = Events(this, "populate", "blocked", "versionchange", "close", { - ready: [promisableChain, nop] - }); - this.once = function(event, callback) { - var fn = function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - _this.on(event).unsubscribe(fn); - callback.apply(_this, args); - }; - return _this.on(event, fn); - }; - this.on.ready.subscribe = override(this.on.ready.subscribe, function(subscribe) { - return function(subscriber, bSticky) { - Dexie4.vip(function() { - var state2 = _this._state; - if (state2.openComplete) { - if (!state2.dbOpenError) - DexiePromise.resolve().then(subscriber); - if (bSticky) - subscribe(subscriber); - } else if (state2.onReadyBeingFired) { - state2.onReadyBeingFired.push(subscriber); - if (bSticky) - subscribe(subscriber); - } else { - subscribe(subscriber); - var db_1 = _this; - if (!bSticky) - subscribe(function unsubscribe() { - db_1.on.ready.unsubscribe(subscriber); - db_1.on.ready.unsubscribe(unsubscribe); - }); - } - }); - }; - }); - this.Collection = createCollectionConstructor(this); - this.Table = createTableConstructor(this); - this.Transaction = createTransactionConstructor(this); - this.Version = createVersionConstructor(this); - this.WhereClause = createWhereClauseConstructor(this); - this.on("versionchange", function(ev) { - if (ev.newVersion > 0) - console.warn("Another connection wants to upgrade database '".concat(_this.name, "'. Closing db now to resume the upgrade.")); - else - console.warn("Another connection wants to delete database '".concat(_this.name, "'. Closing db now to resume the delete request.")); - _this.close({ disableAutoOpen: false }); - }); - this.on("blocked", function(ev) { - if (!ev.newVersion || ev.newVersion < ev.oldVersion) - console.warn("Dexie.delete('".concat(_this.name, "') was blocked")); - else - console.warn("Upgrade '".concat(_this.name, "' blocked by other connection holding version ").concat(ev.oldVersion / 10)); - }); - this._maxKey = getMaxKey(options.IDBKeyRange); - this._createTransaction = function(mode, storeNames, dbschema, parentTransaction) { - return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); - }; - this._fireOnBlocked = function(ev) { - _this.on("blocked").fire(ev); - connections.toArray().filter(function(c) { - return c.name === _this.name && c !== _this && !c._state.vcFired; - }).map(function(c) { - return c.on("versionchange").fire(ev); - }); - }; - this.use(cacheExistingValuesMiddleware); - this.use(cacheMiddleware); - this.use(observabilityMiddleware); - this.use(virtualIndexMiddleware); - this.use(hooksMiddleware); - var vipDB = new Proxy(this, { - get: function(_, prop, receiver) { - if (prop === "_vip") - return true; - if (prop === "table") - return function(tableName) { - return vipify(_this.table(tableName), vipDB); - }; - var rv = Reflect.get(_, prop, receiver); - if (rv instanceof Table) - return vipify(rv, vipDB); - if (prop === "tables") - return rv.map(function(t) { - return vipify(t, vipDB); - }); - if (prop === "_createTransaction") - return function() { - var tx = rv.apply(this, arguments); - return vipify(tx, vipDB); - }; - return rv; - } - }); - this.vip = vipDB; - addons.forEach(function(addon) { - return addon(_this); - }); - } - Dexie4.prototype.version = function(versionNumber) { - if (isNaN(versionNumber) || versionNumber < 0.1) - throw new exceptions.Type("Given version is not a positive number"); - versionNumber = Math.round(versionNumber * 10) / 10; - if (this.idbdb || this._state.isBeingOpened) - throw new exceptions.Schema("Cannot add version when database is open"); - this.verno = Math.max(this.verno, versionNumber); - var versions = this._versions; - var versionInstance = versions.filter(function(v) { - return v._cfg.version === versionNumber; - })[0]; - if (versionInstance) - return versionInstance; - versionInstance = new this.Version(versionNumber); - versions.push(versionInstance); - versions.sort(lowerVersionFirst); - versionInstance.stores({}); - this._state.autoSchema = false; - return versionInstance; - }; - Dexie4.prototype._whenReady = function(fn) { - var _this = this; - return this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip) ? fn() : new DexiePromise(function(resolve, reject) { - if (_this._state.openComplete) { - return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); - } - if (!_this._state.isBeingOpened) { - if (!_this._state.autoOpen) { - reject(new exceptions.DatabaseClosed()); - return; - } - _this.open().catch(nop); - } - _this._state.dbReadyPromise.then(resolve, reject); - }).then(fn); - }; - Dexie4.prototype.use = function(_a2) { - var stack = _a2.stack, create = _a2.create, level = _a2.level, name = _a2.name; - if (name) - this.unuse({ stack, name }); - var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); - middlewares.push({ - stack, - create, - level: level == null ? 10 : level, - name - }); - middlewares.sort(function(a, b) { - return a.level - b.level; - }); - return this; - }; - Dexie4.prototype.unuse = function(_a2) { - var stack = _a2.stack, name = _a2.name, create = _a2.create; - if (stack && this._middlewares[stack]) { - this._middlewares[stack] = this._middlewares[stack].filter(function(mw) { - return create ? mw.create !== create : name ? mw.name !== name : false; - }); - } - return this; - }; - Dexie4.prototype.open = function() { - var _this = this; - return usePSD( - globalPSD, - function() { - return dexieOpen(_this); - } - ); - }; - Dexie4.prototype._close = function() { - this.on.close.fire(new CustomEvent("close")); - var state = this._state; - connections.remove(this); - if (this.idbdb) { - try { - this.idbdb.close(); - } catch (e) { - } - this.idbdb = null; - } - if (!state.isBeingOpened) { - state.dbReadyPromise = new DexiePromise(function(resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function(_, reject) { - state.cancelOpen = reject; - }); - } - }; - Dexie4.prototype.close = function(_a2) { - var _b = _a2 === void 0 ? { disableAutoOpen: true } : _a2, disableAutoOpen = _b.disableAutoOpen; - var state = this._state; - if (disableAutoOpen) { - if (state.isBeingOpened) { - state.cancelOpen(new exceptions.DatabaseClosed()); - } - this._close(); - state.autoOpen = false; - state.dbOpenError = new exceptions.DatabaseClosed(); - } else { - this._close(); - state.autoOpen = this._options.autoOpen || state.isBeingOpened; - state.openComplete = false; - state.dbOpenError = null; - } - }; - Dexie4.prototype.delete = function(closeOptions) { - var _this = this; - if (closeOptions === void 0) { - closeOptions = { disableAutoOpen: true }; - } - var hasInvalidArguments = arguments.length > 0 && typeof arguments[0] !== "object"; - var state = this._state; - return new DexiePromise(function(resolve, reject) { - var doDelete = function() { - _this.close(closeOptions); - var req = _this._deps.indexedDB.deleteDatabase(_this.name); - req.onsuccess = wrap(function() { - _onDatabaseDeleted(_this._deps, _this.name); - resolve(); - }); - req.onerror = eventRejectHandler(reject); - req.onblocked = _this._fireOnBlocked; - }; - if (hasInvalidArguments) - throw new exceptions.InvalidArgument("Invalid closeOptions argument to db.delete()"); - if (state.isBeingOpened) { - state.dbReadyPromise.then(doDelete); - } else { - doDelete(); - } - }); - }; - Dexie4.prototype.backendDB = function() { - return this.idbdb; - }; - Dexie4.prototype.isOpen = function() { - return this.idbdb !== null; - }; - Dexie4.prototype.hasBeenClosed = function() { - var dbOpenError = this._state.dbOpenError; - return dbOpenError && dbOpenError.name === "DatabaseClosed"; - }; - Dexie4.prototype.hasFailed = function() { - return this._state.dbOpenError !== null; - }; - Dexie4.prototype.dynamicallyOpened = function() { - return this._state.autoSchema; - }; - Object.defineProperty(Dexie4.prototype, "tables", { - get: function() { - var _this = this; - return keys(this._allTables).map(function(name) { - return _this._allTables[name]; - }); - }, - enumerable: false, - configurable: true - }); - Dexie4.prototype.transaction = function() { - var args = extractTransactionArgs.apply(this, arguments); - return this._transaction.apply(this, args); - }; - Dexie4.prototype._transaction = function(mode, tables, scopeFunc) { - var _this = this; - var parentTransaction = PSD.trans; - if (!parentTransaction || parentTransaction.db !== this || mode.indexOf("!") !== -1) - parentTransaction = null; - var onlyIfCompatible = mode.indexOf("?") !== -1; - mode = mode.replace("!", "").replace("?", ""); - var idbMode, storeNames; - try { - storeNames = tables.map(function(table) { - var storeName = table instanceof _this.Table ? table.name : table; - if (typeof storeName !== "string") - throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); - return storeName; - }); - if (mode == "r" || mode === READONLY) - idbMode = READONLY; - else if (mode == "rw" || mode == READWRITE) - idbMode = READWRITE; - else - throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); - if (parentTransaction) { - if (parentTransaction.mode === READONLY && idbMode === READWRITE) { - if (onlyIfCompatible) { - parentTransaction = null; - } else - throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); - } - if (parentTransaction) { - storeNames.forEach(function(storeName) { - if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { - if (onlyIfCompatible) { - parentTransaction = null; - } else - throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); - } - }); - } - if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { - parentTransaction = null; - } - } - } catch (e) { - return parentTransaction ? parentTransaction._promise(null, function(_, reject) { - reject(e); - }) : rejection(e); - } - var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); - return parentTransaction ? parentTransaction._promise(idbMode, enterTransaction, "lock") : PSD.trans ? usePSD(PSD.transless, function() { - return _this._whenReady(enterTransaction); - }) : this._whenReady(enterTransaction); - }; - Dexie4.prototype.table = function(tableName) { - if (!hasOwn(this._allTables, tableName)) { - throw new exceptions.InvalidTable("Table ".concat(tableName, " does not exist")); - } - return this._allTables[tableName]; - }; - return Dexie4; - }(); - var symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol ? Symbol.observable : "@@observable"; - var Observable = function() { - function Observable2(subscribe) { - this._subscribe = subscribe; - } - Observable2.prototype.subscribe = function(x, error, complete) { - return this._subscribe(!x || typeof x === "function" ? { next: x, error, complete } : x); - }; - Observable2.prototype[symbolObservable] = function() { - return this; - }; - return Observable2; - }(); - var domDeps; - try { - domDeps = { - indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, - IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange - }; - } catch (e) { - domDeps = { indexedDB: null, IDBKeyRange: null }; - } - function liveQuery2(querier) { - var hasValue = false; - var currentValue; - var observable = new Observable(function(observer) { - var scopeFuncIsAsync = isAsyncFunction(querier); - function execute(ctx) { - var wasRootExec = beginMicroTickScope(); - try { - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var rv = newScope(querier, ctx); - if (scopeFuncIsAsync) { - rv = rv.finally(decrementExpectedAwaits); - } - return rv; - } finally { - wasRootExec && endMicroTickScope(); - } - } - var closed = false; - var abortController; - var accumMuts = {}; - var currentObs = {}; - var subscription = { - get closed() { - return closed; - }, - unsubscribe: function() { - if (closed) - return; - closed = true; - if (abortController) - abortController.abort(); - if (startedListening) - globalEvents.storagemutated.unsubscribe(mutationListener); - } - }; - observer.start && observer.start(subscription); - var startedListening = false; - var doQuery = function() { - return execInGlobalContext(_doQuery); - }; - function shouldNotify() { - return obsSetsOverlap(currentObs, accumMuts); - } - var mutationListener = function(parts) { - extendObservabilitySet(accumMuts, parts); - if (shouldNotify()) { - doQuery(); - } - }; - var _doQuery = function() { - if (closed || !domDeps.indexedDB) { - return; - } - accumMuts = {}; - var subscr = {}; - if (abortController) - abortController.abort(); - abortController = new AbortController(); - var ctx = { - subscr, - signal: abortController.signal, - requery: doQuery, - querier, - trans: null - }; - var ret = execute(ctx); - if (!startedListening) { - globalEvents.storagemutated.subscribe(mutationListener); - startedListening = true; - } - Promise.resolve(ret).then(function(result) { - hasValue = true; - currentValue = result; - if (closed || ctx.signal.aborted) { - return; - } - if (shouldNotify()) { - doQuery(); - } else { - currentObs = subscr; - if (shouldNotify()) { - doQuery(); - } else { - accumMuts = {}; - execInGlobalContext(function() { - return !closed && observer.next && observer.next(result); - }); - } - } - }, function(err) { - hasValue = false; - if (!["DatabaseClosedError", "AbortError"].includes(err === null || err === void 0 ? void 0 : err.name)) { - if (!closed) - execInGlobalContext(function() { - if (closed) - return; - observer.error && observer.error(err); - }); - } - }); - }; - setTimeout(doQuery, 0); - return subscription; - }); - observable.hasValue = function() { - return hasValue; - }; - observable.getValue = function() { - return currentValue; - }; - return observable; - } - var Dexie3 = Dexie$1; - props(Dexie3, __assign(__assign({}, fullNameExceptions), { - delete: function(databaseName) { - var db2 = new Dexie3(databaseName, { addons: [] }); - return db2.delete(); - }, - exists: function(name) { - return new Dexie3(name, { addons: [] }).open().then(function(db2) { - db2.close(); - return true; - }).catch("NoSuchDatabaseError", function() { - return false; - }); - }, - getDatabaseNames: function(cb) { - try { - return getDatabaseNames(Dexie3.dependencies).then(cb); - } catch (_a2) { - return rejection(new exceptions.MissingAPI()); - } - }, - defineClass: function() { - function Class(content) { - extend(this, content); - } - return Class; - }, - ignoreTransaction: function(scopeFunc) { - return PSD.trans ? usePSD(PSD.transless || globalPSD, scopeFunc) : scopeFunc(); - }, - vip, - async: function(generatorFn) { - return function() { - try { - var rv = awaitIterator(generatorFn.apply(this, arguments)); - if (!rv || typeof rv.then !== "function") - return DexiePromise.resolve(rv); - return rv; - } catch (e) { - return rejection(e); - } - }; - }, - spawn: function(generatorFn, args, thiz) { - try { - var rv = awaitIterator(generatorFn.apply(thiz, args || [])); - if (!rv || typeof rv.then !== "function") - return DexiePromise.resolve(rv); - return rv; - } catch (e) { - return rejection(e); - } - }, - currentTransaction: { - get: function() { - return PSD.trans || null; - } - }, - waitFor: function(promiseOrFunction, optionalTimeout) { - var promise = DexiePromise.resolve(typeof promiseOrFunction === "function" ? Dexie3.ignoreTransaction(promiseOrFunction) : promiseOrFunction).timeout(optionalTimeout || 6e4); - return PSD.trans ? PSD.trans.waitFor(promise) : promise; - }, - Promise: DexiePromise, - debug: { - get: function() { - return debug; - }, - set: function(value) { - setDebug(value); - } - }, - derive, - extend, - props, - override, - Events, - on: globalEvents, - liveQuery: liveQuery2, - extendObservabilitySet, - getByKeyPath, - setByKeyPath, - delByKeyPath, - shallowClone, - deepClone, - getObjectDiff, - cmp: cmp3, - asap: asap$1, - minKey, - addons: [], - connections: { - get: connections.toArray - }, - errnames, - dependencies: domDeps, - cache, - semVer: DEXIE_VERSION, - version: DEXIE_VERSION.split(".").map(function(n) { - return parseInt(n); - }).reduce(function(p, c, i) { - return p + c / Math.pow(10, i * 2); - }) - })); - Dexie3.maxKey = getMaxKey(Dexie3.dependencies.IDBKeyRange); - if (typeof dispatchEvent !== "undefined" && typeof addEventListener !== "undefined") { - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function(updatedParts) { - if (!propagatingLocally) { - var event_1; - event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { - detail: updatedParts - }); - propagatingLocally = true; - dispatchEvent(event_1); - propagatingLocally = false; - } - }); - addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function(_a2) { - var detail = _a2.detail; - if (!propagatingLocally) { - propagateLocally(detail); - } - }); - } - function propagateLocally(updateParts) { - var wasMe = propagatingLocally; - try { - propagatingLocally = true; - globalEvents.storagemutated.fire(updateParts); - signalSubscribersNow(updateParts, true); - } finally { - propagatingLocally = wasMe; - } - } - var propagatingLocally = false; - var bc; - var createBC = function() { - }; - if (typeof BroadcastChannel !== "undefined") { - createBC = function() { - bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); - bc.onmessage = function(ev) { - return ev.data && propagateLocally(ev.data); - }; - }; - createBC(); - if (typeof bc.unref === "function") { - bc.unref(); - } - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function(changedParts) { - if (!propagatingLocally) { - bc.postMessage(changedParts); - } - }); - } - if (typeof addEventListener !== "undefined") { - addEventListener("pagehide", function(event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug("Dexie: handling persisted pagehide"); - bc === null || bc === void 0 ? void 0 : bc.close(); - for (var _i = 0, _a2 = connections.toArray(); _i < _a2.length; _i++) { - var db2 = _a2[_i]; - db2.close({ disableAutoOpen: false }); - } - } - }); - addEventListener("pageshow", function(event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug("Dexie: handling persisted pageshow"); - createBC(); - propagateLocally({ all: new RangeSet2(-Infinity, [[]]) }); - } - }); - } - function add2(value) { - return new PropModification2({ add: value }); - } - function remove2(value) { - return new PropModification2({ remove: value }); - } - function replacePrefix2(a, b) { - return new PropModification2({ replacePrefix: [a, b] }); - } - DexiePromise.rejectionMapper = mapError; - setDebug(debug); - var namedExports = /* @__PURE__ */ Object.freeze({ - __proto__: null, - DEFAULT_MAX_CONNECTIONS, - Dexie: Dexie$1, - Entity: Entity2, - PropModification: PropModification2, - RangeSet: RangeSet2, - add: add2, - cmp: cmp3, - default: Dexie$1, - liveQuery: liveQuery2, - mergeRanges: mergeRanges2, - rangesOverlap: rangesOverlap2, - remove: remove2, - replacePrefix: replacePrefix2 - }); - __assign(Dexie$1, namedExports, { default: Dexie$1 }); - return Dexie$1; - }); - } -}); - -// intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/import-wrapper.mjs -var import_dexie, DexieSymbol, Dexie, liveQuery, mergeRanges, rangesOverlap, RangeSet, cmp2, Entity, PropModification, replacePrefix, add, remove, DexieYProvider, import_wrapper_default; -var init_import_wrapper = __esm({ - "intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/import-wrapper.mjs"() { - import_dexie = __toESM(require_dexie(), 1); - DexieSymbol = Symbol.for("Dexie"); - Dexie = globalThis[DexieSymbol] || (globalThis[DexieSymbol] = import_dexie.default); - if (import_dexie.default.semVer !== Dexie.semVer) { - throw new Error(`Two different versions of Dexie loaded in the same app: ${import_dexie.default.semVer} and ${Dexie.semVer}`); - } - ({ - liveQuery, - mergeRanges, - rangesOverlap, - RangeSet, - cmp: cmp2, - Entity, - PropModification, - replacePrefix, - add, - remove, - DexieYProvider - } = Dexie); - import_wrapper_default = Dexie; - } -}); - -// intern-log/src/db/schema.ts -var schema_exports = {}; -__export(schema_exports, { - CATEGORIES: () => CATEGORIES, - DEFAULT_LOCATIONS: () => DEFAULT_LOCATIONS, - EXPENSE_CATEGORIES: () => EXPENSE_CATEGORIES, - INCOME_CATEGORIES: () => INCOME_CATEGORIES, - SCHEMA_VERSION: () => SCHEMA_VERSION, - WorklogDB: () => WorklogDB, - bindDatabase: () => bindDatabase, - categoryLabel: () => categoryLabel, - db: () => db, - unbindDatabase: () => unbindDatabase -}); -function bindDatabase(instance) { - db = instance; -} -function unbindDatabase() { - if (db) db.close(); - db = void 0; -} -function categoryLabel(key) { - const found = CATEGORIES.find((c) => c.key === key); - return found ? found.label : "\u5176\u4ED6"; -} -var WorklogDB, db, SCHEMA_VERSION, EXPENSE_CATEGORIES, INCOME_CATEGORIES, DEFAULT_LOCATIONS, CATEGORIES; -var init_schema = __esm({ - "intern-log/src/db/schema.ts"() { - "use strict"; - init_import_wrapper(); - WorklogDB = class extends import_wrapper_default { - constructor(dbName = "intern_worklog") { - super(dbName); - this.version(1).stores({ - project: "++id, &name, archived", - work_log: "++id, &date", - log_item: "++id, work_log_id, project_id, category", - attendance: "++id, &date", - weekly_note: "++id, &week_start", - setting: "key" - }); - this.version(2).stores({ - memo: "++id, updated_at", - credential: "++id, system, updated_at" - }); - this.version(3).stores({ - transaction: "++id, date, type, category" - }); - this.version(4).stores({ - sync_mirror: "++id, table, uuid", - tombstone: "++id, table, uuid, deleted_at" - }); - } - }; - SCHEMA_VERSION = 4; - EXPENSE_CATEGORIES = ["\u9910\u996E", "\u4EA4\u901A", "\u4F4F\u623F", "\u901A\u8BAF", "\u5B66\u4E60", "\u5A31\u4E50", "\u5176\u4ED6"]; - INCOME_CATEGORIES = ["\u5DE5\u8D44", "\u62A5\u9500", "\u5176\u4ED6"]; - DEFAULT_LOCATIONS = ["\u516C\u53F8", "\u5BA2\u6237\u73B0\u573A", "\u51FA\u5DEE", "\u5C45\u5BB6\u529E\u516C"]; - CATEGORIES = [ - { key: "dev", label: "\u5F00\u53D1" }, - { key: "bugfix", label: "BUG\u4FEE\u590D" }, - { key: "test", label: "\u6D4B\u8BD5" }, - { key: "learning", label: "\u5B66\u4E60\u6210\u957F" }, - { key: "meeting", label: "\u4F1A\u8BAE\u6C9F\u901A" }, - { key: "doc", label: "\u6587\u6863\u8F93\u51FA" }, - { key: "other", label: "\u5176\u4ED6" } - ]; - } -}); - -// intern-log/src/lib/date.ts -function pad(n) { - return n < 10 ? "0" + n : String(n); -} -function toDateStr(d) { - return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()); -} -function nowLocalISO() { - const d = /* @__PURE__ */ new Date(); - return toDateStr(d) + "T" + pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds()); -} -var init_date = __esm({ - "intern-log/src/lib/date.ts"() { - "use strict"; - } -}); - -// intern-log/src/db/repo.ts -async function getSetting(key, fallback) { - const row = await db.setting.get(key); - return row ? row.value : fallback; -} -async function setSetting(key, value) { - await db.setting.put({ key, value }); -} -var init_repo = __esm({ - "intern-log/src/db/repo.ts"() { - "use strict"; - init_schema(); - init_date(); - } -}); - -// intern-log/src/lib/crypto.ts -var init_crypto = __esm({ - "intern-log/src/lib/crypto.ts"() { - "use strict"; - } -}); - -// intern-log/src/db/vault.ts -var init_vault = __esm({ - "intern-log/src/db/vault.ts"() { - "use strict"; - init_schema(); - init_repo(); - init_crypto(); - init_date(); - } -}); - -// intern-log/src/db/auth.ts -function getCloudCreds() { - try { - const raw = localStorage.getItem(CREDS_KEY); - if (!raw) return null; - const c = JSON.parse(raw); - if (c && c.username && c.password) return c; - } catch { - } - return null; -} -var UserRegistry, registry, CREDS_KEY; -var init_auth = __esm({ - "intern-log/src/db/auth.ts"() { - "use strict"; - init_import_wrapper(); - init_schema(); - init_vault(); - init_crypto(); - UserRegistry = class extends import_wrapper_default { - constructor() { - super("intern_worklog_users"); - this.version(1).stores({ user: "id, &username" }); - } - }; - registry = new UserRegistry(); - CREDS_KEY = "dsh_cloud_creds"; - } -}); - -// intern-log/src/sync/engine.ts -var engine_exports = {}; -__export(engine_exports, { - DEFAULT_SYNC_BASE: () => DEFAULT_SYNC_BASE, - SYNC_TABLES: () => SYNC_TABLES, - autoSyncNow: () => autoSyncNow, - enableRealtimeSync: () => enableRealtimeSync, - ensureCloudBinding: () => ensureCloudBinding, - getCloudUser: () => getCloudUser, - getSyncBase: () => getSyncBase, - getSyncLastTime: () => getSyncLastTime, - isSyncConfigured: () => isSyncConfigured, - registerCloudAccount: () => registerCloudAccount, - runSync: () => runSync, - stopRealtime: () => stopRealtime, - syncWithStoredConfig: () => syncWithStoredConfig -}); -function newUuid() { - if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID(); - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = Math.random() * 16 | 0; - return (c === "x" ? r : r & 3 | 8).toString(16); - }); -} -function stripId(row) { - const copy = { ...row }; - delete copy.id; - return copy; -} -function rowHash(row) { - return JSON.stringify(row); -} -async function getTable(name) { - return db.table(name).toArray(); -} -function pkOf(t, row) { - return t === "setting" ? row.key : row.id; -} -async function ensureSyncFields() { - for (const t of TABLES) { - const table = db.table(t); - const rows = await table.toArray(); - for (const row of rows) { - if (t === "setting" && EXCLUDE_SETTING_KEYS.has(row.key)) continue; - const patch = {}; - if (!row.uuid) patch.uuid = newUuid(); - if (!row.updated_at) patch.updated_at = row.created_at || nowLocalISO(); - if (Object.keys(patch).length) await table.update(pkOf(t, row), patch); - } - } -} -async function getSyncBase() { - return await getSetting("sync_base_url", "") || DEFAULT_SYNC_BASE; -} -async function loadSyncConfig() { - const creds = getCloudCreds(); - if (!creds) throw new Error("\u672A\u767B\u5F55\uFF0C\u65E0\u6CD5\u540C\u6B65"); - return { baseUrl: await getSyncBase(), username: creds.username, password: creds.password }; -} -async function syncWithStoredConfig() { - return runSync(await loadSyncConfig()); -} -async function ensureCloudBinding() { - const creds = getCloudCreds(); - if (!creds) throw new Error("\u672A\u767B\u5F55"); - const base = await getSyncBase(); - const headers = { "Content-Type": "application/json" }; - const body = JSON.stringify({ username: creds.username, password: creds.password }); - let resp = await fetch(base + "/api/auth/register", { method: "POST", headers, body }); - if (resp.status === 409) { - resp = await fetch(base + "/api/auth/login", { method: "POST", headers, body }); - if (!resp.ok) throw new Error("\u4E91\u7AEF\u5DF2\u5B58\u5728\u540C\u540D\u8D26\u53F7\u4E14\u5BC6\u7801\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u68C0\u67E5"); - } else if (!resp.ok) { - throw new Error("\u4E91\u7AEF\u7ED1\u5B9A\u5931\u8D25\uFF1A" + resp.status); - } -} -function getCloudUser() { - const c = getCloudCreds(); - return c ? c.username : null; -} -async function isSyncConfigured() { - return getCloudCreds() != null; -} -async function getSyncLastTime() { - return getSetting("sync_last_time", ""); -} -async function registerCloudAccount(baseUrl, username, password) { - const base = baseUrl.trim().replace(/\/+$/, ""); - if (!base || !username.trim() || password.length < 6) { - throw new Error("\u8BF7\u5B8C\u6574\u586B\u5199\u540C\u6B65\u5730\u5740\u3001\u7528\u6237\u540D\u4E0E\u81F3\u5C11 6 \u4F4D\u7684\u5BC6\u7801"); - } - let resp; - try { - resp = await fetch(base + "/api/auth/register", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ username: username.trim(), password }) - }); - } catch { - throw new Error("\u65E0\u6CD5\u8BBF\u95EE\u540C\u6B65\u670D\u52A1\uFF1A\u8BF7\u68C0\u67E5\u5730\u5740\u3001\u7AEF\u53E3\u4E0E\u7F51\u7EDC"); - } - if (resp.status === 409) throw new Error("\u4E91\u7AEF\u7528\u6237\u540D\u5DF2\u5B58\u5728\uFF0C\u53EF\u76F4\u63A5\u540C\u6B65"); - if (!resp.ok) throw new Error("\u4E91\u7AEF\u6CE8\u518C\u5931\u8D25\uFF1A" + resp.status); -} -async function loginCloud(base, config) { - const resp = await fetch(base + "/api/auth/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ username: config.username.trim(), password: config.password }) - }); - if (!resp.ok) throw new Error("\u4E91\u7AEF\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E"); - const j = await resp.json(); - if (!j || !j.token) throw new Error("\u4E91\u7AEF\u767B\u5F55\u5F02\u5E38"); - return String(j.token); -} -async function ensureToken(base, config) { - let token = await getSetting("sync_token", ""); - if (token) return token; - token = await loginCloud(base, config); - await setSetting("sync_token", token); - return token; -} -async function autoSyncNow() { - if (syncRunning) { - pendingSync = true; - return; - } - try { - if (!await isSyncConfigured()) return; - await runSync(await loadSyncConfig()); - } catch { - } -} -function enableRealtimeSync() { - if (realtimeAttached) return; - realtimeAttached = true; - const sub = liveQuery(async () => { - const counts = {}; - for (const t of TABLES) counts[t] = await db.table(t).count(); - return counts; - }); - realtimeSub = sub.subscribe({ - next: () => { - if (changesSuppressed || syncRunning) return; - if (changeDebounce) globalThis.clearTimeout(changeDebounce); - changeDebounce = globalThis.setTimeout(() => { - void autoSyncNow(); - }, 3e3); - }, - error: () => { - } - }); -} -function stopRealtime() { - if (realtimeSub) { - realtimeSub.unsubscribe(); - realtimeSub = null; - } - if (sse) { - sse.close(); - sse = null; - sseKey = ""; - } - if (changeDebounce) { - globalThis.clearTimeout(changeDebounce); - changeDebounce = null; - } -} -function ensureSSE(base, token) { - const key = base + "|" + token; - if (sse && sseKey === key) return; - if (sse) { - sse.close(); - sse = null; - } - try { - sse = new EventSource(base + "/api/events?token=" + encodeURIComponent(token)); - sseKey = key; - sse.onmessage = () => { - void autoSyncNow(); - }; - } catch { - sse = null; - } -} -async function runSync(config) { - if (syncRunning) { - pendingSync = true; - return { pushed: 0, pulled: 0, removed: 0, at: "" }; - } - syncRunning = true; - changesSuppressed = true; - try { - const result = await doRunSync(config); - if (pendingSync) { - pendingSync = false; - globalThis.setTimeout(() => { - void autoSyncNow(); - }, 800); - } - return result; - } finally { - syncRunning = false; - changesSuppressed = false; - } -} -async function doRunSync(config) { - const base = config.baseUrl.trim().replace(/\/+$/, ""); - if (!base) throw new Error("\u8BF7\u5148\u914D\u7F6E\u540C\u6B65\u670D\u52A1\u5730\u5740"); - await ensureSyncFields(); - const mirrorRows = await db.sync_mirror.toArray(); - const mirror = /* @__PURE__ */ new Map(); - for (const m of mirrorRows) mirror.set(m.table + "|" + m.uuid, m); - const pushTables = {}; - const tombstones = []; - let pushed = 0; - for (const t of TABLES) { - let rows = await getTable(t); - if (t === "setting") rows = rows.filter((r) => !EXCLUDE_SETTING_KEYS.has(r.key)); - const current = /* @__PURE__ */ new Map(); - for (const row of rows) current.set(row.uuid, row); - for (const [u, row] of current) { - const clean = stripId(row); - const h = rowHash(clean); - const m = mirror.get(t + "|" + u); - if (!m || m.hash !== h) { - pushTables[t] = pushTables[t] || []; - pushTables[t].push(clean); - pushed++; - } - } - for (const [key, m] of mirror) { - if (key.startsWith(t + "|") && !current.has(m.uuid)) { - tombstones.push({ table: t, uuid: m.uuid, deleted_at: nowLocalISO() }); - } - } - pushTables[t] = pushTables[t] || []; - } - const token = await ensureToken(base, config); - const doPush = (tk) => fetch(base + "/api/sync", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: "Bearer " + tk }, - body: JSON.stringify({ device: "client", tables: pushTables, tombstones }) - }); - let resp = await doPush(token); - if (resp.status === 401) { - await setSetting("sync_token", ""); - const token2 = await loginCloud(base, config); - await setSetting("sync_token", token2); - resp = await doPush(token2); - } - if (!resp.ok) throw new Error("\u540C\u6B65\u670D\u52A1\u8FD4\u56DE " + resp.status); - const data = await resp.json(); - const serverTables = data.tables || {}; - const serverTombstones = data.tombstones || []; - let pulled = 0; - let removed = 0; - const finalMirror = []; - for (const t of TABLES) { - const table = db.table(t); - const localRows = await table.toArray(); - const byUuid = /* @__PURE__ */ new Map(); - for (const row of localRows) byUuid.set(row.uuid, row); - const serverRows = serverTables[t] || []; - const serverByUuid = /* @__PURE__ */ new Map(); - for (const row of serverRows) serverByUuid.set(row.uuid, row); - const dead = new Set(serverTombstones.filter((x) => x.table === t).map((x) => x.uuid)); - for (const [u, row] of byUuid) { - if (dead.has(u)) { - await table.delete(pkOf(t, row)); - removed++; - } - } - for (const srow of serverRows) { - if (dead.has(srow.uuid)) continue; - const local = byUuid.get(srow.uuid); - if (!local) { - await table.add({ ...srow }); - pulled++; - } else { - const localUa = String(local.updated_at || ""); - const serverUa = String(srow.updated_at || ""); - if (serverUa > localUa) { - const patch = { ...srow }; - if (t === "setting") delete patch.key; - await table.update(pkOf(t, local), patch); - pulled++; - } - } - } - const finalRows = await table.toArray(); - for (const row of finalRows) { - if (t === "setting" && EXCLUDE_SETTING_KEYS.has(row.key)) continue; - finalMirror.push({ table: t, uuid: row.uuid, hash: rowHash(stripId(row)) }); - } - } - await db.sync_mirror.clear(); - if (finalMirror.length) await db.sync_mirror.bulkAdd(finalMirror.map((m) => ({ ...m }))); - ensureSSE(base, token); - const at = nowLocalISO(); - await setSetting("sync_last_time", at); - return { pushed, pulled, removed, at }; -} -var DEFAULT_SYNC_BASE, TABLES, EXCLUDE_SETTING_KEYS, SYNC_TABLES, syncRunning, pendingSync, changesSuppressed, changeDebounce, sse, sseKey, realtimeAttached, realtimeSub; -var init_engine = __esm({ - "intern-log/src/sync/engine.ts"() { - "use strict"; - init_import_wrapper(); - init_schema(); - init_repo(); - init_auth(); - init_date(); - DEFAULT_SYNC_BASE = "https://daywk.linyux.cn"; - TABLES = ["project", "work_log", "log_item", "attendance", "weekly_note", "setting", "memo", "credential", "transaction"]; - EXCLUDE_SETTING_KEYS = /* @__PURE__ */ new Set(["sync_cursor", "sync_last_time", "sync_token", "last_project", "last_category"]); - SYNC_TABLES = TABLES; - syncRunning = false; - pendingSync = false; - changesSuppressed = false; - changeDebounce = null; - sse = null; - sseKey = ""; - realtimeAttached = false; - realtimeSub = null; - } -}); - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/errors.js -var messages = { - AbortError: "A request was aborted, for example through a call to IDBTransaction.abort.", - ConstraintError: "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one.", - DataCloneError: "The data being stored could not be cloned by the internal structured cloning algorithm.", - DataError: "Data provided to an operation does not meet requirements.", - InvalidAccessError: "An invalid operation was performed on an object. For example transaction creation attempt was made, but an empty scope was provided.", - InvalidStateError: "An operation was called on an object on which it is not allowed or at a time when it is not allowed. Also occurs if a request is made on a source object that has been deleted or removed. Use TransactionInactiveError or ReadOnlyError when possible, as they are more specific variations of InvalidStateError.", - NotFoundError: "The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.", - ReadOnlyError: 'The mutating operation was attempted in a "readonly" transaction.', - TransactionInactiveError: "A request was placed against a transaction which is currently not active, or which is finished.", - SyntaxError: "The keypath argument contains an invalid key path", - VersionError: "An attempt was made to open a database using a lower version than the existing version." -}; -var setErrorCode = (error, value) => { - Object.defineProperty(error, "code", { - value, - writable: false, - enumerable: true, - configurable: false - }); -}; -var AbortError = class extends DOMException { - constructor(message = messages.AbortError) { - super(message, "AbortError"); - } -}; -var ConstraintError = class extends DOMException { - constructor(message = messages.ConstraintError) { - super(message, "ConstraintError"); - } -}; -var DataError = class extends DOMException { - constructor(message = messages.DataError) { - super(message, "DataError"); - setErrorCode(this, 0); - } -}; -var InvalidAccessError = class extends DOMException { - constructor(message = messages.InvalidAccessError) { - super(message, "InvalidAccessError"); - } -}; -var InvalidStateError = class extends DOMException { - constructor(message = messages.InvalidStateError) { - super(message, "InvalidStateError"); - setErrorCode(this, 11); - } -}; -var NotFoundError = class extends DOMException { - constructor(message = messages.NotFoundError) { - super(message, "NotFoundError"); - } -}; -var ReadOnlyError = class extends DOMException { - constructor(message = messages.ReadOnlyError) { - super(message, "ReadOnlyError"); - } -}; -var SyntaxError2 = class extends DOMException { - constructor(message = messages.VersionError) { - super(message, "SyntaxError"); - setErrorCode(this, 12); - } -}; -var TransactionInactiveError = class extends DOMException { - constructor(message = messages.TransactionInactiveError) { - super(message, "TransactionInactiveError"); - setErrorCode(this, 0); - } -}; -var VersionError = class extends DOMException { - constructor(message = messages.VersionError) { - super(message, "VersionError"); - } -}; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/isSharedArrayBuffer.js -function isSharedArrayBuffer(input) { - return typeof SharedArrayBuffer !== "undefined" && input instanceof SharedArrayBuffer; -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKeyWithoutThrowing.js -var INVALID_TYPE = Symbol("INVALID_TYPE"); -var INVALID_VALUE = Symbol("INVALID_VALUE"); -var valueToKeyWithoutThrowing = (input, seen) => { - if (typeof input === "number") { - if (isNaN(input)) { - return INVALID_VALUE; - } - return input; - } else if (Object.prototype.toString.call(input) === "[object Date]") { - const ms = input.valueOf(); - if (isNaN(ms)) { - return INVALID_VALUE; - } - return new Date(ms); - } else if (typeof input === "string") { - return input; - } else if ( - // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type - input instanceof ArrayBuffer || isSharedArrayBuffer(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input) - ) { - if ("detached" in input ? input.detached : input.byteLength === 0) { - return INVALID_VALUE; - } - let arrayBuffer; - let offset = 0; - let length = 0; - if (input instanceof ArrayBuffer || isSharedArrayBuffer(input)) { - arrayBuffer = input; - length = input.byteLength; - } else { - arrayBuffer = input.buffer; - offset = input.byteOffset; - length = input.byteLength; - } - return arrayBuffer.slice(offset, offset + length); - } else if (Array.isArray(input)) { - if (seen === void 0) { - seen = /* @__PURE__ */ new Set(); - } else if (seen.has(input)) { - return INVALID_VALUE; - } - seen.add(input); - let hasInvalid = false; - const keys = Array.from({ - length: input.length - }, (_, i) => { - if (hasInvalid) { - return; - } - const hop = Object.hasOwn(input, i); - if (!hop) { - hasInvalid = true; - return; - } - const entry = input[i]; - const key = valueToKeyWithoutThrowing(entry, seen); - if (key === INVALID_VALUE || key === INVALID_TYPE) { - hasInvalid = true; - return; - } - return key; - }); - if (hasInvalid) { - return INVALID_VALUE; - } - return keys; - } else { - return INVALID_TYPE; - } -}; -var valueToKeyWithoutThrowing_default = valueToKeyWithoutThrowing; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKey.js -var valueToKey = (input, seen) => { - const result = valueToKeyWithoutThrowing_default(input, seen); - if (result === INVALID_VALUE || result === INVALID_TYPE) { - throw new DataError(); - } - return result; -}; -var valueToKey_default = valueToKey; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/cmp.js -var getType = (x) => { - if (typeof x === "number") { - return "Number"; - } - if (Object.prototype.toString.call(x) === "[object Date]") { - return "Date"; - } - if (Array.isArray(x)) { - return "Array"; - } - if (typeof x === "string") { - return "String"; - } - if (x instanceof ArrayBuffer) { - return "Binary"; - } - throw new DataError(); -}; -var cmp = (first, second) => { - if (second === void 0) { - throw new TypeError(); - } - first = valueToKey_default(first); - second = valueToKey_default(second); - const t1 = getType(first); - const t2 = getType(second); - if (t1 !== t2) { - if (t1 === "Array") { - return 1; - } - if (t1 === "Binary" && (t2 === "String" || t2 === "Date" || t2 === "Number")) { - return 1; - } - if (t1 === "String" && (t2 === "Date" || t2 === "Number")) { - return 1; - } - if (t1 === "Date" && t2 === "Number") { - return 1; - } - return -1; - } - if (t1 === "Binary") { - first = new Uint8Array(first); - second = new Uint8Array(second); - } - if (t1 === "Array" || t1 === "Binary") { - const length = Math.min(first.length, second.length); - for (let i = 0; i < length; i++) { - const result = cmp(first[i], second[i]); - if (result !== 0) { - return result; - } - } - if (first.length > second.length) { - return 1; - } - if (first.length < second.length) { - return -1; - } - return 0; - } - if (t1 === "Date") { - if (first.getTime() === second.getTime()) { - return 0; - } - } else { - if (first === second) { - return 0; - } - } - return first > second ? 1 : -1; -}; -var cmp_default = cmp; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBKeyRange.js -var FDBKeyRange = class _FDBKeyRange { - static only(value) { - if (arguments.length === 0) { - throw new TypeError(); - } - value = valueToKey_default(value); - return new _FDBKeyRange(value, value, false, false); - } - static lowerBound(lower, open = false) { - if (arguments.length === 0) { - throw new TypeError(); - } - lower = valueToKey_default(lower); - return new _FDBKeyRange(lower, void 0, open, true); - } - static upperBound(upper, open = false) { - if (arguments.length === 0) { - throw new TypeError(); - } - upper = valueToKey_default(upper); - return new _FDBKeyRange(void 0, upper, true, open); - } - static bound(lower, upper, lowerOpen = false, upperOpen = false) { - if (arguments.length < 2) { - throw new TypeError(); - } - const cmpResult = cmp_default(lower, upper); - if (cmpResult === 1 || cmpResult === 0 && (lowerOpen || upperOpen)) { - throw new DataError(); - } - lower = valueToKey_default(lower); - upper = valueToKey_default(upper); - return new _FDBKeyRange(lower, upper, lowerOpen, upperOpen); - } - constructor(lower, upper, lowerOpen, upperOpen) { - this.lower = lower; - this.upper = upper; - this.lowerOpen = lowerOpen; - this.upperOpen = upperOpen; - } - // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes - includes(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - key = valueToKey_default(key); - if (this.lower !== void 0) { - const cmpResult = cmp_default(this.lower, key); - if (cmpResult === 1 || cmpResult === 0 && this.lowerOpen) { - return false; - } - } - if (this.upper !== void 0) { - const cmpResult = cmp_default(this.upper, key); - if (cmpResult === -1 || cmpResult === 0 && this.upperOpen) { - return false; - } - } - return true; - } - get [Symbol.toStringTag]() { - return "IDBKeyRange"; - } -}; -var FDBKeyRange_default = FDBKeyRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/extractKey.js -var extractKey = (keyPath, value) => { - if (Array.isArray(keyPath)) { - const result = []; - for (let item of keyPath) { - if (item !== void 0 && item !== null && typeof item !== "string" && item.toString) { - item = item.toString(); - } - const key = extractKey(item, value).key; - result.push(valueToKey_default(key)); - } - return { - type: "found", - key: result - }; - } - if (keyPath === "") { - return { - type: "found", - key: value - }; - } - let remainingKeyPath = keyPath; - let object = value; - while (remainingKeyPath !== null) { - let identifier; - const i = remainingKeyPath.indexOf("."); - if (i >= 0) { - identifier = remainingKeyPath.slice(0, i); - remainingKeyPath = remainingKeyPath.slice(i + 1); - } else { - identifier = remainingKeyPath; - remainingKeyPath = null; - } - const isSpecialIdentifier = identifier === "length" && (typeof object === "string" || Array.isArray(object)) || (identifier === "size" || identifier === "type") && typeof Blob !== "undefined" && object instanceof Blob || (identifier === "name" || identifier === "lastModified") && typeof File !== "undefined" && object instanceof File; - if (!isSpecialIdentifier && (typeof object !== "object" || object === null || !Object.hasOwn(object, identifier))) { - return { - type: "notFound" - }; - } - object = object[identifier]; - } - return { - type: "found", - key: object - }; -}; -var extractKey_default = extractKey; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/cloneValueForInsertion.js -function cloneValueForInsertion(value, transaction) { - if (transaction._state !== "active") { - throw new Error("Assert: transaction state is active"); - } - transaction._state = "inactive"; - try { - return structuredClone(value); - } finally { - transaction._state = "active"; - } -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBCursor.js -var getEffectiveObjectStore = (cursor) => { - if (cursor.source instanceof FDBObjectStore_default) { - return cursor.source; - } - return cursor.source.objectStore; -}; -var makeKeyRange = (range, lowers, uppers) => { - let lower = range !== void 0 ? range.lower : void 0; - let upper = range !== void 0 ? range.upper : void 0; - for (const lowerTemp of lowers) { - if (lowerTemp === void 0) { - continue; - } - if (lower === void 0 || cmp_default(lower, lowerTemp) === 1) { - lower = lowerTemp; - } - } - for (const upperTemp of uppers) { - if (upperTemp === void 0) { - continue; - } - if (upper === void 0 || cmp_default(upper, upperTemp) === -1) { - upper = upperTemp; - } - } - if (lower !== void 0 && upper !== void 0) { - return FDBKeyRange_default.bound(lower, upper); - } - if (lower !== void 0) { - return FDBKeyRange_default.lowerBound(lower); - } - if (upper !== void 0) { - return FDBKeyRange_default.upperBound(upper); - } -}; -var FDBCursor = class { - _gotValue = false; - _position = void 0; - // Key of previously returned record - _objectStorePosition = void 0; - _keyOnly = false; - _key = void 0; - _primaryKey = void 0; - constructor(source, range, direction = "next", request, keyOnly = false) { - this._range = range; - this._source = source; - this._direction = direction; - this._request = request; - this._keyOnly = keyOnly; - } - // Read only properties - get source() { - return this._source; - } - set source(val) { - } - get request() { - return this._request; - } - set request(val) { - } - get direction() { - return this._direction; - } - set direction(val) { - } - get key() { - return this._key; - } - set key(val) { - } - get primaryKey() { - return this._primaryKey; - } - set primaryKey(val) { - } - // https://w3c.github.io/IndexedDB/#iterate-a-cursor - _iterate(key, primaryKey) { - const sourceIsObjectStore = this.source instanceof FDBObjectStore_default; - const records = this.source instanceof FDBObjectStore_default ? this.source._rawObjectStore.records : this.source._rawIndex.records; - let foundRecord; - if (this.direction === "next") { - const range = makeKeyRange(this._range, [key, this._position], []); - for (const record of records.values(range)) { - const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0; - const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0; - if (key !== void 0) { - if (cmpResultKey === -1) { - continue; - } - } - if (primaryKey !== void 0) { - if (cmpResultKey === -1) { - continue; - } - const cmpResultPrimaryKey = cmp_default(record.value, primaryKey); - if (cmpResultKey === 0 && cmpResultPrimaryKey === -1) { - continue; - } - } - if (this._position !== void 0 && sourceIsObjectStore) { - if (cmpResultPosition !== 1) { - continue; - } - } - if (this._position !== void 0 && !sourceIsObjectStore) { - if (cmpResultPosition === -1) { - continue; - } - if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== 1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - foundRecord = record; - break; - } - } else if (this.direction === "nextunique") { - const range = makeKeyRange(this._range, [key, this._position], []); - for (const record of records.values(range)) { - if (key !== void 0) { - if (cmp_default(record.key, key) === -1) { - continue; - } - } - if (this._position !== void 0) { - if (cmp_default(record.key, this._position) !== 1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - foundRecord = record; - break; - } - } else if (this.direction === "prev") { - const range = makeKeyRange(this._range, [], [key, this._position]); - for (const record of records.values(range, "prev")) { - const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0; - const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0; - if (key !== void 0) { - if (cmpResultKey === 1) { - continue; - } - } - if (primaryKey !== void 0) { - if (cmpResultKey === 1) { - continue; - } - const cmpResultPrimaryKey = cmp_default(record.value, primaryKey); - if (cmpResultKey === 0 && cmpResultPrimaryKey === 1) { - continue; - } - } - if (this._position !== void 0 && sourceIsObjectStore) { - if (cmpResultPosition !== -1) { - continue; - } - } - if (this._position !== void 0 && !sourceIsObjectStore) { - if (cmpResultPosition === 1) { - continue; - } - if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== -1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - foundRecord = record; - break; - } - } else if (this.direction === "prevunique") { - let tempRecord; - const range = makeKeyRange(this._range, [], [key, this._position]); - for (const record of records.values(range, "prev")) { - if (key !== void 0) { - if (cmp_default(record.key, key) === 1) { - continue; - } - } - if (this._position !== void 0) { - if (cmp_default(record.key, this._position) !== -1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - tempRecord = record; - break; - } - if (tempRecord) { - foundRecord = records.get(tempRecord.key); - } - } - let result; - if (!foundRecord) { - this._key = void 0; - if (!sourceIsObjectStore) { - this._objectStorePosition = void 0; - } - if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { - this.value = void 0; - } - result = null; - } else { - this._position = foundRecord.key; - if (!sourceIsObjectStore) { - this._objectStorePosition = foundRecord.value; - } - this._key = foundRecord.key; - if (sourceIsObjectStore) { - this._primaryKey = structuredClone(foundRecord.key); - if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { - this.value = structuredClone(foundRecord.value); - } - } else { - this._primaryKey = structuredClone(foundRecord.value); - if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { - if (this.source instanceof FDBObjectStore_default) { - throw new Error("This should never happen"); - } - const value = this.source.objectStore._rawObjectStore.getValue(foundRecord.value); - this.value = structuredClone(value); - } - } - this._gotValue = true; - result = this; - } - return result; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-update-IDBRequest-any-value - update(value) { - if (value === void 0) { - throw new TypeError(); - } - const effectiveObjectStore = getEffectiveObjectStore(this); - const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue || !Object.hasOwn(this, "value")) { - throw new InvalidStateError(); - } - const clone = cloneValueForInsertion(value, transaction); - if (effectiveObjectStore.keyPath !== null) { - let tempKey; - try { - tempKey = extractKey_default(effectiveObjectStore.keyPath, clone).key; - } catch (err) { - } - if (cmp_default(tempKey, effectiveKey) !== 0) { - throw new DataError(); - } - } - const record = { - key: effectiveKey, - value: clone - }; - return transaction._execRequestAsync({ - operation: effectiveObjectStore._rawObjectStore.storeRecord.bind(effectiveObjectStore._rawObjectStore, record, false, transaction._rollbackLog), - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-advance-void-unsigned-long-count - advance(count) { - if (!Number.isInteger(count) || count <= 0) { - throw new TypeError(); - } - const effectiveObjectStore = getEffectiveObjectStore(this); - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue) { - throw new InvalidStateError(); - } - if (this._request) { - this._request.readyState = "pending"; - } - transaction._execRequestAsync({ - operation: () => { - let result; - for (let i = 0; i < count; i++) { - result = this._iterate(); - if (!result) { - break; - } - } - return result; - }, - request: this._request, - source: this.source - }); - this._gotValue = false; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-continue-void-any-key - continue(key) { - const effectiveObjectStore = getEffectiveObjectStore(this); - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue) { - throw new InvalidStateError(); - } - if (key !== void 0) { - key = valueToKey_default(key); - const cmpResult = cmp_default(key, this._position); - if (cmpResult <= 0 && (this.direction === "next" || this.direction === "nextunique") || cmpResult >= 0 && (this.direction === "prev" || this.direction === "prevunique")) { - throw new DataError(); - } - } - if (this._request) { - this._request.readyState = "pending"; - } - transaction._execRequestAsync({ - operation: this._iterate.bind(this, key), - request: this._request, - source: this.source - }); - this._gotValue = false; - } - // hthttps://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey - continuePrimaryKey(key, primaryKey) { - const effectiveObjectStore = getEffectiveObjectStore(this); - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (this.source instanceof FDBObjectStore_default || this.direction !== "next" && this.direction !== "prev") { - throw new InvalidAccessError(); - } - if (!this._gotValue) { - throw new InvalidStateError(); - } - if (key === void 0 || primaryKey === void 0) { - throw new DataError(); - } - key = valueToKey_default(key); - const cmpResult = cmp_default(key, this._position); - if (cmpResult === -1 && this.direction === "next" || cmpResult === 1 && this.direction === "prev") { - throw new DataError(); - } - const cmpResult2 = cmp_default(primaryKey, this._objectStorePosition); - if (cmpResult === 0) { - if (cmpResult2 <= 0 && this.direction === "next" || cmpResult2 >= 0 && this.direction === "prev") { - throw new DataError(); - } - } - if (this._request) { - this._request.readyState = "pending"; - } - transaction._execRequestAsync({ - operation: this._iterate.bind(this, key, primaryKey), - request: this._request, - source: this.source - }); - this._gotValue = false; - } - delete() { - const effectiveObjectStore = getEffectiveObjectStore(this); - const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue || !Object.hasOwn(this, "value")) { - throw new InvalidStateError(); - } - return transaction._execRequestAsync({ - operation: effectiveObjectStore._rawObjectStore.deleteRecord.bind(effectiveObjectStore._rawObjectStore, effectiveKey, transaction._rollbackLog), - source: this - }); - } - get [Symbol.toStringTag]() { - return "IDBCursor"; - } -}; -var FDBCursor_default = FDBCursor; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBCursorWithValue.js -var FDBCursorWithValue = class extends FDBCursor_default { - value = void 0; - constructor(source, range, direction, request) { - super(source, range, direction, request); - } - get [Symbol.toStringTag]() { - return "IDBCursorWithValue"; - } -}; -var FDBCursorWithValue_default = FDBCursorWithValue; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeEventTarget.js -var stopped = (event, listener) => { - return event.immediatePropagationStopped || event.eventPhase === event.CAPTURING_PHASE && listener.capture === false || event.eventPhase === event.BUBBLING_PHASE && listener.capture === true; -}; -var invokeEventListeners = (event, obj) => { - event.currentTarget = obj; - const errors = []; - const invoke = (callbackOrObject) => { - try { - const callback2 = typeof callbackOrObject === "function" ? callbackOrObject : callbackOrObject.handleEvent; - callback2.call(event.currentTarget, event); - } catch (err) { - errors.push(err); - } - }; - for (const listener of obj.listeners.slice()) { - if (event.type !== listener.type || stopped(event, listener)) { - continue; - } - invoke(listener.callback); - } - const typeToProp = { - abort: "onabort", - blocked: "onblocked", - close: "onclose", - complete: "oncomplete", - error: "onerror", - success: "onsuccess", - upgradeneeded: "onupgradeneeded", - versionchange: "onversionchange" - }; - const prop = typeToProp[event.type]; - if (prop === void 0) { - throw new Error(`Unknown event type: "${event.type}"`); - } - const callback = event.currentTarget[prop]; - if (callback) { - const listener = { - callback, - capture: false, - type: event.type - }; - if (!stopped(event, listener)) { - invoke(listener.callback); - } - } - if (errors.length) { - throw new AggregateError(errors); - } -}; -var FakeEventTarget = class { - listeners = []; - // These will be overridden in individual subclasses and made not readonly - addEventListener(type, callback, options) { - const capture = !!(typeof options === "object" && options ? options.capture : options); - this.listeners.push({ - callback, - capture, - type - }); - } - removeEventListener(type, callback, options) { - const capture = !!(typeof options === "object" && options ? options.capture : options); - const i = this.listeners.findIndex((listener) => { - return listener.type === type && listener.callback === callback && listener.capture === capture; - }); - this.listeners.splice(i, 1); - } - // http://www.w3.org/TR/dom/#dispatching-events - dispatchEvent(event) { - if (event.dispatched || !event.initialized) { - throw new InvalidStateError("The object is in an invalid state."); - } - event.isTrusted = false; - event.dispatched = true; - event.target = this; - event.eventPhase = event.CAPTURING_PHASE; - for (const obj of event.eventPath) { - if (!event.propagationStopped) { - invokeEventListeners(event, obj); - } - } - event.eventPhase = event.AT_TARGET; - if (!event.propagationStopped) { - invokeEventListeners(event, event.target); - } - if (event.bubbles) { - event.eventPath.reverse(); - event.eventPhase = event.BUBBLING_PHASE; - for (const obj of event.eventPath) { - if (!event.propagationStopped) { - invokeEventListeners(event, obj); - } - } - } - event.dispatched = false; - event.eventPhase = event.NONE; - event.currentTarget = null; - if (event.canceled) { - return false; - } - return true; - } -}; -var FakeEventTarget_default = FakeEventTarget; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBRequest.js -var FDBRequest = class extends FakeEventTarget_default { - _result = null; - _error = null; - source = null; - transaction = null; - readyState = "pending"; - onsuccess = null; - onerror = null; - get error() { - if (this.readyState === "pending") { - throw new InvalidStateError(); - } - return this._error; - } - set error(value) { - this._error = value; - } - get result() { - if (this.readyState === "pending") { - throw new InvalidStateError(); - } - return this._result; - } - set result(value) { - this._result = value; - } - get [Symbol.toStringTag]() { - return "IDBRequest"; - } -}; -var FDBRequest_default = FDBRequest; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeDOMStringList.js -var FakeDOMStringList = class { - constructor(...values) { - this._values = values; - for (let i = 0; i < values.length; i++) { - this[i] = values[i]; - } - } - contains(value) { - return this._values.includes(value); - } - item(i) { - if (i < 0 || i >= this._values.length) { - return null; - } - return this._values[i]; - } - get length() { - return this._values.length; - } - [Symbol.iterator]() { - return this._values[Symbol.iterator](); - } - // Handled by proxy - // Used internally, should not be used by others. I could maybe get rid of these and replace rather than mutate, but too lazy to check the spec. - _push(...values) { - for (let i = 0; i < values.length; i++) { - this[this._values.length + i] = values[i]; - } - this._values.push(...values); - } - _sort(...values) { - this._values.sort(...values); - for (let i = 0; i < this._values.length; i++) { - this[i] = this._values[i]; - } - return this; - } -}; -var FakeDOMStringList_default = FakeDOMStringList; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKeyRange.js -var valueToKeyRange = (value, nullDisallowedFlag = false) => { - if (value instanceof FDBKeyRange_default) { - return value; - } - if (value === null || value === void 0) { - if (nullDisallowedFlag) { - throw new DataError(); - } - return new FDBKeyRange_default(void 0, void 0, false, false); - } - const key = valueToKey_default(value); - return FDBKeyRange_default.only(key); -}; -var valueToKeyRange_default = valueToKeyRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/getKeyPath.js -var convertKey = (key) => typeof key === "object" && key ? key + "" : key; -function getKeyPath(keyPath) { - return Array.isArray(keyPath) ? keyPath.map(convertKey) : convertKey(keyPath); -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/isPotentiallyValidKeyRange.js -var isPotentiallyValidKeyRange = (value) => { - if (value instanceof FDBKeyRange_default) { - return true; - } - const key = valueToKeyWithoutThrowing_default(value); - return key !== INVALID_TYPE; -}; -var isPotentiallyValidKeyRange_default = isPotentiallyValidKeyRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/enforceRange.js -var enforceRange = (num, type) => { - const min = 0; - const max = type === "unsigned long" ? 4294967295 : 9007199254740991; - if (isNaN(num) || num < min || num > max) { - throw new TypeError(); - } - if (num >= 0) { - return Math.floor(num); - } -}; -var enforceRange_default = enforceRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/extractGetAllOptions.js -var extractGetAllOptions = (queryOrOptions, count, numArguments) => { - let query; - let direction; - if (queryOrOptions === void 0 || queryOrOptions === null || isPotentiallyValidKeyRange_default(queryOrOptions)) { - query = queryOrOptions; - if (numArguments > 1 && count !== void 0) { - count = enforceRange_default(count, "unsigned long"); - } - } else { - const getAllOptions = queryOrOptions; - if (getAllOptions.query !== void 0) { - query = getAllOptions.query; - } - if (getAllOptions.count !== void 0) { - count = enforceRange_default(getAllOptions.count, "unsigned long"); - } - if (getAllOptions.direction !== void 0) { - direction = getAllOptions.direction; - } - } - return { - query, - count, - direction - }; -}; -var extractGetAllOptions_default = extractGetAllOptions; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBIndex.js -var confirmActiveTransaction = (index) => { - if (index._rawIndex.deleted || index.objectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (index.objectStore.transaction._state !== "active") { - throw new TransactionInactiveError(); - } -}; -var FDBIndex = class { - constructor(objectStore, rawIndex) { - this._rawIndex = rawIndex; - this._name = rawIndex.name; - this.objectStore = objectStore; - this.keyPath = getKeyPath(rawIndex.keyPath); - this.multiEntry = rawIndex.multiEntry; - this.unique = rawIndex.unique; - } - get name() { - return this._name; - } - // https://w3c.github.io/IndexedDB/#dom-idbindex-name - set name(name) { - const transaction = this.objectStore.transaction; - if (!transaction.db._runningVersionchangeTransaction) { - throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); - } - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (this._rawIndex.deleted || this.objectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - name = String(name); - if (name === this._name) { - return; - } - if (this.objectStore.indexNames.contains(name)) { - throw new ConstraintError(); - } - const oldName = this._name; - const oldIndexNames = [...this.objectStore.indexNames]; - this._name = name; - this._rawIndex.name = name; - this.objectStore._indexesCache.delete(oldName); - this.objectStore._indexesCache.set(name, this); - this.objectStore._rawObjectStore.rawIndexes.delete(oldName); - this.objectStore._rawObjectStore.rawIndexes.set(name, this._rawIndex); - this.objectStore.indexNames = new FakeDOMStringList_default(...Array.from(this.objectStore._rawObjectStore.rawIndexes.keys()).filter((indexName) => { - const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName); - return index && !index.deleted; - }).sort()); - if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) { - transaction._rollbackLog.push(() => { - this._name = oldName; - this._rawIndex.name = oldName; - this.objectStore._indexesCache.delete(name); - this.objectStore._indexesCache.set(oldName, this); - this.objectStore._rawObjectStore.rawIndexes.delete(name); - this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex); - this.objectStore.indexNames = new FakeDOMStringList_default(...oldIndexNames); - }); - } - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction - openCursor(range, direction) { - confirmActiveTransaction(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.objectStore.transaction; - const cursor = new FDBCursorWithValue_default(this, range, direction, request); - return this.objectStore.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openKeyCursor-IDBRequest-any-range-IDBCursorDirection-direction - openKeyCursor(range, direction) { - confirmActiveTransaction(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.objectStore.transaction; - const cursor = new FDBCursor_default(this, range, direction, request, true); - return this.objectStore.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - get(key) { - confirmActiveTransaction(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getValue.bind(this._rawIndex, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbindex-getall - getAll(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction(this); - const range = valueToKeyRange_default(options.query); - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getAllValues.bind(this._rawIndex, range, options.count, options.direction), - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-getKey-IDBRequest-any-key - getKey(key) { - confirmActiveTransaction(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getKey.bind(this._rawIndex, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys - getAllKeys(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction(this); - const range = valueToKeyRange_default(options.query); - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getAllKeys.bind(this._rawIndex, range, options.count, options.direction), - source: this - }); - } - // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords - getAllRecords(options) { - let query; - let count; - let direction; - if (options !== void 0) { - if (options.query !== void 0) { - query = options.query; - } - if (options.count !== void 0) { - count = enforceRange_default(options.count, "unsigned long"); - } - if (options.direction !== void 0) { - direction = options.direction; - } - } - confirmActiveTransaction(this); - const range = valueToKeyRange_default(query); - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getAllRecords.bind(this._rawIndex, range, count, direction), - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-count-IDBRequest-any-key - count(key) { - confirmActiveTransaction(this); - if (key === null) { - key = void 0; - } - if (key !== void 0 && !(key instanceof FDBKeyRange_default)) { - key = FDBKeyRange_default.only(valueToKey_default(key)); - } - return this.objectStore.transaction._execRequestAsync({ - operation: () => { - return this._rawIndex.count(key); - }, - source: this - }); - } - get [Symbol.toStringTag]() { - return "IDBIndex"; - } -}; -var FDBIndex_default = FDBIndex; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/canInjectKey.js -var canInjectKey = (keyPath, value) => { - if (Array.isArray(keyPath)) { - throw new Error("The key paths used in this section are always strings and never sequences, since it is not possible to create a object store which has a key generator and also has a key path that is a sequence."); - } - const identifiers = keyPath.split("."); - if (identifiers.length === 0) { - throw new Error("Assert: identifiers is not empty"); - } - identifiers.pop(); - for (const identifier of identifiers) { - if (typeof value !== "object" && !Array.isArray(value)) { - return false; - } - const hop = Object.hasOwn(value, identifier); - if (!hop) { - return true; - } - value = value[identifier]; - } - return typeof value === "object" || Array.isArray(value); -}; -var canInjectKey_default = canInjectKey; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBRecord.js -var FDBRecord = class { - constructor(key, primaryKey, value) { - this._key = key; - this._primaryKey = primaryKey; - this._value = value; - } - get key() { - return this._key; - } - set key(_) { - } - get primaryKey() { - return this._primaryKey; - } - set primaryKey(_) { - } - get value() { - return this._value; - } - set value(_) { - } - get [Symbol.toStringTag]() { - return "IDBRecord"; - } -}; -var FDBRecord_default = FDBRecord; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js -var MAX_TOMBSTONE_FACTOR = 2 / 3; -var EVERYTHING_KEY_RANGE = new FDBKeyRange_default(void 0, void 0, false, false); -var BinarySearchTree = class { - _numTombstones = 0; - _numNodes = 0; - /** - * - * @param keysAreUnique - whether keys can be unique, and thus whether we cn skip checking `record.value` when - * comparing. This is basically used to distinguish ObjectStores (where the value is the entire object, not used - * as a key) from non-unique Indexes (where both the key and the value are meaningful keys used for sorting) - */ - constructor(keysAreUnique) { - this._keysAreUnique = !!keysAreUnique; - } - size() { - return this._numNodes - this._numTombstones; - } - get(record) { - return this._getByComparator(this._root, (otherRecord) => this._compare(record, otherRecord)); - } - contains(record) { - return !!this.get(record); - } - _compare(a, b) { - const keyComparison = cmp_default(a.key, b.key); - if (keyComparison !== 0) { - return keyComparison; - } - return this._keysAreUnique ? 0 : cmp_default(a.value, b.value); - } - _getByComparator(node, comparator) { - let current = node; - while (current) { - const comparison = comparator(current.record); - if (comparison < 0) { - current = current.left; - } else if (comparison > 0) { - current = current.right; - } else { - return current.record; - } - } - } - /** - * Put a new record, and return the overwritten record if an overwrite occurred. - * @param record - * @param noOverwrite - throw a ConstraintError in case of overwrite - */ - put(record, noOverwrite = false) { - if (!this._root) { - this._root = { - record, - left: void 0, - right: void 0, - parent: void 0, - deleted: false, - // the root is always black in a red-black tree - red: false - }; - this._numNodes++; - return; - } - return this._put(this._root, record, noOverwrite); - } - _put(node, record, noOverwrite) { - const comparison = this._compare(record, node.record); - if (comparison < 0) { - if (node.left) { - return this._put(node.left, record, noOverwrite); - } else { - node.left = { - record, - left: void 0, - right: void 0, - parent: node, - deleted: false, - red: true - }; - this._onNewNodeInserted(node.left); - } - } else if (comparison > 0) { - if (node.right) { - return this._put(node.right, record, noOverwrite); - } else { - node.right = { - record, - left: void 0, - right: void 0, - parent: node, - deleted: false, - red: true - }; - this._onNewNodeInserted(node.right); - } - } else if (node.deleted) { - node.deleted = false; - node.record = record; - this._numTombstones--; - } else if (noOverwrite) { - throw new ConstraintError(); - } else { - const overwrittenRecord = node.record; - node.record = record; - return overwrittenRecord; - } - } - delete(record) { - if (!this._root) { - return; - } - this._delete(this._root, record); - if (this._numTombstones > this._numNodes * MAX_TOMBSTONE_FACTOR) { - const records = [...this.getAllRecords()]; - this._root = this._rebuild(records, void 0, false); - this._numNodes = records.length; - this._numTombstones = 0; - } - } - _delete(node, record) { - if (!node) { - return; - } - const comparison = this._compare(record, node.record); - if (comparison < 0) { - this._delete(node.left, record); - } else if (comparison > 0) { - this._delete(node.right, record); - } else if (!node.deleted) { - this._numTombstones++; - node.deleted = true; - } - } - *getAllRecords(descending = false) { - yield* this.getRecords(EVERYTHING_KEY_RANGE, descending); - } - *getRecords(keyRange, descending = false) { - yield* this._getRecordsForNode(this._root, keyRange, descending); - } - *_getRecordsForNode(node, keyRange, descending = false) { - if (!node) { - return; - } - yield* this._findRecords(node, keyRange, descending); - } - *_findRecords(node, keyRange, descending = false) { - const { - lower, - upper, - lowerOpen, - upperOpen - } = keyRange; - const { - record: { - key - } - } = node; - const lowerComparison = lower === void 0 ? -1 : cmp_default(lower, key); - const upperComparison = upper === void 0 ? 1 : cmp_default(upper, key); - const moreLeft = this._keysAreUnique ? lowerComparison < 0 : lowerComparison <= 0; - const moreRight = this._keysAreUnique ? upperComparison > 0 : upperComparison >= 0; - const moreStart = descending ? moreRight : moreLeft; - const moreEnd = descending ? moreLeft : moreRight; - const start = descending ? "right" : "left"; - const end = descending ? "left" : "right"; - const lowerMatches = lowerOpen ? lowerComparison < 0 : lowerComparison <= 0; - const upperMatches = upperOpen ? upperComparison > 0 : upperComparison >= 0; - if (moreStart && node[start]) { - yield* this._findRecords(node[start], keyRange, descending); - } - if (lowerMatches && upperMatches && !node.deleted) { - yield node.record; - } - if (moreEnd && node[end]) { - yield* this._findRecords(node[end], keyRange, descending); - } - } - _onNewNodeInserted(newNode) { - this._numNodes++; - this._rebalanceTree(newNode); - } - // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion - _rebalanceTree(node) { - let parent = node.parent; - do { - if (!parent.red) { - return; - } - const grandparent = parent.parent; - if (!grandparent) { - parent.red = false; - return; - } - const parentIsRightChild = parent === grandparent.right; - const uncle = parentIsRightChild ? grandparent.left : grandparent.right; - if (!uncle || !uncle.red) { - if (node === (parentIsRightChild ? parent.left : parent.right)) { - this._rotateSubtree(parent, parentIsRightChild); - node = parent; - parent = parentIsRightChild ? grandparent.right : grandparent.left; - } - this._rotateSubtree(grandparent, !parentIsRightChild); - parent.red = false; - grandparent.red = true; - return; - } - parent.red = false; - uncle.red = false; - grandparent.red = true; - node = grandparent; - } while (node.parent ? parent = node.parent : false); - } - // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Implementation - _rotateSubtree(node, right) { - const parent = node.parent; - const newRoot = right ? node.left : node.right; - const newChild = right ? newRoot.right : newRoot.left; - node[right ? "left" : "right"] = newChild; - if (newChild) { - newChild.parent = node; - } - newRoot[right ? "right" : "left"] = node; - newRoot.parent = parent; - node.parent = newRoot; - if (parent) { - parent[node === parent.right ? "right" : "left"] = newRoot; - } else { - this._root = newRoot; - } - return newRoot; - } - // rebuild the whole tree from scratch, used to avoid too many deletion tombstones accumulating - _rebuild(records, parent, red) { - const { - length - } = records; - if (!length) { - return void 0; - } - const mid = length >>> 1; - const node = { - record: records[mid], - left: void 0, - right: void 0, - parent, - deleted: false, - red - }; - const left = this._rebuild(records.slice(0, mid), node, !red); - const right = this._rebuild(records.slice(mid + 1), node, !red); - node.left = left; - node.right = right; - return node; - } -}; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/RecordStore.js -var RecordStore = class { - constructor(keysAreUnique) { - this.keysAreUnique = keysAreUnique; - this.records = new BinarySearchTree(this.keysAreUnique); - } - get(key) { - const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); - return this.records.getRecords(range).next().value; - } - /** - * Put a new record, and return the overwritten record if an overwrite occurred. - * @param newRecord - * @param noOverwrite - throw a ConstraintError in case of overwrite - */ - put(newRecord, noOverwrite = false) { - return this.records.put(newRecord, noOverwrite); - } - delete(key) { - const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); - const deletedRecords = [...this.records.getRecords(range)]; - for (const record of deletedRecords) { - this.records.delete(record); - } - return deletedRecords; - } - deleteByValue(key) { - const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); - const deletedRecords = []; - for (const record of this.records.getAllRecords()) { - if (range.includes(record.value)) { - this.records.delete(record); - deletedRecords.push(record); - } - } - return deletedRecords; - } - clear() { - const deletedRecords = [...this.records.getAllRecords()]; - this.records = new BinarySearchTree(this.keysAreUnique); - return deletedRecords; - } - values(range, direction = "next") { - const descending = direction === "prev" || direction === "prevunique"; - const records = range ? this.records.getRecords(range, descending) : this.records.getAllRecords(descending); - return { - [Symbol.iterator]: () => { - const next = () => { - return records.next(); - }; - if (direction === "next" || direction === "prev") { - return { - next - }; - } - if (direction === "nextunique") { - let previousValue = void 0; - return { - next: () => { - let current2 = next(); - while (!current2.done && previousValue !== void 0 && cmp_default(previousValue.key, current2.value.key) === 0) { - current2 = next(); - } - previousValue = current2.value; - return current2; - } - }; - } - let current = next(); - let nextResult = next(); - return { - next: () => { - while (!nextResult.done && cmp_default(current.value.key, nextResult.value.key) === 0) { - current = nextResult; - nextResult = next(); - } - const result = current; - current = nextResult; - nextResult = next(); - return result; - } - }; - } - }; - } - size() { - return this.records.size(); - } -}; -var RecordStore_default = RecordStore; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/Index.js -var Index = class { - deleted = false; - // Initialized should be used to decide whether to throw an error or abort the versionchange transaction when there is a - // constraint - initialized = false; - constructor(rawObjectStore, name, keyPath, multiEntry, unique) { - this.rawObjectStore = rawObjectStore; - this.name = name; - this.keyPath = keyPath; - this.multiEntry = multiEntry; - this.unique = unique; - this.records = new RecordStore_default(unique); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-index - getKey(key) { - const record = this.records.get(key); - return record !== void 0 ? record.value : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index - getAllKeys(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(structuredClone(record.value)); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#index-referenced-value-retrieval-operation - getValue(key) { - const record = this.records.get(key); - return record !== void 0 ? this.rawObjectStore.getValue(record.value) : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index - getAllValues(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(this.rawObjectStore.getValue(record.value)); - if (records.length >= count) { - break; - } - } - return records; - } - // https://www.w3.org/TR/IndexedDB/#dom-idbindex-getallrecords - getAllRecords(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(this.rawObjectStore.getKey(record.value)), this.rawObjectStore.getValue(record.value))); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store (step 7) - storeRecord(newRecord) { - let indexKey; - try { - indexKey = extractKey_default(this.keyPath, newRecord.value).key; - } catch (err) { - if (err.name === "DataError") { - return; - } - throw err; - } - if (!this.multiEntry || !Array.isArray(indexKey)) { - try { - valueToKey_default(indexKey); - } catch (e) { - return; - } - } else { - const keep = []; - for (const part of indexKey) { - if (keep.indexOf(part) < 0) { - try { - keep.push(valueToKey_default(part)); - } catch (err) { - } - } - } - indexKey = keep; - } - if (!this.multiEntry || !Array.isArray(indexKey)) { - if (this.unique) { - const existingRecord = this.records.get(indexKey); - if (existingRecord) { - throw new ConstraintError(); - } - } - } else { - if (this.unique) { - for (const individualIndexKey of indexKey) { - const existingRecord = this.records.get(individualIndexKey); - if (existingRecord) { - throw new ConstraintError(); - } - } - } - } - if (!this.multiEntry || !Array.isArray(indexKey)) { - this.records.put({ - key: indexKey, - value: newRecord.key - }); - } else { - for (const individualIndexKey of indexKey) { - this.records.put({ - key: individualIndexKey, - value: newRecord.key - }); - } - } - } - initialize(transaction) { - if (this.initialized) { - throw new Error("Index already initialized"); - } - transaction._execRequestAsync({ - operation: () => { - try { - for (const record of this.rawObjectStore.records.values()) { - this.storeRecord(record); - } - this.initialized = true; - } catch (err) { - transaction._abort(err.name); - } - }, - source: null - }); - } - count(range) { - let count = 0; - for (const record of this.records.values(range)) { - count += 1; - } - return count; - } -}; -var Index_default = Index; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/validateKeyPath.js -var validateKeyPath = (keyPath, parent) => { - if (keyPath !== void 0 && keyPath !== null && typeof keyPath !== "string" && keyPath.toString && (parent === "array" || !Array.isArray(keyPath))) { - keyPath = keyPath.toString(); - } - if (typeof keyPath === "string") { - if (keyPath === "" && parent !== "string") { - return; - } - try { - const validIdentifierRegex = ( - // eslint-disable-next-line no-misleading-character-class - /^(?:[$A-Z_a-z\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B2\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\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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])(?:[$0-9A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC])*$/ - ); - if (keyPath.length >= 1 && validIdentifierRegex.test(keyPath)) { - return; - } - } catch (err) { - throw new SyntaxError2(err.message); - } - if (keyPath.indexOf(" ") >= 0) { - throw new SyntaxError2("The keypath argument contains an invalid key path (no spaces allowed)."); - } - } - if (Array.isArray(keyPath) && keyPath.length > 0) { - if (parent) { - throw new SyntaxError2("The keypath argument contains an invalid key path (nested arrays)."); - } - for (const part of keyPath) { - validateKeyPath(part, "array"); - } - return; - } else if (typeof keyPath === "string" && keyPath.indexOf(".") >= 0) { - keyPath = keyPath.split("."); - for (const part of keyPath) { - validateKeyPath(part, "string"); - } - return; - } - throw new SyntaxError2(); -}; -var validateKeyPath_default = validateKeyPath; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBObjectStore.js -var confirmActiveTransaction2 = (objectStore) => { - if (objectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (objectStore.transaction._state !== "active") { - throw new TransactionInactiveError(); - } -}; -var buildRecordAddPut = (objectStore, value, key) => { - confirmActiveTransaction2(objectStore); - if (objectStore.transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (objectStore.keyPath !== null) { - if (key !== void 0) { - throw new DataError(); - } - } - const clone = cloneValueForInsertion(value, objectStore.transaction); - if (objectStore.keyPath !== null) { - const tempKey = extractKey_default(objectStore.keyPath, clone); - if (tempKey.type === "found") { - valueToKey_default(tempKey.key); - } else { - if (!objectStore._rawObjectStore.keyGenerator) { - throw new DataError(); - } else if (!canInjectKey_default(objectStore.keyPath, clone)) { - throw new DataError(); - } - } - } - if (objectStore.keyPath === null && objectStore._rawObjectStore.keyGenerator === null && key === void 0) { - throw new DataError(); - } - if (key !== void 0) { - key = valueToKey_default(key); - } - return { - key, - value: clone - }; -}; -var FDBObjectStore = class { - _indexesCache = /* @__PURE__ */ new Map(); - constructor(transaction, rawObjectStore) { - this._rawObjectStore = rawObjectStore; - this._name = rawObjectStore.name; - this.keyPath = getKeyPath(rawObjectStore.keyPath); - this.autoIncrement = rawObjectStore.autoIncrement; - this.transaction = transaction; - this.indexNames = new FakeDOMStringList_default(...Array.from(rawObjectStore.rawIndexes.keys()).sort()); - } - get name() { - return this._name; - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-name - set name(name) { - const transaction = this.transaction; - if (!transaction.db._runningVersionchangeTransaction) { - throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); - } - confirmActiveTransaction2(this); - name = String(name); - if (name === this._name) { - return; - } - if (this._rawObjectStore.rawDatabase.rawObjectStores.has(name)) { - throw new ConstraintError(); - } - const oldName = this._name; - const oldObjectStoreNames = [...transaction.db.objectStoreNames]; - this._name = name; - this._rawObjectStore.name = name; - this.transaction._objectStoresCache.delete(oldName); - this.transaction._objectStoresCache.set(name, this); - this._rawObjectStore.rawDatabase.rawObjectStores.delete(oldName); - this._rawObjectStore.rawDatabase.rawObjectStores.set(name, this._rawObjectStore); - transaction.db.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._rawObjectStore.rawDatabase.rawObjectStores.keys()).filter((objectStoreName) => { - const objectStore = this._rawObjectStore.rawDatabase.rawObjectStores.get(objectStoreName); - return objectStore && !objectStore.deleted; - }).sort()); - const oldScope = new Set(transaction._scope); - const oldTransactionObjectStoreNames = [...transaction.objectStoreNames]; - this.transaction._scope.delete(oldName); - transaction._scope.add(name); - transaction.objectStoreNames = new FakeDOMStringList_default(...Array.from(transaction._scope).sort()); - if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) { - transaction._rollbackLog.push(() => { - this._name = oldName; - this._rawObjectStore.name = oldName; - this.transaction._objectStoresCache.delete(name); - this.transaction._objectStoresCache.set(oldName, this); - this._rawObjectStore.rawDatabase.rawObjectStores.delete(name); - this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore); - transaction.db.objectStoreNames = new FakeDOMStringList_default(...oldObjectStoreNames); - transaction._scope = oldScope; - transaction.objectStoreNames = new FakeDOMStringList_default(...oldTransactionObjectStoreNames); - }); - } - } - put(value, key) { - if (arguments.length === 0) { - throw new TypeError(); - } - const record = buildRecordAddPut(this, value, key); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, false, this.transaction._rollbackLog), - source: this - }); - } - add(value, key) { - if (arguments.length === 0) { - throw new TypeError(); - } - const record = buildRecordAddPut(this, value, key); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, true, this.transaction._rollbackLog), - source: this - }); - } - delete(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - confirmActiveTransaction2(this); - if (this.transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.deleteRecord.bind(this._rawObjectStore, key, this.transaction._rollbackLog), - source: this - }); - } - get(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - confirmActiveTransaction2(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getValue.bind(this._rawObjectStore, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall - getAll(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction2(this); - const range = valueToKeyRange_default(options.query); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getAllValues.bind(this._rawObjectStore, range, options.count, options.direction), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey - getKey(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - confirmActiveTransaction2(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getKey.bind(this._rawObjectStore, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys - getAllKeys(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction2(this); - const range = valueToKeyRange_default(options.query); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getAllKeys.bind(this._rawObjectStore, range, options.count, options.direction), - source: this - }); - } - // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords - getAllRecords(options) { - let query; - let count; - let direction; - if (options !== void 0) { - if (options.query !== void 0) { - query = options.query; - } - if (options.count !== void 0) { - count = enforceRange_default(options.count, "unsigned long"); - } - if (options.direction !== void 0) { - direction = options.direction; - } - } - confirmActiveTransaction2(this); - const range = valueToKeyRange_default(query); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getAllRecords.bind(this._rawObjectStore, range, count, direction), - source: this - }); - } - clear() { - confirmActiveTransaction2(this); - if (this.transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.clear.bind(this._rawObjectStore, this.transaction._rollbackLog), - source: this - }); - } - openCursor(range, direction) { - confirmActiveTransaction2(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.transaction; - const cursor = new FDBCursorWithValue_default(this, range, direction, request); - return this.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - openKeyCursor(range, direction) { - confirmActiveTransaction2(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.transaction; - const cursor = new FDBCursor_default(this, range, direction, request, true); - return this.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - // tslint:-next-line max-line-length - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-createIndex-IDBIndex-DOMString-name-DOMString-sequence-DOMString--keyPath-IDBIndexParameters-optionalParameters - createIndex(name, keyPath, optionalParameters = {}) { - if (arguments.length < 2) { - throw new TypeError(); - } - const multiEntry = optionalParameters.multiEntry !== void 0 ? optionalParameters.multiEntry : false; - const unique = optionalParameters.unique !== void 0 ? optionalParameters.unique : false; - if (this.transaction.mode !== "versionchange") { - throw new InvalidStateError(); - } - confirmActiveTransaction2(this); - if (this.indexNames.contains(name)) { - throw new ConstraintError(); - } - validateKeyPath_default(keyPath); - if (Array.isArray(keyPath) && multiEntry) { - throw new InvalidAccessError(); - } - const indexNames = [...this.indexNames]; - const index = new Index_default(this._rawObjectStore, name, keyPath, multiEntry, unique); - this.indexNames._push(name); - this.indexNames._sort(); - this.transaction._createdIndexes.add(index); - this._rawObjectStore.rawIndexes.set(name, index); - index.initialize(this.transaction); - this.transaction._rollbackLog.push(() => { - index.deleted = true; - this.indexNames = new FakeDOMStringList_default(...indexNames); - this._rawObjectStore.rawIndexes.delete(index.name); - }); - return new FDBIndex_default(this, index); - } - // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index - index(name) { - if (arguments.length === 0) { - throw new TypeError(); - } - if (this._rawObjectStore.deleted || this.transaction._state === "finished") { - throw new InvalidStateError(); - } - const index = this._indexesCache.get(name); - if (index !== void 0) { - return index; - } - const rawIndex = this._rawObjectStore.rawIndexes.get(name); - if (!this.indexNames.contains(name) || rawIndex === void 0) { - throw new NotFoundError(); - } - const index2 = new FDBIndex_default(this, rawIndex); - this._indexesCache.set(name, index2); - return index2; - } - deleteIndex(name) { - if (arguments.length === 0) { - throw new TypeError(); - } - if (this.transaction.mode !== "versionchange") { - throw new InvalidStateError(); - } - confirmActiveTransaction2(this); - const rawIndex = this._rawObjectStore.rawIndexes.get(name); - if (rawIndex === void 0) { - throw new NotFoundError(); - } - this.transaction._rollbackLog.push(() => { - rawIndex.deleted = false; - this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex); - this.indexNames._push(rawIndex.name); - this.indexNames._sort(); - }); - this.indexNames = new FakeDOMStringList_default(...Array.from(this.indexNames).filter((indexName) => { - return indexName !== name; - })); - rawIndex.deleted = true; - this.transaction._execRequestAsync({ - operation: () => { - const rawIndex2 = this._rawObjectStore.rawIndexes.get(name); - if (rawIndex === rawIndex2) { - this._rawObjectStore.rawIndexes.delete(name); - } - }, - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-count-IDBRequest-any-key - count(key) { - confirmActiveTransaction2(this); - if (key === null) { - key = void 0; - } - if (key !== void 0 && !(key instanceof FDBKeyRange_default)) { - key = FDBKeyRange_default.only(valueToKey_default(key)); - } - return this.transaction._execRequestAsync({ - operation: () => { - return this._rawObjectStore.count(key); - }, - source: this - }); - } - get [Symbol.toStringTag]() { - return "IDBObjectStore"; - } -}; -var FDBObjectStore_default = FDBObjectStore; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeEvent.js -var Event = class { - eventPath = []; - NONE = 0; - CAPTURING_PHASE = 1; - AT_TARGET = 2; - BUBBLING_PHASE = 3; - // Flags - propagationStopped = false; - immediatePropagationStopped = false; - canceled = false; - initialized = true; - dispatched = false; - target = null; - currentTarget = null; - eventPhase = 0; - defaultPrevented = false; - isTrusted = false; - timeStamp = Date.now(); - constructor(type, eventInitDict = {}) { - this.type = type; - this.bubbles = eventInitDict.bubbles !== void 0 ? eventInitDict.bubbles : false; - this.cancelable = eventInitDict.cancelable !== void 0 ? eventInitDict.cancelable : false; - } - preventDefault() { - if (this.cancelable) { - this.canceled = true; - } - } - stopPropagation() { - this.propagationStopped = true; - } - stopImmediatePropagation() { - this.propagationStopped = true; - this.immediatePropagationStopped = true; - } -}; -var FakeEvent_default = Event; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/scheduling.js -function getSetImmediateFromJsdom() { - if (typeof navigator !== "undefined" && /jsdom/.test(navigator.userAgent)) { - const outerRealmFunctionConstructor = Node.constructor; - return new outerRealmFunctionConstructor("return setImmediate")(); - } else { - return void 0; - } -} -var schedulerPostTask = typeof scheduler !== "undefined" && ((fn) => scheduler.postTask(fn)); -var doSetTimeout = (fn) => setTimeout(fn, 0); -var queueTask = (fn) => { - const setImmediate2 = globalThis.setImmediate || getSetImmediateFromJsdom() || schedulerPostTask || doSetTimeout; - setImmediate2(fn); -}; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBTransaction.js -var prioritizedListenerTypes = ["error", "abort", "complete"]; -var FDBTransaction = class extends FakeEventTarget_default { - _state = "active"; - _started = false; - _rollbackLog = []; - _objectStoresCache = /* @__PURE__ */ new Map(); - _openRequest = null; - error = null; - onabort = null; - oncomplete = null; - onerror = null; - _prioritizedListeners = /* @__PURE__ */ new Map(); - _requests = []; - _createdIndexes = /* @__PURE__ */ new Set(); - _createdObjectStores = /* @__PURE__ */ new Set(); - constructor(storeNames, mode, durability, db2) { - super(); - this._scope = new Set(storeNames); - this.mode = mode; - this.durability = durability; - this.db = db2; - this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._scope).sort()); - for (const type of prioritizedListenerTypes) { - this.addEventListener(type, () => { - this._prioritizedListeners.get(type)?.(); - }); - } - } - // https://w3c.github.io/IndexedDB/#abort-transaction - _abort(errName) { - for (const f of this._rollbackLog.reverse()) { - f(); - } - if (errName !== null) { - const e = new DOMException(void 0, errName); - this.error = e; - } - for (const { - request - } of this._requests) { - if (request.readyState !== "done") { - request.readyState = "done"; - if (request.source) { - queueTask(() => { - request.result = void 0; - request.error = new AbortError(); - const event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - event.eventPath = [this.db, this]; - try { - request.dispatchEvent(event); - } catch (_err) { - if (this._state === "active") { - this._abort("AbortError"); - } - } - }); - } - } - } - queueTask(() => { - const isUpgradeTransaction = this.mode === "versionchange"; - if (isUpgradeTransaction) { - this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter((connection) => !connection._rawDatabase.transactions.includes(this)); - } - const event = new FakeEvent_default("abort", { - bubbles: true, - cancelable: false - }); - event.eventPath = [this.db]; - this.dispatchEvent(event); - if (isUpgradeTransaction) { - const request = this._openRequest; - request.transaction = null; - request.result = void 0; - } - }); - this._state = "finished"; - } - abort() { - if (this._state === "committing" || this._state === "finished") { - throw new InvalidStateError(); - } - this._state = "active"; - this._abort(null); - } - // http://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore - objectStore(name) { - if (this._state !== "active") { - throw new InvalidStateError(); - } - const objectStore = this._objectStoresCache.get(name); - if (objectStore !== void 0) { - return objectStore; - } - const rawObjectStore = this.db._rawDatabase.rawObjectStores.get(name); - if (!this._scope.has(name) || rawObjectStore === void 0) { - throw new NotFoundError(); - } - const objectStore2 = new FDBObjectStore_default(this, rawObjectStore); - this._objectStoresCache.set(name, objectStore2); - return objectStore2; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-asynchronously-executing-a-request - _execRequestAsync(obj) { - const source = obj.source; - const operation = obj.operation; - let request = Object.hasOwn(obj, "request") ? obj.request : null; - if (this._state !== "active") { - throw new TransactionInactiveError(); - } - if (!request) { - if (!source) { - request = new FDBRequest_default(); - } else { - request = new FDBRequest_default(); - request.source = source; - request.transaction = source.transaction; - } - } - this._requests.push({ - operation, - request - }); - return request; - } - _start() { - this._started = true; - let operation; - let request; - while (this._requests.length > 0) { - const r = this._requests.shift(); - if (r && r.request.readyState !== "done") { - request = r.request; - operation = r.operation; - break; - } - } - if (request && operation) { - if (!request.source) { - operation(); - } else { - let defaultAction; - let event; - try { - const result = operation(); - request.readyState = "done"; - request.result = result; - request.error = void 0; - if (this._state === "inactive") { - this._state = "active"; - } - event = new FakeEvent_default("success", { - bubbles: false, - cancelable: false - }); - } catch (err) { - request.readyState = "done"; - request.result = void 0; - request.error = err; - if (this._state === "inactive") { - this._state = "active"; - } - event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - defaultAction = this._abort.bind(this, err.name); - } - try { - event.eventPath = [this.db, this]; - request.dispatchEvent(event); - } catch (_err) { - if (this._state === "active") { - this._abort("AbortError"); - defaultAction = void 0; - } - } - if (!event.canceled) { - if (defaultAction) { - defaultAction(); - } - } - } - queueTask(this._start.bind(this)); - return; - } - if (this._state !== "finished") { - this._state = "finished"; - if (!this.error) { - const event = new FakeEvent_default("complete"); - this.dispatchEvent(event); - } - } - } - commit() { - if (this._state !== "active") { - throw new InvalidStateError(); - } - this._state = "committing"; - } - get [Symbol.toStringTag]() { - return "IDBTransaction"; - } -}; -var FDBTransaction_default = FDBTransaction; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/KeyGenerator.js -var MAX_KEY = 9007199254740992; -var KeyGenerator = class { - // This is kind of wrong. Should start at 1 and increment only after record is saved - num = 0; - next() { - if (this.num >= MAX_KEY) { - throw new ConstraintError(); - } - this.num += 1; - return this.num; - } - // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator - setIfLarger(num) { - const value = Math.floor(Math.min(num, MAX_KEY)) - 1; - if (value >= this.num) { - this.num = value + 1; - } - } -}; -var KeyGenerator_default = KeyGenerator; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/ObjectStore.js -var ObjectStore = class { - deleted = false; - records = new RecordStore_default(true); - rawIndexes = /* @__PURE__ */ new Map(); - constructor(rawDatabase, name, keyPath, autoIncrement) { - this.rawDatabase = rawDatabase; - this.keyGenerator = autoIncrement === true ? new KeyGenerator_default() : null; - this.deleted = false; - this.name = name; - this.keyPath = keyPath; - this.autoIncrement = autoIncrement; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store - getKey(key) { - const record = this.records.get(key); - return record !== void 0 ? structuredClone(record.key) : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-keys-from-an-object-store - getAllKeys(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(structuredClone(record.key)); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store - getValue(key) { - const record = this.records.get(key); - return record !== void 0 ? structuredClone(record.value) : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-values-from-an-object-store - getAllValues(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(structuredClone(record.value)); - if (records.length >= count) { - break; - } - } - return records; - } - // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords - getAllRecords(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(record.key), structuredClone(record.value))); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store - storeRecord(newRecord, noOverwrite, rollbackLog) { - if (this.keyPath !== null) { - const key = extractKey_default(this.keyPath, newRecord.value).key; - if (key !== void 0) { - newRecord.key = key; - } - } - const rollbackLogForThisOperation = []; - if (this.keyGenerator !== null && newRecord.key === void 0) { - let rolledBack2 = false; - const keyGeneratorBefore = this.keyGenerator.num; - const rollbackKeyGenerator = () => { - if (rolledBack2) { - return; - } - rolledBack2 = true; - if (this.keyGenerator) { - this.keyGenerator.num = keyGeneratorBefore; - } - }; - rollbackLogForThisOperation.push(rollbackKeyGenerator); - if (rollbackLog) { - rollbackLog.push(rollbackKeyGenerator); - } - newRecord.key = this.keyGenerator.next(); - if (this.keyPath !== null) { - if (Array.isArray(this.keyPath)) { - throw new Error("Cannot have an array key path in an object store with a key generator"); - } - let remainingKeyPath = this.keyPath; - let object = newRecord.value; - let identifier; - let i = 0; - while (i >= 0) { - if (typeof object !== "object") { - throw new DataError(); - } - i = remainingKeyPath.indexOf("."); - if (i >= 0) { - identifier = remainingKeyPath.slice(0, i); - remainingKeyPath = remainingKeyPath.slice(i + 1); - if (!Object.hasOwn(object, identifier)) { - Object.defineProperty(object, identifier, { - configurable: true, - enumerable: true, - writable: true, - value: {} - }); - } - object = object[identifier]; - } - } - identifier = remainingKeyPath; - Object.defineProperty(object, identifier, { - configurable: true, - enumerable: true, - writable: true, - value: newRecord.key - }); - } - } else if (this.keyGenerator !== null && typeof newRecord.key === "number") { - this.keyGenerator.setIfLarger(newRecord.key); - } - const existingRecord = this.records.put(newRecord, noOverwrite); - let rolledBack = false; - const rollbackStoreRecord = () => { - if (rolledBack) { - return; - } - rolledBack = true; - if (existingRecord) { - this.storeRecord(existingRecord, false); - } else { - this.deleteRecord(newRecord.key); - } - }; - rollbackLogForThisOperation.push(rollbackStoreRecord); - if (rollbackLog) { - rollbackLog.push(rollbackStoreRecord); - } - if (existingRecord) { - for (const rawIndex of this.rawIndexes.values()) { - rawIndex.records.deleteByValue(newRecord.key); - } - } - try { - for (const rawIndex of this.rawIndexes.values()) { - if (rawIndex.initialized) { - rawIndex.storeRecord(newRecord); - } - } - } catch (err) { - if (err.name === "ConstraintError") { - for (const rollback of rollbackLogForThisOperation) { - rollback(); - } - } - throw err; - } - return newRecord.key; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-records-from-an-object-store - deleteRecord(key, rollbackLog) { - const deletedRecords = this.records.delete(key); - if (rollbackLog) { - for (const record of deletedRecords) { - rollbackLog.push(() => { - this.storeRecord(record, true); - }); - } - } - for (const rawIndex of this.rawIndexes.values()) { - rawIndex.records.deleteByValue(key); - } - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-clearing-an-object-store - clear(rollbackLog) { - const deletedRecords = this.records.clear(); - if (rollbackLog) { - for (const record of deletedRecords) { - rollbackLog.push(() => { - this.storeRecord(record, true); - }); - } - } - for (const rawIndex of this.rawIndexes.values()) { - rawIndex.records.clear(); - } - } - count(range) { - if (range === void 0 || range.lower === void 0 && range.upper === void 0) { - return this.records.size(); - } - let count = 0; - for (const record of this.records.values(range)) { - count += 1; - } - return count; - } -}; -var ObjectStore_default = ObjectStore; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/closeConnection.js -var closeConnection = (connection, forced = false) => { - connection._closePending = true; - const transactionsComplete = connection._rawDatabase.transactions.every((transaction) => { - return transaction._state === "finished"; - }); - if (transactionsComplete) { - connection._closed = true; - connection._rawDatabase.connections = connection._rawDatabase.connections.filter((otherConnection) => { - return connection !== otherConnection; - }); - if (forced) { - const event = new FakeEvent_default("close", { - bubbles: false, - cancelable: false - }); - event.eventPath = []; - connection.dispatchEvent(event); - } - } else { - queueTask(() => { - closeConnection(connection, forced); - }); - } -}; -var closeConnection_default = closeConnection; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBDatabase.js -var confirmActiveVersionchangeTransaction = (database) => { - let transaction; - if (database._runningVersionchangeTransaction) { - transaction = database._rawDatabase.transactions.findLast((tx) => { - return tx.mode === "versionchange"; - }); - } - if (!transaction) { - throw new InvalidStateError(); - } - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - return transaction; -}; -var FDBDatabase = class extends FakeEventTarget_default { - _closePending = false; - _closed = false; - _runningVersionchangeTransaction = false; - constructor(rawDatabase) { - super(); - this._rawDatabase = rawDatabase; - this._rawDatabase.connections.push(this); - this.name = rawDatabase.name; - this.version = rawDatabase.version; - this.objectStoreNames = new FakeDOMStringList_default(...Array.from(rawDatabase.rawObjectStores.keys()).sort()); - } - // http://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore - createObjectStore(name, options = {}) { - if (name === void 0) { - throw new TypeError(); - } - const transaction = confirmActiveVersionchangeTransaction(this); - const keyPath = options !== null && options.keyPath !== void 0 ? options.keyPath : null; - const autoIncrement = options !== null && options.autoIncrement !== void 0 ? options.autoIncrement : false; - if (keyPath !== null) { - validateKeyPath_default(keyPath); - } - if (this._rawDatabase.rawObjectStores.has(name)) { - throw new ConstraintError(); - } - if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) { - throw new InvalidAccessError(); - } - const objectStoreNames = [...this.objectStoreNames]; - const transactionObjectStoreNames = [...transaction.objectStoreNames]; - const rawObjectStore = new ObjectStore_default(this._rawDatabase, name, keyPath, autoIncrement); - this.objectStoreNames._push(name); - this.objectStoreNames._sort(); - transaction._scope.add(name); - transaction._createdObjectStores.add(rawObjectStore); - this._rawDatabase.rawObjectStores.set(name, rawObjectStore); - transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames); - transaction._rollbackLog.push(() => { - rawObjectStore.deleted = true; - this.objectStoreNames = new FakeDOMStringList_default(...objectStoreNames); - transaction.objectStoreNames = new FakeDOMStringList_default(...transactionObjectStoreNames); - transaction._scope.delete(rawObjectStore.name); - this._rawDatabase.rawObjectStores.delete(rawObjectStore.name); - }); - return transaction.objectStore(name); - } - // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore - deleteObjectStore(name) { - if (name === void 0) { - throw new TypeError(); - } - const transaction = confirmActiveVersionchangeTransaction(this); - const store = this._rawDatabase.rawObjectStores.get(name); - if (store === void 0) { - throw new NotFoundError(); - } - this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this.objectStoreNames).filter((objectStoreName) => { - return objectStoreName !== name; - })); - transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames); - const objectStore = transaction._objectStoresCache.get(name); - let prevIndexNames; - if (objectStore) { - prevIndexNames = [...objectStore.indexNames]; - objectStore.indexNames = new FakeDOMStringList_default(); - } - transaction._rollbackLog.push(() => { - store.deleted = false; - this._rawDatabase.rawObjectStores.set(store.name, store); - this.objectStoreNames._push(store.name); - transaction.objectStoreNames._push(store.name); - this.objectStoreNames._sort(); - if (objectStore && prevIndexNames) { - objectStore.indexNames = new FakeDOMStringList_default(...prevIndexNames); - } - }); - store.deleted = true; - this._rawDatabase.rawObjectStores.delete(name); - transaction._objectStoresCache.delete(name); - } - transaction(storeNames, mode, options) { - mode = mode !== void 0 ? mode : "readonly"; - if (mode !== "readonly" && mode !== "readwrite" && mode !== "versionchange") { - throw new TypeError("Invalid mode: " + mode); - } - const hasActiveVersionchange = this._rawDatabase.transactions.some((transaction) => { - return transaction._state === "active" && transaction.mode === "versionchange" && transaction.db === this; - }); - if (hasActiveVersionchange) { - throw new InvalidStateError(); - } - if (this._closePending) { - throw new InvalidStateError(); - } - if (!Array.isArray(storeNames)) { - storeNames = [storeNames]; - } - if (storeNames.length === 0 && mode !== "versionchange") { - throw new InvalidAccessError(); - } - for (const storeName of storeNames) { - if (!this.objectStoreNames.contains(storeName)) { - throw new NotFoundError("No objectStore named " + storeName + " in this database"); - } - } - const durability = options?.durability ?? "default"; - if (durability !== "default" && durability !== "strict" && durability !== "relaxed") { - throw new TypeError( - // based on Firefox's error message - `'${durability}' (value of 'durability' member of IDBTransactionOptions) is not a valid value for enumeration IDBTransactionDurability` - ); - } - const tx = new FDBTransaction_default(storeNames, mode, durability, this); - this._rawDatabase.transactions.push(tx); - this._rawDatabase.processTransactions(); - return tx; - } - close() { - closeConnection_default(this); - } - get [Symbol.toStringTag]() { - return "IDBDatabase"; - } -}; -var FDBDatabase_default = FDBDatabase; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBOpenDBRequest.js -var FDBOpenDBRequest = class extends FDBRequest_default { - onupgradeneeded = null; - onblocked = null; - get [Symbol.toStringTag]() { - return "IDBOpenDBRequest"; - } -}; -var FDBOpenDBRequest_default = FDBOpenDBRequest; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBVersionChangeEvent.js -var FDBVersionChangeEvent = class extends FakeEvent_default { - constructor(type, parameters = {}) { - super(type); - this.newVersion = parameters.newVersion !== void 0 ? parameters.newVersion : null; - this.oldVersion = parameters.oldVersion !== void 0 ? parameters.oldVersion : 0; - } - get [Symbol.toStringTag]() { - return "IDBVersionChangeEvent"; - } -}; -var FDBVersionChangeEvent_default = FDBVersionChangeEvent; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/intersection.js -function intersection(set1, set2) { - if ("intersection" in set1) { - return set1.intersection(set2); - } - return new Set([...set1].filter((item) => set2.has(item))); -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/Database.js -var Database = class { - transactions = []; - rawObjectStores = /* @__PURE__ */ new Map(); - connections = []; - constructor(name, version) { - this.name = name; - this.version = version; - this.processTransactions = this.processTransactions.bind(this); - } - processTransactions() { - queueTask(() => { - const running = this.transactions.filter((transaction) => transaction._started && transaction._state !== "finished"); - const waiting = this.transactions.filter((transaction) => !transaction._started && transaction._state !== "finished"); - const next = waiting.find((transaction, i) => { - const anyRunning = running.some((other) => !(transaction.mode === "readonly" && other.mode === "readonly") && intersection(other._scope, transaction._scope).size > 0); - if (anyRunning) { - return false; - } - const anyWaiting = waiting.slice(0, i).some((other) => intersection(other._scope, transaction._scope).size > 0); - return !anyWaiting; - }); - if (next) { - next.addEventListener("complete", this.processTransactions); - next.addEventListener("abort", this.processTransactions); - next._start(); - } - }); - } -}; -var Database_default = Database; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/validateRequiredArguments.js -function validateRequiredArguments(numArguments, expectedNumArguments, methodName) { - if (numArguments < expectedNumArguments) { - throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} required, but only ${arguments.length} passed`); - } -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBFactory.js -var runTaskInConnectionQueue = (connectionQueues, name, task) => { - const queue = connectionQueues.get(name) ?? Promise.resolve(); - connectionQueues.set(name, queue.then(task)); -}; -var waitForOthersClosedDelete = (databases, name, openDatabases, cb) => { - const anyOpen = openDatabases.some((openDatabase2) => { - return !openDatabase2._closed && !openDatabase2._closePending; - }); - if (anyOpen) { - queueTask(() => waitForOthersClosedDelete(databases, name, openDatabases, cb)); - return; - } - databases.delete(name); - cb(null); -}; -var deleteDatabase = (databases, connectionQueues, name, request, cb) => { - const deleteDBTask = () => { - return new Promise((resolve) => { - const db2 = databases.get(name); - const oldVersion = db2 !== void 0 ? db2.version : 0; - const onComplete = (err) => { - try { - if (err) { - cb(err); - } else { - cb(null, oldVersion); - } - } finally { - resolve(); - } - }; - try { - const db3 = databases.get(name); - if (db3 === void 0) { - onComplete(null); - return; - } - const openConnections = db3.connections.filter((connection) => { - return !connection._closed; - }); - for (const openDatabase2 of openConnections) { - if (!openDatabase2._closePending) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("versionchange", { - newVersion: null, - oldVersion: db3.version - }); - openDatabase2.dispatchEvent(event); - }); - } - } - queueTask(() => { - const anyOpen = openConnections.some((openDatabase3) => { - return !openDatabase3._closed && !openDatabase3._closePending; - }); - if (anyOpen) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("blocked", { - newVersion: null, - oldVersion: db3.version - }); - request.dispatchEvent(event); - }); - } - waitForOthersClosedDelete(databases, name, openConnections, onComplete); - }); - } catch (err) { - onComplete(err); - } - }); - }; - runTaskInConnectionQueue(connectionQueues, name, deleteDBTask); -}; -var runVersionchangeTransaction = (connection, version, request, cb) => { - connection._runningVersionchangeTransaction = true; - const oldVersion = connection._oldVersion = connection.version; - const openConnections = connection._rawDatabase.connections.filter((otherDatabase) => { - return connection !== otherDatabase; - }); - for (const openDatabase2 of openConnections) { - if (!openDatabase2._closed && !openDatabase2._closePending) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("versionchange", { - newVersion: version, - oldVersion - }); - openDatabase2.dispatchEvent(event); - }); - } - } - queueTask(() => { - const anyOpen = openConnections.some((openDatabase3) => { - return !openDatabase3._closed && !openDatabase3._closePending; - }); - if (anyOpen) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("blocked", { - newVersion: version, - oldVersion - }); - request.dispatchEvent(event); - }); - } - const waitForOthersClosed = () => { - const anyOpen2 = openConnections.some((openDatabase2) => { - return !openDatabase2._closed && !openDatabase2._closePending; - }); - if (anyOpen2) { - queueTask(waitForOthersClosed); - return; - } - connection._rawDatabase.version = version; - connection.version = version; - const transaction = connection.transaction(Array.from(connection.objectStoreNames), "versionchange"); - transaction._openRequest = request; - request.result = connection; - request.readyState = "done"; - request.transaction = transaction; - transaction._rollbackLog.push(() => { - connection._rawDatabase.version = oldVersion; - connection.version = oldVersion; - }); - transaction._state = "active"; - const event = new FDBVersionChangeEvent_default("upgradeneeded", { - newVersion: version, - oldVersion - }); - let didThrow = false; - try { - request.dispatchEvent(event); - } catch (_err) { - didThrow = true; - } - const concludeUpgrade = () => { - if (transaction._state === "active") { - transaction._state = "inactive"; - if (didThrow) { - transaction._abort("AbortError"); - } - } - }; - if (didThrow) { - concludeUpgrade(); - } else { - queueTask(concludeUpgrade); - } - transaction._prioritizedListeners.set("error", () => { - connection._runningVersionchangeTransaction = false; - connection._oldVersion = void 0; - }); - transaction._prioritizedListeners.set("abort", () => { - connection._runningVersionchangeTransaction = false; - connection._oldVersion = void 0; - queueTask(() => { - request.transaction = null; - cb(new AbortError()); - }); - }); - transaction._prioritizedListeners.set("complete", () => { - connection._runningVersionchangeTransaction = false; - connection._oldVersion = void 0; - queueTask(() => { - request.transaction = null; - if (connection._closePending) { - cb(new AbortError()); - } else { - cb(null); - } - }); - }); - }; - waitForOthersClosed(); - }); -}; -var openDatabase = (databases, connectionQueues, name, version, request, cb) => { - const openDBTask = () => { - return new Promise((resolve) => { - const onComplete = (err) => { - try { - if (err) { - cb(err); - } else { - cb(null, connection); - } - } finally { - resolve(); - } - }; - let db2 = databases.get(name); - if (db2 === void 0) { - db2 = new Database_default(name, 0); - databases.set(name, db2); - } - if (version === void 0) { - version = db2.version !== 0 ? db2.version : 1; - } - if (db2.version > version) { - return onComplete(new VersionError()); - } - const connection = new FDBDatabase_default(db2); - if (db2.version < version) { - runVersionchangeTransaction(connection, version, request, (err) => { - onComplete(err); - }); - } else { - onComplete(null); - } - }); - }; - runTaskInConnectionQueue(connectionQueues, name, openDBTask); -}; -var FDBFactory = class { - _databases = /* @__PURE__ */ new Map(); - // https://w3c.github.io/IndexedDB/#connection-queue - _connectionQueues = /* @__PURE__ */ new Map(); - // promise chain as lightweight FIFO task queue - // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp - cmp(first, second) { - validateRequiredArguments(arguments.length, 2, "IDBFactory.cmp"); - return cmp_default(first, second); - } - // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase - deleteDatabase(name) { - validateRequiredArguments(arguments.length, 1, "IDBFactory.deleteDatabase"); - const request = new FDBOpenDBRequest_default(); - request.source = null; - queueTask(() => { - deleteDatabase(this._databases, this._connectionQueues, name, request, (err, oldVersion) => { - if (err) { - request.error = new DOMException(err.message, err.name); - request.readyState = "done"; - const event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - event.eventPath = []; - request.dispatchEvent(event); - return; - } - request.result = void 0; - request.readyState = "done"; - const event2 = new FDBVersionChangeEvent_default("success", { - newVersion: null, - oldVersion - }); - request.dispatchEvent(event2); - }); - }); - return request; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version - open(name, version) { - validateRequiredArguments(arguments.length, 1, "IDBFactory.open"); - if (arguments.length > 1 && version !== void 0) { - version = enforceRange_default(version, "MAX_SAFE_INTEGER"); - } - if (version === 0) { - throw new TypeError("Database version cannot be 0"); - } - const request = new FDBOpenDBRequest_default(); - request.source = null; - queueTask(() => { - openDatabase(this._databases, this._connectionQueues, name, version, request, (err, connection) => { - if (err) { - request.result = void 0; - request.readyState = "done"; - request.error = new DOMException(err.message, err.name); - const event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - event.eventPath = []; - request.dispatchEvent(event); - return; - } - request.result = connection; - request.readyState = "done"; - const event2 = new FakeEvent_default("success"); - event2.eventPath = []; - request.dispatchEvent(event2); - }); - }); - return request; - } - // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases - databases() { - return Promise.resolve(Array.from(this._databases.entries(), ([name, database]) => { - const activeVersionChangeConnection = database.connections.find((connection) => connection._runningVersionchangeTransaction); - const version = activeVersionChangeConnection ? activeVersionChangeConnection._oldVersion : database.version; - return { - name, - version - }; - }).filter(({ - version - }) => { - return version > 0; - })); - } - get [Symbol.toStringTag]() { - return "IDBFactory"; - } -}; -var FDBFactory_default = FDBFactory; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/fakeIndexedDB.js -var fakeIndexedDB = new FDBFactory_default(); -var fakeIndexedDB_default = fakeIndexedDB; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/auto/index.mjs -var globalVar = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" ? self : typeof global !== "undefined" ? global : Function("return this;")(); -var createPropertyDescriptor = (value) => { - return { - value, - enumerable: false, - configurable: true, - writable: true - }; -}; -Object.defineProperties(globalVar, { - indexedDB: createPropertyDescriptor(fakeIndexedDB_default), - IDBCursor: createPropertyDescriptor(FDBCursor_default), - IDBCursorWithValue: createPropertyDescriptor(FDBCursorWithValue_default), - IDBDatabase: createPropertyDescriptor(FDBDatabase_default), - IDBFactory: createPropertyDescriptor(FDBFactory_default), - IDBIndex: createPropertyDescriptor(FDBIndex_default), - IDBKeyRange: createPropertyDescriptor(FDBKeyRange_default), - IDBObjectStore: createPropertyDescriptor(FDBObjectStore_default), - IDBOpenDBRequest: createPropertyDescriptor(FDBOpenDBRequest_default), - IDBRecord: createPropertyDescriptor(FDBRecord_default), - IDBRequest: createPropertyDescriptor(FDBRequest_default), - IDBTransaction: createPropertyDescriptor(FDBTransaction_default), - IDBVersionChangeEvent: createPropertyDescriptor(FDBVersionChangeEvent_default) -}); - -// intern-log/repro/sync-repro.ts -init_schema(); -async function main() { - bindDatabase(new WorklogDB("repro_db")); - const mod = await Promise.resolve().then(() => (init_schema(), schema_exports)); - const db2 = mod.db; - await db2.project.bulkAdd([{ name: "P1", archived: 0, created_at: "2025-01-01T00:00:00" }]); - await db2.work_log.bulkAdd([{ date: "2025-01-02", created_at: "2025-01-02T00:00:00" }]); - await db2.setting.bulkAdd([ - { key: "work_start", value: "09:00" }, - { key: "sync_base_url", value: "http://127.0.0.1:3780" } - ]); - await db2.attendance.bulkAdd([{ date: "2025-01-02", clock_in_at: "2025-01-02T09:00:00", clock_out_at: "2025-01-02T18:00:00", kind: "normal", note: null, created_at: "2025-01-02T09:00:00" }]); - await db2.table("transaction").bulkAdd([{ type: "expense", category: "\u9910\u996E", amount: 2500, date: "2025-01-02", note: "lunch", reimbursable: 1, reimbursed: 0, created_at: "2025-01-02T12:00:00" }]); - const engine = await Promise.resolve().then(() => (init_engine(), engine_exports)); - engine.enableRealtimeSync(); - await fetch("http://127.0.0.1:3780/api/auth/register", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ username: "rt", password: "rt123456" }) - }).catch(() => { - }); - const r1 = await engine.runSync({ baseUrl: "http://127.0.0.1:3780", username: "rt", password: "rt123456" }); - console.log("SYNC1 OK:", JSON.stringify(r1)); - await db2.table("log_item").add({ - work_log_id: 1, - content: "\u5B9E\u65F6\u6D4B\u8BD5\u6761\u76EE", - project_id: null, - category: "dev", - minutes: null, - is_milestone: 0, - needs_followup: 0, - takeaway: null, - remark: null, - sort_order: 0, - created_at: "2025-01-02T10:00:00" - }); - await new Promise((r) => setTimeout(r, 4500)); - console.log("REALTIME PATH DONE"); - const r2 = await engine.runSync({ baseUrl: "http://127.0.0.1:3780", username: "rt", password: "rt123456" }); - console.log("SYNC2 OK:", JSON.stringify(r2)); - process.exit(0); -} -main().catch((e) => { - console.error("FAILED:", e && (e.stack || e.message) || e); - process.exit(1); -}); diff --git a/intern-log/repro/two-device.cjs b/intern-log/repro/two-device.cjs deleted file mode 100644 index eb2d046..0000000 --- a/intern-log/repro/two-device.cjs +++ /dev/null @@ -1,68371 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/dist/dexie.js -var require_dexie = __commonJS({ - "intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/dist/dexie.js"(exports2, module2) { - (function(global2, factory) { - typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.Dexie = factory()); - })(exports2, function() { - "use strict"; - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { - d2.__proto__ = b2; - } || function(d2, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; - }; - return extendStatics(d, b); - }; - function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - var __assign = function() { - __assign = Object.assign || function __assign2(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - } - typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; - }; - var _global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; - var keys = Object.keys; - var isArray = Array.isArray; - if (typeof Promise !== "undefined" && !_global.Promise) { - _global.Promise = Promise; - } - function extend(obj, extension) { - if (typeof extension !== "object") - return obj; - keys(extension).forEach(function(key) { - obj[key] = extension[key]; - }); - return obj; - } - var getProto = Object.getPrototypeOf; - var _hasOwn = {}.hasOwnProperty; - function hasOwn(obj, prop) { - return _hasOwn.call(obj, prop); - } - function props(proto, extension) { - if (typeof extension === "function") - extension = extension(getProto(proto)); - (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(function(key) { - setProp(proto, key, extension[key]); - }); - } - var defineProperty = Object.defineProperty; - function setProp(obj, prop, functionOrGetSet, options) { - defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === "function" ? { - get: functionOrGetSet.get, - set: functionOrGetSet.set, - configurable: true - } : { value: functionOrGetSet, configurable: true, writable: true }, options)); - } - function derive(Child) { - return { - from: function(Parent) { - Child.prototype = Object.create(Parent.prototype); - setProp(Child.prototype, "constructor", Child); - return { - extend: props.bind(null, Child.prototype) - }; - } - }; - } - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - function getPropertyDescriptor(obj, prop) { - var pd = getOwnPropertyDescriptor(obj, prop); - var proto; - return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); - } - var _slice = [].slice; - function slice(args, start, end) { - return _slice.call(args, start, end); - } - function override(origFunc, overridedFactory) { - return overridedFactory(origFunc); - } - function assert(b) { - if (!b) - throw new Error("Assertion Failed"); - } - function asap$1(fn) { - if (_global.setImmediate) - setImmediate(fn); - else - setTimeout(fn, 0); - } - function arrayToObject(array, extractor) { - return array.reduce(function(result, item, i) { - var nameAndValue = extractor(item, i); - if (nameAndValue) - result[nameAndValue[0]] = nameAndValue[1]; - return result; - }, {}); - } - function getByKeyPath(obj, keyPath) { - if (typeof keyPath === "string" && hasOwn(obj, keyPath)) - return obj[keyPath]; - if (!keyPath) - return obj; - if (typeof keyPath !== "string") { - var rv = []; - for (var i = 0, l = keyPath.length; i < l; ++i) { - var val = getByKeyPath(obj, keyPath[i]); - rv.push(val); - } - return rv; - } - var period = keyPath.indexOf("."); - if (period !== -1) { - var innerObj = obj[keyPath.substr(0, period)]; - return innerObj == null ? void 0 : getByKeyPath(innerObj, keyPath.substr(period + 1)); - } - return void 0; - } - function setByKeyPath(obj, keyPath, value) { - if (!obj || keyPath === void 0) - return; - if ("isFrozen" in Object && Object.isFrozen(obj)) - return; - if (typeof keyPath !== "string" && "length" in keyPath) { - assert(typeof value !== "string" && "length" in value); - for (var i = 0, l = keyPath.length; i < l; ++i) { - setByKeyPath(obj, keyPath[i], value[i]); - } - } else { - var period = keyPath.indexOf("."); - if (period !== -1) { - var currentKeyPath = keyPath.substr(0, period); - var remainingKeyPath = keyPath.substr(period + 1); - if (remainingKeyPath === "") - if (value === void 0) { - if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) - obj.splice(currentKeyPath, 1); - else - delete obj[currentKeyPath]; - } else - obj[currentKeyPath] = value; - else { - var innerObj = obj[currentKeyPath]; - if (!innerObj || !hasOwn(obj, currentKeyPath)) { - if (value === void 0) - return; - innerObj = obj[currentKeyPath] = {}; - } - setByKeyPath(innerObj, remainingKeyPath, value); - } - } else { - if (value === void 0) { - if (isArray(obj) && !isNaN(parseInt(keyPath))) - obj.splice(keyPath, 1); - else - delete obj[keyPath]; - } else - obj[keyPath] = value; - } - } - } - function delByKeyPath(obj, keyPath) { - if (typeof keyPath === "string") - setByKeyPath(obj, keyPath, void 0); - else if ("length" in keyPath) - [].map.call(keyPath, function(kp) { - setByKeyPath(obj, kp, void 0); - }); - } - function shallowClone(obj) { - var rv = {}; - for (var m in obj) { - if (hasOwn(obj, m)) - rv[m] = obj[m]; - } - return rv; - } - var concat = [].concat; - function flatten(a) { - return concat.apply([], a); - } - var intrinsicTypeNames = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(flatten([8, 16, 32, 64].map(function(num) { - return ["Int", "Uint", "Float"].map(function(t) { - return t + num + "Array"; - }); - }))).filter(function(t) { - return _global[t]; - }); - var intrinsicTypes = new Set(intrinsicTypeNames.map(function(t) { - return _global[t]; - })); - function cloneSimpleObjectTree(o) { - var rv = {}; - for (var k in o) - if (hasOwn(o, k)) { - var v = o[k]; - rv[k] = !v || typeof v !== "object" || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v); - } - return rv; - } - var circularRefs = null; - function deepClone(any) { - circularRefs = /* @__PURE__ */ new WeakMap(); - var rv = innerDeepClone(any); - circularRefs = null; - return rv; - } - function innerDeepClone(x) { - if (!x || typeof x !== "object") - return x; - var rv = circularRefs.get(x); - if (rv) - return rv; - if (isArray(x)) { - rv = []; - circularRefs.set(x, rv); - for (var i = 0, l = x.length; i < l; ++i) { - rv.push(innerDeepClone(x[i])); - } - } else if (intrinsicTypes.has(x.constructor)) { - rv = x; - } else { - var proto = getProto(x); - rv = proto === Object.prototype ? {} : Object.create(proto); - circularRefs.set(x, rv); - for (var prop in x) { - if (hasOwn(x, prop)) { - rv[prop] = innerDeepClone(x[prop]); - } - } - } - return rv; - } - var toString = {}.toString; - function toStringTag(o) { - return toString.call(o).slice(8, -1); - } - var iteratorSymbol = typeof Symbol !== "undefined" ? Symbol.iterator : "@@iterator"; - var getIteratorOf = typeof iteratorSymbol === "symbol" ? function(x) { - var i; - return x != null && (i = x[iteratorSymbol]) && i.apply(x); - } : function() { - return null; - }; - function delArrayItem(a, x) { - var i = a.indexOf(x); - if (i >= 0) - a.splice(i, 1); - return i >= 0; - } - var NO_CHAR_ARRAY = {}; - function getArrayOf(arrayLike) { - var i, a, x, it; - if (arguments.length === 1) { - if (isArray(arrayLike)) - return arrayLike.slice(); - if (this === NO_CHAR_ARRAY && typeof arrayLike === "string") - return [arrayLike]; - if (it = getIteratorOf(arrayLike)) { - a = []; - while (x = it.next(), !x.done) - a.push(x.value); - return a; - } - if (arrayLike == null) - return [arrayLike]; - i = arrayLike.length; - if (typeof i === "number") { - a = new Array(i); - while (i--) - a[i] = arrayLike[i]; - return a; - } - return [arrayLike]; - } - i = arguments.length; - a = new Array(i); - while (i--) - a[i] = arguments[i]; - return a; - } - var isAsyncFunction = typeof Symbol !== "undefined" ? function(fn) { - return fn[Symbol.toStringTag] === "AsyncFunction"; - } : function() { - return false; - }; - var dexieErrorNames = [ - "Modify", - "Bulk", - "OpenFailed", - "VersionChange", - "Schema", - "Upgrade", - "InvalidTable", - "MissingAPI", - "NoSuchDatabase", - "InvalidArgument", - "SubTransaction", - "Unsupported", - "Internal", - "DatabaseClosed", - "PrematureCommit", - "ForeignAwait" - ]; - var idbDomErrorNames = [ - "Unknown", - "Constraint", - "Data", - "TransactionInactive", - "ReadOnly", - "Version", - "NotFound", - "InvalidState", - "InvalidAccess", - "Abort", - "Timeout", - "QuotaExceeded", - "Syntax", - "DataClone" - ]; - var errorList = dexieErrorNames.concat(idbDomErrorNames); - var defaultTexts = { - VersionChanged: "Database version changed by other database connection", - DatabaseClosed: "Database has been closed", - Abort: "Transaction aborted", - TransactionInactive: "Transaction has already completed or failed", - MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" - }; - function DexieError(name, msg) { - this.name = name; - this.message = msg; - } - derive(DexieError).from(Error).extend({ - toString: function() { - return this.name + ": " + this.message; - } - }); - function getMultiErrorMessage(msg, failures) { - return msg + ". Errors: " + Object.keys(failures).map(function(key) { - return failures[key].toString(); - }).filter(function(v, i, s) { - return s.indexOf(v) === i; - }).join("\n"); - } - function ModifyError(msg, failures, successCount, failedKeys) { - this.failures = failures; - this.failedKeys = failedKeys; - this.successCount = successCount; - this.message = getMultiErrorMessage(msg, failures); - } - derive(ModifyError).from(DexieError); - function BulkError(msg, failures) { - this.name = "BulkError"; - this.failures = Object.keys(failures).map(function(pos) { - return failures[pos]; - }); - this.failuresByPos = failures; - this.message = getMultiErrorMessage(msg, this.failures); - } - derive(BulkError).from(DexieError); - var errnames = errorList.reduce(function(obj, name) { - return obj[name] = name + "Error", obj; - }, {}); - var BaseException = DexieError; - var exceptions = errorList.reduce(function(obj, name) { - var fullName = name + "Error"; - function DexieError2(msgOrInner, inner) { - this.name = fullName; - if (!msgOrInner) { - this.message = defaultTexts[name] || fullName; - this.inner = null; - } else if (typeof msgOrInner === "string") { - this.message = "".concat(msgOrInner).concat(!inner ? "" : "\n " + inner); - this.inner = inner || null; - } else if (typeof msgOrInner === "object") { - this.message = "".concat(msgOrInner.name, " ").concat(msgOrInner.message); - this.inner = msgOrInner; - } - } - derive(DexieError2).from(BaseException); - obj[name] = DexieError2; - return obj; - }, {}); - exceptions.Syntax = SyntaxError; - exceptions.Type = TypeError; - exceptions.Range = RangeError; - var exceptionMap = idbDomErrorNames.reduce(function(obj, name) { - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - function mapError(domError, message) { - if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) - return domError; - var rv = new exceptionMap[domError.name](message || domError.message, domError); - if ("stack" in domError) { - setProp(rv, "stack", { - get: function() { - return this.inner.stack; - } - }); - } - return rv; - } - var fullNameExceptions = errorList.reduce(function(obj, name) { - if (["Syntax", "Type", "Range"].indexOf(name) === -1) - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - fullNameExceptions.ModifyError = ModifyError; - fullNameExceptions.DexieError = DexieError; - fullNameExceptions.BulkError = BulkError; - function nop() { - } - function mirror(val) { - return val; - } - function pureFunctionChain(f1, f2) { - if (f1 == null || f1 === mirror) - return f2; - return function(val) { - return f2(f1(val)); - }; - } - function callBoth(on1, on2) { - return function() { - on1.apply(this, arguments); - on2.apply(this, arguments); - }; - } - function hookCreatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - var res = f1.apply(this, arguments); - if (res !== void 0) - arguments[0] = res; - var onsuccess = this.onsuccess, onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res2 !== void 0 ? res2 : res; - }; - } - function hookDeletingChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - f1.apply(this, arguments); - var onsuccess = this.onsuccess, onerror = this.onerror; - this.onsuccess = this.onerror = null; - f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - }; - } - function hookUpdatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - var res = f1.apply(this, arguments); - var modifications = arguments[0]; - extend(modifications, res); - var onsuccess = this.onsuccess, onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res === void 0 ? res2 === void 0 ? void 0 : res2 : extend(res, res2); - }; - } - function reverseStoppableEventChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - if (f2.apply(this, arguments) === false) - return false; - return f1.apply(this, arguments); - }; - } - function promisableChain(f1, f2) { - if (f1 === nop) - return f2; - return function() { - var res = f1.apply(this, arguments); - if (res && typeof res.then === "function") { - var thiz = this, i = arguments.length, args = new Array(i); - while (i--) - args[i] = arguments[i]; - return res.then(function() { - return f2.apply(thiz, args); - }); - } - return f2.apply(this, arguments); - }; - } - var debug = typeof location !== "undefined" && /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); - function setDebug(value, filter) { - debug = value; - } - var INTERNAL = {}; - var ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === "undefined" ? [] : function() { - var globalP = Promise.resolve(); - if (typeof crypto === "undefined" || !crypto.subtle) - return [globalP, getProto(globalP), globalP]; - var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); - return [nativeP, getProto(nativeP), globalP]; - }(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; - var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; - var patchGlobalPromise = !!resolvedGlobalPromise; - function schedulePhysicalTick() { - queueMicrotask(physicalTick); - } - var asap = function(callback, args) { - microtickQueue.push([callback, args]); - if (needsNewPhysicalTick) { - schedulePhysicalTick(); - needsNewPhysicalTick = false; - } - }; - var isOutsideMicroTick = true, needsNewPhysicalTick = true, unhandledErrors = [], rejectingErrors = [], rejectionMapper = mirror; - var globalPSD = { - id: "global", - global: true, - ref: 0, - unhandleds: [], - onunhandled: nop, - pgp: false, - env: {}, - finalize: nop - }; - var PSD = globalPSD; - var microtickQueue = []; - var numScheduledCalls = 0; - var tickFinalizers = []; - function DexiePromise(fn) { - if (typeof this !== "object") - throw new TypeError("Promises must be constructed via new"); - this._listeners = []; - this._lib = false; - var psd = this._PSD = PSD; - if (typeof fn !== "function") { - if (fn !== INTERNAL) - throw new TypeError("Not a function"); - this._state = arguments[1]; - this._value = arguments[2]; - if (this._state === false) - handleRejection(this, this._value); - return; - } - this._state = null; - this._value = null; - ++psd.ref; - executePromiseTask(this, fn); - } - var thenProp = { - get: function() { - var psd = PSD, microTaskId = totalEchoes; - function then(onFulfilled, onRejected) { - var _this = this; - var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); - var cleanup = possibleAwait && !decrementExpectedAwaits(); - var rv = new DexiePromise(function(resolve, reject) { - propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); - }); - if (this._consoleTask) - rv._consoleTask = this._consoleTask; - return rv; - } - then.prototype = INTERNAL; - return then; - }, - set: function(value) { - setProp(this, "then", value && value.prototype === INTERNAL ? thenProp : { - get: function() { - return value; - }, - set: thenProp.set - }); - } - }; - props(DexiePromise.prototype, { - then: thenProp, - _then: function(onFulfilled, onRejected) { - propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); - }, - catch: function(onRejected) { - if (arguments.length === 1) - return this.then(null, onRejected); - var type2 = arguments[0], handler = arguments[1]; - return typeof type2 === "function" ? this.then(null, function(err) { - return err instanceof type2 ? handler(err) : PromiseReject(err); - }) : this.then(null, function(err) { - return err && err.name === type2 ? handler(err) : PromiseReject(err); - }); - }, - finally: function(onFinally) { - return this.then(function(value) { - return DexiePromise.resolve(onFinally()).then(function() { - return value; - }); - }, function(err) { - return DexiePromise.resolve(onFinally()).then(function() { - return PromiseReject(err); - }); - }); - }, - timeout: function(ms, msg) { - var _this = this; - return ms < Infinity ? new DexiePromise(function(resolve, reject) { - var handle = setTimeout(function() { - return reject(new exceptions.Timeout(msg)); - }, ms); - _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); - }) : this; - } - }); - if (typeof Symbol !== "undefined" && Symbol.toStringTag) - setProp(DexiePromise.prototype, Symbol.toStringTag, "Dexie.Promise"); - globalPSD.env = snapShot(); - function Listener(onFulfilled, onRejected, resolve, reject, zone) { - this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null; - this.onRejected = typeof onRejected === "function" ? onRejected : null; - this.resolve = resolve; - this.reject = reject; - this.psd = zone; - } - props(DexiePromise, { - all: function() { - var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve, reject) { - if (values.length === 0) - resolve([]); - var remaining = values.length; - values.forEach(function(a, i) { - return DexiePromise.resolve(a).then(function(x) { - values[i] = x; - if (!--remaining) - resolve(values); - }, reject); - }); - }); - }, - resolve: function(value) { - if (value instanceof DexiePromise) - return value; - if (value && typeof value.then === "function") - return new DexiePromise(function(resolve, reject) { - value.then(resolve, reject); - }); - var rv = new DexiePromise(INTERNAL, true, value); - return rv; - }, - reject: PromiseReject, - race: function() { - var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve, reject) { - values.map(function(value) { - return DexiePromise.resolve(value).then(resolve, reject); - }); - }); - }, - PSD: { - get: function() { - return PSD; - }, - set: function(value) { - return PSD = value; - } - }, - totalEchoes: { get: function() { - return totalEchoes; - } }, - newPSD: newScope, - usePSD, - scheduler: { - get: function() { - return asap; - }, - set: function(value) { - asap = value; - } - }, - rejectionMapper: { - get: function() { - return rejectionMapper; - }, - set: function(value) { - rejectionMapper = value; - } - }, - follow: function(fn, zoneProps) { - return new DexiePromise(function(resolve, reject) { - return newScope(function(resolve2, reject2) { - var psd = PSD; - psd.unhandleds = []; - psd.onunhandled = reject2; - psd.finalize = callBoth(function() { - var _this = this; - run_at_end_of_this_or_next_physical_tick(function() { - _this.unhandleds.length === 0 ? resolve2() : reject2(_this.unhandleds[0]); - }); - }, psd.finalize); - fn(); - }, zoneProps, resolve, reject); - }); - } - }); - if (NativePromise) { - if (NativePromise.allSettled) - setProp(DexiePromise, "allSettled", function() { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve) { - if (possiblePromises.length === 0) - resolve([]); - var remaining = possiblePromises.length; - var results = new Array(remaining); - possiblePromises.forEach(function(p, i) { - return DexiePromise.resolve(p).then(function(value) { - return results[i] = { status: "fulfilled", value }; - }, function(reason) { - return results[i] = { status: "rejected", reason }; - }).then(function() { - return --remaining || resolve(results); - }); - }); - }); - }); - if (NativePromise.any && typeof AggregateError !== "undefined") - setProp(DexiePromise, "any", function() { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function(resolve, reject) { - if (possiblePromises.length === 0) - reject(new AggregateError([])); - var remaining = possiblePromises.length; - var failures = new Array(remaining); - possiblePromises.forEach(function(p, i) { - return DexiePromise.resolve(p).then(function(value) { - return resolve(value); - }, function(failure) { - failures[i] = failure; - if (!--remaining) - reject(new AggregateError(failures)); - }); - }); - }); - }); - if (NativePromise.withResolvers) - DexiePromise.withResolvers = NativePromise.withResolvers; - } - function executePromiseTask(promise, fn) { - try { - fn(function(value) { - if (promise._state !== null) - return; - if (value === promise) - throw new TypeError("A promise cannot be resolved with itself."); - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - if (value && typeof value.then === "function") { - executePromiseTask(promise, function(resolve, reject) { - value instanceof DexiePromise ? value._then(resolve, reject) : value.then(resolve, reject); - }); - } else { - promise._state = true; - promise._value = value; - propagateAllListeners(promise); - } - if (shouldExecuteTick) - endMicroTickScope(); - }, handleRejection.bind(null, promise)); - } catch (ex) { - handleRejection(promise, ex); - } - } - function handleRejection(promise, reason) { - rejectingErrors.push(reason); - if (promise._state !== null) - return; - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - reason = rejectionMapper(reason); - promise._state = false; - promise._value = reason; - addPossiblyUnhandledError(promise); - propagateAllListeners(promise); - if (shouldExecuteTick) - endMicroTickScope(); - } - function propagateAllListeners(promise) { - var listeners = promise._listeners; - promise._listeners = []; - for (var i = 0, len = listeners.length; i < len; ++i) { - propagateToListener(promise, listeners[i]); - } - var psd = promise._PSD; - --psd.ref || psd.finalize(); - if (numScheduledCalls === 0) { - ++numScheduledCalls; - asap(function() { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - } - function propagateToListener(promise, listener) { - if (promise._state === null) { - promise._listeners.push(listener); - return; - } - var cb = promise._state ? listener.onFulfilled : listener.onRejected; - if (cb === null) { - return (promise._state ? listener.resolve : listener.reject)(promise._value); - } - ++listener.psd.ref; - ++numScheduledCalls; - asap(callListener, [cb, promise, listener]); - } - function callListener(cb, promise, listener) { - try { - var ret, value = promise._value; - if (!promise._state && rejectingErrors.length) - rejectingErrors = []; - ret = debug && promise._consoleTask ? promise._consoleTask.run(function() { - return cb(value); - }) : cb(value); - if (!promise._state && rejectingErrors.indexOf(value) === -1) { - markErrorAsHandled(promise); - } - listener.resolve(ret); - } catch (e) { - listener.reject(e); - } finally { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - --listener.psd.ref || listener.psd.finalize(); - } - } - function physicalTick() { - usePSD(globalPSD, function() { - beginMicroTickScope() && endMicroTickScope(); - }); - } - function beginMicroTickScope() { - var wasRootExec = isOutsideMicroTick; - isOutsideMicroTick = false; - needsNewPhysicalTick = false; - return wasRootExec; - } - function endMicroTickScope() { - var callbacks, i, l; - do { - while (microtickQueue.length > 0) { - callbacks = microtickQueue; - microtickQueue = []; - l = callbacks.length; - for (i = 0; i < l; ++i) { - var item = callbacks[i]; - item[0].apply(null, item[1]); - } - } - } while (microtickQueue.length > 0); - isOutsideMicroTick = true; - needsNewPhysicalTick = true; - } - function finalizePhysicalTick() { - var unhandledErrs = unhandledErrors; - unhandledErrors = []; - unhandledErrs.forEach(function(p) { - p._PSD.onunhandled.call(null, p._value, p); - }); - var finalizers = tickFinalizers.slice(0); - var i = finalizers.length; - while (i) - finalizers[--i](); - } - function run_at_end_of_this_or_next_physical_tick(fn) { - function finalizer() { - fn(); - tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); - } - tickFinalizers.push(finalizer); - ++numScheduledCalls; - asap(function() { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - function addPossiblyUnhandledError(promise) { - if (!unhandledErrors.some(function(p) { - return p._value === promise._value; - })) - unhandledErrors.push(promise); - } - function markErrorAsHandled(promise) { - var i = unhandledErrors.length; - while (i) - if (unhandledErrors[--i]._value === promise._value) { - unhandledErrors.splice(i, 1); - return; - } - } - function PromiseReject(reason) { - return new DexiePromise(INTERNAL, false, reason); - } - function wrap(fn, errorCatcher) { - var psd = PSD; - return function() { - var wasRootExec = beginMicroTickScope(), outerScope = PSD; - try { - switchToZone(psd, true); - return fn.apply(this, arguments); - } catch (e) { - errorCatcher && errorCatcher(e); - } finally { - switchToZone(outerScope, false); - if (wasRootExec) - endMicroTickScope(); - } - }; - } - var task = { awaits: 0, echoes: 0, id: 0 }; - var taskCounter = 0; - var zoneStack = []; - var zoneEchoes = 0; - var totalEchoes = 0; - var zone_id_counter = 0; - function newScope(fn, props2, a1, a2) { - var parent = PSD, psd = Object.create(parent); - psd.parent = parent; - psd.ref = 0; - psd.global = false; - psd.id = ++zone_id_counter; - globalPSD.env; - psd.env = patchGlobalPromise ? { - Promise: DexiePromise, - PromiseProp: { - value: DexiePromise, - configurable: true, - writable: true - }, - all: DexiePromise.all, - race: DexiePromise.race, - allSettled: DexiePromise.allSettled, - any: DexiePromise.any, - resolve: DexiePromise.resolve, - reject: DexiePromise.reject - } : {}; - if (props2) - extend(psd, props2); - ++parent.ref; - psd.finalize = function() { - --this.parent.ref || this.parent.finalize(); - }; - var rv = usePSD(psd, fn, a1, a2); - if (psd.ref === 0) - psd.finalize(); - return rv; - } - function incrementExpectedAwaits() { - if (!task.id) - task.id = ++taskCounter; - ++task.awaits; - task.echoes += ZONE_ECHO_LIMIT; - return task.id; - } - function decrementExpectedAwaits() { - if (!task.awaits) - return false; - if (--task.awaits === 0) - task.id = 0; - task.echoes = task.awaits * ZONE_ECHO_LIMIT; - return true; - } - if (("" + nativePromiseThen).indexOf("[native code]") === -1) { - incrementExpectedAwaits = decrementExpectedAwaits = nop; - } - function onPossibleParallellAsync(possiblePromise) { - if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { - incrementExpectedAwaits(); - return possiblePromise.then(function(x) { - decrementExpectedAwaits(); - return x; - }, function(e) { - decrementExpectedAwaits(); - return rejection(e); - }); - } - return possiblePromise; - } - function zoneEnterEcho(targetZone) { - ++totalEchoes; - if (!task.echoes || --task.echoes === 0) { - task.echoes = task.awaits = task.id = 0; - } - zoneStack.push(PSD); - switchToZone(targetZone, true); - } - function zoneLeaveEcho() { - var zone = zoneStack[zoneStack.length - 1]; - zoneStack.pop(); - switchToZone(zone, false); - } - function switchToZone(targetZone, bEnteringZone) { - var currentZone = PSD; - if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { - queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); - } - if (targetZone === PSD) - return; - PSD = targetZone; - if (currentZone === globalPSD) - globalPSD.env = snapShot(); - if (patchGlobalPromise) { - var GlobalPromise = globalPSD.env.Promise; - var targetEnv = targetZone.env; - if (currentZone.global || targetZone.global) { - Object.defineProperty(_global, "Promise", targetEnv.PromiseProp); - GlobalPromise.all = targetEnv.all; - GlobalPromise.race = targetEnv.race; - GlobalPromise.resolve = targetEnv.resolve; - GlobalPromise.reject = targetEnv.reject; - if (targetEnv.allSettled) - GlobalPromise.allSettled = targetEnv.allSettled; - if (targetEnv.any) - GlobalPromise.any = targetEnv.any; - } - } - } - function snapShot() { - var GlobalPromise = _global.Promise; - return patchGlobalPromise ? { - Promise: GlobalPromise, - PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), - all: GlobalPromise.all, - race: GlobalPromise.race, - allSettled: GlobalPromise.allSettled, - any: GlobalPromise.any, - resolve: GlobalPromise.resolve, - reject: GlobalPromise.reject - } : {}; - } - function usePSD(psd, fn, a1, a2, a3) { - var outerScope = PSD; - try { - switchToZone(psd, true); - return fn(a1, a2, a3); - } finally { - switchToZone(outerScope, false); - } - } - function nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { - return typeof fn !== "function" ? fn : function() { - var outerZone = PSD; - if (possibleAwait) - incrementExpectedAwaits(); - switchToZone(zone, true); - try { - return fn.apply(this, arguments); - } finally { - switchToZone(outerZone, false); - if (cleanup) - queueMicrotask(decrementExpectedAwaits); - } - }; - } - function execInGlobalContext(cb) { - if (Promise === NativePromise && task.echoes === 0) { - if (zoneEchoes === 0) { - cb(); - } else { - enqueueNativeMicroTask(cb); - } - } else { - setTimeout(cb, 0); - } - } - var rejection = DexiePromise.reject; - function tempTransaction(db2, mode, storeNames, fn) { - if (!db2.idbdb || !db2._state.openComplete && !PSD.letThrough && !db2._vip) { - if (db2._state.openComplete) { - return rejection(new exceptions.DatabaseClosed(db2._state.dbOpenError)); - } - if (!db2._state.isBeingOpened) { - if (!db2._state.autoOpen) - return rejection(new exceptions.DatabaseClosed()); - db2.open().catch(nop); - } - return db2._state.dbReadyPromise.then(function() { - return tempTransaction(db2, mode, storeNames, fn); - }); - } else { - var trans = db2._createTransaction(mode, storeNames, db2._dbSchema); - try { - trans.create(); - db2._state.PR1398_maxLoop = 3; - } catch (ex) { - if (ex.name === errnames.InvalidState && db2.isOpen() && --db2._state.PR1398_maxLoop > 0) { - console.warn("Dexie: Need to reopen db"); - db2.close({ disableAutoOpen: false }); - return db2.open().then(function() { - return tempTransaction(db2, mode, storeNames, fn); - }); - } - return rejection(ex); - } - return trans._promise(mode, function(resolve, reject) { - return newScope(function() { - PSD.trans = trans; - return fn(resolve, reject, trans); - }); - }).then(function(result) { - if (mode === "readwrite") - try { - trans.idbtrans.commit(); - } catch (_a2) { - } - return mode === "readonly" ? result : trans._completion.then(function() { - return result; - }); - }); - } - } - var DEXIE_VERSION = "4.4.6"; - var maxString = String.fromCharCode(65535); - var minKey = -Infinity; - var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; - var STRING_EXPECTED = "String expected."; - var DEFAULT_MAX_CONNECTIONS = 1e3; - var DBNAMES_DB = "__dbnames"; - var READONLY = "readonly"; - var READWRITE = "readwrite"; - function combine(filter1, filter2) { - return filter1 ? filter2 ? function() { - return filter1.apply(this, arguments) && filter2.apply(this, arguments); - } : filter1 : filter2; - } - var AnyRange = { - type: 3, - lower: -Infinity, - lowerOpen: false, - upper: [[]], - upperOpen: false - }; - function workaroundForUndefinedPrimKey(keyPath) { - return typeof keyPath === "string" && !/\./.test(keyPath) ? function(obj) { - if (obj[keyPath] === void 0 && keyPath in obj) { - obj = deepClone(obj); - delete obj[keyPath]; - } - return obj; - } : function(obj) { - return obj; - }; - } - function Entity2() { - throw exceptions.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor."); - } - function cmp3(a, b) { - try { - var ta = type(a); - var tb = type(b); - if (ta !== tb) { - if (ta === "Array") - return 1; - if (tb === "Array") - return -1; - if (ta === "binary") - return 1; - if (tb === "binary") - return -1; - if (ta === "string") - return 1; - if (tb === "string") - return -1; - if (ta === "Date") - return 1; - if (tb !== "Date") - return NaN; - return -1; - } - switch (ta) { - case "number": - case "Date": - case "string": - return a > b ? 1 : a < b ? -1 : 0; - case "binary": { - return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); - } - case "Array": - return compareArrays(a, b); - } - } catch (_a2) { - } - return NaN; - } - function compareArrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - var res = cmp3(a[i], b[i]); - if (res !== 0) - return res; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function compareUint8Arrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - if (a[i] !== b[i]) - return a[i] < b[i] ? -1 : 1; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function type(x) { - var t = typeof x; - if (t !== "object") - return t; - if (ArrayBuffer.isView(x)) - return "binary"; - var tsTag = toStringTag(x); - return tsTag === "ArrayBuffer" ? "binary" : tsTag; - } - function getUint8Array(a) { - if (a instanceof Uint8Array) - return a; - if (ArrayBuffer.isView(a)) - return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); - return new Uint8Array(a); - } - function builtInDeletionTrigger(table, keys2, res) { - var yProps = table.schema.yProps; - if (!yProps) - return res; - if (keys2 && res.numFailures > 0) - keys2 = keys2.filter(function(_, i) { - return !res.failures[i]; - }); - return Promise.all(yProps.map(function(_a2) { - var updatesTable = _a2.updatesTable; - return keys2 ? table.db.table(updatesTable).where("k").anyOf(keys2).delete() : table.db.table(updatesTable).clear(); - })).then(function() { - return res; - }); - } - var PropModification2 = function() { - function PropModification3(spec) { - this["@@propmod"] = spec; - } - PropModification3.prototype.execute = function(value) { - var _a2; - var spec = this["@@propmod"]; - if (spec.add !== void 0) { - var term = spec.add; - if (isArray(term)) { - return __spreadArray(__spreadArray([], isArray(value) ? value : [], true), term, true).sort(); - } - if (typeof term === "number") - return (Number(value) || 0) + term; - if (typeof term === "bigint") { - try { - return BigInt(value) + term; - } catch (_b) { - return BigInt(0) + term; - } - } - throw new TypeError("Invalid term ".concat(term)); - } - if (spec.remove !== void 0) { - var subtrahend_1 = spec.remove; - if (isArray(subtrahend_1)) { - return isArray(value) ? value.filter(function(item) { - return !subtrahend_1.includes(item); - }).sort() : []; - } - if (typeof subtrahend_1 === "number") - return Number(value) - subtrahend_1; - if (typeof subtrahend_1 === "bigint") { - try { - return BigInt(value) - subtrahend_1; - } catch (_c) { - return BigInt(0) - subtrahend_1; - } - } - throw new TypeError("Invalid subtrahend ".concat(subtrahend_1)); - } - var prefixToReplace = (_a2 = spec.replacePrefix) === null || _a2 === void 0 ? void 0 : _a2[0]; - if (prefixToReplace && typeof value === "string" && value.startsWith(prefixToReplace)) { - return spec.replacePrefix[1] + value.substring(prefixToReplace.length); - } - return value; - }; - return PropModification3; - }(); - function applyUpdateSpec(obj, changes) { - var keyPaths = keys(changes); - var numKeys = keyPaths.length; - var anythingModified = false; - for (var i = 0; i < numKeys; ++i) { - var keyPath = keyPaths[i]; - var value = changes[keyPath]; - var origValue = getByKeyPath(obj, keyPath); - if (value instanceof PropModification2) { - setByKeyPath(obj, keyPath, value.execute(origValue)); - anythingModified = true; - } else if (origValue !== value) { - setByKeyPath(obj, keyPath, value); - anythingModified = true; - } - } - return anythingModified; - } - var Table = function() { - function Table2() { - } - Table2.prototype._trans = function(mode, fn, writeLocked) { - var trans = this._tx || PSD.trans; - var tableName = this.name; - var task2 = debug && typeof console !== "undefined" && console.createTask && console.createTask("Dexie: ".concat(mode === "readonly" ? "read" : "write", " ").concat(this.name)); - function checkTableInTransaction(resolve, reject, trans2) { - if (!trans2.schema[tableName]) - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - return fn(trans2.idbtrans, trans2); - } - var wasRootExec = beginMicroTickScope(); - try { - var p = trans && trans.db._novip === this.db._novip ? trans === PSD.trans ? trans._promise(mode, checkTableInTransaction, writeLocked) : newScope(function() { - return trans._promise(mode, checkTableInTransaction, writeLocked); - }, { trans, transless: PSD.transless || PSD }) : tempTransaction(this.db, mode, [this.name], checkTableInTransaction); - if (task2) { - p._consoleTask = task2; - p = p.catch(function(err) { - console.trace(err); - return rejection(err); - }); - } - return p; - } finally { - if (wasRootExec) - endMicroTickScope(); - } - }; - Table2.prototype.get = function(keyOrCrit, cb) { - var _this = this; - if (keyOrCrit && keyOrCrit.constructor === Object) - return this.where(keyOrCrit).first(cb); - if (keyOrCrit == null) - return rejection(new exceptions.Type("Invalid argument to Table.get()")); - return this._trans("readonly", function(trans) { - return _this.core.get({ trans, key: keyOrCrit }).then(function(res) { - return _this.hook.reading.fire(res); - }); - }).then(cb); - }; - Table2.prototype.where = function(indexOrCrit) { - if (typeof indexOrCrit === "string") - return new this.db.WhereClause(this, indexOrCrit); - if (isArray(indexOrCrit)) - return new this.db.WhereClause(this, "[".concat(indexOrCrit.join("+"), "]")); - var keyPaths = keys(indexOrCrit); - if (keyPaths.length === 1) - return this.where(keyPaths[0]).equals(indexOrCrit[keyPaths[0]]); - var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function(ix) { - if (ix.compound && keyPaths.every(function(keyPath) { - return ix.keyPath.indexOf(keyPath) >= 0; - })) { - for (var i = 0; i < keyPaths.length; ++i) { - if (keyPaths.indexOf(ix.keyPath[i]) === -1) - return false; - } - return true; - } - return false; - }).sort(function(a, b) { - return a.keyPath.length - b.keyPath.length; - })[0]; - if (compoundIndex && this.db._maxKey !== maxString) { - var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); - return this.where(keyPathsInValidOrder).equals(keyPathsInValidOrder.map(function(kp) { - return indexOrCrit[kp]; - })); - } - if (!compoundIndex && debug) - console.warn("The query ".concat(JSON.stringify(indexOrCrit), " on ").concat(this.name, " would benefit from a ") + "compound index [".concat(keyPaths.join("+"), "]")); - var idxByName = this.schema.idxByName; - function equals(a, b) { - return cmp3(a, b) === 0; - } - var _a2 = keyPaths.reduce(function(_a3, keyPath) { - var prevIndex = _a3[0], prevFilterFn = _a3[1]; - var index = idxByName[keyPath]; - var value = indexOrCrit[keyPath]; - return [ - prevIndex || index, - prevIndex || !index ? combine(prevFilterFn, index && index.multi ? function(x) { - var prop = getByKeyPath(x, keyPath); - return isArray(prop) && prop.some(function(item) { - return equals(value, item); - }); - } : function(x) { - return equals(value, getByKeyPath(x, keyPath)); - }) : prevFilterFn - ]; - }, [null, null]), idx = _a2[0], filterFunction = _a2[1]; - return idx ? this.where(idx.name).equals(indexOrCrit[idx.keyPath]).filter(filterFunction) : compoundIndex ? this.filter(filterFunction) : this.where(keyPaths).equals(""); - }; - Table2.prototype.filter = function(filterFunction) { - return this.toCollection().and(filterFunction); - }; - Table2.prototype.count = function(thenShortcut) { - return this.toCollection().count(thenShortcut); - }; - Table2.prototype.offset = function(offset) { - return this.toCollection().offset(offset); - }; - Table2.prototype.limit = function(numRows) { - return this.toCollection().limit(numRows); - }; - Table2.prototype.each = function(callback) { - return this.toCollection().each(callback); - }; - Table2.prototype.toArray = function(thenShortcut) { - return this.toCollection().toArray(thenShortcut); - }; - Table2.prototype.toCollection = function() { - return new this.db.Collection(new this.db.WhereClause(this)); - }; - Table2.prototype.orderBy = function(index) { - return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? "[".concat(index.join("+"), "]") : index)); - }; - Table2.prototype.reverse = function() { - return this.toCollection().reverse(); - }; - Table2.prototype.mapToClass = function(constructor) { - var _a2 = this, db2 = _a2.db, tableName = _a2.name; - this.schema.mappedClass = constructor; - if (constructor.prototype instanceof Entity2) { - constructor = function(_super) { - __extends(class_1, _super); - function class_1() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(class_1.prototype, "db", { - get: function() { - return db2; - }, - enumerable: false, - configurable: true - }); - class_1.prototype.table = function() { - return tableName; - }; - return class_1; - }(constructor); - } - var inheritedProps = /* @__PURE__ */ new Set(); - for (var proto = constructor.prototype; proto; proto = getProto(proto)) { - Object.getOwnPropertyNames(proto).forEach(function(propName) { - return inheritedProps.add(propName); - }); - } - var readHook = function(obj) { - if (!obj) - return obj; - var res = Object.create(constructor.prototype); - for (var m in obj) - if (!inheritedProps.has(m)) - try { - res[m] = obj[m]; - } catch (_) { - } - return res; - }; - if (this.schema.readHook) { - this.hook.reading.unsubscribe(this.schema.readHook); - } - this.schema.readHook = readHook; - this.hook("reading", readHook); - return constructor; - }; - Table2.prototype.defineClass = function() { - function Class(content) { - extend(this, content); - } - return this.mapToClass(Class); - }; - Table2.prototype.add = function(obj, key) { - var _this = this; - var _a2 = this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ - trans, - type: "add", - keys: key != null ? [key] : null, - values: [objToAdd] - }); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; - }).then(function(lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } catch (_) { - } - } - return lastResult; - }); - }; - Table2.prototype.upsert = function(key, modifications) { - var _this = this; - var keyPath = this.schema.primKey.keyPath; - return this._trans("readwrite", function(trans) { - return _this.core.get({ trans, key }).then(function(existing) { - var obj = existing !== null && existing !== void 0 ? existing : {}; - applyUpdateSpec(obj, modifications); - if (keyPath) - setByKeyPath(obj, keyPath, key); - return _this.core.mutate({ - trans, - type: "put", - values: [obj], - keys: [key], - upsert: true, - updates: { keys: [key], changeSpecs: [modifications] } - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : !!existing; - }); - }); - }); - }; - Table2.prototype.update = function(keyOrObject, modifications) { - if (typeof keyOrObject === "object" && !isArray(keyOrObject)) { - var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); - if (key === void 0) - return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); - return this.where(":id").equals(key).modify(modifications); - } else { - return this.where(":id").equals(keyOrObject).modify(modifications); - } - }; - Table2.prototype.put = function(obj, key) { - var _this = this; - var _a2 = this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ - trans, - type: "put", - values: [objToAdd], - keys: key != null ? [key] : null - }); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; - }).then(function(lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } catch (_) { - } - } - return lastResult; - }); - }; - Table2.prototype.delete = function(key) { - var _this = this; - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ trans, type: "delete", keys: [key] }).then(function(res) { - return builtInDeletionTrigger(_this, [key], res); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : void 0; - }); - }); - }; - Table2.prototype.clear = function() { - var _this = this; - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ trans, type: "deleteRange", range: AnyRange }).then(function(res) { - return builtInDeletionTrigger(_this, null, res); - }); - }).then(function(res) { - return res.numFailures ? DexiePromise.reject(res.failures[0]) : void 0; - }); - }; - Table2.prototype.bulkGet = function(keys2) { - var _this = this; - return this._trans("readonly", function(trans) { - return _this.core.getMany({ - keys: keys2, - trans - }).then(function(result) { - return result.map(function(res) { - return _this.hook.reading.fire(res); - }); - }); - }); - }; - Table2.prototype.bulkAdd = function(objects, keysOrOptions, options) { - var _this = this; - var keys2 = Array.isArray(keysOrOptions) ? keysOrOptions : void 0; - options = options || (keys2 ? void 0 : keysOrOptions); - var wantResults = options ? options.allKeys : void 0; - return this._trans("readwrite", function(trans) { - var _a2 = _this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - if (keyPath && keys2) - throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); - if (keys2 && keys2.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToAdd = keyPath && auto ? objects.map(workaroundForUndefinedPrimKey(keyPath)) : objects; - return _this.core.mutate({ - trans, - type: "add", - keys: keys2, - values: objectsToAdd, - wantResults - }).then(function(_a3) { - var numFailures = _a3.numFailures, results = _a3.results, lastResult = _a3.lastResult, failures = _a3.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkAdd(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table2.prototype.bulkPut = function(objects, keysOrOptions, options) { - var _this = this; - var keys2 = Array.isArray(keysOrOptions) ? keysOrOptions : void 0; - options = options || (keys2 ? void 0 : keysOrOptions); - var wantResults = options ? options.allKeys : void 0; - return this._trans("readwrite", function(trans) { - var _a2 = _this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; - if (keyPath && keys2) - throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); - if (keys2 && keys2.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToPut = keyPath && auto ? objects.map(workaroundForUndefinedPrimKey(keyPath)) : objects; - return _this.core.mutate({ - trans, - type: "put", - keys: keys2, - values: objectsToPut, - wantResults - }).then(function(_a3) { - var numFailures = _a3.numFailures, results = _a3.results, lastResult = _a3.lastResult, failures = _a3.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkPut(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table2.prototype.bulkUpdate = function(keysAndChanges) { - var _this = this; - var coreTable = this.core; - var keys2 = keysAndChanges.map(function(entry) { - return entry.key; - }); - var changeSpecs = keysAndChanges.map(function(entry) { - return entry.changes; - }); - var offsetMap = []; - return this._trans("readwrite", function(trans) { - return coreTable.getMany({ trans, keys: keys2, cache: "clone" }).then(function(objs) { - var resultKeys = []; - var resultObjs = []; - keysAndChanges.forEach(function(_a2, idx) { - var key = _a2.key, changes = _a2.changes; - var obj = objs[idx]; - if (obj) { - for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) { - var keyPath = _b[_i]; - var value = changes[keyPath]; - if (keyPath === _this.schema.primKey.keyPath) { - if (cmp3(value, key) !== 0) { - throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()"); - } - } else { - setByKeyPath(obj, keyPath, value); - } - } - offsetMap.push(idx); - resultKeys.push(key); - resultObjs.push(obj); - } - }); - var numEntries = resultKeys.length; - return coreTable.mutate({ - trans, - type: "put", - keys: resultKeys, - values: resultObjs, - updates: { - keys: keys2, - changeSpecs - } - }).then(function(_a2) { - var numFailures = _a2.numFailures, failures = _a2.failures; - if (numFailures === 0) - return numEntries; - for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) { - var offset = _b[_i]; - var mappedOffset = offsetMap[Number(offset)]; - if (mappedOffset != null) { - var failure = failures[offset]; - delete failures[offset]; - failures[mappedOffset] = failure; - } - } - throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures); - }); - }); - }); - }; - Table2.prototype.bulkDelete = function(keys2) { - var _this = this; - var numKeys = keys2.length; - return this._trans("readwrite", function(trans) { - return _this.core.mutate({ trans, type: "delete", keys: keys2 }).then(function(res) { - return builtInDeletionTrigger(_this, keys2, res); - }); - }).then(function(_a2) { - var numFailures = _a2.numFailures, lastResult = _a2.lastResult, failures = _a2.failures; - if (numFailures === 0) - return lastResult; - throw new BulkError("".concat(_this.name, ".bulkDelete(): ").concat(numFailures, " of ").concat(numKeys, " operations failed"), failures); - }); - }; - return Table2; - }(); - function Events(ctx) { - var evs = {}; - var rv = function(eventName, subscriber) { - if (subscriber) { - var i2 = arguments.length, args = new Array(i2 - 1); - while (--i2) - args[i2 - 1] = arguments[i2]; - evs[eventName].subscribe.apply(null, args); - return ctx; - } else if (typeof eventName === "string") { - return evs[eventName]; - } - }; - rv.addEventType = add3; - for (var i = 1, l = arguments.length; i < l; ++i) { - add3(arguments[i]); - } - return rv; - function add3(eventName, chainFunction, defaultFunction) { - if (typeof eventName === "object") - return addConfiguredEvents(eventName); - if (!chainFunction) - chainFunction = reverseStoppableEventChain; - if (!defaultFunction) - defaultFunction = nop; - var context = { - subscribers: [], - fire: defaultFunction, - subscribe: function(cb) { - if (context.subscribers.indexOf(cb) === -1) { - context.subscribers.push(cb); - context.fire = chainFunction(context.fire, cb); - } - }, - unsubscribe: function(cb) { - context.subscribers = context.subscribers.filter(function(fn) { - return fn !== cb; - }); - context.fire = context.subscribers.reduce(chainFunction, defaultFunction); - } - }; - evs[eventName] = rv[eventName] = context; - return context; - } - function addConfiguredEvents(cfg) { - keys(cfg).forEach(function(eventName) { - var args = cfg[eventName]; - if (isArray(args)) { - add3(eventName, cfg[eventName][0], cfg[eventName][1]); - } else if (args === "asap") { - var context = add3(eventName, mirror, function fire() { - var i2 = arguments.length, args2 = new Array(i2); - while (i2--) - args2[i2] = arguments[i2]; - context.subscribers.forEach(function(fn) { - asap$1(function fireEvent() { - fn.apply(null, args2); - }); - }); - }); - } else - throw new exceptions.InvalidArgument("Invalid event config"); - }); - } - } - function makeClassConstructor(prototype, constructor) { - derive(constructor).from({ prototype }); - return constructor; - } - function createTableConstructor(db2) { - return makeClassConstructor(Table.prototype, function Table2(name, tableSchema, trans) { - this.db = db2; - this._tx = trans; - this.name = name; - this.schema = tableSchema; - this.hook = db2._allTables[name] ? db2._allTables[name].hook : Events(null, { - creating: [hookCreatingChain, nop], - reading: [pureFunctionChain, mirror], - updating: [hookUpdatingChain, nop], - deleting: [hookDeletingChain, nop] - }); - }); - } - function isPlainKeyRange(ctx, ignoreLimitFilter) { - return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); - } - function addFilter(ctx, fn) { - ctx.filter = combine(ctx.filter, fn); - } - function addReplayFilter(ctx, factory, isLimitFilter) { - var curr = ctx.replayFilter; - ctx.replayFilter = curr ? function() { - return combine(curr(), factory()); - } : factory; - ctx.justLimit = isLimitFilter && !curr; - } - function addMatchFilter(ctx, fn) { - ctx.isMatch = combine(ctx.isMatch, fn); - } - function getIndexOrStore(ctx, coreSchema) { - if (ctx.isPrimKey) - return coreSchema.primaryKey; - var index = coreSchema.getIndexByKeyPath(ctx.index); - if (!index) - throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); - return index; - } - function openCursor(ctx, coreTable, trans) { - var index = getIndexOrStore(ctx, coreTable.schema); - return coreTable.openCursor({ - trans, - values: !ctx.keysOnly, - reverse: ctx.dir === "prev", - unique: !!ctx.unique, - query: { - index, - range: ctx.range - } - }); - } - function iter(ctx, fn, coreTrans, coreTable) { - var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; - if (!ctx.or) { - return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); - } else { - var set_1 = {}; - var union = function(item, cursor, advance) { - if (!filter || filter(cursor, advance, function(result) { - return cursor.stop(result); - }, function(err) { - return cursor.fail(err); - })) { - var primaryKey = cursor.primaryKey; - var key = "" + primaryKey; - if (key === "[object ArrayBuffer]") - key = "" + new Uint8Array(primaryKey); - if (!hasOwn(set_1, key)) { - set_1[key] = true; - fn(item, cursor, advance); - } - } - }; - return Promise.all([ - ctx.or._iterate(union, coreTrans), - iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) - ]); - } - } - function iterate(cursorPromise, filter, fn, valueMapper) { - var mappedFn = valueMapper ? function(x, c, a) { - return fn(valueMapper(x), c, a); - } : fn; - var wrappedFn = wrap(mappedFn); - return cursorPromise.then(function(cursor) { - if (cursor) { - return cursor.start(function() { - var c = function() { - return cursor.continue(); - }; - if (!filter || filter(cursor, function(advancer) { - return c = advancer; - }, function(val) { - cursor.stop(val); - c = nop; - }, function(e) { - cursor.fail(e); - c = nop; - })) - wrappedFn(cursor.value, cursor, function(advancer) { - return c = advancer; - }); - c(); - }); - } - }); - } - var Collection = function() { - function Collection2() { - } - Collection2.prototype._read = function(fn, cb) { - var ctx = this._ctx; - return ctx.error ? ctx.table._trans(null, rejection.bind(null, ctx.error)) : ctx.table._trans("readonly", fn).then(cb); - }; - Collection2.prototype._write = function(fn) { - var ctx = this._ctx; - return ctx.error ? ctx.table._trans(null, rejection.bind(null, ctx.error)) : ctx.table._trans("readwrite", fn, "locked"); - }; - Collection2.prototype._addAlgorithm = function(fn) { - var ctx = this._ctx; - ctx.algorithm = combine(ctx.algorithm, fn); - }; - Collection2.prototype._iterate = function(fn, coreTrans) { - return iter(this._ctx, fn, coreTrans, this._ctx.table.core); - }; - Collection2.prototype.clone = function(props2) { - var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); - if (props2) - extend(ctx, props2); - rv._ctx = ctx; - return rv; - }; - Collection2.prototype.raw = function() { - this._ctx.valueMapper = null; - return this; - }; - Collection2.prototype.each = function(fn) { - var ctx = this._ctx; - return this._read(function(trans) { - return iter(ctx, fn, trans, ctx.table.core); - }); - }; - Collection2.prototype.count = function(cb) { - var _this = this; - return this._read(function(trans) { - var ctx = _this._ctx; - var coreTable = ctx.table.core; - if (isPlainKeyRange(ctx, true)) { - return coreTable.count({ - trans, - query: { - index: getIndexOrStore(ctx, coreTable.schema), - range: ctx.range - } - }).then(function(count2) { - return Math.min(count2, ctx.limit); - }); - } else { - var count = 0; - return iter(ctx, function() { - ++count; - return false; - }, trans, coreTable).then(function() { - return count; - }); - } - }).then(cb); - }; - Collection2.prototype.sortBy = function(keyPath, cb) { - var parts = keyPath.split(".").reverse(), lastPart = parts[0], lastIndex = parts.length - 1; - function getval(obj, i) { - if (i) - return getval(obj[parts[i]], i - 1); - return obj[lastPart]; - } - var order = this._ctx.dir === "next" ? 1 : -1; - function sorter(a, b) { - var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); - return cmp3(aVal, bVal) * order; - } - return this.toArray(function(a) { - return a.slice().sort(sorter); - }).then(cb); - }; - Collection2.prototype.toArray = function(cb) { - var _this = this; - return this._read(function(trans) { - var ctx = _this._ctx; - if (isPlainKeyRange(ctx, true) && ctx.limit > 0) { - var valueMapper_1 = ctx.valueMapper; - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans, - limit: ctx.limit, - values: true, - direction: ctx.dir === "prev" ? "prev" : void 0, - query: { - index, - range: ctx.range - } - }).then(function(_a2) { - var result = _a2.result; - return valueMapper_1 ? result.map(valueMapper_1) : result; - }); - } else { - var a_1 = []; - return iter(ctx, function(item) { - return a_1.push(item); - }, trans, ctx.table.core).then(function() { - return a_1; - }); - } - }, cb); - }; - Collection2.prototype.offset = function(offset) { - var ctx = this._ctx; - if (offset <= 0) - return this; - ctx.offset += offset; - if (isPlainKeyRange(ctx)) { - addReplayFilter(ctx, function() { - var offsetLeft = offset; - return function(cursor, advance) { - if (offsetLeft === 0) - return true; - if (offsetLeft === 1) { - --offsetLeft; - return false; - } - advance(function() { - cursor.advance(offsetLeft); - offsetLeft = 0; - }); - return false; - }; - }); - } else { - addReplayFilter(ctx, function() { - var offsetLeft = offset; - return function() { - return --offsetLeft < 0; - }; - }); - } - return this; - }; - Collection2.prototype.limit = function(numRows) { - this._ctx.limit = Math.min(this._ctx.limit, numRows); - addReplayFilter(this._ctx, function() { - var rowsLeft = numRows; - return function(cursor, advance, resolve) { - if (--rowsLeft <= 0) - advance(resolve); - return rowsLeft >= 0; - }; - }, true); - return this; - }; - Collection2.prototype.until = function(filterFunction, bIncludeStopEntry) { - addFilter(this._ctx, function(cursor, advance, resolve) { - if (filterFunction(cursor.value)) { - advance(resolve); - return bIncludeStopEntry; - } else { - return true; - } - }); - return this; - }; - Collection2.prototype.first = function(cb) { - return this.limit(1).toArray(function(a) { - return a[0]; - }).then(cb); - }; - Collection2.prototype.last = function(cb) { - return this.reverse().first(cb); - }; - Collection2.prototype.filter = function(filterFunction) { - addFilter(this._ctx, function(cursor) { - return filterFunction(cursor.value); - }); - addMatchFilter(this._ctx, filterFunction); - return this; - }; - Collection2.prototype.and = function(filter) { - return this.filter(filter); - }; - Collection2.prototype.or = function(indexName) { - return new this.db.WhereClause(this._ctx.table, indexName, this); - }; - Collection2.prototype.reverse = function() { - this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev"; - if (this._ondirectionchange) - this._ondirectionchange(this._ctx.dir); - return this; - }; - Collection2.prototype.desc = function() { - return this.reverse(); - }; - Collection2.prototype.eachKey = function(cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function(val, cursor) { - cb(cursor.key, cursor); - }); - }; - Collection2.prototype.eachUniqueKey = function(cb) { - this._ctx.unique = "unique"; - return this.eachKey(cb); - }; - Collection2.prototype.eachPrimaryKey = function(cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function(val, cursor) { - cb(cursor.primaryKey, cursor); - }); - }; - Collection2.prototype.keys = function(cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function(item, cursor) { - a.push(cursor.key); - }).then(function() { - return a; - }).then(cb); - }; - Collection2.prototype.primaryKeys = function(cb) { - var ctx = this._ctx; - if (isPlainKeyRange(ctx, true) && ctx.limit > 0) { - return this._read(function(trans) { - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans, - values: false, - limit: ctx.limit, - direction: ctx.dir === "prev" ? "prev" : void 0, - query: { - index, - range: ctx.range - } - }); - }).then(function(_a2) { - var result = _a2.result; - return result; - }).then(cb); - } - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function(item, cursor) { - a.push(cursor.primaryKey); - }).then(function() { - return a; - }).then(cb); - }; - Collection2.prototype.uniqueKeys = function(cb) { - this._ctx.unique = "unique"; - return this.keys(cb); - }; - Collection2.prototype.firstKey = function(cb) { - return this.limit(1).keys(function(a) { - return a[0]; - }).then(cb); - }; - Collection2.prototype.lastKey = function(cb) { - return this.reverse().firstKey(cb); - }; - Collection2.prototype.distinct = function() { - var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; - if (!idx || !idx.multi) - return this; - var set = {}; - addFilter(this._ctx, function(cursor) { - var strKey = cursor.primaryKey.toString(); - var found = hasOwn(set, strKey); - set[strKey] = true; - return !found; - }); - return this; - }; - Collection2.prototype.modify = function(changes) { - var _this = this; - var ctx = this._ctx; - return this._write(function(trans) { - var modifyer; - if (typeof changes === "function") { - modifyer = changes; - } else { - modifyer = function(item) { - return applyUpdateSpec(item, changes); - }; - } - var coreTable = ctx.table.core; - var _a2 = coreTable.schema.primaryKey, outbound = _a2.outbound, extractKey2 = _a2.extractKey; - var limit = 200; - var modifyChunkSize = _this.db._options.modifyChunkSize; - if (modifyChunkSize) { - if (typeof modifyChunkSize == "object") { - limit = modifyChunkSize[coreTable.name] || modifyChunkSize["*"] || 200; - } else { - limit = modifyChunkSize; - } - } - var totalFailures = []; - var successCount = 0; - var failedKeys = []; - var applyMutateResult = function(expectedCount, res) { - var failures = res.failures, numFailures = res.numFailures; - successCount += expectedCount - numFailures; - for (var _i = 0, _a3 = keys(failures); _i < _a3.length; _i++) { - var pos = _a3[_i]; - totalFailures.push(failures[pos]); - } - }; - var isUnconditionalDelete = changes === deleteCallback; - return _this.clone().primaryKeys().then(function(keys2) { - var criteria = isPlainKeyRange(ctx) && ctx.limit === Infinity && (typeof changes !== "function" || isUnconditionalDelete) && { - index: ctx.index, - range: ctx.range - }; - var nextChunk = function(offset) { - var count = Math.min(limit, keys2.length - offset); - var keysInChunk = keys2.slice(offset, offset + count); - return (isUnconditionalDelete ? Promise.resolve([]) : coreTable.getMany({ - trans, - keys: keysInChunk, - cache: "immutable" - })).then(function(values) { - var addValues = []; - var putValues = []; - var putKeys = outbound ? [] : null; - var deleteKeys = isUnconditionalDelete ? keysInChunk : []; - if (!isUnconditionalDelete) - for (var i = 0; i < count; ++i) { - var origValue = values[i]; - var ctx_1 = { - value: deepClone(origValue), - primKey: keys2[offset + i] - }; - if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { - if (ctx_1.value == null) { - deleteKeys.push(keys2[offset + i]); - } else if (!outbound && cmp3(extractKey2(origValue), extractKey2(ctx_1.value)) !== 0) { - deleteKeys.push(keys2[offset + i]); - addValues.push(ctx_1.value); - } else { - putValues.push(ctx_1.value); - if (outbound) - putKeys.push(keys2[offset + i]); - } - } - } - return Promise.resolve(addValues.length > 0 && coreTable.mutate({ trans, type: "add", values: addValues }).then(function(res) { - for (var pos in res.failures) { - deleteKeys.splice(parseInt(pos), 1); - } - applyMutateResult(addValues.length, res); - })).then(function() { - return (putValues.length > 0 || criteria && typeof changes === "object") && coreTable.mutate({ - trans, - type: "put", - keys: putKeys, - values: putValues, - criteria, - changeSpec: typeof changes !== "function" && changes, - isAdditionalChunk: offset > 0 - }).then(function(res) { - return applyMutateResult(putValues.length, res); - }); - }).then(function() { - return (deleteKeys.length > 0 || criteria && isUnconditionalDelete) && coreTable.mutate({ - trans, - type: "delete", - keys: deleteKeys, - criteria, - isAdditionalChunk: offset > 0 - }).then(function(res) { - return builtInDeletionTrigger(ctx.table, deleteKeys, res); - }).then(function(res) { - return applyMutateResult(deleteKeys.length, res); - }); - }).then(function() { - return keys2.length > offset + count && nextChunk(offset + limit); - }); - }); - }; - return nextChunk(0).then(function() { - if (totalFailures.length > 0) - throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); - return keys2.length; - }); - }); - }); - }; - Collection2.prototype.delete = function() { - var ctx = this._ctx, range = ctx.range; - if (isPlainKeyRange(ctx) && !ctx.table.schema.yProps && (ctx.isPrimKey || range.type === 3)) { - return this._write(function(trans) { - var primaryKey = ctx.table.core.schema.primaryKey; - var coreRange = range; - return ctx.table.core.count({ trans, query: { index: primaryKey, range: coreRange } }).then(function(count) { - return ctx.table.core.mutate({ trans, type: "deleteRange", range: coreRange }).then(function(_a2) { - var failures = _a2.failures, numFailures = _a2.numFailures; - if (numFailures) - throw new ModifyError("Could not delete some values", Object.keys(failures).map(function(pos) { - return failures[pos]; - }), count - numFailures); - return count - numFailures; - }); - }); - }); - } - return this.modify(deleteCallback); - }; - return Collection2; - }(); - var deleteCallback = function(value, ctx) { - return ctx.value = null; - }; - function createCollectionConstructor(db2) { - return makeClassConstructor(Collection.prototype, function Collection2(whereClause, keyRangeGenerator) { - this.db = db2; - var keyRange = AnyRange, error = null; - if (keyRangeGenerator) - try { - keyRange = keyRangeGenerator(); - } catch (ex) { - error = ex; - } - var whereCtx = whereClause._ctx; - var table = whereCtx.table; - var readingHook = table.hook.reading.fire; - this._ctx = { - table, - index: whereCtx.index, - isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name, - range: keyRange, - keysOnly: false, - dir: "next", - unique: "", - algorithm: null, - filter: null, - replayFilter: null, - justLimit: true, - isMatch: null, - offset: 0, - limit: Infinity, - error, - or: whereCtx.or, - valueMapper: readingHook !== mirror ? readingHook : null - }; - }); - } - function simpleCompare(a, b) { - return a < b ? -1 : a === b ? 0 : 1; - } - function simpleCompareReverse(a, b) { - return a > b ? -1 : a === b ? 0 : 1; - } - function fail2(collectionOrWhereClause, err, T) { - var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause.Collection(collectionOrWhereClause) : collectionOrWhereClause; - collection._ctx.error = T ? new T(err) : new TypeError(err); - return collection; - } - function emptyCollection(whereClause) { - return new whereClause.Collection(whereClause, function() { - return rangeEqual(""); - }).limit(0); - } - function upperFactory(dir) { - return dir === "next" ? function(s) { - return s.toUpperCase(); - } : function(s) { - return s.toLowerCase(); - }; - } - function lowerFactory(dir) { - return dir === "next" ? function(s) { - return s.toLowerCase(); - } : function(s) { - return s.toUpperCase(); - }; - } - function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp4, dir) { - var length = Math.min(key.length, lowerNeedle.length); - var llp = -1; - for (var i = 0; i < length; ++i) { - var lwrKeyChar = lowerKey[i]; - if (lwrKeyChar !== lowerNeedle[i]) { - if (cmp4(key[i], upperNeedle[i]) < 0) - return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); - if (cmp4(key[i], lowerNeedle[i]) < 0) - return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); - if (llp >= 0) - return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); - return null; - } - if (cmp4(key[i], lwrKeyChar) < 0) - llp = i; - } - if (length < lowerNeedle.length && dir === "next") - return key + upperNeedle.substr(key.length); - if (length < key.length && dir === "prev") - return key.substr(0, upperNeedle.length); - return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1); - } - function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { - var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; - if (!needles.every(function(s) { - return typeof s === "string"; - })) { - return fail2(whereClause, STRING_EXPECTED); - } - function initDirection(dir) { - upper = upperFactory(dir); - lower = lowerFactory(dir); - compare = dir === "next" ? simpleCompare : simpleCompareReverse; - var needleBounds = needles.map(function(needle) { - return { lower: lower(needle), upper: upper(needle) }; - }).sort(function(a, b) { - return compare(a.lower, b.lower); - }); - upperNeedles = needleBounds.map(function(nb) { - return nb.upper; - }); - lowerNeedles = needleBounds.map(function(nb) { - return nb.lower; - }); - direction = dir; - nextKeySuffix = dir === "next" ? "" : suffix; - } - initDirection("next"); - var c = new whereClause.Collection(whereClause, function() { - return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); - }); - c._ondirectionchange = function(direction2) { - initDirection(direction2); - }; - var firstPossibleNeedle = 0; - c._addAlgorithm(function(cursor, advance, resolve) { - var key = cursor.key; - if (typeof key !== "string") - return false; - var lowerKey = lower(key); - if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { - return true; - } else { - var lowestPossibleCasing = null; - for (var i = firstPossibleNeedle; i < needlesLen; ++i) { - var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); - if (casing === null && lowestPossibleCasing === null) - firstPossibleNeedle = i + 1; - else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { - lowestPossibleCasing = casing; - } - } - if (lowestPossibleCasing !== null) { - advance(function() { - cursor.continue(lowestPossibleCasing + nextKeySuffix); - }); - } else { - advance(resolve); - } - return false; - } - }); - return c; - } - function createRange(lower, upper, lowerOpen, upperOpen) { - return { - type: 2, - lower, - upper, - lowerOpen, - upperOpen - }; - } - function rangeEqual(value) { - return { - type: 1, - lower: value, - upper: value - }; - } - var WhereClause = function() { - function WhereClause2() { - } - Object.defineProperty(WhereClause2.prototype, "Collection", { - get: function() { - return this._ctx.table.db.Collection; - }, - enumerable: false, - configurable: true - }); - WhereClause2.prototype.between = function(lower, upper, includeLower, includeUpper) { - includeLower = includeLower !== false; - includeUpper = includeUpper === true; - try { - if (this._cmp(lower, upper) > 0 || this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) - return emptyCollection(this); - return new this.Collection(this, function() { - return createRange(lower, upper, !includeLower, !includeUpper); - }); - } catch (e) { - return fail2(this, INVALID_KEY_ARGUMENT); - } - }; - WhereClause2.prototype.equals = function(value) { - if (value == null) - return fail2(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return rangeEqual(value); - }); - }; - WhereClause2.prototype.above = function(value) { - if (value == null) - return fail2(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(value, void 0, true); - }); - }; - WhereClause2.prototype.aboveOrEqual = function(value) { - if (value == null) - return fail2(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(value, void 0, false); - }); - }; - WhereClause2.prototype.below = function(value) { - if (value == null) - return fail2(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(void 0, value, false, true); - }); - }; - WhereClause2.prototype.belowOrEqual = function(value) { - if (value == null) - return fail2(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function() { - return createRange(void 0, value); - }); - }; - WhereClause2.prototype.startsWith = function(str) { - if (typeof str !== "string") - return fail2(this, STRING_EXPECTED); - return this.between(str, str + maxString, true, true); - }; - WhereClause2.prototype.startsWithIgnoreCase = function(str) { - if (str === "") - return this.startsWith(str); - return addIgnoreCaseAlgorithm(this, function(x, a) { - return x.indexOf(a[0]) === 0; - }, [str], maxString); - }; - WhereClause2.prototype.equalsIgnoreCase = function(str) { - return addIgnoreCaseAlgorithm(this, function(x, a) { - return x === a[0]; - }, [str], ""); - }; - WhereClause2.prototype.anyOfIgnoreCase = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function(x, a) { - return a.indexOf(x) !== -1; - }, set, ""); - }; - WhereClause2.prototype.startsWithAnyOfIgnoreCase = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function(x, a) { - return a.some(function(n) { - return x.indexOf(n) === 0; - }); - }, set, maxString); - }; - WhereClause2.prototype.anyOf = function() { - var _this = this; - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - var compare = this._cmp; - try { - set.sort(compare); - } catch (e) { - return fail2(this, INVALID_KEY_ARGUMENT); - } - if (set.length === 0) - return emptyCollection(this); - var c = new this.Collection(this, function() { - return createRange(set[0], set[set.length - 1]); - }); - c._ondirectionchange = function(direction) { - compare = direction === "next" ? _this._ascending : _this._descending; - set.sort(compare); - }; - var i = 0; - c._addAlgorithm(function(cursor, advance, resolve) { - var key = cursor.key; - while (compare(key, set[i]) > 0) { - ++i; - if (i === set.length) { - advance(resolve); - return false; - } - } - if (compare(key, set[i]) === 0) { - return true; - } else { - advance(function() { - cursor.continue(set[i]); - }); - return false; - } - }); - return c; - }; - WhereClause2.prototype.notEqual = function(value) { - return this.inAnyRange([ - [minKey, value], - [value, this.db._maxKey] - ], { includeLowers: false, includeUppers: false }); - }; - WhereClause2.prototype.noneOf = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return new this.Collection(this); - try { - set.sort(this._ascending); - } catch (e) { - return fail2(this, INVALID_KEY_ARGUMENT); - } - var ranges = set.reduce(function(res, val) { - return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; - }, null); - ranges.push([set[set.length - 1], this.db._maxKey]); - return this.inAnyRange(ranges, { - includeLowers: false, - includeUppers: false - }); - }; - WhereClause2.prototype.inAnyRange = function(ranges, options) { - var _this = this; - var cmp4 = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; - if (ranges.length === 0) - return emptyCollection(this); - if (!ranges.every(function(range) { - return range[0] !== void 0 && range[1] !== void 0 && ascending(range[0], range[1]) <= 0; - })) { - return fail2(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); - } - var includeLowers = !options || options.includeLowers !== false; - var includeUppers = options && options.includeUppers === true; - function addRange2(ranges2, newRange) { - var i = 0, l = ranges2.length; - for (; i < l; ++i) { - var range = ranges2[i]; - if (cmp4(newRange[0], range[1]) < 0 && cmp4(newRange[1], range[0]) > 0) { - range[0] = min(range[0], newRange[0]); - range[1] = max(range[1], newRange[1]); - break; - } - } - if (i === l) - ranges2.push(newRange); - return ranges2; - } - var sortDirection = ascending; - function rangeSorter(a, b) { - return sortDirection(a[0], b[0]); - } - var set; - try { - set = ranges.reduce(addRange2, []); - set.sort(rangeSorter); - } catch (ex) { - return fail2(this, INVALID_KEY_ARGUMENT); - } - var rangePos = 0; - var keyIsBeyondCurrentEntry = includeUppers ? function(key) { - return ascending(key, set[rangePos][1]) > 0; - } : function(key) { - return ascending(key, set[rangePos][1]) >= 0; - }; - var keyIsBeforeCurrentEntry = includeLowers ? function(key) { - return descending(key, set[rangePos][0]) > 0; - } : function(key) { - return descending(key, set[rangePos][0]) >= 0; - }; - function keyWithinCurrentRange(key) { - return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); - } - var checkKey = keyIsBeyondCurrentEntry; - var c = new this.Collection(this, function() { - return createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); - }); - c._ondirectionchange = function(direction) { - if (direction === "next") { - checkKey = keyIsBeyondCurrentEntry; - sortDirection = ascending; - } else { - checkKey = keyIsBeforeCurrentEntry; - sortDirection = descending; - } - set.sort(rangeSorter); - }; - c._addAlgorithm(function(cursor, advance, resolve) { - var key = cursor.key; - while (checkKey(key)) { - ++rangePos; - if (rangePos === set.length) { - advance(resolve); - return false; - } - } - if (keyWithinCurrentRange(key)) { - return true; - } else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { - return false; - } else { - advance(function() { - if (sortDirection === ascending) - cursor.continue(set[rangePos][0]); - else - cursor.continue(set[rangePos][1]); - }); - return false; - } - }); - return c; - }; - WhereClause2.prototype.startsWithAnyOf = function() { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (!set.every(function(s) { - return typeof s === "string"; - })) { - return fail2(this, "startsWithAnyOf() only works with strings"); - } - if (set.length === 0) - return emptyCollection(this); - return this.inAnyRange(set.map(function(str) { - return [str, str + maxString]; - })); - }; - return WhereClause2; - }(); - function createWhereClauseConstructor(db2) { - return makeClassConstructor(WhereClause.prototype, function WhereClause2(table, index, orCollection) { - this.db = db2; - this._ctx = { - table, - index: index === ":id" ? null : index, - or: orCollection - }; - this._cmp = this._ascending = cmp3; - this._descending = function(a, b) { - return cmp3(b, a); - }; - this._max = function(a, b) { - return cmp3(a, b) > 0 ? a : b; - }; - this._min = function(a, b) { - return cmp3(a, b) < 0 ? a : b; - }; - this._IDBKeyRange = db2._deps.IDBKeyRange; - if (!this._IDBKeyRange) - throw new exceptions.MissingAPI(); - }); - } - function eventRejectHandler(reject) { - return wrap(function(event) { - preventDefault(event); - reject(event.target.error); - return false; - }); - } - function preventDefault(event) { - if (event.stopPropagation) - event.stopPropagation(); - if (event.preventDefault) - event.preventDefault(); - } - var DEXIE_STORAGE_MUTATED_EVENT_NAME = "storagemutated"; - var STORAGE_MUTATED_DOM_EVENT_NAME = "x-storagemutated-1"; - var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); - var Transaction = function() { - function Transaction2() { - } - Transaction2.prototype._lock = function() { - assert(!PSD.global); - ++this._reculock; - if (this._reculock === 1 && !PSD.global) - PSD.lockOwnerFor = this; - return this; - }; - Transaction2.prototype._unlock = function() { - assert(!PSD.global); - if (--this._reculock === 0) { - if (!PSD.global) - PSD.lockOwnerFor = null; - while (this._blockedFuncs.length > 0 && !this._locked()) { - var fnAndPSD = this._blockedFuncs.shift(); - try { - usePSD(fnAndPSD[1], fnAndPSD[0]); - } catch (e) { - } - } - } - return this; - }; - Transaction2.prototype._locked = function() { - return this._reculock && PSD.lockOwnerFor !== this; - }; - Transaction2.prototype.create = function(idbtrans) { - var _this = this; - if (!this.mode) - return this; - var idbdb = this.db.idbdb; - var dbOpenError = this.db._state.dbOpenError; - assert(!this.idbtrans); - if (!idbtrans && !idbdb) { - switch (dbOpenError && dbOpenError.name) { - case "DatabaseClosedError": - throw new exceptions.DatabaseClosed(dbOpenError); - case "MissingAPIError": - throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); - default: - throw new exceptions.OpenFailed(dbOpenError); - } - } - if (!this.active) - throw new exceptions.TransactionInactive(); - assert(this._completion._state === null); - idbtrans = this.idbtrans = idbtrans || (this.db.core ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) : idbdb.transaction(this.storeNames, this.mode, { - durability: this.chromeTransactionDurability - })); - idbtrans.onerror = wrap(function(ev) { - preventDefault(ev); - _this._reject(idbtrans.error); - }); - idbtrans.onabort = wrap(function(ev) { - preventDefault(ev); - _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); - _this.active = false; - _this.on("abort").fire(ev); - }); - idbtrans.oncomplete = wrap(function() { - _this.active = false; - _this._resolve(); - if ("mutatedParts" in idbtrans) { - globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); - } - }); - return this; - }; - Transaction2.prototype._promise = function(mode, fn, bWriteLock) { - var _this = this; - if (mode === "readwrite" && this.mode !== "readwrite") - return rejection(new exceptions.ReadOnly("Transaction is readonly")); - if (!this.active) - return rejection(new exceptions.TransactionInactive()); - if (this._locked()) { - return new DexiePromise(function(resolve, reject) { - _this._blockedFuncs.push([ - function() { - _this._promise(mode, fn, bWriteLock).then(resolve, reject); - }, - PSD - ]); - }); - } else if (bWriteLock) { - return newScope(function() { - var p2 = new DexiePromise(function(resolve, reject) { - _this._lock(); - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p2.finally(function() { - return _this._unlock(); - }); - p2._lib = true; - return p2; - }); - } else { - var p = new DexiePromise(function(resolve, reject) { - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p._lib = true; - return p; - } - }; - Transaction2.prototype._root = function() { - return this.parent ? this.parent._root() : this; - }; - Transaction2.prototype.waitFor = function(promiseLike) { - var root = this._root(); - var promise = DexiePromise.resolve(promiseLike); - if (root._waitingFor) { - root._waitingFor = root._waitingFor.then(function() { - return promise; - }); - } else { - root._waitingFor = promise; - root._waitingQueue = []; - var store = root.idbtrans.objectStore(root.storeNames[0]); - (function spin() { - ++root._spinCount; - while (root._waitingQueue.length) - root._waitingQueue.shift()(); - if (root._waitingFor) - store.get(-Infinity).onsuccess = spin; - })(); - } - var currentWaitPromise = root._waitingFor; - return new DexiePromise(function(resolve, reject) { - promise.then(function(res) { - return root._waitingQueue.push(wrap(resolve.bind(null, res))); - }, function(err) { - return root._waitingQueue.push(wrap(reject.bind(null, err))); - }).finally(function() { - if (root._waitingFor === currentWaitPromise) { - root._waitingFor = null; - } - }); - }); - }; - Transaction2.prototype.abort = function() { - if (this.active) { - this.active = false; - if (this.idbtrans) - this.idbtrans.abort(); - this._reject(new exceptions.Abort()); - } - }; - Transaction2.prototype.table = function(tableName) { - var memoizedTables = this._memoizedTables || (this._memoizedTables = {}); - if (hasOwn(memoizedTables, tableName)) - return memoizedTables[tableName]; - var tableSchema = this.schema[tableName]; - if (!tableSchema) { - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - } - var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); - transactionBoundTable.core = this.db.core.table(tableName); - memoizedTables[tableName] = transactionBoundTable; - return transactionBoundTable; - }; - return Transaction2; - }(); - function createTransactionConstructor(db2) { - return makeClassConstructor(Transaction.prototype, function Transaction2(mode, storeNames, dbschema, chromeTransactionDurability, parent) { - var _this = this; - if (mode !== "readonly") - storeNames.forEach(function(storeName) { - var _a2; - var yProps = (_a2 = dbschema[storeName]) === null || _a2 === void 0 ? void 0 : _a2.yProps; - if (yProps) - storeNames = storeNames.concat(yProps.map(function(p) { - return p.updatesTable; - })); - }); - this.db = db2; - this.mode = mode; - this.storeNames = storeNames; - this.schema = dbschema; - this.chromeTransactionDurability = chromeTransactionDurability; - this.idbtrans = null; - this.on = Events(this, "complete", "error", "abort"); - this.parent = parent || null; - this.active = true; - this._reculock = 0; - this._blockedFuncs = []; - this._resolve = null; - this._reject = null; - this._waitingFor = null; - this._waitingQueue = null; - this._spinCount = 0; - this._completion = new DexiePromise(function(resolve, reject) { - _this._resolve = resolve; - _this._reject = reject; - }); - this._completion.then(function() { - _this.active = false; - _this.on.complete.fire(); - }, function(e) { - var wasActive = _this.active; - _this.active = false; - _this.on.error.fire(e); - _this.parent ? _this.parent._reject(e) : wasActive && _this.idbtrans && _this.idbtrans.abort(); - return rejection(e); - }); - }); - } - function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey, type2) { - return { - name, - keyPath, - unique, - multi, - auto, - compound, - src: (unique && !isPrimKey ? "&" : "") + (multi ? "*" : "") + (auto ? "++" : "") + nameFromKeyPath(keyPath), - type: type2 - }; - } - function nameFromKeyPath(keyPath) { - return typeof keyPath === "string" ? keyPath : keyPath ? "[" + [].join.call(keyPath, "+") + "]" : ""; - } - function createTableSchema(name, primKey, indexes) { - return { - name, - primKey, - indexes, - mappedClass: null, - idxByName: arrayToObject(indexes, function(index) { - return [index.name, index]; - }) - }; - } - function safariMultiStoreFix(storeNames) { - return storeNames.length === 1 ? storeNames[0] : storeNames; - } - var getMaxKey = function(IdbKeyRange) { - try { - IdbKeyRange.only([[]]); - getMaxKey = function() { - return [[]]; - }; - return [[]]; - } catch (e) { - getMaxKey = function() { - return maxString; - }; - return maxString; - } - }; - function getKeyExtractor(keyPath) { - if (keyPath == null) { - return function() { - return void 0; - }; - } else if (typeof keyPath === "string") { - return getSinglePathKeyExtractor(keyPath); - } else { - return function(obj) { - return getByKeyPath(obj, keyPath); - }; - } - } - function getSinglePathKeyExtractor(keyPath) { - var split = keyPath.split("."); - if (split.length === 1) { - return function(obj) { - return obj[keyPath]; - }; - } else { - return function(obj) { - return getByKeyPath(obj, keyPath); - }; - } - } - function arrayify(arrayLike) { - return [].slice.call(arrayLike); - } - var _id_counter = 0; - function getKeyPathAlias(keyPath) { - return keyPath == null ? ":id" : typeof keyPath === "string" ? keyPath : "[".concat(keyPath.join("+"), "]"); - } - function createDBCore(db2, IdbKeyRange, tmpTrans) { - function extractSchema(db3, trans) { - var tables2 = arrayify(db3.objectStoreNames); - var tempStore = tables2.length > 0 ? trans.objectStore(tables2[0]) : {}; - return { - schema: { - name: db3.name, - tables: tables2.map(function(table) { - return trans.objectStore(table); - }).map(function(store) { - var keyPath = store.keyPath, autoIncrement = store.autoIncrement; - var compound = isArray(keyPath); - var outbound = keyPath == null; - var indexByKeyPath = {}; - var result = { - name: store.name, - primaryKey: { - name: null, - isPrimaryKey: true, - outbound, - compound, - keyPath, - autoIncrement, - unique: true, - extractKey: getKeyExtractor(keyPath) - }, - indexes: arrayify(store.indexNames).map(function(indexName) { - return store.index(indexName); - }).map(function(index) { - var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath2 = index.keyPath; - var compound2 = isArray(keyPath2); - var result2 = { - name, - compound: compound2, - keyPath: keyPath2, - unique, - multiEntry, - extractKey: getKeyExtractor(keyPath2) - }; - indexByKeyPath[getKeyPathAlias(keyPath2)] = result2; - return result2; - }), - getIndexByKeyPath: function(keyPath2) { - return indexByKeyPath[getKeyPathAlias(keyPath2)]; - } - }; - indexByKeyPath[":id"] = result.primaryKey; - if (keyPath != null) { - indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; - } - return result; - }) - }, - hasGetAll: tables2.length > 0 && "getAll" in tempStore && !(typeof navigator !== "undefined" && /Safari/.test(navigator.userAgent) && !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604), - hasIdb3Features: "getAllRecords" in tempStore - }; - } - function makeIDBKeyRange(range) { - if (range.type === 3) - return null; - if (range.type === 4) - throw new Error("Cannot convert never type to IDBKeyRange"); - var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; - var idbRange = lower === void 0 ? upper === void 0 ? null : IdbKeyRange.upperBound(upper, !!upperOpen) : upper === void 0 ? IdbKeyRange.lowerBound(lower, !!lowerOpen) : IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); - return idbRange; - } - function createDbCoreTable(tableSchema) { - var tableName = tableSchema.name; - function mutate(_a3) { - var trans = _a3.trans, type2 = _a3.type, keys2 = _a3.keys, values = _a3.values, range = _a3.range; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var outbound = store.keyPath == null; - var isAddOrPut = type2 === "put" || type2 === "add"; - if (!isAddOrPut && type2 !== "delete" && type2 !== "deleteRange") - throw new Error("Invalid operation type: " + type2); - var length = (keys2 || values || { length: 1 }).length; - if (keys2 && values && keys2.length !== values.length) { - throw new Error("Given keys array must have same length as given values array."); - } - if (length === 0) - return resolve({ - numFailures: 0, - failures: {}, - results: [], - lastResult: void 0 - }); - var req; - var reqs = []; - var failures = []; - var numFailures = 0; - var errorHandler = function(event) { - ++numFailures; - preventDefault(event); - }; - if (type2 === "deleteRange") { - if (range.type === 4) - return resolve({ - numFailures, - failures, - results: [], - lastResult: void 0 - }); - if (range.type === 3) - reqs.push(req = store.clear()); - else - reqs.push(req = store.delete(makeIDBKeyRange(range))); - } else { - var _a4 = isAddOrPut ? outbound ? [values, keys2] : [values, null] : [keys2, null], args1 = _a4[0], args2 = _a4[1]; - if (isAddOrPut) { - for (var i = 0; i < length; ++i) { - reqs.push(req = args2 && args2[i] !== void 0 ? store[type2](args1[i], args2[i]) : store[type2](args1[i])); - req.onerror = errorHandler; - } - } else { - for (var i = 0; i < length; ++i) { - reqs.push(req = store[type2](args1[i])); - req.onerror = errorHandler; - } - } - } - var done = function(event) { - var lastResult = event.target.result; - reqs.forEach(function(req2, i2) { - return req2.error != null && (failures[i2] = req2.error); - }); - resolve({ - numFailures, - failures, - results: type2 === "delete" ? keys2 : reqs.map(function(req2) { - return req2.result; - }), - lastResult - }); - }; - req.onerror = function(event) { - errorHandler(event); - done(event); - }; - req.onsuccess = done; - }); - } - function openCursor2(_a3) { - var trans = _a3.trans, values = _a3.values, query2 = _a3.query, reverse = _a3.reverse, unique = _a3.unique; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var index = query2.index, range = query2.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var direction = reverse ? unique ? "prevunique" : "prev" : unique ? "nextunique" : "next"; - var req = values || !("openKeyCursor" in source) ? source.openCursor(makeIDBKeyRange(range), direction) : source.openKeyCursor(makeIDBKeyRange(range), direction); - req.onerror = eventRejectHandler(reject); - req.onsuccess = wrap(function(ev) { - var cursor = req.result; - if (!cursor) { - resolve(null); - return; - } - cursor.___id = ++_id_counter; - cursor.done = false; - var _cursorContinue = cursor.continue.bind(cursor); - var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; - if (_cursorContinuePrimaryKey) - _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); - var _cursorAdvance = cursor.advance.bind(cursor); - var doThrowCursorIsNotStarted = function() { - throw new Error("Cursor not started"); - }; - var doThrowCursorIsStopped = function() { - throw new Error("Cursor not stopped"); - }; - cursor.trans = trans; - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; - cursor.fail = wrap(reject); - cursor.next = function() { - var _this = this; - var gotOne = 1; - return this.start(function() { - return gotOne-- ? _this.continue() : _this.stop(); - }).then(function() { - return _this; - }); - }; - cursor.start = function(callback) { - var iterationPromise = new Promise(function(resolveIteration, rejectIteration) { - resolveIteration = wrap(resolveIteration); - req.onerror = eventRejectHandler(rejectIteration); - cursor.fail = rejectIteration; - cursor.stop = function(value) { - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; - resolveIteration(value); - }; - }); - var guardedCallback = function() { - if (req.result) { - try { - callback(); - } catch (err) { - cursor.fail(err); - } - } else { - cursor.done = true; - cursor.start = function() { - throw new Error("Cursor behind last entry"); - }; - cursor.stop(); - } - }; - req.onsuccess = wrap(function(ev2) { - req.onsuccess = guardedCallback; - guardedCallback(); - }); - cursor.continue = _cursorContinue; - cursor.continuePrimaryKey = _cursorContinuePrimaryKey; - cursor.advance = _cursorAdvance; - guardedCallback(); - return iterationPromise; - }; - resolve(cursor); - }, reject); - }); - } - function query(hasGetAll2, hasIdb3Features2) { - return function(request) { - return new Promise(function(resolve, reject) { - var _a3; - resolve = wrap(resolve); - var trans = request.trans, values = request.values, limit = request.limit, query2 = request.query; - var direction = (_a3 = request.direction) !== null && _a3 !== void 0 ? _a3 : "next"; - var nonInfinitLimit = limit === Infinity ? void 0 : limit; - var index = query2.index, range = query2.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - if (limit === 0) - return resolve({ result: [] }); - if (hasIdb3Features2) { - var options = { - query: idbKeyRange, - count: nonInfinitLimit, - direction - }; - var req = values ? source.getAll(options) : source.getAllKeys(options); - req.onsuccess = function(event) { - return resolve({ result: event.target.result }); - }; - req.onerror = eventRejectHandler(reject); - } else if (hasGetAll2 && direction === "next") { - var req = values ? source.getAll(idbKeyRange, nonInfinitLimit) : source.getAllKeys(idbKeyRange, nonInfinitLimit); - req.onsuccess = function(event) { - return resolve({ result: event.target.result }); - }; - req.onerror = eventRejectHandler(reject); - } else { - var count_1 = 0; - var req_1 = values || !("openKeyCursor" in source) ? source.openCursor(idbKeyRange, direction) : source.openKeyCursor(idbKeyRange, direction); - var result_1 = []; - req_1.onsuccess = function() { - var cursor = req_1.result; - if (!cursor) - return resolve({ result: result_1 }); - result_1.push(values ? cursor.value : cursor.primaryKey); - if (++count_1 === limit) - return resolve({ result: result_1 }); - cursor.continue(); - }; - req_1.onerror = eventRejectHandler(reject); - } - }); - }; - } - return { - name: tableName, - schema: tableSchema, - mutate, - getMany: function(_a3) { - var trans = _a3.trans, keys2 = _a3.keys; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var length = keys2.length; - var result = new Array(length); - var keyCount = 0; - var callbackCount = 0; - var req; - var successHandler = function(event) { - var req2 = event.target; - if ((result[req2._pos] = req2.result) != null) - ; - if (++callbackCount === keyCount) - resolve(result); - }; - var errorHandler = eventRejectHandler(reject); - for (var i = 0; i < length; ++i) { - var key = keys2[i]; - if (key != null) { - req = store.get(keys2[i]); - req._pos = i; - req.onsuccess = successHandler; - req.onerror = errorHandler; - ++keyCount; - } - } - if (keyCount === 0) - resolve(result); - }); - }, - get: function(_a3) { - var trans = _a3.trans, key = _a3.key; - return new Promise(function(resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var req = store.get(key); - req.onsuccess = function(event) { - return resolve(event.target.result); - }; - req.onerror = eventRejectHandler(reject); - }); - }, - query: query(hasGetAll, hasIdb3Features), - openCursor: openCursor2, - count: function(_a3) { - var query2 = _a3.query, trans = _a3.trans; - var index = query2.index, range = query2.range; - return new Promise(function(resolve, reject) { - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); - req.onsuccess = wrap(function(ev) { - return resolve(ev.target.result); - }); - req.onerror = eventRejectHandler(reject); - }); - } - }; - } - var _a2 = extractSchema(db2, tmpTrans), schema = _a2.schema, hasGetAll = _a2.hasGetAll, hasIdb3Features = _a2.hasIdb3Features; - var tables = schema.tables.map(function(tableSchema) { - return createDbCoreTable(tableSchema); - }); - var tableMap = {}; - tables.forEach(function(table) { - return tableMap[table.name] = table; - }); - return { - stack: "dbcore", - transaction: db2.transaction.bind(db2), - table: function(name) { - var result = tableMap[name]; - if (!result) - throw new Error("Table '".concat(name, "' not found")); - return tableMap[name]; - }, - MIN_KEY: -Infinity, - MAX_KEY: getMaxKey(IdbKeyRange), - schema - }; - } - function createMiddlewareStack(stackImpl, middlewares) { - return middlewares.reduce(function(down, _a2) { - var create = _a2.create; - return __assign(__assign({}, down), create(down)); - }, stackImpl); - } - function createMiddlewareStacks(middlewares, idbdb, _a2, tmpTrans) { - var IDBKeyRange = _a2.IDBKeyRange; - _a2.indexedDB; - var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); - return { - dbcore - }; - } - function generateMiddlewareStacks(db2, tmpTrans) { - var idbdb = tmpTrans.db; - var stacks = createMiddlewareStacks(db2._middlewares, idbdb, db2._deps, tmpTrans); - db2.core = stacks.dbcore; - db2.tables.forEach(function(table) { - var tableName = table.name; - if (db2.core.schema.tables.some(function(tbl) { - return tbl.name === tableName; - })) { - table.core = db2.core.table(tableName); - if (db2[tableName] instanceof db2.Table) { - db2[tableName].core = table.core; - } - } - }); - } - function setApiOnPlace(db2, objs, tableNames, dbschema) { - tableNames.forEach(function(tableName) { - var schema = dbschema[tableName]; - objs.forEach(function(obj) { - var propDesc = getPropertyDescriptor(obj, tableName); - if (!propDesc || "value" in propDesc && propDesc.value === void 0) { - if (obj === db2.Transaction.prototype || obj instanceof db2.Transaction) { - setProp(obj, tableName, { - get: function() { - return this.table(tableName); - }, - set: function(value) { - defineProperty(this, tableName, { - value, - writable: true, - configurable: true, - enumerable: true - }); - } - }); - } else { - obj[tableName] = new db2.Table(tableName, schema); - } - } - }); - }); - } - function removeTablesApi(db2, objs) { - objs.forEach(function(obj) { - for (var key in obj) { - if (obj[key] instanceof db2.Table) - delete obj[key]; - } - }); - } - function lowerVersionFirst(a, b) { - return a._cfg.version - b._cfg.version; - } - function runUpgraders(db2, oldVersion, idbUpgradeTrans, reject) { - var globalSchema = db2._dbSchema; - if (idbUpgradeTrans.objectStoreNames.contains("$meta") && !globalSchema.$meta) { - globalSchema.$meta = createTableSchema("$meta", parseIndexSyntax("")[0], []); - db2._storeNames.push("$meta"); - } - var trans = db2._createTransaction("readwrite", db2._storeNames, globalSchema); - trans.create(idbUpgradeTrans); - trans._completion.catch(reject); - var rejectTransaction = trans._reject.bind(trans); - var transless = PSD.transless || PSD; - newScope(function() { - PSD.trans = trans; - PSD.transless = transless; - if (oldVersion === 0) { - keys(globalSchema).forEach(function(tableName) { - createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); - }); - generateMiddlewareStacks(db2, idbUpgradeTrans); - DexiePromise.follow(function() { - return db2.on.populate.fire(trans); - }).catch(rejectTransaction); - } else { - generateMiddlewareStacks(db2, idbUpgradeTrans); - return getExistingVersion(db2, trans, oldVersion).then(function(oldVersion2) { - return updateTablesAndIndexes(db2, oldVersion2, trans, idbUpgradeTrans); - }).catch(rejectTransaction); - } - }); - } - function patchCurrentVersion(db2, idbUpgradeTrans) { - createMissingTables(db2._dbSchema, idbUpgradeTrans); - if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains("$meta")) { - idbUpgradeTrans.db.createObjectStore("$meta").add(Math.ceil(idbUpgradeTrans.db.version / 10 - 1), "version"); - } - var globalSchema = buildGlobalSchema(db2, db2.idbdb, idbUpgradeTrans); - adjustToExistingIndexNames(db2, db2._dbSchema, idbUpgradeTrans); - var diff = getSchemaDiff(globalSchema, db2._dbSchema); - var _loop_1 = function(tableChange2) { - if (tableChange2.change.length || tableChange2.recreate) { - console.warn("Unable to patch indexes of table ".concat(tableChange2.name, " because it has changes on the type of index or primary key.")); - return { value: void 0 }; - } - var store = idbUpgradeTrans.objectStore(tableChange2.name); - tableChange2.add.forEach(function(idx) { - if (debug) - console.debug("Dexie upgrade patch: Creating missing index ".concat(tableChange2.name, ".").concat(idx.src)); - addIndex(store, idx); - }); - }; - for (var _i = 0, _a2 = diff.change; _i < _a2.length; _i++) { - var tableChange = _a2[_i]; - var state_1 = _loop_1(tableChange); - if (typeof state_1 === "object") - return state_1.value; - } - } - function getExistingVersion(db2, trans, oldVersion) { - if (trans.storeNames.includes("$meta")) { - return trans.table("$meta").get("version").then(function(metaVersion) { - return metaVersion != null ? metaVersion : oldVersion; - }); - } else { - return DexiePromise.resolve(oldVersion); - } - } - function updateTablesAndIndexes(db2, oldVersion, trans, idbUpgradeTrans) { - var queue = []; - var versions = db2._versions; - var globalSchema = db2._dbSchema = buildGlobalSchema(db2, db2.idbdb, idbUpgradeTrans); - var versToRun = versions.filter(function(v) { - return v._cfg.version >= oldVersion; - }); - if (versToRun.length === 0) { - return DexiePromise.resolve(); - } - versToRun.forEach(function(version) { - queue.push(function() { - var oldSchema = globalSchema; - var newSchema = version._cfg.dbschema; - adjustToExistingIndexNames(db2, oldSchema, idbUpgradeTrans); - adjustToExistingIndexNames(db2, newSchema, idbUpgradeTrans); - globalSchema = db2._dbSchema = newSchema; - var diff = getSchemaDiff(oldSchema, newSchema); - diff.add.forEach(function(tuple) { - createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); - }); - diff.change.forEach(function(change) { - if (change.recreate) { - throw new exceptions.Upgrade("Not yet support for changing primary key"); - } else { - var store_1 = idbUpgradeTrans.objectStore(change.name); - change.add.forEach(function(idx) { - return addIndex(store_1, idx); - }); - change.change.forEach(function(idx) { - store_1.deleteIndex(idx.name); - addIndex(store_1, idx); - }); - change.del.forEach(function(idxName) { - return store_1.deleteIndex(idxName); - }); - } - }); - var contentUpgrade = version._cfg.contentUpgrade; - if (contentUpgrade && version._cfg.version > oldVersion) { - generateMiddlewareStacks(db2, idbUpgradeTrans); - trans._memoizedTables = {}; - var upgradeSchema_1 = shallowClone(newSchema); - diff.del.forEach(function(table) { - upgradeSchema_1[table] = oldSchema[table]; - }); - removeTablesApi(db2, [db2.Transaction.prototype]); - setApiOnPlace(db2, [db2.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); - trans.schema = upgradeSchema_1; - var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); - if (contentUpgradeIsAsync_1) { - incrementExpectedAwaits(); - } - var returnValue_1; - var promiseFollowed = DexiePromise.follow(function() { - returnValue_1 = contentUpgrade(trans); - if (returnValue_1) { - if (contentUpgradeIsAsync_1) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue_1.then(decrementor, decrementor); - } - } - }); - return returnValue_1 && typeof returnValue_1.then === "function" ? DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function() { - return returnValue_1; - }); - } - }); - queue.push(function(idbtrans) { - var newSchema = version._cfg.dbschema; - deleteRemovedTables(newSchema, idbtrans); - removeTablesApi(db2, [db2.Transaction.prototype]); - setApiOnPlace(db2, [db2.Transaction.prototype], db2._storeNames, db2._dbSchema); - trans.schema = db2._dbSchema; - }); - queue.push(function(idbtrans) { - if (db2.idbdb.objectStoreNames.contains("$meta")) { - if (Math.ceil(db2.idbdb.version / 10) === version._cfg.version) { - db2.idbdb.deleteObjectStore("$meta"); - delete db2._dbSchema.$meta; - db2._storeNames = db2._storeNames.filter(function(name) { - return name !== "$meta"; - }); - } else { - idbtrans.objectStore("$meta").put(version._cfg.version, "version"); - } - } - }); - }); - function runQueue() { - return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : DexiePromise.resolve(); - } - return runQueue().then(function() { - createMissingTables(globalSchema, idbUpgradeTrans); - }); - } - function getSchemaDiff(oldSchema, newSchema) { - var diff = { - del: [], - add: [], - change: [] - }; - var table; - for (table in oldSchema) { - if (!newSchema[table]) - diff.del.push(table); - } - for (table in newSchema) { - var oldDef = oldSchema[table], newDef = newSchema[table]; - if (!oldDef) { - diff.add.push([table, newDef]); - } else { - var change = { - name: table, - def: newDef, - recreate: false, - del: [], - add: [], - change: [] - }; - if ("" + (oldDef.primKey.keyPath || "") !== "" + (newDef.primKey.keyPath || "") || oldDef.primKey.auto !== newDef.primKey.auto) { - change.recreate = true; - diff.change.push(change); - } else { - var oldIndexes = oldDef.idxByName; - var newIndexes = newDef.idxByName; - var idxName = void 0; - for (idxName in oldIndexes) { - if (!newIndexes[idxName]) - change.del.push(idxName); - } - for (idxName in newIndexes) { - var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; - if (!oldIdx) - change.add.push(newIdx); - else if (oldIdx.src !== newIdx.src) - change.change.push(newIdx); - } - if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { - diff.change.push(change); - } - } - } - } - return diff; - } - function createTable(idbtrans, tableName, primKey, indexes) { - var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); - indexes.forEach(function(idx) { - return addIndex(store, idx); - }); - return store; - } - function createMissingTables(newSchema, idbtrans) { - keys(newSchema).forEach(function(tableName) { - if (!idbtrans.db.objectStoreNames.contains(tableName)) { - if (debug) - console.debug("Dexie: Creating missing table", tableName); - createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); - } - }); - } - function deleteRemovedTables(newSchema, idbtrans) { - [].slice.call(idbtrans.db.objectStoreNames).forEach(function(storeName) { - return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName); - }); - } - function addIndex(store, idx) { - store.createIndex(idx.name, idx.keyPath, { - unique: idx.unique, - multiEntry: idx.multi - }); - } - function buildGlobalSchema(db2, idbdb, tmpTrans) { - var globalSchema = {}; - var dbStoreNames = slice(idbdb.objectStoreNames, 0); - dbStoreNames.forEach(function(storeName) { - var store = tmpTrans.objectStore(storeName); - var keyPath = store.keyPath; - var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", true, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); - var indexes = []; - for (var j = 0; j < store.indexNames.length; ++j) { - var idbindex = store.index(store.indexNames[j]); - keyPath = idbindex.keyPath; - var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); - indexes.push(index); - } - globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); - }); - return globalSchema; - } - function readGlobalSchema(db2, idbdb, tmpTrans) { - db2.verno = idbdb.version / 10; - var globalSchema = db2._dbSchema = buildGlobalSchema(db2, idbdb, tmpTrans); - db2._storeNames = slice(idbdb.objectStoreNames, 0); - setApiOnPlace(db2, [db2._allTables], keys(globalSchema), globalSchema); - } - function verifyInstalledSchema(db2, tmpTrans) { - var installedSchema = buildGlobalSchema(db2, db2.idbdb, tmpTrans); - var diff = getSchemaDiff(installedSchema, db2._dbSchema); - return !(diff.add.length || diff.change.some(function(ch) { - return ch.add.length || ch.change.length; - })); - } - function adjustToExistingIndexNames(db2, schema, idbtrans) { - var storeNames = idbtrans.db.objectStoreNames; - for (var i = 0; i < storeNames.length; ++i) { - var storeName = storeNames[i]; - var store = idbtrans.objectStore(storeName); - db2._hasGetAll = "getAll" in store; - for (var j = 0; j < store.indexNames.length; ++j) { - var indexName = store.indexNames[j]; - var keyPath = store.index(indexName).keyPath; - var dexieName = typeof keyPath === "string" ? keyPath : "[" + slice(keyPath).join("+") + "]"; - if (schema[storeName]) { - var indexSpec = schema[storeName].idxByName[dexieName]; - if (indexSpec) { - indexSpec.name = indexName; - delete schema[storeName].idxByName[dexieName]; - schema[storeName].idxByName[indexName] = indexSpec; - } - } - } - } - if (typeof navigator !== "undefined" && /Safari/.test(navigator.userAgent) && !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { - db2._hasGetAll = false; - } - } - function parseIndexSyntax(primKeyAndIndexes) { - return primKeyAndIndexes.split(",").map(function(index, indexNum) { - var _a2; - var typeSplit = index.split(":"); - var type2 = (_a2 = typeSplit[1]) === null || _a2 === void 0 ? void 0 : _a2.trim(); - index = typeSplit[0].trim(); - var name = index.replace(/([&*]|\+\+)/g, ""); - var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split("+") : name; - return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0, type2); - }); - } - var Version = function() { - function Version2() { - } - Version2.prototype._createTableSchema = function(name, primKey, indexes) { - return createTableSchema(name, primKey, indexes); - }; - Version2.prototype._parseIndexSyntax = function(primKeyAndIndexes) { - return parseIndexSyntax(primKeyAndIndexes); - }; - Version2.prototype._parseStoresSpec = function(stores, outSchema) { - var _this = this; - keys(stores).forEach(function(tableName) { - if (stores[tableName] !== null) { - var indexes = _this._parseIndexSyntax(stores[tableName]); - var primKey = indexes.shift(); - if (!primKey) { - throw new exceptions.Schema("Invalid schema for table " + tableName + ": " + stores[tableName]); - } - primKey.unique = true; - if (primKey.multi) - throw new exceptions.Schema("Primary key cannot be multiEntry*"); - indexes.forEach(function(idx) { - if (idx.auto) - throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); - if (!idx.keyPath) - throw new exceptions.Schema("Index must have a name and cannot be an empty string"); - }); - var tblSchema = _this._createTableSchema(tableName, primKey, indexes); - outSchema[tableName] = tblSchema; - } - }); - }; - Version2.prototype.stores = function(stores) { - var db2 = this.db; - this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; - var versions = db2._versions; - var storesSpec = {}; - var dbschema = {}; - versions.forEach(function(version) { - extend(storesSpec, version._cfg.storesSource); - dbschema = version._cfg.dbschema = {}; - version._parseStoresSpec(storesSpec, dbschema); - }); - db2._dbSchema = dbschema; - removeTablesApi(db2, [db2._allTables, db2, db2.Transaction.prototype]); - setApiOnPlace(db2, [db2._allTables, db2, db2.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); - db2._storeNames = keys(dbschema); - return this; - }; - Version2.prototype.upgrade = function(upgradeFunction) { - this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); - return this; - }; - return Version2; - }(); - function createVersionConstructor(db2) { - return makeClassConstructor(Version.prototype, function Version2(versionNumber) { - this.db = db2; - this._cfg = { - version: versionNumber, - storesSource: null, - dbschema: {}, - tables: {}, - contentUpgrade: null - }; - }); - } - var connections = createConnectionsManager(); - function createConnectionsManager() { - if (typeof FinalizationRegistry !== "undefined" && typeof WeakRef !== "undefined") { - var _refs_1 = /* @__PURE__ */ new Set(); - var _registry_1 = new FinalizationRegistry(function(ref2) { - _refs_1.delete(ref2); - }); - var toArray = function() { - return Array.from(_refs_1).map(function(ref2) { - return ref2.deref(); - }).filter(function(db2) { - return db2 !== void 0; - }); - }; - var add3 = function(db2) { - var ref2 = new WeakRef(db2._novip); - _refs_1.add(ref2); - _registry_1.register(db2._novip, ref2, ref2); - if (_refs_1.size > db2._options.maxConnections) { - var oldestRef = _refs_1.values().next().value; - _refs_1.delete(oldestRef); - _registry_1.unregister(oldestRef); - } - }; - var remove3 = function(db2) { - if (!db2) - return; - var iterator = _refs_1.values(); - var result = iterator.next(); - while (!result.done) { - var ref2 = result.value; - if (ref2.deref() === db2._novip) { - _refs_1.delete(ref2); - _registry_1.unregister(ref2); - return; - } - result = iterator.next(); - } - }; - return { toArray, add: add3, remove: remove3 }; - } else { - var connections_1 = []; - var toArray = function() { - return connections_1; - }; - var add3 = function(db2) { - connections_1.push(db2._novip); - }; - var remove3 = function(db2) { - if (!db2) - return; - var index = connections_1.indexOf(db2._novip); - if (index !== -1) { - connections_1.splice(index, 1); - } - }; - return { toArray, add: add3, remove: remove3 }; - } - } - function getDbNamesTable(indexedDB2, IDBKeyRange) { - var dbNamesDB = indexedDB2["_dbNamesDB"]; - if (!dbNamesDB) { - dbNamesDB = indexedDB2["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { - addons: [], - indexedDB: indexedDB2, - IDBKeyRange - }); - dbNamesDB.version(1).stores({ dbnames: "name" }); - } - return dbNamesDB.table("dbnames"); - } - function hasDatabasesNative(indexedDB2) { - return indexedDB2 && typeof indexedDB2.databases === "function"; - } - function getDatabaseNames(_a2) { - var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; - return hasDatabasesNative(indexedDB2) ? Promise.resolve(indexedDB2.databases()).then(function(infos) { - return infos.map(function(info) { - return info.name; - }).filter(function(name) { - return name !== DBNAMES_DB; - }); - }) : getDbNamesTable(indexedDB2, IDBKeyRange).toCollection().primaryKeys(); - } - function _onDatabaseCreated(_a2, name) { - var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; - !hasDatabasesNative(indexedDB2) && name !== DBNAMES_DB && getDbNamesTable(indexedDB2, IDBKeyRange).put({ name }).catch(nop); - } - function _onDatabaseDeleted(_a2, name) { - var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; - !hasDatabasesNative(indexedDB2) && name !== DBNAMES_DB && getDbNamesTable(indexedDB2, IDBKeyRange).delete(name).catch(nop); - } - function vip(fn) { - return newScope(function() { - PSD.letThrough = true; - return fn(); - }); - } - function idbReady() { - var isSafari = !navigator.userAgentData && /Safari\//.test(navigator.userAgent) && !/Chrom(e|ium)\//.test(navigator.userAgent); - if (!isSafari || !indexedDB.databases) - return Promise.resolve(); - var intervalId; - return new Promise(function(resolve) { - var tryIdb = function() { - return indexedDB.databases().finally(resolve); - }; - intervalId = setInterval(tryIdb, 100); - tryIdb(); - }).finally(function() { - return clearInterval(intervalId); - }); - } - var _a; - function isEmptyRange(node) { - return !("from" in node); - } - var RangeSet2 = function(fromOrTree, to) { - if (this) { - extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); - } else { - var rv = new RangeSet2(); - if (fromOrTree && "d" in fromOrTree) { - extend(rv, fromOrTree); - } - return rv; - } - }; - props(RangeSet2.prototype, (_a = { - add: function(rangeSet) { - mergeRanges2(this, rangeSet); - return this; - }, - addKey: function(key) { - addRange(this, key, key); - return this; - }, - addKeys: function(keys2) { - var _this = this; - keys2.forEach(function(key) { - return addRange(_this, key, key); - }); - return this; - }, - hasKey: function(key) { - var node = getRangeSetIterator(this).next(key).value; - return node && cmp3(node.from, key) <= 0 && cmp3(node.to, key) >= 0; - } - }, _a[iteratorSymbol] = function() { - return getRangeSetIterator(this); - }, _a)); - function addRange(target, from, to) { - var diff = cmp3(from, to); - if (isNaN(diff)) - return; - if (diff > 0) - throw RangeError(); - if (isEmptyRange(target)) - return extend(target, { from, to, d: 1 }); - var left = target.l; - var right = target.r; - if (cmp3(to, target.from) < 0) { - left ? addRange(left, from, to) : target.l = { from, to, d: 1, l: null, r: null }; - return rebalance(target); - } - if (cmp3(from, target.to) > 0) { - right ? addRange(right, from, to) : target.r = { from, to, d: 1, l: null, r: null }; - return rebalance(target); - } - if (cmp3(from, target.from) < 0) { - target.from = from; - target.l = null; - target.d = right ? right.d + 1 : 1; - } - if (cmp3(to, target.to) > 0) { - target.to = to; - target.r = null; - target.d = target.l ? target.l.d + 1 : 1; - } - var rightWasCutOff = !target.r; - if (left && !target.l) { - mergeRanges2(target, left); - } - if (right && rightWasCutOff) { - mergeRanges2(target, right); - } - } - function mergeRanges2(target, newSet) { - function _addRangeSet(target2, _a2) { - var from = _a2.from, to = _a2.to, l = _a2.l, r = _a2.r; - addRange(target2, from, to); - if (l) - _addRangeSet(target2, l); - if (r) - _addRangeSet(target2, r); - } - if (!isEmptyRange(newSet)) - _addRangeSet(target, newSet); - } - function rangesOverlap2(rangeSet1, rangeSet2) { - var i1 = getRangeSetIterator(rangeSet2); - var nextResult1 = i1.next(); - if (nextResult1.done) - return false; - var a = nextResult1.value; - var i2 = getRangeSetIterator(rangeSet1); - var nextResult2 = i2.next(a.from); - var b = nextResult2.value; - while (!nextResult1.done && !nextResult2.done) { - if (cmp3(b.from, a.to) <= 0 && cmp3(b.to, a.from) >= 0) - return true; - cmp3(a.from, b.from) < 0 ? a = (nextResult1 = i1.next(b.from)).value : b = (nextResult2 = i2.next(a.from)).value; - } - return false; - } - function getRangeSetIterator(node) { - var state = isEmptyRange(node) ? null : { s: 0, n: node }; - return { - next: function(key) { - var keyProvided = arguments.length > 0; - while (state) { - switch (state.s) { - case 0: - state.s = 1; - if (keyProvided) { - while (state.n.l && cmp3(key, state.n.from) < 0) - state = { up: state, n: state.n.l, s: 1 }; - } else { - while (state.n.l) - state = { up: state, n: state.n.l, s: 1 }; - } - case 1: - state.s = 2; - if (!keyProvided || cmp3(key, state.n.to) <= 0) - return { value: state.n, done: false }; - case 2: - if (state.n.r) { - state.s = 3; - state = { up: state, n: state.n.r, s: 0 }; - continue; - } - case 3: - state = state.up; - } - } - return { done: true }; - } - }; - } - function rebalance(target) { - var _a2, _b; - var diff = (((_a2 = target.r) === null || _a2 === void 0 ? void 0 : _a2.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); - var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; - if (r) { - var l = r === "r" ? "l" : "r"; - var rootClone = __assign({}, target); - var oldRootRight = target[r]; - target.from = oldRootRight.from; - target.to = oldRootRight.to; - target[r] = oldRootRight[r]; - rootClone[r] = oldRootRight[l]; - target[l] = rootClone; - rootClone.d = computeDepth(rootClone); - } - target.d = computeDepth(target); - } - function computeDepth(_a2) { - var r = _a2.r, l = _a2.l; - return (r ? l ? Math.max(r.d, l.d) : r.d : l ? l.d : 0) + 1; - } - function extendObservabilitySet(target, newSet) { - keys(newSet).forEach(function(part) { - if (target[part]) - mergeRanges2(target[part], newSet[part]); - else - target[part] = cloneSimpleObjectTree(newSet[part]); - }); - return target; - } - function obsSetsOverlap(os1, os2) { - return os1.all || os2.all || Object.keys(os1).some(function(key) { - return os2[key] && rangesOverlap2(os2[key], os1[key]); - }); - } - var cache = {}; - var unsignaledParts = {}; - var isTaskEnqueued = false; - function signalSubscribersLazily(part, optimistic) { - extendObservabilitySet(unsignaledParts, part); - if (!isTaskEnqueued) { - isTaskEnqueued = true; - setTimeout(function() { - isTaskEnqueued = false; - var parts = unsignaledParts; - unsignaledParts = {}; - signalSubscribersNow(parts, false); - }, 0); - } - } - function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) { - if (deleteAffectedCacheEntries === void 0) { - deleteAffectedCacheEntries = false; - } - var queriesToSignal = /* @__PURE__ */ new Set(); - if (updatedParts.all) { - for (var _i = 0, _a2 = Object.values(cache); _i < _a2.length; _i++) { - var tblCache = _a2[_i]; - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } else { - for (var key in updatedParts) { - var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); - if (parts) { - var dbName = parts[1], tableName = parts[2]; - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (tblCache) - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } - } - queriesToSignal.forEach(function(requery) { - return requery(); - }); - } - function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { - var updatedEntryLists = []; - for (var _i = 0, _a2 = Object.entries(tblCache.queries.query); _i < _a2.length; _i++) { - var _b = _a2[_i], indexName = _b[0], entries = _b[1]; - var filteredEntries = []; - for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) { - var entry = entries_1[_c]; - if (obsSetsOverlap(updatedParts, entry.obsSet)) { - entry.subscribers.forEach(function(requery) { - return outQueriesToSignal.add(requery); - }); - } else if (deleteAffectedCacheEntries) { - filteredEntries.push(entry); - } - } - if (deleteAffectedCacheEntries) - updatedEntryLists.push([indexName, filteredEntries]); - } - if (deleteAffectedCacheEntries) { - for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) { - var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1]; - tblCache.queries.query[indexName] = filteredEntries; - } - } - } - function dexieOpen(db2) { - var state = db2._state; - var indexedDB2 = db2._deps.indexedDB; - if (state.isBeingOpened || db2.idbdb) - return state.dbReadyPromise.then(function() { - return state.dbOpenError ? rejection(state.dbOpenError) : db2; - }); - state.isBeingOpened = true; - state.dbOpenError = null; - state.openComplete = false; - var openCanceller = state.openCanceller; - var nativeVerToOpen = Math.round(db2.verno * 10); - var schemaPatchMode = false; - function throwIfCancelled() { - if (state.openCanceller !== openCanceller) - throw new exceptions.DatabaseClosed("db.open() was cancelled"); - } - var resolveDbReady = state.dbReadyResolve, upgradeTransaction = null, wasCreated = false; - var tryOpenDB = function() { - return new DexiePromise(function(resolve, reject) { - throwIfCancelled(); - if (!indexedDB2) - throw new exceptions.MissingAPI(); - var dbName = db2.name; - var req = state.autoSchema || !nativeVerToOpen ? indexedDB2.open(dbName) : indexedDB2.open(dbName, nativeVerToOpen); - if (!req) - throw new exceptions.MissingAPI(); - req.onerror = eventRejectHandler(reject); - req.onblocked = wrap(db2._fireOnBlocked); - req.onupgradeneeded = wrap(function(e) { - upgradeTransaction = req.transaction; - if (state.autoSchema && !db2._options.allowEmptyDB) { - req.onerror = preventDefault; - upgradeTransaction.abort(); - req.result.close(); - var delreq = indexedDB2.deleteDatabase(dbName); - delreq.onsuccess = delreq.onerror = wrap(function() { - reject(new exceptions.NoSuchDatabase("Database ".concat(dbName, " doesnt exist"))); - }); - } else { - upgradeTransaction.onerror = eventRejectHandler(reject); - var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; - wasCreated = oldVer < 1; - db2.idbdb = req.result; - if (schemaPatchMode) { - patchCurrentVersion(db2, upgradeTransaction); - } - runUpgraders(db2, oldVer / 10, upgradeTransaction, reject); - } - }, reject); - req.onsuccess = wrap(function() { - upgradeTransaction = null; - var idbdb = db2.idbdb = req.result; - var objectStoreNames = slice(idbdb.objectStoreNames); - if (objectStoreNames.length > 0) - try { - var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), "readonly"); - if (state.autoSchema) - readGlobalSchema(db2, idbdb, tmpTrans); - else { - adjustToExistingIndexNames(db2, db2._dbSchema, tmpTrans); - if (!verifyInstalledSchema(db2, tmpTrans) && !schemaPatchMode) { - console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."); - idbdb.close(); - nativeVerToOpen = idbdb.version + 1; - schemaPatchMode = true; - return resolve(tryOpenDB()); - } - } - generateMiddlewareStacks(db2, tmpTrans); - } catch (e) { - } - connections.add(db2); - idbdb.onversionchange = wrap(function(ev) { - state.vcFired = true; - db2.on("versionchange").fire(ev); - }); - idbdb.onclose = wrap(function() { - db2.close({ disableAutoOpen: false }); - }); - if (wasCreated) - _onDatabaseCreated(db2._deps, dbName); - resolve(); - }, reject); - }).catch(function(err) { - switch (err === null || err === void 0 ? void 0 : err.name) { - case "UnknownError": - if (state.PR1398_maxLoop > 0) { - state.PR1398_maxLoop--; - console.warn("Dexie: Workaround for Chrome UnknownError on open()"); - return tryOpenDB(); - } - break; - case "VersionError": - if (nativeVerToOpen > 0) { - nativeVerToOpen = 0; - return tryOpenDB(); - } - break; - } - return DexiePromise.reject(err); - }); - }; - return DexiePromise.race([ - openCanceller, - (typeof navigator === "undefined" ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) - ]).then(function() { - throwIfCancelled(); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function() { - return db2.on.ready.fire(db2.vip); - })).then(function fireRemainders() { - if (state.onReadyBeingFired.length > 0) { - var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function() { - return remainders_1(db2.vip); - })).then(fireRemainders); - } - }); - }).finally(function() { - if (state.openCanceller === openCanceller) { - state.onReadyBeingFired = null; - state.isBeingOpened = false; - } - }).catch(function(err) { - state.dbOpenError = err; - try { - upgradeTransaction && upgradeTransaction.abort(); - } catch (_a2) { - } - if (openCanceller === state.openCanceller) { - db2._close(); - } - return rejection(err); - }).finally(function() { - state.openComplete = true; - resolveDbReady(); - }).then(function() { - if (wasCreated) { - var everything_1 = {}; - db2.tables.forEach(function(table) { - table.schema.indexes.forEach(function(idx) { - if (idx.name) - everything_1["idb://".concat(db2.name, "/").concat(table.name, "/").concat(idx.name)] = new RangeSet2(-Infinity, [[[]]]); - }); - everything_1["idb://".concat(db2.name, "/").concat(table.name, "/")] = everything_1["idb://".concat(db2.name, "/").concat(table.name, "/:dels")] = new RangeSet2(-Infinity, [[[]]]); - }); - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1); - signalSubscribersNow(everything_1, true); - } - return db2; - }); - } - function awaitIterator(iterator) { - var callNext = function(result) { - return iterator.next(result); - }, doThrow = function(error) { - return iterator.throw(error); - }, onSuccess = step(callNext), onError = step(doThrow); - function step(getNext) { - return function(val) { - var next = getNext(val), value = next.value; - return next.done ? value : !value || typeof value.then !== "function" ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError); - }; - } - return step(callNext)(); - } - function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { - var i = arguments.length; - if (i < 2) - throw new exceptions.InvalidArgument("Too few arguments"); - var args = new Array(i - 1); - while (--i) - args[i - 1] = arguments[i]; - scopeFunc = args.pop(); - var tables = flatten(args); - return [mode, tables, scopeFunc]; - } - function enterTransactionScope(db2, mode, storeNames, parentTransaction, scopeFunc) { - return DexiePromise.resolve().then(function() { - var transless = PSD.transless || PSD; - var trans = db2._createTransaction(mode, storeNames, db2._dbSchema, parentTransaction); - trans.explicit = true; - var zoneProps = { - trans, - transless - }; - if (parentTransaction) { - trans.idbtrans = parentTransaction.idbtrans; - } else { - try { - trans.create(); - trans.idbtrans._explicit = true; - db2._state.PR1398_maxLoop = 3; - } catch (ex) { - if (ex.name === errnames.InvalidState && db2.isOpen() && --db2._state.PR1398_maxLoop > 0) { - console.warn("Dexie: Need to reopen db"); - db2.close({ disableAutoOpen: false }); - return db2.open().then(function() { - return enterTransactionScope(db2, mode, storeNames, null, scopeFunc); - }); - } - return rejection(ex); - } - } - var scopeFuncIsAsync = isAsyncFunction(scopeFunc); - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var returnValue; - var promiseFollowed = DexiePromise.follow(function() { - returnValue = scopeFunc.call(trans, trans); - if (returnValue) { - if (scopeFuncIsAsync) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue.then(decrementor, decrementor); - } else if (typeof returnValue.next === "function" && typeof returnValue.throw === "function") { - returnValue = awaitIterator(returnValue); - } - } - }, zoneProps); - return (returnValue && typeof returnValue.then === "function" ? DexiePromise.resolve(returnValue).then(function(x) { - return trans.active ? x : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); - }) : promiseFollowed.then(function() { - return returnValue; - })).then(function(x) { - if (parentTransaction) - trans._resolve(); - return trans._completion.then(function() { - return x; - }); - }).catch(function(e) { - trans._reject(e); - return rejection(e); - }); - }); - } - function pad2(a, value, count) { - var result = isArray(a) ? a.slice() : [a]; - for (var i = 0; i < count; ++i) - result.push(value); - return result; - } - function createVirtualIndexMiddleware(down) { - return __assign(__assign({}, down), { table: function(tableName) { - var table = down.table(tableName); - var schema = table.schema; - var indexLookup = /* @__PURE__ */ Object.create(null); - var allVirtualIndexes = []; - function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { - var keyPathAlias = getKeyPathAlias(keyPath); - var indexList = indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []; - var keyLength = keyPath == null ? 0 : typeof keyPath === "string" ? 1 : keyPath.length; - var isVirtual = keyTail > 0; - var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual ? "".concat(keyPathAlias, "(virtual-from:").concat(lowLevelIndex.name, ")") : lowLevelIndex.name, lowLevelIndex, isVirtual, keyTail, keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); - indexList.push(virtualIndex); - if (!virtualIndex.isPrimaryKey) { - allVirtualIndexes.push(virtualIndex); - } - if (keyLength > 1) { - var virtualKeyPath = keyLength === 2 ? keyPath[0] : keyPath.slice(0, keyLength - 1); - addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); - } - indexList.sort(function(a, b) { - return a.keyTail - b.keyTail; - }); - return virtualIndex; - } - var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); - indexLookup[":id"] = [primaryKey]; - for (var _i = 0, _a2 = schema.indexes; _i < _a2.length; _i++) { - var index = _a2[_i]; - addVirtualIndexes(index.keyPath, 0, index); - } - function findBestIndex(keyPath) { - var result2 = indexLookup[getKeyPathAlias(keyPath)]; - return result2 && result2[0]; - } - function translateRange(range, keyTail) { - return { - type: range.type === 1 ? 2 : range.type, - lower: pad2(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), - lowerOpen: true, - upper: pad2(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), - upperOpen: true - }; - } - function translateRequest(req) { - var index2 = req.query.index; - return index2.isVirtual ? __assign(__assign({}, req), { query: { - index: index2.lowLevelIndex, - range: translateRange(req.query.range, index2.keyTail) - } }) : req; - } - var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function(req) { - return table.count(translateRequest(req)); - }, query: function(req) { - return table.query(translateRequest(req)); - }, openCursor: function(req) { - var _a3 = req.query.index, keyTail = _a3.keyTail, isVirtual = _a3.isVirtual, keyLength = _a3.keyLength; - if (!isVirtual) - return table.openCursor(req); - function createVirtualCursor(cursor) { - function _continue(key) { - key != null ? cursor.continue(pad2(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : req.unique ? cursor.continue(cursor.key.slice(0, keyLength).concat(req.reverse ? down.MIN_KEY : down.MAX_KEY, keyTail)) : cursor.continue(); - } - var virtualCursor = Object.create(cursor, { - continue: { value: _continue }, - continuePrimaryKey: { - value: function(key, primaryKey2) { - cursor.continuePrimaryKey(pad2(key, down.MAX_KEY, keyTail), primaryKey2); - } - }, - primaryKey: { - get: function() { - return cursor.primaryKey; - } - }, - key: { - get: function() { - var key = cursor.key; - return keyLength === 1 ? key[0] : key.slice(0, keyLength); - } - }, - value: { - get: function() { - return cursor.value; - } - } - }); - return virtualCursor; - } - return table.openCursor(translateRequest(req)).then(function(cursor) { - return cursor && createVirtualCursor(cursor); - }); - } }); - return result; - } }); - } - var virtualIndexMiddleware = { - stack: "dbcore", - name: "VirtualIndexMiddleware", - level: 1, - create: createVirtualIndexMiddleware - }; - function getObjectDiff(a, b, rv, prfx) { - rv = rv || {}; - prfx = prfx || ""; - keys(a).forEach(function(prop) { - if (!hasOwn(b, prop)) { - rv[prfx + prop] = void 0; - } else { - var ap = a[prop], bp = b[prop]; - if (typeof ap === "object" && typeof bp === "object" && ap && bp) { - var apTypeName = toStringTag(ap); - var bpTypeName = toStringTag(bp); - if (apTypeName !== bpTypeName) { - rv[prfx + prop] = b[prop]; - } else if (apTypeName === "Object") { - getObjectDiff(ap, bp, rv, prfx + prop + "."); - } else if (ap !== bp) { - rv[prfx + prop] = b[prop]; - } - } else if (ap !== bp) - rv[prfx + prop] = b[prop]; - } - }); - keys(b).forEach(function(prop) { - if (!hasOwn(a, prop)) { - rv[prfx + prop] = b[prop]; - } - }); - return rv; - } - function getEffectiveKeys(primaryKey, req) { - if (req.type === "delete") - return req.keys; - return req.keys || req.values.map(primaryKey.extractKey); - } - var hooksMiddleware = { - stack: "dbcore", - name: "HooksMiddleware", - level: 2, - create: function(downCore) { - return __assign(__assign({}, downCore), { table: function(tableName) { - var downTable = downCore.table(tableName); - var primaryKey = downTable.schema.primaryKey; - var tableMiddleware = __assign(__assign({}, downTable), { mutate: function(req) { - var dxTrans = PSD.trans; - var _a2 = dxTrans.table(tableName).hook, deleting = _a2.deleting, creating = _a2.creating, updating = _a2.updating; - switch (req.type) { - case "add": - if (creating.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return addPutOrDelete(req); - }, true); - case "put": - if (creating.fire === nop && updating.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return addPutOrDelete(req); - }, true); - case "delete": - if (deleting.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return addPutOrDelete(req); - }, true); - case "deleteRange": - if (deleting.fire === nop) - break; - return dxTrans._promise("readwrite", function() { - return deleteRange(req); - }, true); - } - return downTable.mutate(req); - function addPutOrDelete(req2) { - var dxTrans2 = PSD.trans; - var keys2 = req2.keys || getEffectiveKeys(primaryKey, req2); - if (!keys2) - throw new Error("Keys missing"); - req2 = req2.type === "add" || req2.type === "put" ? __assign(__assign({}, req2), { keys: keys2 }) : __assign({}, req2); - if (req2.type !== "delete") - req2.values = __spreadArray([], req2.values, true); - if (req2.keys) - req2.keys = __spreadArray([], req2.keys, true); - return getExistingValues(downTable, req2, keys2).then(function(existingValues) { - var contexts = keys2.map(function(key, i) { - var existingValue = existingValues[i]; - var ctx = { onerror: null, onsuccess: null }; - if (req2.type === "delete") { - deleting.fire.call(ctx, key, existingValue, dxTrans2); - } else if (req2.type === "add" || existingValue === void 0) { - var generatedPrimaryKey = creating.fire.call(ctx, key, req2.values[i], dxTrans2); - if (key == null && generatedPrimaryKey != null) { - key = generatedPrimaryKey; - req2.keys[i] = key; - if (!primaryKey.outbound) { - setByKeyPath(req2.values[i], primaryKey.keyPath, key); - } - } - } else { - var objectDiff = getObjectDiff(existingValue, req2.values[i]); - var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans2); - if (additionalChanges_1) { - var requestedValue_1 = req2.values[i]; - Object.keys(additionalChanges_1).forEach(function(keyPath) { - if (hasOwn(requestedValue_1, keyPath)) { - requestedValue_1[keyPath] = additionalChanges_1[keyPath]; - } else { - setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); - } - }); - } - } - return ctx; - }); - return downTable.mutate(req2).then(function(_a3) { - var failures = _a3.failures, results = _a3.results, numFailures = _a3.numFailures, lastResult = _a3.lastResult; - for (var i = 0; i < keys2.length; ++i) { - var primKey = results ? results[i] : keys2[i]; - var ctx = contexts[i]; - if (primKey == null) { - ctx.onerror && ctx.onerror(failures[i]); - } else { - ctx.onsuccess && ctx.onsuccess( - req2.type === "put" && existingValues[i] ? req2.values[i] : primKey - ); - } - } - return { failures, results, numFailures, lastResult }; - }).catch(function(error) { - contexts.forEach(function(ctx) { - return ctx.onerror && ctx.onerror(error); - }); - return Promise.reject(error); - }); - }); - } - function deleteRange(req2) { - return deleteNextChunk(req2.trans, req2.range, 1e4); - } - function deleteNextChunk(trans, range, limit) { - return downTable.query({ - trans, - values: false, - query: { index: primaryKey, range }, - limit - }).then(function(_a3) { - var result = _a3.result; - return addPutOrDelete({ - type: "delete", - keys: result, - trans - }).then(function(res) { - if (res.numFailures > 0) - return Promise.reject(res.failures[0]); - if (result.length < limit) { - return { - failures: [], - numFailures: 0, - lastResult: void 0 - }; - } else { - return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); - } - }); - }); - } - } }); - return tableMiddleware; - } }); - } - }; - function getExistingValues(table, req, effectiveKeys) { - return req.type === "add" ? Promise.resolve([]) : table.getMany({ - trans: req.trans, - keys: effectiveKeys, - cache: "immutable" - }); - } - function getFromTransactionCache(keys2, cache2, clone) { - try { - if (!cache2) - return null; - if (cache2.keys.length < keys2.length) - return null; - var result = []; - for (var i = 0, j = 0; i < cache2.keys.length && j < keys2.length; ++i) { - if (cmp3(cache2.keys[i], keys2[j]) !== 0) - continue; - result.push(clone ? deepClone(cache2.values[i]) : cache2.values[i]); - ++j; - } - return result.length === keys2.length ? result : null; - } catch (_a2) { - return null; - } - } - var cacheExistingValuesMiddleware = { - stack: "dbcore", - level: -1, - create: function(core) { - return { - table: function(tableName) { - var table = core.table(tableName); - return __assign(__assign({}, table), { getMany: function(req) { - if (!req.cache) { - return table.getMany(req); - } - var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); - if (cachedResult) { - return DexiePromise.resolve(cachedResult); - } - return table.getMany(req).then(function(res) { - req.trans["_cache"] = { - keys: req.keys, - values: req.cache === "clone" ? deepClone(res) : res - }; - return res; - }); - }, mutate: function(req) { - if (req.type !== "add") - req.trans["_cache"] = null; - return table.mutate(req); - } }); - } - }; - } - }; - function isCachableContext(ctx, table) { - return ctx.trans.mode === "readonly" && !!ctx.subscr && !ctx.trans.explicit && ctx.trans.db._options.cache !== "disabled" && !table.schema.primaryKey.outbound; - } - function isCachableRequest(type2, req) { - switch (type2) { - case "query": - return req.values && !req.unique; - case "get": - return false; - case "getMany": - return false; - case "count": - return false; - case "openCursor": - return false; - } - } - var observabilityMiddleware = { - stack: "dbcore", - level: 0, - name: "Observability", - create: function(core) { - var dbName = core.schema.name; - var FULL_RANGE = new RangeSet2(core.MIN_KEY, core.MAX_KEY); - return __assign(__assign({}, core), { transaction: function(stores, mode, options) { - if (PSD.subscr && mode !== "readonly") { - throw new exceptions.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(PSD.querier)); - } - return core.transaction(stores, mode, options); - }, table: function(tableName) { - var table = core.table(tableName); - var schema = table.schema; - var primaryKey = schema.primaryKey, indexes = schema.indexes; - var extractKey2 = primaryKey.extractKey, outbound = primaryKey.outbound; - var indexesWithAutoIncPK = primaryKey.autoIncrement && indexes.filter(function(index) { - return index.compound && index.keyPath.includes(primaryKey.keyPath); - }); - var tableClone = __assign(__assign({}, table), { mutate: function(req) { - var _a2, _b; - var trans = req.trans; - var mutatedParts = req.mutatedParts || (req.mutatedParts = {}); - var getRangeSet = function(indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return mutatedParts[part] || (mutatedParts[part] = new RangeSet2()); - }; - var pkRangeSet = getRangeSet(""); - var delsRangeSet = getRangeSet(":dels"); - var type2 = req.type; - var _c = req.type === "deleteRange" ? [req.range] : req.type === "delete" ? [req.keys] : req.values.length < 50 ? [ - getEffectiveKeys(primaryKey, req).filter(function(id) { - return id; - }), - req.values - ] : [], keys2 = _c[0], newObjs = _c[1]; - var oldCache = req.trans["_cache"]; - if (isArray(keys2)) { - pkRangeSet.addKeys(keys2); - var oldObjs = type2 === "delete" || keys2.length === newObjs.length ? getFromTransactionCache(keys2, oldCache) : null; - if (!oldObjs) { - delsRangeSet.addKeys(keys2); - } - if (oldObjs || newObjs) { - trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); - } - } else if (keys2) { - var range = { - from: (_a2 = keys2.lower) !== null && _a2 !== void 0 ? _a2 : core.MIN_KEY, - to: (_b = keys2.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY - }; - delsRangeSet.add(range); - pkRangeSet.add(range); - } else { - pkRangeSet.add(FULL_RANGE); - delsRangeSet.add(FULL_RANGE); - schema.indexes.forEach(function(idx) { - return getRangeSet(idx.name).add(FULL_RANGE); - }); - } - return table.mutate(req).then(function(res) { - if (keys2 && (req.type === "add" || req.type === "put")) { - pkRangeSet.addKeys(res.results); - if (indexesWithAutoIncPK) { - indexesWithAutoIncPK.forEach(function(idx) { - var idxVals = req.values.map(function(v) { - return idx.extractKey(v); - }); - var pkPos = idx.keyPath.findIndex(function(prop) { - return prop === primaryKey.keyPath; - }); - for (var i = 0, len = res.results.length; i < len; ++i) { - idxVals[i][pkPos] = res.results[i]; - } - getRangeSet(idx.name).addKeys(idxVals); - }); - } - } - trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); - return res; - }); - } }); - var getRange = function(_a2) { - var _b, _c; - var _d = _a2.query, index = _d.index, range = _d.range; - return [ - index, - new RangeSet2((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY) - ]; - }; - var readSubscribers = { - get: function(req) { - return [primaryKey, new RangeSet2(req.key)]; - }, - getMany: function(req) { - return [primaryKey, new RangeSet2().addKeys(req.keys)]; - }, - count: getRange, - query: getRange, - openCursor: getRange - }; - keys(readSubscribers).forEach(function(method) { - tableClone[method] = function(req) { - var subscr = PSD.subscr; - var isLiveQuery = !!subscr; - var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); - var obsSet = cachable ? req.obsSet = {} : subscr; - if (isLiveQuery) { - var getRangeSet = function(indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return obsSet[part] || (obsSet[part] = new RangeSet2()); - }; - var pkRangeSet_1 = getRangeSet(""); - var delsRangeSet_1 = getRangeSet(":dels"); - var _a2 = readSubscribers[method](req), queriedIndex = _a2[0], queriedRanges = _a2[1]; - if (method === "query" && queriedIndex.isPrimaryKey && !req.values) { - delsRangeSet_1.add(queriedRanges); - } else { - getRangeSet(queriedIndex.name || "").add(queriedRanges); - } - if (!queriedIndex.isPrimaryKey) { - if (method === "count") { - delsRangeSet_1.add(FULL_RANGE); - } else { - var keysPromise_1 = method === "query" && outbound && req.values && table.query(__assign(__assign({}, req), { values: false })); - return table[method].apply(this, arguments).then(function(res) { - if (method === "query") { - if (outbound && req.values) { - return keysPromise_1.then(function(_a3) { - var resultingKeys = _a3.result; - pkRangeSet_1.addKeys(resultingKeys); - return res; - }); - } - var pKeys = req.values ? res.result.map(extractKey2) : res.result; - if (req.values) { - pkRangeSet_1.addKeys(pKeys); - } else { - delsRangeSet_1.addKeys(pKeys); - } - } else if (method === "openCursor") { - var cursor_1 = res; - var wantValues_1 = req.values; - return cursor_1 && Object.create(cursor_1, { - key: { - get: function() { - delsRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.key; - } - }, - primaryKey: { - get: function() { - var pkey = cursor_1.primaryKey; - delsRangeSet_1.addKey(pkey); - return pkey; - } - }, - value: { - get: function() { - wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.value; - } - } - }); - } - return res; - }); - } - } - } - return table[method].apply(this, arguments); - }; - }); - return tableClone; - } }); - } - }; - function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { - function addAffectedIndex(ix) { - var rangeSet = getRangeSet(ix.name || ""); - function extractKey2(obj) { - return obj != null ? ix.extractKey(obj) : null; - } - var addKeyOrKeys = function(key) { - return ix.multiEntry && isArray(key) ? key.forEach(function(key2) { - return rangeSet.addKey(key2); - }) : rangeSet.addKey(key); - }; - (oldObjs || newObjs).forEach(function(_, i) { - var oldKey = oldObjs && extractKey2(oldObjs[i]); - var newKey = newObjs && extractKey2(newObjs[i]); - if (cmp3(oldKey, newKey) !== 0) { - if (oldKey != null) - addKeyOrKeys(oldKey); - if (newKey != null) - addKeyOrKeys(newKey); - } - }); - } - schema.indexes.forEach(addAffectedIndex); - } - function adjustOptimisticFromFailures(tblCache, req, res) { - if (res.numFailures === 0) - return req; - if (req.type === "deleteRange") { - return null; - } - var numBulkOps = req.keys ? req.keys.length : "values" in req && req.values ? req.values.length : 1; - if (res.numFailures === numBulkOps) { - return null; - } - var clone = __assign({}, req); - if (isArray(clone.keys)) { - clone.keys = clone.keys.filter(function(_, i) { - return !(i in res.failures); - }); - } - if ("values" in clone && isArray(clone.values)) { - clone.values = clone.values.filter(function(_, i) { - return !(i in res.failures); - }); - } - return clone; - } - function isAboveLower(key, range) { - return range.lower === void 0 ? true : range.lowerOpen ? cmp3(key, range.lower) > 0 : cmp3(key, range.lower) >= 0; - } - function isBelowUpper(key, range) { - return range.upper === void 0 ? true : range.upperOpen ? cmp3(key, range.upper) < 0 : cmp3(key, range.upper) <= 0; - } - function isWithinRange(key, range) { - return isAboveLower(key, range) && isBelowUpper(key, range); - } - function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { - if (!ops || ops.length === 0) - return result; - var index = req.query.index; - var multiEntry = index.multiEntry; - var queryRange = req.query.range; - var primaryKey = table.schema.primaryKey; - var extractPrimKey = primaryKey.extractKey; - var extractIndex = index.extractKey; - var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; - var finalResult = ops.reduce(function(result2, op) { - var modifedResult = result2; - var includedValues = []; - if (op.type === "add" || op.type === "put") { - var includedPKs = new RangeSet2(); - for (var i = op.values.length - 1; i >= 0; --i) { - var value = op.values[i]; - var pk = extractPrimKey(value); - if (includedPKs.hasKey(pk)) - continue; - var key = extractIndex(value); - if (multiEntry && isArray(key) ? key.some(function(k) { - return isWithinRange(k, queryRange); - }) : isWithinRange(key, queryRange)) { - includedPKs.addKey(pk); - includedValues.push(value); - } - } - } - switch (op.type) { - case "add": { - var existingKeys_1 = new RangeSet2().addKeys(req.values ? result2.map(function(v) { - return extractPrimKey(v); - }) : result2); - modifedResult = result2.concat(req.values ? includedValues.filter(function(v) { - var key2 = extractPrimKey(v); - if (existingKeys_1.hasKey(key2)) - return false; - existingKeys_1.addKey(key2); - return true; - }) : includedValues.map(function(v) { - return extractPrimKey(v); - }).filter(function(k) { - if (existingKeys_1.hasKey(k)) - return false; - existingKeys_1.addKey(k); - return true; - })); - break; - } - case "put": { - var keySet_1 = new RangeSet2().addKeys(op.values.map(function(v) { - return extractPrimKey(v); - })); - modifedResult = result2.filter( - function(item) { - return !keySet_1.hasKey(req.values ? extractPrimKey(item) : item); - } - ).concat( - req.values ? includedValues : includedValues.map(function(v) { - return extractPrimKey(v); - }) - ); - break; - } - case "delete": - var keysToDelete_1 = new RangeSet2().addKeys(op.keys); - modifedResult = result2.filter(function(item) { - return !keysToDelete_1.hasKey(req.values ? extractPrimKey(item) : item); - }); - break; - case "deleteRange": - var range_1 = op.range; - modifedResult = result2.filter(function(item) { - return !isWithinRange(extractPrimKey(item), range_1); - }); - break; - } - return modifedResult; - }, result); - if (finalResult === result) - return result; - var sorter = function(a, b) { - return cmp3(extractLowLevelIndex(a), extractLowLevelIndex(b)) || cmp3(extractPrimKey(a), extractPrimKey(b)); - }; - finalResult.sort(req.direction === "prev" || req.direction === "prevunique" ? function(a, b) { - return sorter(b, a); - } : sorter); - if (req.limit && req.limit < Infinity) { - if (finalResult.length > req.limit) { - finalResult.length = req.limit; - } else if (result.length === req.limit && finalResult.length < req.limit) { - cacheEntry.dirty = true; - } - } - return immutable ? Object.freeze(finalResult) : finalResult; - } - function areRangesEqual(r1, r2) { - return cmp3(r1.lower, r2.lower) === 0 && cmp3(r1.upper, r2.upper) === 0 && !!r1.lowerOpen === !!r2.lowerOpen && !!r1.upperOpen === !!r2.upperOpen; - } - function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { - if (lower1 === void 0) - return lower2 !== void 0 ? -1 : 0; - if (lower2 === void 0) - return 1; - var c = cmp3(lower1, lower2); - if (c === 0) { - if (lowerOpen1 && lowerOpen2) - return 0; - if (lowerOpen1) - return 1; - if (lowerOpen2) - return -1; - } - return c; - } - function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { - if (upper1 === void 0) - return upper2 !== void 0 ? 1 : 0; - if (upper2 === void 0) - return -1; - var c = cmp3(upper1, upper2); - if (c === 0) { - if (upperOpen1 && upperOpen2) - return 0; - if (upperOpen1) - return -1; - if (upperOpen2) - return 1; - } - return c; - } - function isSuperRange(r1, r2) { - return compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0; - } - function findCompatibleQuery(dbName, tableName, type2, req) { - var _a2; - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return []; - var queries = tblCache.queries[type2]; - if (!queries) - return [null, false, tblCache, null]; - var indexName = req.query ? req.query.index.name : null; - var entries = queries[indexName || ""]; - if (!entries) - return [null, false, tblCache, null]; - switch (type2) { - case "query": - var reqDirection_1 = (_a2 = req.direction) !== null && _a2 !== void 0 ? _a2 : "next"; - var equalEntry = entries.find(function(entry) { - var _a3; - return entry.req.limit === req.limit && entry.req.values === req.values && ((_a3 = entry.req.direction) !== null && _a3 !== void 0 ? _a3 : "next") === reqDirection_1 && areRangesEqual(entry.req.query.range, req.query.range); - }); - if (equalEntry) - return [ - equalEntry, - true, - tblCache, - entries - ]; - var superEntry = entries.find(function(entry) { - var _a3; - var limit = "limit" in entry.req ? entry.req.limit : Infinity; - return limit >= req.limit && ((_a3 = entry.req.direction) !== null && _a3 !== void 0 ? _a3 : "next") === reqDirection_1 && (req.values ? entry.req.values : true) && isSuperRange(entry.req.query.range, req.query.range); - }); - return [superEntry, false, tblCache, entries]; - case "count": - var countQuery = entries.find(function(entry) { - return areRangesEqual(entry.req.query.range, req.query.range); - }); - return [countQuery, !!countQuery, tblCache, entries]; - } - } - function subscribeToCacheEntry(cacheEntry, container, requery, signal) { - cacheEntry.subscribers.add(requery); - signal.addEventListener("abort", function() { - cacheEntry.subscribers.delete(requery); - if (cacheEntry.subscribers.size === 0) { - enqueForDeletion(cacheEntry, container); - } - }); - } - function enqueForDeletion(cacheEntry, container) { - setTimeout(function() { - if (cacheEntry.subscribers.size === 0) { - delArrayItem(container, cacheEntry); - } - }, 3e3); - } - var cacheMiddleware = { - stack: "dbcore", - level: 0, - name: "Cache", - create: function(core) { - var dbName = core.schema.name; - var coreMW = __assign(__assign({}, core), { transaction: function(stores, mode, options) { - var idbtrans = core.transaction(stores, mode, options); - if (mode === "readwrite") { - var ac_1 = new AbortController(); - var signal = ac_1.signal; - var endTransaction = function(wasCommitted) { - return function() { - ac_1.abort(); - if (mode === "readwrite") { - var affectedSubscribers_1 = /* @__PURE__ */ new Set(); - for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) { - var storeName = stores_1[_i]; - var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)]; - if (tblCache) { - var table = core.table(storeName); - var ops = tblCache.optimisticOps.filter(function(op) { - return op.trans === idbtrans; - }); - if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) { - for (var _a2 = 0, _b = Object.values(tblCache.queries.query); _a2 < _b.length; _a2++) { - var entries = _b[_a2]; - for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) { - var entry = _d[_c]; - if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function(requery) { - return affectedSubscribers_1.add(requery); - }); - } - } - } - } else if (ops.length > 0) { - tblCache.optimisticOps = tblCache.optimisticOps.filter(function(op) { - return op.trans !== idbtrans; - }); - for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) { - var entries = _f[_e]; - for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) { - var entry = _h[_g]; - if (entry.res != null && idbtrans.mutatedParts) { - if (wasCommitted && !entry.dirty) { - var freezeResults = Object.isFrozen(entry.res); - var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); - if (entry.dirty) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function(requery) { - return affectedSubscribers_1.add(requery); - }); - } else if (modRes !== entry.res) { - entry.res = modRes; - entry.promise = DexiePromise.resolve({ - result: modRes - }); - } - } else { - if (entry.dirty) { - delArrayItem(entries, entry); - } - entry.subscribers.forEach(function(requery) { - return affectedSubscribers_1.add(requery); - }); - } - } - } - } - } - } - } - affectedSubscribers_1.forEach(function(requery) { - return requery(); - }); - } - }; - }; - idbtrans.addEventListener("abort", endTransaction(false), { - signal - }); - idbtrans.addEventListener("error", endTransaction(false), { - signal - }); - idbtrans.addEventListener("complete", endTransaction(true), { - signal - }); - } - return idbtrans; - }, table: function(tableName) { - var downTable = core.table(tableName); - var primKey = downTable.schema.primaryKey; - var tableMW = __assign(__assign({}, downTable), { mutate: function(req) { - var trans = PSD.trans; - if (primKey.outbound || trans.db._options.cache === "disabled" || trans.explicit || trans.idbtrans.mode !== "readwrite") { - return downTable.mutate(req); - } - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return downTable.mutate(req); - var promise = downTable.mutate(req); - if ((req.type === "add" || req.type === "put") && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function(key) { - return key == null; - }))) { - promise.then(function(res) { - var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function(value, i) { - var _a2; - if (res.failures[i]) - return value; - var valueWithKey = ((_a2 = primKey.keyPath) === null || _a2 === void 0 ? void 0 : _a2.includes(".")) ? deepClone(value) : __assign({}, value); - setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); - return valueWithKey; - }) }); - var adjustedReq = adjustOptimisticFromFailures(tblCache, reqWithResolvedKeys, res); - tblCache.optimisticOps.push(adjustedReq); - queueMicrotask(function() { - return req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - }); - }); - } else { - tblCache.optimisticOps.push(req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - promise.then(function(res) { - if (res.numFailures > 0) { - delArrayItem(tblCache.optimisticOps, req); - var adjustedReq = adjustOptimisticFromFailures(tblCache, req, res); - if (adjustedReq) { - tblCache.optimisticOps.push(adjustedReq); - } - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - } - }); - promise.catch(function() { - delArrayItem(tblCache.optimisticOps, req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - }); - } - return promise; - }, query: function(req) { - var _a2; - if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) - return downTable.query(req); - var freezeResults = ((_a2 = PSD.trans) === null || _a2 === void 0 ? void 0 : _a2.db._options.cache) === "immutable"; - var _b = PSD, requery = _b.requery, signal = _b.signal; - var _c = findCompatibleQuery(dbName, tableName, "query", req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3]; - if (cacheEntry && exactMatch) { - cacheEntry.obsSet = req.obsSet; - } else { - var promise = downTable.query(req).then(function(res) { - var result = res.result; - if (cacheEntry) - cacheEntry.res = result; - if (freezeResults) { - for (var i = 0, l = result.length; i < l; ++i) { - Object.freeze(result[i]); - } - Object.freeze(result); - } - return res; - }).catch(function(error) { - if (container && cacheEntry) - delArrayItem(container, cacheEntry); - return Promise.reject(error); - }); - cacheEntry = { - obsSet: req.obsSet, - promise, - subscribers: /* @__PURE__ */ new Set(), - type: "query", - req, - dirty: false - }; - if (container) { - container.push(cacheEntry); - } else { - container = [cacheEntry]; - if (!tblCache) { - tblCache = cache["idb://".concat(dbName, "/").concat(tableName)] = { - queries: { - query: {}, - count: {} - }, - objs: /* @__PURE__ */ new Map(), - optimisticOps: [], - unsignaledParts: {} - }; - } - tblCache.queries.query[req.query.index.name || ""] = container; - } - } - subscribeToCacheEntry(cacheEntry, container, requery, signal); - return cacheEntry.promise.then(function(res) { - var result = applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults); - return { - result: freezeResults ? result : deepClone(result) - }; - }); - } }); - return tableMW; - } }); - return coreMW; - } - }; - function vipify(target, vipDb) { - return new Proxy(target, { - get: function(target2, prop, receiver) { - if (prop === "db") - return vipDb; - return Reflect.get(target2, prop, receiver); - } - }); - } - var Dexie$1 = function() { - function Dexie4(name, options) { - var _this = this; - this._middlewares = {}; - this.verno = 0; - var deps = Dexie4.dependencies; - this._options = options = __assign({ - addons: Dexie4.addons, - autoOpen: true, - indexedDB: deps.indexedDB, - IDBKeyRange: deps.IDBKeyRange, - cache: "cloned", - maxConnections: DEFAULT_MAX_CONNECTIONS - }, options); - this._deps = { - indexedDB: options.indexedDB, - IDBKeyRange: options.IDBKeyRange - }; - var addons = options.addons; - this._dbSchema = {}; - this._versions = []; - this._storeNames = []; - this._allTables = {}; - this.idbdb = null; - this._novip = this; - var state = { - dbOpenError: null, - isBeingOpened: false, - onReadyBeingFired: null, - openComplete: false, - dbReadyResolve: nop, - dbReadyPromise: null, - cancelOpen: nop, - openCanceller: null, - autoSchema: true, - PR1398_maxLoop: 3, - autoOpen: options.autoOpen - }; - state.dbReadyPromise = new DexiePromise(function(resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function(_, reject) { - state.cancelOpen = reject; - }); - this._state = state; - this.name = name; - this.on = Events(this, "populate", "blocked", "versionchange", "close", { - ready: [promisableChain, nop] - }); - this.once = function(event, callback) { - var fn = function() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - _this.on(event).unsubscribe(fn); - callback.apply(_this, args); - }; - return _this.on(event, fn); - }; - this.on.ready.subscribe = override(this.on.ready.subscribe, function(subscribe) { - return function(subscriber, bSticky) { - Dexie4.vip(function() { - var state2 = _this._state; - if (state2.openComplete) { - if (!state2.dbOpenError) - DexiePromise.resolve().then(subscriber); - if (bSticky) - subscribe(subscriber); - } else if (state2.onReadyBeingFired) { - state2.onReadyBeingFired.push(subscriber); - if (bSticky) - subscribe(subscriber); - } else { - subscribe(subscriber); - var db_1 = _this; - if (!bSticky) - subscribe(function unsubscribe() { - db_1.on.ready.unsubscribe(subscriber); - db_1.on.ready.unsubscribe(unsubscribe); - }); - } - }); - }; - }); - this.Collection = createCollectionConstructor(this); - this.Table = createTableConstructor(this); - this.Transaction = createTransactionConstructor(this); - this.Version = createVersionConstructor(this); - this.WhereClause = createWhereClauseConstructor(this); - this.on("versionchange", function(ev) { - if (ev.newVersion > 0) - console.warn("Another connection wants to upgrade database '".concat(_this.name, "'. Closing db now to resume the upgrade.")); - else - console.warn("Another connection wants to delete database '".concat(_this.name, "'. Closing db now to resume the delete request.")); - _this.close({ disableAutoOpen: false }); - }); - this.on("blocked", function(ev) { - if (!ev.newVersion || ev.newVersion < ev.oldVersion) - console.warn("Dexie.delete('".concat(_this.name, "') was blocked")); - else - console.warn("Upgrade '".concat(_this.name, "' blocked by other connection holding version ").concat(ev.oldVersion / 10)); - }); - this._maxKey = getMaxKey(options.IDBKeyRange); - this._createTransaction = function(mode, storeNames, dbschema, parentTransaction) { - return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); - }; - this._fireOnBlocked = function(ev) { - _this.on("blocked").fire(ev); - connections.toArray().filter(function(c) { - return c.name === _this.name && c !== _this && !c._state.vcFired; - }).map(function(c) { - return c.on("versionchange").fire(ev); - }); - }; - this.use(cacheExistingValuesMiddleware); - this.use(cacheMiddleware); - this.use(observabilityMiddleware); - this.use(virtualIndexMiddleware); - this.use(hooksMiddleware); - var vipDB = new Proxy(this, { - get: function(_, prop, receiver) { - if (prop === "_vip") - return true; - if (prop === "table") - return function(tableName) { - return vipify(_this.table(tableName), vipDB); - }; - var rv = Reflect.get(_, prop, receiver); - if (rv instanceof Table) - return vipify(rv, vipDB); - if (prop === "tables") - return rv.map(function(t) { - return vipify(t, vipDB); - }); - if (prop === "_createTransaction") - return function() { - var tx = rv.apply(this, arguments); - return vipify(tx, vipDB); - }; - return rv; - } - }); - this.vip = vipDB; - addons.forEach(function(addon) { - return addon(_this); - }); - } - Dexie4.prototype.version = function(versionNumber) { - if (isNaN(versionNumber) || versionNumber < 0.1) - throw new exceptions.Type("Given version is not a positive number"); - versionNumber = Math.round(versionNumber * 10) / 10; - if (this.idbdb || this._state.isBeingOpened) - throw new exceptions.Schema("Cannot add version when database is open"); - this.verno = Math.max(this.verno, versionNumber); - var versions = this._versions; - var versionInstance = versions.filter(function(v) { - return v._cfg.version === versionNumber; - })[0]; - if (versionInstance) - return versionInstance; - versionInstance = new this.Version(versionNumber); - versions.push(versionInstance); - versions.sort(lowerVersionFirst); - versionInstance.stores({}); - this._state.autoSchema = false; - return versionInstance; - }; - Dexie4.prototype._whenReady = function(fn) { - var _this = this; - return this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip) ? fn() : new DexiePromise(function(resolve, reject) { - if (_this._state.openComplete) { - return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); - } - if (!_this._state.isBeingOpened) { - if (!_this._state.autoOpen) { - reject(new exceptions.DatabaseClosed()); - return; - } - _this.open().catch(nop); - } - _this._state.dbReadyPromise.then(resolve, reject); - }).then(fn); - }; - Dexie4.prototype.use = function(_a2) { - var stack = _a2.stack, create = _a2.create, level = _a2.level, name = _a2.name; - if (name) - this.unuse({ stack, name }); - var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); - middlewares.push({ - stack, - create, - level: level == null ? 10 : level, - name - }); - middlewares.sort(function(a, b) { - return a.level - b.level; - }); - return this; - }; - Dexie4.prototype.unuse = function(_a2) { - var stack = _a2.stack, name = _a2.name, create = _a2.create; - if (stack && this._middlewares[stack]) { - this._middlewares[stack] = this._middlewares[stack].filter(function(mw) { - return create ? mw.create !== create : name ? mw.name !== name : false; - }); - } - return this; - }; - Dexie4.prototype.open = function() { - var _this = this; - return usePSD( - globalPSD, - function() { - return dexieOpen(_this); - } - ); - }; - Dexie4.prototype._close = function() { - this.on.close.fire(new CustomEvent("close")); - var state = this._state; - connections.remove(this); - if (this.idbdb) { - try { - this.idbdb.close(); - } catch (e) { - } - this.idbdb = null; - } - if (!state.isBeingOpened) { - state.dbReadyPromise = new DexiePromise(function(resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function(_, reject) { - state.cancelOpen = reject; - }); - } - }; - Dexie4.prototype.close = function(_a2) { - var _b = _a2 === void 0 ? { disableAutoOpen: true } : _a2, disableAutoOpen = _b.disableAutoOpen; - var state = this._state; - if (disableAutoOpen) { - if (state.isBeingOpened) { - state.cancelOpen(new exceptions.DatabaseClosed()); - } - this._close(); - state.autoOpen = false; - state.dbOpenError = new exceptions.DatabaseClosed(); - } else { - this._close(); - state.autoOpen = this._options.autoOpen || state.isBeingOpened; - state.openComplete = false; - state.dbOpenError = null; - } - }; - Dexie4.prototype.delete = function(closeOptions) { - var _this = this; - if (closeOptions === void 0) { - closeOptions = { disableAutoOpen: true }; - } - var hasInvalidArguments = arguments.length > 0 && typeof arguments[0] !== "object"; - var state = this._state; - return new DexiePromise(function(resolve, reject) { - var doDelete = function() { - _this.close(closeOptions); - var req = _this._deps.indexedDB.deleteDatabase(_this.name); - req.onsuccess = wrap(function() { - _onDatabaseDeleted(_this._deps, _this.name); - resolve(); - }); - req.onerror = eventRejectHandler(reject); - req.onblocked = _this._fireOnBlocked; - }; - if (hasInvalidArguments) - throw new exceptions.InvalidArgument("Invalid closeOptions argument to db.delete()"); - if (state.isBeingOpened) { - state.dbReadyPromise.then(doDelete); - } else { - doDelete(); - } - }); - }; - Dexie4.prototype.backendDB = function() { - return this.idbdb; - }; - Dexie4.prototype.isOpen = function() { - return this.idbdb !== null; - }; - Dexie4.prototype.hasBeenClosed = function() { - var dbOpenError = this._state.dbOpenError; - return dbOpenError && dbOpenError.name === "DatabaseClosed"; - }; - Dexie4.prototype.hasFailed = function() { - return this._state.dbOpenError !== null; - }; - Dexie4.prototype.dynamicallyOpened = function() { - return this._state.autoSchema; - }; - Object.defineProperty(Dexie4.prototype, "tables", { - get: function() { - var _this = this; - return keys(this._allTables).map(function(name) { - return _this._allTables[name]; - }); - }, - enumerable: false, - configurable: true - }); - Dexie4.prototype.transaction = function() { - var args = extractTransactionArgs.apply(this, arguments); - return this._transaction.apply(this, args); - }; - Dexie4.prototype._transaction = function(mode, tables, scopeFunc) { - var _this = this; - var parentTransaction = PSD.trans; - if (!parentTransaction || parentTransaction.db !== this || mode.indexOf("!") !== -1) - parentTransaction = null; - var onlyIfCompatible = mode.indexOf("?") !== -1; - mode = mode.replace("!", "").replace("?", ""); - var idbMode, storeNames; - try { - storeNames = tables.map(function(table) { - var storeName = table instanceof _this.Table ? table.name : table; - if (typeof storeName !== "string") - throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); - return storeName; - }); - if (mode == "r" || mode === READONLY) - idbMode = READONLY; - else if (mode == "rw" || mode == READWRITE) - idbMode = READWRITE; - else - throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); - if (parentTransaction) { - if (parentTransaction.mode === READONLY && idbMode === READWRITE) { - if (onlyIfCompatible) { - parentTransaction = null; - } else - throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); - } - if (parentTransaction) { - storeNames.forEach(function(storeName) { - if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { - if (onlyIfCompatible) { - parentTransaction = null; - } else - throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); - } - }); - } - if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { - parentTransaction = null; - } - } - } catch (e) { - return parentTransaction ? parentTransaction._promise(null, function(_, reject) { - reject(e); - }) : rejection(e); - } - var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); - return parentTransaction ? parentTransaction._promise(idbMode, enterTransaction, "lock") : PSD.trans ? usePSD(PSD.transless, function() { - return _this._whenReady(enterTransaction); - }) : this._whenReady(enterTransaction); - }; - Dexie4.prototype.table = function(tableName) { - if (!hasOwn(this._allTables, tableName)) { - throw new exceptions.InvalidTable("Table ".concat(tableName, " does not exist")); - } - return this._allTables[tableName]; - }; - return Dexie4; - }(); - var symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol ? Symbol.observable : "@@observable"; - var Observable = function() { - function Observable2(subscribe) { - this._subscribe = subscribe; - } - Observable2.prototype.subscribe = function(x, error, complete) { - return this._subscribe(!x || typeof x === "function" ? { next: x, error, complete } : x); - }; - Observable2.prototype[symbolObservable] = function() { - return this; - }; - return Observable2; - }(); - var domDeps; - try { - domDeps = { - indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, - IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange - }; - } catch (e) { - domDeps = { indexedDB: null, IDBKeyRange: null }; - } - function liveQuery2(querier) { - var hasValue = false; - var currentValue; - var observable = new Observable(function(observer) { - var scopeFuncIsAsync = isAsyncFunction(querier); - function execute(ctx) { - var wasRootExec = beginMicroTickScope(); - try { - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var rv = newScope(querier, ctx); - if (scopeFuncIsAsync) { - rv = rv.finally(decrementExpectedAwaits); - } - return rv; - } finally { - wasRootExec && endMicroTickScope(); - } - } - var closed = false; - var abortController; - var accumMuts = {}; - var currentObs = {}; - var subscription = { - get closed() { - return closed; - }, - unsubscribe: function() { - if (closed) - return; - closed = true; - if (abortController) - abortController.abort(); - if (startedListening) - globalEvents.storagemutated.unsubscribe(mutationListener); - } - }; - observer.start && observer.start(subscription); - var startedListening = false; - var doQuery = function() { - return execInGlobalContext(_doQuery); - }; - function shouldNotify() { - return obsSetsOverlap(currentObs, accumMuts); - } - var mutationListener = function(parts) { - extendObservabilitySet(accumMuts, parts); - if (shouldNotify()) { - doQuery(); - } - }; - var _doQuery = function() { - if (closed || !domDeps.indexedDB) { - return; - } - accumMuts = {}; - var subscr = {}; - if (abortController) - abortController.abort(); - abortController = new AbortController(); - var ctx = { - subscr, - signal: abortController.signal, - requery: doQuery, - querier, - trans: null - }; - var ret = execute(ctx); - if (!startedListening) { - globalEvents.storagemutated.subscribe(mutationListener); - startedListening = true; - } - Promise.resolve(ret).then(function(result) { - hasValue = true; - currentValue = result; - if (closed || ctx.signal.aborted) { - return; - } - if (shouldNotify()) { - doQuery(); - } else { - currentObs = subscr; - if (shouldNotify()) { - doQuery(); - } else { - accumMuts = {}; - execInGlobalContext(function() { - return !closed && observer.next && observer.next(result); - }); - } - } - }, function(err) { - hasValue = false; - if (!["DatabaseClosedError", "AbortError"].includes(err === null || err === void 0 ? void 0 : err.name)) { - if (!closed) - execInGlobalContext(function() { - if (closed) - return; - observer.error && observer.error(err); - }); - } - }); - }; - setTimeout(doQuery, 0); - return subscription; - }); - observable.hasValue = function() { - return hasValue; - }; - observable.getValue = function() { - return currentValue; - }; - return observable; - } - var Dexie3 = Dexie$1; - props(Dexie3, __assign(__assign({}, fullNameExceptions), { - delete: function(databaseName) { - var db2 = new Dexie3(databaseName, { addons: [] }); - return db2.delete(); - }, - exists: function(name) { - return new Dexie3(name, { addons: [] }).open().then(function(db2) { - db2.close(); - return true; - }).catch("NoSuchDatabaseError", function() { - return false; - }); - }, - getDatabaseNames: function(cb) { - try { - return getDatabaseNames(Dexie3.dependencies).then(cb); - } catch (_a2) { - return rejection(new exceptions.MissingAPI()); - } - }, - defineClass: function() { - function Class(content) { - extend(this, content); - } - return Class; - }, - ignoreTransaction: function(scopeFunc) { - return PSD.trans ? usePSD(PSD.transless || globalPSD, scopeFunc) : scopeFunc(); - }, - vip, - async: function(generatorFn) { - return function() { - try { - var rv = awaitIterator(generatorFn.apply(this, arguments)); - if (!rv || typeof rv.then !== "function") - return DexiePromise.resolve(rv); - return rv; - } catch (e) { - return rejection(e); - } - }; - }, - spawn: function(generatorFn, args, thiz) { - try { - var rv = awaitIterator(generatorFn.apply(thiz, args || [])); - if (!rv || typeof rv.then !== "function") - return DexiePromise.resolve(rv); - return rv; - } catch (e) { - return rejection(e); - } - }, - currentTransaction: { - get: function() { - return PSD.trans || null; - } - }, - waitFor: function(promiseOrFunction, optionalTimeout) { - var promise = DexiePromise.resolve(typeof promiseOrFunction === "function" ? Dexie3.ignoreTransaction(promiseOrFunction) : promiseOrFunction).timeout(optionalTimeout || 6e4); - return PSD.trans ? PSD.trans.waitFor(promise) : promise; - }, - Promise: DexiePromise, - debug: { - get: function() { - return debug; - }, - set: function(value) { - setDebug(value); - } - }, - derive, - extend, - props, - override, - Events, - on: globalEvents, - liveQuery: liveQuery2, - extendObservabilitySet, - getByKeyPath, - setByKeyPath, - delByKeyPath, - shallowClone, - deepClone, - getObjectDiff, - cmp: cmp3, - asap: asap$1, - minKey, - addons: [], - connections: { - get: connections.toArray - }, - errnames, - dependencies: domDeps, - cache, - semVer: DEXIE_VERSION, - version: DEXIE_VERSION.split(".").map(function(n) { - return parseInt(n); - }).reduce(function(p, c, i) { - return p + c / Math.pow(10, i * 2); - }) - })); - Dexie3.maxKey = getMaxKey(Dexie3.dependencies.IDBKeyRange); - if (typeof dispatchEvent !== "undefined" && typeof addEventListener !== "undefined") { - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function(updatedParts) { - if (!propagatingLocally) { - var event_1; - event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { - detail: updatedParts - }); - propagatingLocally = true; - dispatchEvent(event_1); - propagatingLocally = false; - } - }); - addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function(_a2) { - var detail = _a2.detail; - if (!propagatingLocally) { - propagateLocally(detail); - } - }); - } - function propagateLocally(updateParts) { - var wasMe = propagatingLocally; - try { - propagatingLocally = true; - globalEvents.storagemutated.fire(updateParts); - signalSubscribersNow(updateParts, true); - } finally { - propagatingLocally = wasMe; - } - } - var propagatingLocally = false; - var bc; - var createBC = function() { - }; - if (typeof BroadcastChannel !== "undefined") { - createBC = function() { - bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); - bc.onmessage = function(ev) { - return ev.data && propagateLocally(ev.data); - }; - }; - createBC(); - if (typeof bc.unref === "function") { - bc.unref(); - } - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function(changedParts) { - if (!propagatingLocally) { - bc.postMessage(changedParts); - } - }); - } - if (typeof addEventListener !== "undefined") { - addEventListener("pagehide", function(event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug("Dexie: handling persisted pagehide"); - bc === null || bc === void 0 ? void 0 : bc.close(); - for (var _i = 0, _a2 = connections.toArray(); _i < _a2.length; _i++) { - var db2 = _a2[_i]; - db2.close({ disableAutoOpen: false }); - } - } - }); - addEventListener("pageshow", function(event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug("Dexie: handling persisted pageshow"); - createBC(); - propagateLocally({ all: new RangeSet2(-Infinity, [[]]) }); - } - }); - } - function add2(value) { - return new PropModification2({ add: value }); - } - function remove2(value) { - return new PropModification2({ remove: value }); - } - function replacePrefix2(a, b) { - return new PropModification2({ replacePrefix: [a, b] }); - } - DexiePromise.rejectionMapper = mapError; - setDebug(debug); - var namedExports = /* @__PURE__ */ Object.freeze({ - __proto__: null, - DEFAULT_MAX_CONNECTIONS, - Dexie: Dexie$1, - Entity: Entity2, - PropModification: PropModification2, - RangeSet: RangeSet2, - add: add2, - cmp: cmp3, - default: Dexie$1, - liveQuery: liveQuery2, - mergeRanges: mergeRanges2, - rangesOverlap: rangesOverlap2, - remove: remove2, - replacePrefix: replacePrefix2 - }); - __assign(Dexie$1, namedExports, { default: Dexie$1 }); - return Dexie$1; - }); - } -}); - -// intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/import-wrapper.mjs -var import_dexie, DexieSymbol, Dexie, liveQuery, mergeRanges, rangesOverlap, RangeSet, cmp2, Entity, PropModification, replacePrefix, add, remove, DexieYProvider, import_wrapper_default; -var init_import_wrapper = __esm({ - "intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/import-wrapper.mjs"() { - import_dexie = __toESM(require_dexie(), 1); - DexieSymbol = Symbol.for("Dexie"); - Dexie = globalThis[DexieSymbol] || (globalThis[DexieSymbol] = import_dexie.default); - if (import_dexie.default.semVer !== Dexie.semVer) { - throw new Error(`Two different versions of Dexie loaded in the same app: ${import_dexie.default.semVer} and ${Dexie.semVer}`); - } - ({ - liveQuery, - mergeRanges, - rangesOverlap, - RangeSet, - cmp: cmp2, - Entity, - PropModification, - replacePrefix, - add, - remove, - DexieYProvider - } = Dexie); - import_wrapper_default = Dexie; - } -}); - -// intern-log/src/db/schema.ts -var schema_exports = {}; -__export(schema_exports, { - CATEGORIES: () => CATEGORIES, - DEFAULT_LOCATIONS: () => DEFAULT_LOCATIONS, - EXPENSE_CATEGORIES: () => EXPENSE_CATEGORIES, - INCOME_CATEGORIES: () => INCOME_CATEGORIES, - SCHEMA_VERSION: () => SCHEMA_VERSION, - WorklogDB: () => WorklogDB, - bindDatabase: () => bindDatabase, - categoryLabel: () => categoryLabel, - db: () => db, - unbindDatabase: () => unbindDatabase -}); -function bindDatabase(instance) { - db = instance; -} -function unbindDatabase() { - if (db) db.close(); - db = void 0; -} -function categoryLabel(key) { - const found = CATEGORIES.find((c) => c.key === key); - return found ? found.label : "\u5176\u4ED6"; -} -var WorklogDB, db, SCHEMA_VERSION, EXPENSE_CATEGORIES, INCOME_CATEGORIES, DEFAULT_LOCATIONS, CATEGORIES; -var init_schema = __esm({ - "intern-log/src/db/schema.ts"() { - "use strict"; - init_import_wrapper(); - WorklogDB = class extends import_wrapper_default { - constructor(dbName = "intern_worklog") { - super(dbName); - this.version(1).stores({ - project: "++id, &name, archived", - work_log: "++id, &date", - log_item: "++id, work_log_id, project_id, category", - attendance: "++id, &date", - weekly_note: "++id, &week_start", - setting: "key" - }); - this.version(2).stores({ - memo: "++id, updated_at", - credential: "++id, system, updated_at" - }); - this.version(3).stores({ - transaction: "++id, date, type, category" - }); - this.version(4).stores({ - sync_mirror: "++id, table, uuid", - tombstone: "++id, table, uuid, deleted_at" - }); - } - }; - SCHEMA_VERSION = 4; - EXPENSE_CATEGORIES = ["\u9910\u996E", "\u4EA4\u901A", "\u4F4F\u623F", "\u901A\u8BAF", "\u5B66\u4E60", "\u5A31\u4E50", "\u5176\u4ED6"]; - INCOME_CATEGORIES = ["\u5DE5\u8D44", "\u62A5\u9500", "\u5176\u4ED6"]; - DEFAULT_LOCATIONS = ["\u516C\u53F8", "\u5BA2\u6237\u73B0\u573A", "\u51FA\u5DEE", "\u5C45\u5BB6\u529E\u516C"]; - CATEGORIES = [ - { key: "dev", label: "\u5F00\u53D1" }, - { key: "bugfix", label: "BUG\u4FEE\u590D" }, - { key: "test", label: "\u6D4B\u8BD5" }, - { key: "learning", label: "\u5B66\u4E60\u6210\u957F" }, - { key: "meeting", label: "\u4F1A\u8BAE\u6C9F\u901A" }, - { key: "doc", label: "\u6587\u6863\u8F93\u51FA" }, - { key: "other", label: "\u5176\u4ED6" } - ]; - } -}); - -// intern-log/src/lib/date.ts -function pad(n) { - return n < 10 ? "0" + n : String(n); -} -function toDateStr(d) { - return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()); -} -function nowLocalISO() { - const d = /* @__PURE__ */ new Date(); - return toDateStr(d) + "T" + pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds()); -} -var init_date = __esm({ - "intern-log/src/lib/date.ts"() { - "use strict"; - } -}); - -// intern-log/src/db/repo.ts -async function getSetting(key, fallback) { - const row = await db.setting.get(key); - return row ? row.value : fallback; -} -async function setSetting(key, value) { - await db.setting.put({ key, value }); -} -var init_repo = __esm({ - "intern-log/src/db/repo.ts"() { - "use strict"; - init_schema(); - init_date(); - } -}); - -// intern-log/src/lib/crypto.ts -var init_crypto = __esm({ - "intern-log/src/lib/crypto.ts"() { - "use strict"; - } -}); - -// intern-log/src/db/vault.ts -var init_vault = __esm({ - "intern-log/src/db/vault.ts"() { - "use strict"; - init_schema(); - init_repo(); - init_crypto(); - init_date(); - } -}); - -// intern-log/src/db/auth.ts -function getCloudCreds() { - try { - const raw = localStorage.getItem(CREDS_KEY); - if (!raw) return null; - const c = JSON.parse(raw); - if (c && c.username && c.password) return c; - } catch { - } - return null; -} -var UserRegistry, registry, CREDS_KEY; -var init_auth = __esm({ - "intern-log/src/db/auth.ts"() { - "use strict"; - init_import_wrapper(); - init_schema(); - init_vault(); - init_crypto(); - UserRegistry = class extends import_wrapper_default { - constructor() { - super("intern_worklog_users"); - this.version(1).stores({ user: "id, &username" }); - } - }; - registry = new UserRegistry(); - CREDS_KEY = "dsh_cloud_creds"; - } -}); - -// intern-log/node_modules/.pnpm/@vue+shared@3.5.44/node_modules/@vue/shared/dist/shared.cjs.prod.js -var require_shared_cjs_prod = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+shared@3.5.44/node_modules/@vue/shared/dist/shared.cjs.prod.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - // @__NO_SIDE_EFFECTS__ - function makeMap(str) { - const map = /* @__PURE__ */ Object.create(null); - for (const key of str.split(",")) map[key] = 1; - return (val) => val in map; - } - var EMPTY_OBJ = {}; - var EMPTY_ARR = []; - var NOOP = () => { - }; - var NO = () => false; - var isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter - (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); - var isModelListener = (key) => key.startsWith("onUpdate:"); - var extend = Object.assign; - var remove2 = (arr, el) => { - const i = arr.indexOf(el); - if (i > -1) { - arr.splice(i, 1); - } - }; - var hasOwnProperty2 = Object.prototype.hasOwnProperty; - var hasOwn = (val, key) => hasOwnProperty2.call(val, key); - var isArray = Array.isArray; - var isMap = (val) => toTypeString(val) === "[object Map]"; - var isSet = (val) => toTypeString(val) === "[object Set]"; - var isDate = (val) => toTypeString(val) === "[object Date]"; - var isRegExp = (val) => toTypeString(val) === "[object RegExp]"; - var isFunction = (val) => typeof val === "function"; - var isString = (val) => typeof val === "string"; - var isSymbol = (val) => typeof val === "symbol"; - var isObject = (val) => val !== null && typeof val === "object"; - var isPromise = (val) => { - return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch); - }; - var objectToString = Object.prototype.toString; - var toTypeString = (value) => objectToString.call(value); - var toRawType = (value) => { - return toTypeString(value).slice(8, -1); - }; - var isPlainObject = (val) => toTypeString(val) === "[object Object]"; - var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; - var 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" - ); - var isBuiltInDirective = /* @__PURE__ */ makeMap( - "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" - ); - var cacheStringFunction = (fn) => { - const cache = /* @__PURE__ */ Object.create(null); - return (str) => { - const hit = cache[str]; - return hit || (cache[str] = fn(str)); - }; - }; - var camelizeRE = /-\w/g; - var camelize = cacheStringFunction( - (str) => { - return str.replace(camelizeRE, (c) => c.slice(1).toUpperCase()); - } - ); - var hyphenateRE = /\B([A-Z])/g; - var hyphenate = cacheStringFunction( - (str) => str.replace(hyphenateRE, "-$1").toLowerCase() - ); - var capitalize = cacheStringFunction((str) => { - return str.charAt(0).toUpperCase() + str.slice(1); - }); - var toHandlerKey = cacheStringFunction( - (str) => { - const s = str ? `on${capitalize(str)}` : ``; - return s; - } - ); - var hasChanged = (value, oldValue) => !Object.is(value, oldValue); - var invokeArrayFns = (fns, ...arg) => { - for (let i = 0; i < fns.length; i++) { - fns[i](...arg); - } - }; - var def = (obj, key, value, writable = false) => { - Object.defineProperty(obj, key, { - configurable: true, - enumerable: false, - writable, - value - }); - }; - var looseToNumber = (val) => { - const n = parseFloat(val); - return isNaN(n) ? val : n; - }; - var toNumber = (val) => { - const n = isString(val) ? Number(val) : NaN; - return isNaN(n) ? val : n; - }; - var _globalThis; - var getGlobalThis = () => { - return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); - }; - var 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)}]`; - } - function genCacheKey(source, options) { - return source + JSON.stringify( - options, - (_, val) => typeof val === "function" ? val.toString() : val - ); - } - var PatchFlags = { - "TEXT": 1, - "1": "TEXT", - "CLASS": 2, - "2": "CLASS", - "STYLE": 4, - "4": "STYLE", - "PROPS": 8, - "8": "PROPS", - "FULL_PROPS": 16, - "16": "FULL_PROPS", - "NEED_HYDRATION": 32, - "32": "NEED_HYDRATION", - "STABLE_FRAGMENT": 64, - "64": "STABLE_FRAGMENT", - "KEYED_FRAGMENT": 128, - "128": "KEYED_FRAGMENT", - "UNKEYED_FRAGMENT": 256, - "256": "UNKEYED_FRAGMENT", - "NEED_PATCH": 512, - "512": "NEED_PATCH", - "DYNAMIC_SLOTS": 1024, - "1024": "DYNAMIC_SLOTS", - "DEV_ROOT_FRAGMENT": 2048, - "2048": "DEV_ROOT_FRAGMENT", - "CACHED": -1, - "-1": "CACHED", - "BAIL": -2, - "-2": "BAIL" - }; - var 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]: `CACHED`, - [-2]: `BAIL` - }; - var ShapeFlags = { - "ELEMENT": 1, - "1": "ELEMENT", - "FUNCTIONAL_COMPONENT": 2, - "2": "FUNCTIONAL_COMPONENT", - "STATEFUL_COMPONENT": 4, - "4": "STATEFUL_COMPONENT", - "TEXT_CHILDREN": 8, - "8": "TEXT_CHILDREN", - "ARRAY_CHILDREN": 16, - "16": "ARRAY_CHILDREN", - "SLOTS_CHILDREN": 32, - "32": "SLOTS_CHILDREN", - "TELEPORT": 64, - "64": "TELEPORT", - "SUSPENSE": 128, - "128": "SUSPENSE", - "COMPONENT_SHOULD_KEEP_ALIVE": 256, - "256": "COMPONENT_SHOULD_KEEP_ALIVE", - "COMPONENT_KEPT_ALIVE": 512, - "512": "COMPONENT_KEPT_ALIVE", - "COMPONENT": 6, - "6": "COMPONENT" - }; - var SlotFlags = { - "STABLE": 1, - "1": "STABLE", - "DYNAMIC": 2, - "2": "DYNAMIC", - "FORWARDED": 3, - "3": "FORWARDED" - }; - var slotFlagsText = { - [1]: "STABLE", - [2]: "DYNAMIC", - [3]: "FORWARDED" - }; - var 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,Symbol"; - var isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED); - var isGloballyWhitelisted = isGloballyAllowed; - var range = 2; - function generateCodeFrame(source, start = 0, end = source.length) { - start = Math.max(0, Math.min(start, source.length)); - end = Math.max(0, Math.min(end, source.length)); - if (start > end) return ""; - 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 pad2 = start - (count - (lineLength + newLineSeqLength)); - const length = Math.max( - 1, - end > count ? lineLength - pad2 : end - start - ); - res.push(` | ` + " ".repeat(pad2) + "^".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(value)) { - const res = {}; - for (let i = 0; i < value.length; i++) { - const item = value[i]; - const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item); - if (normalized) { - for (const key in normalized) { - res[key] = normalized[key]; - } - } - } - return res; - } else if (isString(value) || isObject(value)) { - return value; - } - } - var listDelimiterRE = /;(?![^(]*\))/g; - var propertyDelimiterRE = /:([^]+)/; - var styleCommentRE = /"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g; - function parseStringStyle(cssText) { - const ret = {}; - cssText.replace(styleCommentRE, (match) => match.startsWith("/*") ? "" : match).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) { - if (!styles) return ""; - if (isString(styles)) return styles; - let ret = ""; - for (const key in styles) { - const value = styles[key]; - if (isString(value) || typeof value === "number") { - const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); - ret += `${normalizedKey}:${value};`; - } - } - return ret; - } - function normalizeClass(value) { - let res = ""; - if (isString(value)) { - res = value; - } else if (isArray(value)) { - for (let i = 0; i < value.length; i++) { - const normalized = normalizeClass(value[i]); - if (normalized) { - res += normalized + " "; - } - } - } else if (isObject(value)) { - for (const name in value) { - if (value[name]) { - res += name + " "; - } - } - } - return res.trim(); - } - function normalizeProps(props) { - if (!props) return null; - let { class: klass, style } = props; - if (klass && !isString(klass)) { - props.class = normalizeClass(klass); - } - if (style) { - props.style = normalizeStyle(style); - } - return props; - } - var 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"; - var 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"; - var 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"; - var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; - var isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); - var isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); - var isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS); - var isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); - var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`; - var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); - var isBooleanAttr = /* @__PURE__ */ makeMap( - specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` - ); - function includeBooleanAttr(value) { - return !!value || value === ""; - } - var unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u000d\u0020]/; - var 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; - } - var propsToAttrMap = { - acceptCharset: "accept-charset", - className: "class", - htmlFor: "for", - httpEquiv: "http-equiv" - }; - var 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` - ); - var 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` - ); - var isKnownMathMLAttr = /* @__PURE__ */ makeMap( - `accent,accentunder,actiontype,align,alignmentscope,altimg,altimg-height,altimg-valign,altimg-width,alttext,bevelled,close,columnsalign,columnlines,columnspan,denomalign,depth,dir,display,displaystyle,encoding,equalcolumns,equalrows,fence,fontstyle,fontweight,form,frame,framespacing,groupalign,height,href,id,indentalign,indentalignfirst,indentalignlast,indentshift,indentshiftfirst,indentshiftlast,indextype,justify,largetop,largeop,lquote,lspace,mathbackground,mathcolor,mathsize,mathvariant,maxsize,minlabelspacing,mode,other,overflow,position,rowalign,rowlines,rowspan,rquote,rspace,scriptlevel,scriptminsize,scriptsizemultiplier,selection,separator,separators,shift,side,src,stackalign,stretchy,subscriptshift,superscriptshift,symmetric,voffset,width,widths,xlink:href,xlink:show,xlink:type,xmlns` - ); - function isRenderableAttrValue(value) { - if (value == null) { - return false; - } - const type = typeof value; - return type === "string" || type === "number" || type === "boolean"; - } - var 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; - } - var commentStripRE = /^(?:-?>)+||--!>|?@[\\\]^`{|}~]/g; - function getEscapedCssVarName(key, doubleEscape) { - return key.replace( - cssVarNameEscapeSymbolsRE, - (s) => doubleEscape ? s === '"' ? '\\\\\\"' : `\\\\${s}` : `\\${s}` - ); - } - function looseCompareArrays(a, b, seen) { - if (a.length !== b.length) return false; - let equal = true; - for (let i = 0; equal && i < a.length; i++) { - equal = looseEqual(a[i], b[i], seen); - } - return equal; - } - function looseCompareCollections(a, b, seen) { - if (a.size !== b.size) return false; - const candidates = Array.from(b); - const matched = new Uint8Array(candidates.length); - for (const item of a) { - let index = -1; - for (let i = 0; i < candidates.length; i++) { - if (!matched[i] && looseEqual(item, candidates[i], seen)) { - index = i; - break; - } - } - if (index < 0) return false; - matched[index] = 1; - } - return true; - } - function looseCompareObjects(a, b, seen) { - let aValidType = isMap(a); - let bValidType = isMap(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false; - } - aValidType = isSet(a); - bValidType = isSet(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false; - } - const aKeysCount = Object.keys(a).length; - const bKeysCount = Object.keys(b).length; - if (aKeysCount !== bKeysCount) { - return false; - } - for (const key in a) { - const aHasKey = a.hasOwnProperty(key); - const bHasKey = b.hasOwnProperty(key); - if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key], seen)) { - return false; - } - } - return String(a) === String(b); - } - function looseCompareNested(a, b, seen, compare) { - if (!seen) { - seen = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()]; - } - const [seenA, seenB] = seen; - if (seenA.has(a) || seenB.has(b)) { - return seenA.get(a) === b && seenB.get(b) === a; - } - seenA.set(a, b); - seenB.set(b, a); - const equal = compare(a, b, seen); - seenA.delete(a); - seenB.delete(b); - return equal; - } - function looseEqual(a, b, seen) { - if (a === b) return true; - let aValidType = isDate(a); - let bValidType = isDate(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? a.getTime() === b.getTime() : false; - } - aValidType = isSymbol(a); - bValidType = isSymbol(b); - if (aValidType || bValidType) { - return a === b; - } - aValidType = isArray(a); - bValidType = isArray(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? looseCompareNested(a, b, seen, looseCompareArrays) : false; - } - aValidType = isObject(a); - bValidType = isObject(b); - if (aValidType || bValidType) { - if (!aValidType || !bValidType) { - return false; - } - return looseCompareNested(a, b, seen, looseCompareObjects); - } - return String(a) === String(b); - } - function looseIndexOf(arr, val) { - return arr.findIndex((item) => looseEqual(item, val)); - } - var isRef = (val) => { - return !!(val && val["__v_isRef"] === true); - }; - var toDisplayString = (val) => { - return isString(val) ? val : val == null ? "" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? isRef(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val); - }; - var replacer = (_key, val) => { - if (isRef(val)) { - 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(val)) { - return stringifySymbol(val); - } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { - return String(val); - } - return val; - }; - var stringifySymbol = (v, i = "") => { - var _a; - return ( - // Symbol.description in es2019+ so we need to cast here to pass - // the lib: es2016 check - isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v - ); - }; - function normalizeCssVarValue(value) { - if (value == null) { - return "initial"; - } - if (typeof value === "string") { - return value === "" ? " " : value; - } - return String(value); - } - exports2.EMPTY_ARR = EMPTY_ARR; - exports2.EMPTY_OBJ = EMPTY_OBJ; - exports2.NO = NO; - exports2.NOOP = NOOP; - exports2.PatchFlagNames = PatchFlagNames; - exports2.PatchFlags = PatchFlags; - exports2.ShapeFlags = ShapeFlags; - exports2.SlotFlags = SlotFlags; - exports2.camelize = camelize; - exports2.capitalize = capitalize; - exports2.cssVarNameEscapeSymbolsRE = cssVarNameEscapeSymbolsRE; - exports2.def = def; - exports2.escapeHtml = escapeHtml; - exports2.escapeHtmlComment = escapeHtmlComment; - exports2.extend = extend; - exports2.genCacheKey = genCacheKey; - exports2.genPropsAccessExp = genPropsAccessExp; - exports2.generateCodeFrame = generateCodeFrame; - exports2.getEscapedCssVarName = getEscapedCssVarName; - exports2.getGlobalThis = getGlobalThis; - exports2.hasChanged = hasChanged; - exports2.hasOwn = hasOwn; - exports2.hyphenate = hyphenate; - exports2.includeBooleanAttr = includeBooleanAttr; - exports2.invokeArrayFns = invokeArrayFns; - exports2.isArray = isArray; - exports2.isBooleanAttr = isBooleanAttr; - exports2.isBuiltInDirective = isBuiltInDirective; - exports2.isDate = isDate; - exports2.isFunction = isFunction; - exports2.isGloballyAllowed = isGloballyAllowed; - exports2.isGloballyWhitelisted = isGloballyWhitelisted; - exports2.isHTMLTag = isHTMLTag; - exports2.isIntegerKey = isIntegerKey; - exports2.isKnownHtmlAttr = isKnownHtmlAttr; - exports2.isKnownMathMLAttr = isKnownMathMLAttr; - exports2.isKnownSvgAttr = isKnownSvgAttr; - exports2.isMap = isMap; - exports2.isMathMLTag = isMathMLTag; - exports2.isModelListener = isModelListener; - exports2.isObject = isObject; - exports2.isOn = isOn; - exports2.isPlainObject = isPlainObject; - exports2.isPromise = isPromise; - exports2.isRegExp = isRegExp; - exports2.isRenderableAttrValue = isRenderableAttrValue; - exports2.isReservedProp = isReservedProp; - exports2.isSSRSafeAttrName = isSSRSafeAttrName; - exports2.isSVGTag = isSVGTag; - exports2.isSet = isSet; - exports2.isSpecialBooleanAttr = isSpecialBooleanAttr; - exports2.isString = isString; - exports2.isSymbol = isSymbol; - exports2.isVoidTag = isVoidTag; - exports2.looseEqual = looseEqual; - exports2.looseIndexOf = looseIndexOf; - exports2.looseToNumber = looseToNumber; - exports2.makeMap = makeMap; - exports2.normalizeClass = normalizeClass; - exports2.normalizeCssVarValue = normalizeCssVarValue; - exports2.normalizeProps = normalizeProps; - exports2.normalizeStyle = normalizeStyle; - exports2.objectToString = objectToString; - exports2.parseStringStyle = parseStringStyle; - exports2.propsToAttrMap = propsToAttrMap; - exports2.remove = remove2; - exports2.slotFlagsText = slotFlagsText; - exports2.stringifyStyle = stringifyStyle; - exports2.toDisplayString = toDisplayString; - exports2.toHandlerKey = toHandlerKey; - exports2.toNumber = toNumber; - exports2.toRawType = toRawType; - exports2.toTypeString = toTypeString; - } -}); - -// intern-log/node_modules/.pnpm/@vue+shared@3.5.44/node_modules/@vue/shared/dist/shared.cjs.js -var require_shared_cjs = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+shared@3.5.44/node_modules/@vue/shared/dist/shared.cjs.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - // @__NO_SIDE_EFFECTS__ - function makeMap(str) { - const map = /* @__PURE__ */ Object.create(null); - for (const key of str.split(",")) map[key] = 1; - return (val) => val in map; - } - var EMPTY_OBJ = Object.freeze({}); - var EMPTY_ARR = Object.freeze([]); - var NOOP = () => { - }; - var NO = () => false; - var isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter - (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); - var isModelListener = (key) => key.startsWith("onUpdate:"); - var extend = Object.assign; - var remove2 = (arr, el) => { - const i = arr.indexOf(el); - if (i > -1) { - arr.splice(i, 1); - } - }; - var hasOwnProperty2 = Object.prototype.hasOwnProperty; - var hasOwn = (val, key) => hasOwnProperty2.call(val, key); - var isArray = Array.isArray; - var isMap = (val) => toTypeString(val) === "[object Map]"; - var isSet = (val) => toTypeString(val) === "[object Set]"; - var isDate = (val) => toTypeString(val) === "[object Date]"; - var isRegExp = (val) => toTypeString(val) === "[object RegExp]"; - var isFunction = (val) => typeof val === "function"; - var isString = (val) => typeof val === "string"; - var isSymbol = (val) => typeof val === "symbol"; - var isObject = (val) => val !== null && typeof val === "object"; - var isPromise = (val) => { - return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch); - }; - var objectToString = Object.prototype.toString; - var toTypeString = (value) => objectToString.call(value); - var toRawType = (value) => { - return toTypeString(value).slice(8, -1); - }; - var isPlainObject = (val) => toTypeString(val) === "[object Object]"; - var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; - var 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" - ); - var isBuiltInDirective = /* @__PURE__ */ makeMap( - "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" - ); - var cacheStringFunction = (fn) => { - const cache = /* @__PURE__ */ Object.create(null); - return (str) => { - const hit = cache[str]; - return hit || (cache[str] = fn(str)); - }; - }; - var camelizeRE = /-\w/g; - var camelize = cacheStringFunction( - (str) => { - return str.replace(camelizeRE, (c) => c.slice(1).toUpperCase()); - } - ); - var hyphenateRE = /\B([A-Z])/g; - var hyphenate = cacheStringFunction( - (str) => str.replace(hyphenateRE, "-$1").toLowerCase() - ); - var capitalize = cacheStringFunction((str) => { - return str.charAt(0).toUpperCase() + str.slice(1); - }); - var toHandlerKey = cacheStringFunction( - (str) => { - const s = str ? `on${capitalize(str)}` : ``; - return s; - } - ); - var hasChanged = (value, oldValue) => !Object.is(value, oldValue); - var invokeArrayFns = (fns, ...arg) => { - for (let i = 0; i < fns.length; i++) { - fns[i](...arg); - } - }; - var def = (obj, key, value, writable = false) => { - Object.defineProperty(obj, key, { - configurable: true, - enumerable: false, - writable, - value - }); - }; - var looseToNumber = (val) => { - const n = parseFloat(val); - return isNaN(n) ? val : n; - }; - var toNumber = (val) => { - const n = isString(val) ? Number(val) : NaN; - return isNaN(n) ? val : n; - }; - var _globalThis; - var getGlobalThis = () => { - return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); - }; - var 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)}]`; - } - function genCacheKey(source, options) { - return source + JSON.stringify( - options, - (_, val) => typeof val === "function" ? val.toString() : val - ); - } - var PatchFlags = { - "TEXT": 1, - "1": "TEXT", - "CLASS": 2, - "2": "CLASS", - "STYLE": 4, - "4": "STYLE", - "PROPS": 8, - "8": "PROPS", - "FULL_PROPS": 16, - "16": "FULL_PROPS", - "NEED_HYDRATION": 32, - "32": "NEED_HYDRATION", - "STABLE_FRAGMENT": 64, - "64": "STABLE_FRAGMENT", - "KEYED_FRAGMENT": 128, - "128": "KEYED_FRAGMENT", - "UNKEYED_FRAGMENT": 256, - "256": "UNKEYED_FRAGMENT", - "NEED_PATCH": 512, - "512": "NEED_PATCH", - "DYNAMIC_SLOTS": 1024, - "1024": "DYNAMIC_SLOTS", - "DEV_ROOT_FRAGMENT": 2048, - "2048": "DEV_ROOT_FRAGMENT", - "CACHED": -1, - "-1": "CACHED", - "BAIL": -2, - "-2": "BAIL" - }; - var 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]: `CACHED`, - [-2]: `BAIL` - }; - var ShapeFlags = { - "ELEMENT": 1, - "1": "ELEMENT", - "FUNCTIONAL_COMPONENT": 2, - "2": "FUNCTIONAL_COMPONENT", - "STATEFUL_COMPONENT": 4, - "4": "STATEFUL_COMPONENT", - "TEXT_CHILDREN": 8, - "8": "TEXT_CHILDREN", - "ARRAY_CHILDREN": 16, - "16": "ARRAY_CHILDREN", - "SLOTS_CHILDREN": 32, - "32": "SLOTS_CHILDREN", - "TELEPORT": 64, - "64": "TELEPORT", - "SUSPENSE": 128, - "128": "SUSPENSE", - "COMPONENT_SHOULD_KEEP_ALIVE": 256, - "256": "COMPONENT_SHOULD_KEEP_ALIVE", - "COMPONENT_KEPT_ALIVE": 512, - "512": "COMPONENT_KEPT_ALIVE", - "COMPONENT": 6, - "6": "COMPONENT" - }; - var SlotFlags = { - "STABLE": 1, - "1": "STABLE", - "DYNAMIC": 2, - "2": "DYNAMIC", - "FORWARDED": 3, - "3": "FORWARDED" - }; - var slotFlagsText = { - [1]: "STABLE", - [2]: "DYNAMIC", - [3]: "FORWARDED" - }; - var 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,Symbol"; - var isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED); - var isGloballyWhitelisted = isGloballyAllowed; - var range = 2; - function generateCodeFrame(source, start = 0, end = source.length) { - start = Math.max(0, Math.min(start, source.length)); - end = Math.max(0, Math.min(end, source.length)); - if (start > end) return ""; - 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 pad2 = start - (count - (lineLength + newLineSeqLength)); - const length = Math.max( - 1, - end > count ? lineLength - pad2 : end - start - ); - res.push(` | ` + " ".repeat(pad2) + "^".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(value)) { - const res = {}; - for (let i = 0; i < value.length; i++) { - const item = value[i]; - const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item); - if (normalized) { - for (const key in normalized) { - res[key] = normalized[key]; - } - } - } - return res; - } else if (isString(value) || isObject(value)) { - return value; - } - } - var listDelimiterRE = /;(?![^(]*\))/g; - var propertyDelimiterRE = /:([^]+)/; - var styleCommentRE = /"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g; - function parseStringStyle(cssText) { - const ret = {}; - cssText.replace(styleCommentRE, (match) => match.startsWith("/*") ? "" : match).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) { - if (!styles) return ""; - if (isString(styles)) return styles; - let ret = ""; - for (const key in styles) { - const value = styles[key]; - if (isString(value) || typeof value === "number") { - const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); - ret += `${normalizedKey}:${value};`; - } - } - return ret; - } - function normalizeClass(value) { - let res = ""; - if (isString(value)) { - res = value; - } else if (isArray(value)) { - for (let i = 0; i < value.length; i++) { - const normalized = normalizeClass(value[i]); - if (normalized) { - res += normalized + " "; - } - } - } else if (isObject(value)) { - for (const name in value) { - if (value[name]) { - res += name + " "; - } - } - } - return res.trim(); - } - function normalizeProps(props) { - if (!props) return null; - let { class: klass, style } = props; - if (klass && !isString(klass)) { - props.class = normalizeClass(klass); - } - if (style) { - props.style = normalizeStyle(style); - } - return props; - } - var 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"; - var 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"; - var 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"; - var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; - var isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); - var isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); - var isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS); - var isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); - var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`; - var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); - var isBooleanAttr = /* @__PURE__ */ makeMap( - specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` - ); - function includeBooleanAttr(value) { - return !!value || value === ""; - } - var unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u000d\u0020]/; - var 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; - } - var propsToAttrMap = { - acceptCharset: "accept-charset", - className: "class", - htmlFor: "for", - httpEquiv: "http-equiv" - }; - var 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` - ); - var 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` - ); - var isKnownMathMLAttr = /* @__PURE__ */ makeMap( - `accent,accentunder,actiontype,align,alignmentscope,altimg,altimg-height,altimg-valign,altimg-width,alttext,bevelled,close,columnsalign,columnlines,columnspan,denomalign,depth,dir,display,displaystyle,encoding,equalcolumns,equalrows,fence,fontstyle,fontweight,form,frame,framespacing,groupalign,height,href,id,indentalign,indentalignfirst,indentalignlast,indentshift,indentshiftfirst,indentshiftlast,indextype,justify,largetop,largeop,lquote,lspace,mathbackground,mathcolor,mathsize,mathvariant,maxsize,minlabelspacing,mode,other,overflow,position,rowalign,rowlines,rowspan,rquote,rspace,scriptlevel,scriptminsize,scriptsizemultiplier,selection,separator,separators,shift,side,src,stackalign,stretchy,subscriptshift,superscriptshift,symmetric,voffset,width,widths,xlink:href,xlink:show,xlink:type,xmlns` - ); - function isRenderableAttrValue(value) { - if (value == null) { - return false; - } - const type = typeof value; - return type === "string" || type === "number" || type === "boolean"; - } - var 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; - } - var commentStripRE = /^(?:-?>)+||--!>|?@[\\\]^`{|}~]/g; - function getEscapedCssVarName(key, doubleEscape) { - return key.replace( - cssVarNameEscapeSymbolsRE, - (s) => doubleEscape ? s === '"' ? '\\\\\\"' : `\\\\${s}` : `\\${s}` - ); - } - function looseCompareArrays(a, b, seen) { - if (a.length !== b.length) return false; - let equal = true; - for (let i = 0; equal && i < a.length; i++) { - equal = looseEqual(a[i], b[i], seen); - } - return equal; - } - function looseCompareCollections(a, b, seen) { - if (a.size !== b.size) return false; - const candidates = Array.from(b); - const matched = new Uint8Array(candidates.length); - for (const item of a) { - let index = -1; - for (let i = 0; i < candidates.length; i++) { - if (!matched[i] && looseEqual(item, candidates[i], seen)) { - index = i; - break; - } - } - if (index < 0) return false; - matched[index] = 1; - } - return true; - } - function looseCompareObjects(a, b, seen) { - let aValidType = isMap(a); - let bValidType = isMap(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false; - } - aValidType = isSet(a); - bValidType = isSet(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false; - } - const aKeysCount = Object.keys(a).length; - const bKeysCount = Object.keys(b).length; - if (aKeysCount !== bKeysCount) { - return false; - } - for (const key in a) { - const aHasKey = a.hasOwnProperty(key); - const bHasKey = b.hasOwnProperty(key); - if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key], seen)) { - return false; - } - } - return String(a) === String(b); - } - function looseCompareNested(a, b, seen, compare) { - if (!seen) { - seen = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()]; - } - const [seenA, seenB] = seen; - if (seenA.has(a) || seenB.has(b)) { - return seenA.get(a) === b && seenB.get(b) === a; - } - seenA.set(a, b); - seenB.set(b, a); - const equal = compare(a, b, seen); - seenA.delete(a); - seenB.delete(b); - return equal; - } - function looseEqual(a, b, seen) { - if (a === b) return true; - let aValidType = isDate(a); - let bValidType = isDate(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? a.getTime() === b.getTime() : false; - } - aValidType = isSymbol(a); - bValidType = isSymbol(b); - if (aValidType || bValidType) { - return a === b; - } - aValidType = isArray(a); - bValidType = isArray(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? looseCompareNested(a, b, seen, looseCompareArrays) : false; - } - aValidType = isObject(a); - bValidType = isObject(b); - if (aValidType || bValidType) { - if (!aValidType || !bValidType) { - return false; - } - return looseCompareNested(a, b, seen, looseCompareObjects); - } - return String(a) === String(b); - } - function looseIndexOf(arr, val) { - return arr.findIndex((item) => looseEqual(item, val)); - } - var isRef = (val) => { - return !!(val && val["__v_isRef"] === true); - }; - var toDisplayString = (val) => { - return isString(val) ? val : val == null ? "" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? isRef(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val); - }; - var replacer = (_key, val) => { - if (isRef(val)) { - 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(val)) { - return stringifySymbol(val); - } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { - return String(val); - } - return val; - }; - var stringifySymbol = (v, i = "") => { - var _a; - return ( - // Symbol.description in es2019+ so we need to cast here to pass - // the lib: es2016 check - isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v - ); - }; - function normalizeCssVarValue(value) { - if (value == null) { - return "initial"; - } - if (typeof value === "string") { - return value === "" ? " " : value; - } - if (typeof value !== "number" || !Number.isFinite(value)) { - { - console.warn( - "[Vue warn] Invalid value used for CSS binding. Expected a string or a finite number but received:", - value - ); - } - } - return String(value); - } - exports2.EMPTY_ARR = EMPTY_ARR; - exports2.EMPTY_OBJ = EMPTY_OBJ; - exports2.NO = NO; - exports2.NOOP = NOOP; - exports2.PatchFlagNames = PatchFlagNames; - exports2.PatchFlags = PatchFlags; - exports2.ShapeFlags = ShapeFlags; - exports2.SlotFlags = SlotFlags; - exports2.camelize = camelize; - exports2.capitalize = capitalize; - exports2.cssVarNameEscapeSymbolsRE = cssVarNameEscapeSymbolsRE; - exports2.def = def; - exports2.escapeHtml = escapeHtml; - exports2.escapeHtmlComment = escapeHtmlComment; - exports2.extend = extend; - exports2.genCacheKey = genCacheKey; - exports2.genPropsAccessExp = genPropsAccessExp; - exports2.generateCodeFrame = generateCodeFrame; - exports2.getEscapedCssVarName = getEscapedCssVarName; - exports2.getGlobalThis = getGlobalThis; - exports2.hasChanged = hasChanged; - exports2.hasOwn = hasOwn; - exports2.hyphenate = hyphenate; - exports2.includeBooleanAttr = includeBooleanAttr; - exports2.invokeArrayFns = invokeArrayFns; - exports2.isArray = isArray; - exports2.isBooleanAttr = isBooleanAttr; - exports2.isBuiltInDirective = isBuiltInDirective; - exports2.isDate = isDate; - exports2.isFunction = isFunction; - exports2.isGloballyAllowed = isGloballyAllowed; - exports2.isGloballyWhitelisted = isGloballyWhitelisted; - exports2.isHTMLTag = isHTMLTag; - exports2.isIntegerKey = isIntegerKey; - exports2.isKnownHtmlAttr = isKnownHtmlAttr; - exports2.isKnownMathMLAttr = isKnownMathMLAttr; - exports2.isKnownSvgAttr = isKnownSvgAttr; - exports2.isMap = isMap; - exports2.isMathMLTag = isMathMLTag; - exports2.isModelListener = isModelListener; - exports2.isObject = isObject; - exports2.isOn = isOn; - exports2.isPlainObject = isPlainObject; - exports2.isPromise = isPromise; - exports2.isRegExp = isRegExp; - exports2.isRenderableAttrValue = isRenderableAttrValue; - exports2.isReservedProp = isReservedProp; - exports2.isSSRSafeAttrName = isSSRSafeAttrName; - exports2.isSVGTag = isSVGTag; - exports2.isSet = isSet; - exports2.isSpecialBooleanAttr = isSpecialBooleanAttr; - exports2.isString = isString; - exports2.isSymbol = isSymbol; - exports2.isVoidTag = isVoidTag; - exports2.looseEqual = looseEqual; - exports2.looseIndexOf = looseIndexOf; - exports2.looseToNumber = looseToNumber; - exports2.makeMap = makeMap; - exports2.normalizeClass = normalizeClass; - exports2.normalizeCssVarValue = normalizeCssVarValue; - exports2.normalizeProps = normalizeProps; - exports2.normalizeStyle = normalizeStyle; - exports2.objectToString = objectToString; - exports2.parseStringStyle = parseStringStyle; - exports2.propsToAttrMap = propsToAttrMap; - exports2.remove = remove2; - exports2.slotFlagsText = slotFlagsText; - exports2.stringifyStyle = stringifyStyle; - exports2.toDisplayString = toDisplayString; - exports2.toHandlerKey = toHandlerKey; - exports2.toNumber = toNumber; - exports2.toRawType = toRawType; - exports2.toTypeString = toTypeString; - } -}); - -// intern-log/node_modules/.pnpm/@vue+shared@3.5.44/node_modules/@vue/shared/index.js -var require_shared = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+shared@3.5.44/node_modules/@vue/shared/index.js"(exports2, module2) { - "use strict"; - if (process.env.NODE_ENV === "production") { - module2.exports = require_shared_cjs_prod(); - } else { - module2.exports = require_shared_cjs(); - } - } -}); - -// intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/decode-codepoint.js -var require_decode_codepoint = __commonJS({ - "intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/decode-codepoint.js"(exports2) { - "use strict"; - var _a; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.fromCodePoint = void 0; - exports2.replaceCodePoint = replaceCodePoint; - exports2.decodeCodePoint = decodeCodePoint; - var decodeMap = /* @__PURE__ */ 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] - ]); - exports2.fromCodePoint = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, n/no-unsupported-features/es-builtins - (_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : (codePoint) => { - let output = ""; - if (codePoint > 65535) { - codePoint -= 65536; - output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - output += String.fromCharCode(codePoint); - return output; - }; - function replaceCodePoint(codePoint) { - var _a2; - if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) { - return 65533; - } - return (_a2 = decodeMap.get(codePoint)) !== null && _a2 !== void 0 ? _a2 : codePoint; - } - function decodeCodePoint(codePoint) { - return (0, exports2.fromCodePoint)(replaceCodePoint(codePoint)); - } - } -}); - -// intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/internal/decode-shared.js -var require_decode_shared = __commonJS({ - "intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/internal/decode-shared.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.decodeBase64 = decodeBase64; - function decodeBase64(input) { - const binary = ( - // eslint-disable-next-line n/no-unsupported-features/node-builtins - typeof atob === "function" ? ( - // Browser (and Node >=16) - // eslint-disable-next-line n/no-unsupported-features/node-builtins - atob(input) - ) : ( - // Older Node versions (<16) - // eslint-disable-next-line n/no-unsupported-features/node-builtins - typeof Buffer.from === "function" ? ( - // eslint-disable-next-line n/no-unsupported-features/node-builtins - Buffer.from(input, "base64").toString("binary") - ) : ( - // eslint-disable-next-line unicorn/no-new-buffer, n/no-deprecated-api - new Buffer(input, "base64").toString("binary") - ) - ) - ); - const evenLength = binary.length & ~1; - const out = new Uint16Array(evenLength / 2); - for (let index = 0, outIndex = 0; index < evenLength; index += 2) { - const lo = binary.charCodeAt(index); - const hi = binary.charCodeAt(index + 1); - out[outIndex++] = lo | hi << 8; - } - return out; - } - } -}); - -// intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/generated/decode-data-html.js -var require_decode_data_html = __commonJS({ - "intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/generated/decode-data-html.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.htmlDecodeTree = void 0; - var decode_shared_js_1 = require_decode_shared(); - exports2.htmlDecodeTree = (0, decode_shared_js_1.decodeBase64)("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg"); - } -}); - -// intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/generated/decode-data-xml.js -var require_decode_data_xml = __commonJS({ - "intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/generated/decode-data-xml.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.xmlDecodeTree = void 0; - var decode_shared_js_1 = require_decode_shared(); - exports2.xmlDecodeTree = (0, decode_shared_js_1.decodeBase64)("AAJhZ2xxBwARABMAFQBtAg0AAAAAAA8AcAAmYG8AcwAnYHQAPmB0ADxg9SFvdCJg"); - } -}); - -// intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/internal/bin-trie-flags.js -var require_bin_trie_flags = __commonJS({ - "intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/internal/bin-trie-flags.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.BinTrieFlags = void 0; - var BinTrieFlags; - (function(BinTrieFlags2) { - BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; - BinTrieFlags2[BinTrieFlags2["FLAG13"] = 8192] = "FLAG13"; - BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 8064] = "BRANCH_LENGTH"; - BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE"; - })(BinTrieFlags || (exports2.BinTrieFlags = BinTrieFlags = {})); - } -}); - -// intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/decode.js -var require_decode = __commonJS({ - "intern-log/node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/commonjs/decode.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.xmlDecodeTree = exports2.htmlDecodeTree = exports2.replaceCodePoint = exports2.fromCodePoint = exports2.decodeCodePoint = exports2.EntityDecoder = exports2.DecodingMode = void 0; - exports2.determineBranch = determineBranch; - exports2.decodeHTML = decodeHTML; - exports2.decodeHTMLAttribute = decodeHTMLAttribute; - exports2.decodeHTMLStrict = decodeHTMLStrict; - exports2.decodeXML = decodeXML; - var decode_codepoint_js_1 = require_decode_codepoint(); - var decode_data_html_js_1 = require_decode_data_html(); - var decode_data_xml_js_1 = require_decode_data_xml(); - var bin_trie_flags_js_1 = require_bin_trie_flags(); - var CharCodes; - (function(CharCodes2) { - CharCodes2[CharCodes2["NUM"] = 35] = "NUM"; - CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI"; - CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS"; - CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO"; - CharCodes2[CharCodes2["NINE"] = 57] = "NINE"; - CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A"; - CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F"; - CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X"; - CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z"; - CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A"; - CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F"; - CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z"; - })(CharCodes || (CharCodes = {})); - var TO_LOWER_BIT = 32; - function isNumber(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(code); - } - function isEntityInAttributeInvalidEnd(code) { - return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); - } - var EntityDecoderState; - (function(EntityDecoderState2) { - EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart"; - EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart"; - EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal"; - EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex"; - EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity"; - })(EntityDecoderState || (EntityDecoderState = {})); - var DecodingMode; - (function(DecodingMode2) { - DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy"; - DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict"; - DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute"; - })(DecodingMode || (exports2.DecodingMode = DecodingMode = {})); - var EntityDecoder = class { - constructor(decodeTree, emitCodePoint, errors) { - this.decodeTree = decodeTree; - this.emitCodePoint = emitCodePoint; - this.errors = errors; - this.state = EntityDecoderState.EntityStart; - this.consumed = 1; - this.result = 0; - this.treeIndex = 0; - this.excess = 1; - this.decodeMode = DecodingMode.Strict; - this.runConsumed = 0; - } - /** 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; - this.runConsumed = 0; - } - /** - * 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 input 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(input, offset) { - switch (this.state) { - case EntityDecoderState.EntityStart: { - if (input.charCodeAt(offset) === CharCodes.NUM) { - this.state = EntityDecoderState.NumericStart; - this.consumed += 1; - return this.stateNumericStart(input, offset + 1); - } - this.state = EntityDecoderState.NamedEntity; - return this.stateNamedEntity(input, offset); - } - case EntityDecoderState.NumericStart: { - return this.stateNumericStart(input, offset); - } - case EntityDecoderState.NumericDecimal: { - return this.stateNumericDecimal(input, offset); - } - case EntityDecoderState.NumericHex: { - return this.stateNumericHex(input, offset); - } - case EntityDecoderState.NamedEntity: { - return this.stateNamedEntity(input, offset); - } - } - } - /** - * Switches between the numeric decimal and hexadecimal states. - * - * Equivalent to the `Numeric character reference state` in the HTML spec. - * - * @param input 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(input, offset) { - if (offset >= input.length) { - return -1; - } - if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { - this.state = EntityDecoderState.NumericHex; - this.consumed += 1; - return this.stateNumericHex(input, offset + 1); - } - this.state = EntityDecoderState.NumericDecimal; - return this.stateNumericDecimal(input, offset); - } - /** - * Parses a hexadecimal numeric entity. - * - * Equivalent to the `Hexademical character reference state` in the HTML spec. - * - * @param input 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(input, offset) { - while (offset < input.length) { - const char = input.charCodeAt(offset); - if (isNumber(char) || isHexadecimalCharacter(char)) { - const digit = char <= CharCodes.NINE ? char - CharCodes.ZERO : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10; - this.result = this.result * 16 + digit; - this.consumed++; - offset++; - } else { - return this.emitNumericEntity(char, 3); - } - } - return -1; - } - /** - * Parses a decimal numeric entity. - * - * Equivalent to the `Decimal character reference state` in the HTML spec. - * - * @param input 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(input, offset) { - while (offset < input.length) { - const char = input.charCodeAt(offset); - if (isNumber(char)) { - this.result = this.result * 10 + (char - CharCodes.ZERO); - this.consumed++; - offset++; - } else { - return this.emitNumericEntity(char, 2); - } - } - 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; - if (this.consumed <= expectedLength) { - (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); - return 0; - } - if (lastCp === CharCodes.SEMI) { - this.consumed += 1; - } else if (this.decodeMode === DecodingMode.Strict) { - return 0; - } - this.emitCodePoint((0, decode_codepoint_js_1.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 input 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(input, offset) { - const { decodeTree } = this; - let current = decodeTree[this.treeIndex]; - let valueLength = (current & bin_trie_flags_js_1.BinTrieFlags.VALUE_LENGTH) >> 14; - while (offset < input.length) { - if (valueLength === 0 && (current & bin_trie_flags_js_1.BinTrieFlags.FLAG13) !== 0) { - const runLength = (current & bin_trie_flags_js_1.BinTrieFlags.BRANCH_LENGTH) >> 7; - if (this.runConsumed === 0) { - const firstChar = current & bin_trie_flags_js_1.BinTrieFlags.JUMP_TABLE; - if (input.charCodeAt(offset) !== firstChar) { - return this.result === 0 ? 0 : this.emitNotTerminatedNamedEntity(); - } - offset++; - this.excess++; - this.runConsumed++; - } - while (this.runConsumed < runLength) { - if (offset >= input.length) { - return -1; - } - const charIndexInPacked = this.runConsumed - 1; - const packedWord = decodeTree[this.treeIndex + 1 + (charIndexInPacked >> 1)]; - const expectedChar = charIndexInPacked % 2 === 0 ? packedWord & 255 : packedWord >> 8 & 255; - if (input.charCodeAt(offset) !== expectedChar) { - this.runConsumed = 0; - return this.result === 0 ? 0 : this.emitNotTerminatedNamedEntity(); - } - offset++; - this.excess++; - this.runConsumed++; - } - this.runConsumed = 0; - this.treeIndex += 1 + (runLength >> 1); - current = decodeTree[this.treeIndex]; - valueLength = (current & bin_trie_flags_js_1.BinTrieFlags.VALUE_LENGTH) >> 14; - } - if (offset >= input.length) - break; - const char = input.charCodeAt(offset); - if (char === CharCodes.SEMI && valueLength !== 0 && (current & bin_trie_flags_js_1.BinTrieFlags.FLAG13) !== 0) { - return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); - } - 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 & bin_trie_flags_js_1.BinTrieFlags.VALUE_LENGTH) >> 14; - if (valueLength !== 0) { - if (char === CharCodes.SEMI) { - return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); - } - if (this.decodeMode !== DecodingMode.Strict && (current & bin_trie_flags_js_1.BinTrieFlags.FLAG13) === 0) { - this.result = this.treeIndex; - this.consumed += this.excess; - this.excess = 0; - } - } - offset++; - this.excess++; - } - 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] & bin_trie_flags_js_1.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] & ~(bin_trie_flags_js_1.BinTrieFlags.VALUE_LENGTH | bin_trie_flags_js_1.BinTrieFlags.FLAG13) : decodeTree[result + 1], consumed); - if (valueLength === 3) { - 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: { - return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0; - } - 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; - } - } - } - }; - exports2.EntityDecoder = EntityDecoder; - function getDecoder(decodeTree) { - let returnValue = ""; - const decoder = new EntityDecoder(decodeTree, (data) => returnValue += (0, decode_codepoint_js_1.fromCodePoint)(data)); - return function decodeWithTrie(input, decodeMode) { - let lastIndex = 0; - let offset = 0; - while ((offset = input.indexOf("&", offset)) >= 0) { - returnValue += input.slice(lastIndex, offset); - decoder.startEntity(decodeMode); - const length = decoder.write( - input, - // Skip the "&" - offset + 1 - ); - if (length < 0) { - lastIndex = offset + decoder.end(); - break; - } - lastIndex = offset + length; - offset = length === 0 ? lastIndex + 1 : lastIndex; - } - const result = returnValue + input.slice(lastIndex); - returnValue = ""; - return result; - }; - } - function determineBranch(decodeTree, current, nodeIndex, char) { - const branchCount = (current & bin_trie_flags_js_1.BinTrieFlags.BRANCH_LENGTH) >> 7; - const jumpOffset = current & bin_trie_flags_js_1.BinTrieFlags.JUMP_TABLE; - if (branchCount === 0) { - return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1; - } - if (jumpOffset) { - const value = char - jumpOffset; - return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIndex + value] - 1; - } - const packedKeySlots = branchCount + 1 >> 1; - let lo = 0; - let hi = branchCount - 1; - while (lo <= hi) { - const mid = lo + hi >>> 1; - const slot = mid >> 1; - const packed = decodeTree[nodeIndex + slot]; - const midKey = packed >> (mid & 1) * 8 & 255; - if (midKey < char) { - lo = mid + 1; - } else if (midKey > char) { - hi = mid - 1; - } else { - return decodeTree[nodeIndex + packedKeySlots + mid]; - } - } - return -1; - } - var htmlDecoder = /* @__PURE__ */ getDecoder(decode_data_html_js_1.htmlDecodeTree); - var xmlDecoder = /* @__PURE__ */ getDecoder(decode_data_xml_js_1.xmlDecodeTree); - function decodeHTML(htmlString, mode = DecodingMode.Legacy) { - return htmlDecoder(htmlString, mode); - } - function decodeHTMLAttribute(htmlAttribute) { - return htmlDecoder(htmlAttribute, DecodingMode.Attribute); - } - function decodeHTMLStrict(htmlString) { - return htmlDecoder(htmlString, DecodingMode.Strict); - } - function decodeXML(xmlString) { - return xmlDecoder(xmlString, DecodingMode.Strict); - } - var decode_codepoint_js_2 = require_decode_codepoint(); - Object.defineProperty(exports2, "decodeCodePoint", { enumerable: true, get: function() { - return decode_codepoint_js_2.decodeCodePoint; - } }); - Object.defineProperty(exports2, "fromCodePoint", { enumerable: true, get: function() { - return decode_codepoint_js_2.fromCodePoint; - } }); - Object.defineProperty(exports2, "replaceCodePoint", { enumerable: true, get: function() { - return decode_codepoint_js_2.replaceCodePoint; - } }); - var decode_data_html_js_2 = require_decode_data_html(); - Object.defineProperty(exports2, "htmlDecodeTree", { enumerable: true, get: function() { - return decode_data_html_js_2.htmlDecodeTree; - } }); - var decode_data_xml_js_2 = require_decode_data_xml(); - Object.defineProperty(exports2, "xmlDecodeTree", { enumerable: true, get: function() { - return decode_data_xml_js_2.xmlDecodeTree; - } }); - } -}); - -// intern-log/node_modules/.pnpm/@babel+parser@7.29.9/node_modules/@babel/parser/lib/index.js -var require_lib = __commonJS({ - "intern-log/node_modules/.pnpm/@babel+parser@7.29.9/node_modules/@babel/parser/lib/index.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { - value: true - }); - function _objectWithoutPropertiesLoose(r, e) { - if (null == r) return {}; - var t = {}; - for (var n in r) if ({}.hasOwnProperty.call(r, n)) { - if (-1 !== e.indexOf(n)) continue; - t[n] = r[n]; - } - return t; - } - var Position = class { - 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; - } - }; - var SourceLocation = class { - 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); - } - var 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 - } - }; - var 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" - }; - var toNodeDescription = (node) => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.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.", - 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.", - 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\`. -- 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 `deprecatedImportAssert` parser plugin to suppress this error.", - ImportBindingIsString: ({ - importName - }) => `A string literal cannot be used as an imported binding. -- Did you mean \`import { "${importName}" as foo }\`?`, - ImportCallArity: `\`import()\` requires exactly 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.", - InvalidCoverDiscardElement: "'void' must be followed by an expression when not used in a binding position.", - 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.", - SuperCallNotNewExpression: "Cannot use new with super(...).", - 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` or in the bare case statement.", - UnexpectedVoidPattern: "Unexpected void binding.", - 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.", - UsingDeclarationExport: "Using declaration cannot be exported.", - UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", - VarRedeclaration: ({ - identifierName - }) => `Identifier '${identifierName}' has already been declared.`, - VoidPatternCatchClauseParam: "A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.", - VoidPatternInitializer: "A void binding may not have an initializer.", - YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", - YieldInParameter: "Yield expression is not allowed in formal parameters.", - YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.", - 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." - }; - var ParseExpressionErrors = { - ParseExpressionEmptyInput: "Unexpected parseExpression() input: The input is empty or contains only comments.", - ParseExpressionExpectsEOF: ({ - unexpected - }) => `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.` - }; - var UnparenthesizedPipeBodyDescriptions = /* @__PURE__ */ new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); - var PipelineOperatorErrors = Object.assign({ - 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.' - }); - var FunctionBindErrors = { - UnsupportedBind: "Binding should be performed on object property.", - UnsupportedBindRHS: "The right-hand side of binding can not be super or import." - }; - var _excluded = ["message"]; - function defineHidden(obj, key, value) { - Object.defineProperty(obj, key, { - enumerable: false, - configurable: true, - value - }); - } - function toParseErrorConstructor({ - toMessage, - code: code2, - reasonCode, - syntaxPlugin - }) { - const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins"; - const oldReasonCodes = { - AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter", - AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters", - ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference", - SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter", - SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter", - SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType" - }; - if (oldReasonCodes[reasonCode]) { - reasonCode = oldReasonCodes[reasonCode]; - } - return function constructor(loc, details) { - const error = new SyntaxError(); - error.code = code2; - error.reasonCode = reasonCode; - error.loc = loc; - error.pos = loc.index; - error.syntaxPlugin = syntaxPlugin; - if (hasMissingPlugin) { - 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 _ref = typeof template === "string" ? { - message: () => template - } : typeof template === "function" ? { - message: template - } : template, { - message - } = _ref, rest = _objectWithoutPropertiesLoose(_ref, _excluded); - const toMessage = typeof message === "string" ? () => message : message; - ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({ - code: "BABEL_PARSER_SYNTAX_ERROR", - reasonCode, - toMessage - }, syntaxPlugin ? { - syntaxPlugin - } : {}, rest)); - } - return ParseErrorConstructors; - } - var Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum(ParseExpressionErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors), ParseErrorEnum`functionBind`(FunctionBindErrors)); - function createDefaultOptions() { - return { - sourceType: "script", - sourceFilename: void 0, - startIndex: 0, - startColumn: 0, - startLine: 1, - allowAwaitOutsideFunction: false, - allowReturnOutsideFunction: false, - allowNewTargetOutsideFunction: false, - allowImportExportEverywhere: false, - allowSuperOutsideMethod: false, - allowUndeclaredExports: false, - allowYieldOutsideFunction: false, - plugins: [], - strictMode: void 0, - ranges: false, - tokens: false, - createImportExpressions: false, - createParenthesizedExpressions: false, - errorRecovery: false, - attachComment: true, - annexB: true - }; - } - function getOptions(opts) { - const options = createDefaultOptions(); - if (opts == null) { - return options; - } - if (opts.annexB != null && opts.annexB !== false) { - throw new Error("The `annexB` option can only be set to `false`."); - } - for (const key of Object.keys(options)) { - if (opts[key] != null) options[key] = opts[key]; - } - if (options.startLine === 1) { - if (opts.startIndex == null && options.startColumn > 0) { - options.startIndex = options.startColumn; - } else if (opts.startColumn == null && options.startIndex > 0) { - options.startColumn = options.startIndex; - } - } else if (opts.startColumn == null || opts.startIndex == null) { - if (opts.startIndex != null) { - throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`."); - } - } - if (options.sourceType === "commonjs") { - if (opts.allowAwaitOutsideFunction != null) { - throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`."); - } - if (opts.allowReturnOutsideFunction != null) { - throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`."); - } - if (opts.allowNewTargetOutsideFunction != null) { - throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`."); - } - } - return options; - } - var { - defineProperty - } = Object; - var toUnenumerable = (object, key) => { - if (object) { - defineProperty(object, key, { - enumerable: false, - value: object[key] - }); - } - }; - function toESTreeLocation(node) { - toUnenumerable(node.loc.start, "index"); - toUnenumerable(node.loc.end, "index"); - return node; - } - var estree = (superClass) => class ESTreeParserMixin extends superClass { - parse() { - const file = toESTreeLocation(super.parse()); - if (this.optionFlags & 256) { - file.tokens = file.tokens.map(toESTreeLocation); - } - return file; - } - parseRegExpLiteral({ - pattern, - flags - }) { - let regex = null; - try { - regex = new RegExp(pattern, flags); - } catch (_) { - } - 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); - } - estreeParseChainExpression(node, endLoc) { - const chain = this.startNodeAtNode(node); - chain.expression = node; - return this.finishNodeAt(chain, "ChainExpression", endLoc); - } - directiveToStmt(directive) { - const expression = directive.value; - delete directive.value; - this.castNodeTo(expression, "Literal"); - expression.raw = expression.extra.raw; - expression.value = expression.extra.expressionValue; - const stmt = this.castNodeTo(directive, "ExpressionStatement"); - stmt.expression = expression; - stmt.directive = expression.extra.rawValue; - delete expression.extra; - return stmt; - } - fillOptionalPropertiesForTSESLint(node) { - } - cloneEstreeStringLiteral(node) { - const { - start, - end, - loc, - range, - raw, - value - } = node; - const cloned = Object.create(node.constructor.prototype); - cloned.type = "Literal"; - cloned.start = start; - cloned.end = end; - cloned.loc = loc; - cloned.range = range; - cloned.raw = raw; - cloned.value = value; - return cloned; - } - 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; - } - parsePrivateName() { - const node = super.parsePrivateName(); - if (!this.getPluginOption("estree", "classFeatures")) { - return node; - } - return this.convertPrivateNameToPrivateIdentifier(node); - } - convertPrivateNameToPrivateIdentifier(node) { - const name = super.getPrivateNameSV(node); - delete node.id; - node.name = name; - return this.castNodeTo(node, "PrivateIdentifier"); - } - 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); - delete funcNode.kind; - const { - typeParameters - } = node; - if (typeParameters) { - delete node.typeParameters; - funcNode.typeParameters = typeParameters; - this.resetStartLocationFromNode(funcNode, typeParameters); - } - const valueNode = this.castNodeTo(funcNode, "FunctionExpression"); - node.value = valueNode; - if (type === "ClassPrivateMethod") { - node.computed = false; - } - if (type === "ObjectMethod") { - if (node.kind === "method") { - node.kind = "init"; - } - node.shorthand = false; - return this.finishNode(node, "Property"); - } else { - return this.finishNode(node, "MethodDefinition"); - } - } - nameIsConstructor(key) { - if (key.type === "Literal") return key.value === "constructor"; - return super.nameIsConstructor(key); - } - parseClassProperty(...args) { - const propertyNode = super.parseClassProperty(...args); - if (!this.getPluginOption("estree", "classFeatures")) { - return propertyNode; - } - this.castNodeTo(propertyNode, "PropertyDefinition"); - return propertyNode; - } - parseClassPrivateProperty(...args) { - const propertyNode = super.parseClassPrivateProperty(...args); - if (!this.getPluginOption("estree", "classFeatures")) { - return propertyNode; - } - this.castNodeTo(propertyNode, "PropertyDefinition"); - propertyNode.computed = false; - return propertyNode; - } - parseClassAccessorProperty(node) { - const accessorPropertyNode = super.parseClassAccessorProperty(node); - if (!this.getPluginOption("estree", "classFeatures")) { - return accessorPropertyNode; - } - if (accessorPropertyNode.abstract && this.hasPlugin("typescript")) { - delete accessorPropertyNode.abstract; - this.castNodeTo(accessorPropertyNode, "TSAbstractAccessorProperty"); - } else { - this.castNodeTo(accessorPropertyNode, "AccessorProperty"); - } - return accessorPropertyNode; - } - parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { - const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); - if (node) { - node.kind = "init"; - this.castNodeTo(node, "Property"); - } - return node; - } - finishObjectProperty(node) { - node.kind = "init"; - return this.finishNode(node, "Property"); - } - isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { - return type === "Property" ? "value" : super.isValidLVal(type, disallowCallExpression, 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.type === "Property" && (prop.kind === "get" || prop.kind === "set")) { - this.raise(Errors.PatternHasAccessor, prop.key); - } else if (prop.type === "Property" && 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") { - var _ref, _ref2; - this.castNodeTo(node, "ImportExpression"); - node.source = node.arguments[0]; - node.options = (_ref = node.arguments[1]) != null ? _ref : null; - node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null; - delete node.arguments; - delete node.callee; - } else if (node.type === "OptionalCallExpression") { - this.castNodeTo(node, "CallExpression"); - } else { - node.optional = false; - } - 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") { - this.castNodeTo(node, "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; - } - stopParseSubscript(base, state) { - const node = super.stopParseSubscript(base, state); - if (state.optionalChainMember) { - return this.estreeParseChainExpression(node, base.loc.end); - } - return node; - } - parseMember(base, startLoc, state, computed, optional) { - const node = super.parseMember(base, startLoc, state, computed, optional); - if (node.type === "OptionalMemberExpression") { - this.castNodeTo(node, "MemberExpression"); - } else { - 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.type === "Property" && (node.method || node.kind === "get" || node.kind === "set"); - } - castNodeTo(node, type) { - const result = super.castNodeTo(node, type); - this.fillOptionalPropertiesForTSESLint(result); - return result; - } - cloneIdentifier(node) { - const cloned = super.cloneIdentifier(node); - this.fillOptionalPropertiesForTSESLint(cloned); - return cloned; - } - cloneStringLiteral(node) { - if (node.type === "Literal") { - return this.cloneEstreeStringLiteral(node); - } - return super.cloneStringLiteral(node); - } - finishNodeAt(node, type, endLoc) { - return toESTreeLocation(super.finishNodeAt(node, type, endLoc)); - } - finishNode(node, type) { - const result = super.finishNode(node, type); - this.fillOptionalPropertiesForTSESLint(result); - return result; - } - resetStartLocation(node, startLoc) { - super.resetStartLocation(node, startLoc); - toESTreeLocation(node); - } - resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { - super.resetEndLocation(node, endLoc); - toESTreeLocation(node); - } - }; - var TokContext = class { - constructor(token, preserveSpace) { - this.token = void 0; - this.preserveSpace = void 0; - this.token = token; - this.preserveSpace = !!preserveSpace; - } - }; - var types = { - brace: new TokContext("{"), - j_oTag: new TokContext("...", true) - }; - types.template = new TokContext("`", true); - var beforeExpr = true; - var startsExpr = true; - var isLoop = true; - var isAssign = true; - var prefix = true; - var postfix = true; - var ExportedTokenType = class { - 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; - } - }; - var keywords$1 = /* @__PURE__ */ 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 - }); - } - var tokenTypeCounter = -1; - var tokenTypes = []; - var tokenLabels = []; - var tokenBinops = []; - var tokenBeforeExprs = []; - var tokenStartsExprs = []; - var 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.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.push(new ExportedTokenType("name", options)); - return tokenTypeCounter; - } - var 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 - }), - placeholder: createToken("%%", { - 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 - }), - jsxTagStart: createToken("jsxTagStart", { - startsExpr - }), - jsxTagEnd: createToken("jsxTagEnd") - }; - function tokenIsIdentifier(token) { - return token >= 93 && token <= 133; - } - function tokenKeywordOrIdentifierIsKeyword(token) { - return token <= 92; - } - function tokenIsKeywordOrIdentifier(token) { - return token >= 58 && token <= 133; - } - function tokenIsLiteralPropertyName(token) { - return token >= 58 && token <= 137; - } - 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[token]; - } - tokenTypes[8].updateContext = (context) => { - context.pop(); - }; - tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = (context) => { - context.push(types.brace); - }; - tokenTypes[22].updateContext = (context) => { - if (context[context.length - 1] === types.template) { - context.pop(); - } else { - context.push(types.template); - } - }; - tokenTypes[143].updateContext = (context) => { - context.push(types.j_expr, types.j_oTag); - }; - var 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-\u088F\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\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\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-\u1C8A\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-\uA7DC\uA7F1-\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"; - var nonASCIIidentifierChars = "\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\u0897-\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-\u1ADD\u1AE0-\u1AEB\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"; - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - var 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, 4, 51, 13, 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, 7, 25, 39, 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, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 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, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 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, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 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, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 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, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489]; - var 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, 7, 9, 32, 4, 318, 1, 78, 5, 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, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 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, 199, 7, 137, 9, 54, 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, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 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, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; - function isInAstralSet(code2, set) { - let pos = 65536; - for (let i = 0, length = set.length; i < length; i += 2) { - pos += set[i]; - if (pos > code2) return false; - pos += set[i + 1]; - if (pos >= code2) return true; - } - return false; - } - function isIdentifierStart(code2) { - if (code2 < 65) return code2 === 36; - if (code2 <= 90) return true; - if (code2 < 97) return code2 === 95; - if (code2 <= 122) return true; - if (code2 <= 65535) { - return code2 >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code2)); - } - return isInAstralSet(code2, astralIdentifierStartCodes); - } - function isIdentifierChar(code2) { - if (code2 < 48) return code2 === 36; - if (code2 < 58) return true; - if (code2 < 65) return false; - if (code2 <= 90) return true; - if (code2 < 97) return code2 === 95; - if (code2 <= 122) return true; - if (code2 <= 65535) { - return code2 >= 170 && nonASCIIidentifier.test(String.fromCharCode(code2)); - } - return isInAstralSet(code2, astralIdentifierStartCodes) || isInAstralSet(code2, astralIdentifierCodes); - } - var 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"] - }; - var keywords = new Set(reservedWords.keyword); - var reservedWordsStrictSet = new Set(reservedWords.strict); - var 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); - } - var reservedWordLikeSet = /* @__PURE__ */ 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); - } - var Scope = class { - constructor(flags) { - this.flags = 0; - this.names = /* @__PURE__ */ new Map(); - this.firstLexicalName = ""; - this.flags = flags; - } - }; - var ScopeHandler = class { - constructor(parser, inModule) { - this.parser = void 0; - this.scopeStack = []; - this.inModule = void 0; - this.undefinedExports = /* @__PURE__ */ 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 allowNewTarget() { - return (this.currentThisScopeFlags() & 512) > 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 & (1667 | 64)) { - return false; - } - } - } - get inNonArrowFunction() { - return (this.currentThisScopeFlags() & 2) > 0; - } - get inBareCaseStatement() { - return (this.currentScope().flags & 256) > 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 & 1667) 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) || 0; - 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 & 1667) { - return flags; - } - } - } - currentThisScopeFlags() { - for (let i = this.scopeStack.length - 1; ; i--) { - const { - flags - } = this.scopeStack[i]; - if (flags & (1667 | 64) && !(flags & 4)) { - return flags; - } - } - } - }; - var FlowScope = class extends Scope { - constructor(...args) { - super(...args); - this.declareFunctions = /* @__PURE__ */ new Set(); - } - }; - var FlowScopeHandler = class 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); - } - } - }; - var reservedTypes = /* @__PURE__ */ new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); - var 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 ` async () => {}`, use `async () => {}`.", - 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"; - } - var 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]; - } - var FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; - var flow = (superClass) => class FlowParserMixin extends superClass { - constructor(...args) { - super(...args); - this.flowPragma = void 0; - } - getScopeHandler() { - return FlowScopeHandler; - } - shouldParseTypes() { - return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; - } - finishToken(type, val) { - if (type !== 134 && type !== 13 && type !== 28) { - if (this.flowPragma === void 0) { - this.flowPragma = null; - } - } - super.finishToken(type, val); - } - addComment(comment) { - if (this.flowPragma === void 0) { - 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); - } - throw this.unexpected(); - } - flowParseDeclareVariable(node) { - this.next(); - node.id = this.flowParseTypeAnnotatableIdentifier(); - 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(134)) { - 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)) { - const bodyNode2 = this.startNode(); - if (this.match(83)) { - this.next(); - if (!this.isContextual(130) && !this.match(87)) { - this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc); - } - body.push(super.parseImport(bodyNode2)); - } else { - this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule); - body.push(this.flowParseDeclare(bodyNode2, true)); - } - } - 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.default = false; - delete node.exportKind; - return this.castNodeTo(node, "DeclareExportDeclaration"); - } else { - return this.castNodeTo(node, "DeclareExportAllDeclaration"); - } - } - } - throw 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); - this.castNodeTo(finished, "DeclareTypeAlias"); - return finished; - } - flowParseDeclareOpaqueType(node) { - this.next(); - const finished = this.flowParseOpaqueType(node, true); - this.castNodeTo(finished, "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 - }); - } - flowParseRestrictedIdentifierName(liberal, declaration) { - this.checkReservedType(this.state.value, this.state.startLoc, declaration); - return this.parseIdentifierName(liberal); - } - flowParseRestrictedIdentifier(liberal, declaration) { - const node = this.startNode(); - const name = this.flowParseRestrictedIdentifierName(liberal, declaration); - return this.createIdentifier(node, name); - } - 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"); - } - flowParseTypeParameterBound() { - if (this.match(14) || this.isContextual(81)) { - const node = this.startNode(); - this.next(); - node.typeAnnotation = this.flowParseType(); - return this.finishNode(node, "TypeAnnotation"); - } - } - flowParseTypeParameter(requireDefault = false) { - const nodeStartLoc = this.state.startLoc; - const node = this.startNode(); - const variance = this.flowParseVariance(); - node.name = this.flowParseRestrictedIdentifierName(); - node.variance = variance; - node.bound = this.flowParseTypeParameterBound(); - 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(143)) { - 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"); - } - flowInTopLevelContext(cb) { - if (this.curContext() !== types.brace) { - const oldContext = this.state.context; - this.state.context = [oldContext[0]]; - try { - return cb(); - } finally { - this.state.context = oldContext; - } - } else { - return cb(); - } - } - flowParseTypeParameterInstantiationInExpression() { - if (this.reScan_lt() !== 47) return; - return this.flowParseTypeParameterInstantiation(); - } - flowParseTypeParameterInstantiation() { - const node = this.startNode(); - const oldInType = this.state.inType; - this.state.inType = true; - node.params = []; - this.flowInTopLevelContext(() => { - 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.state.inType = oldInType; - if (!this.state.inType && this.curContext() === types.brace) { - this.reScan_lt_gt(); - } - this.expect(48); - return this.finishNode(node, "TypeParameterInstantiation"); - } - flowParseTypeParameterInstantiationCallOrNew() { - if (this.reScan_lt() !== 47) return null; - 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(135) || this.match(134) ? 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) { - 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: { - const node2 = this.startNode(); - node2.typeParameters = this.flowParseTypeParameterDeclaration(); - this.expect(10); - tmp = this.flowParseFunctionTypeParams(); - node2.params = tmp.params; - node2.rest = tmp.rest; - node2.this = tmp._this; - this.expect(11); - this.expect(19); - node2.returnType = this.flowParseType(); - return this.finishNode(node2, "FunctionTypeAnnotation"); - } - case 10: { - const node2 = this.startNode(); - 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(); - } - node2.params = tmp.params; - node2.rest = tmp.rest; - node2.this = tmp._this; - this.expect(11); - this.expect(19); - node2.returnType = this.flowParseType(); - node2.typeParameters = null; - return this.finishNode(node2, "FunctionTypeAnnotation"); - } - case 134: - 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(135)) { - return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node); - } - if (this.match(136)) { - return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node); - } - throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc); - } - throw this.unexpected(); - case 135: - return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); - case 136: - 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()); - } - } - throw 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() { - const node = this.startNode(); - const name = this.parseIdentifierName(); - if (this.match(14)) { - node.typeAnnotation = this.flowParseTypeAnnotation(); - } - return this.createIdentifier(node, name); - } - 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.isContextual(126)) { - const node = this.startNode(); - this.next(); - return this.flowParseEnumDeclaration(node); - } - const stmt = super.parseStatementLike(flags); - if (this.flowPragma === void 0 && !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 (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) { - return !this.state.containsEsc; - } - return super.shouldParseExportDeclaration(); - } - isExportDefaultSpecifier() { - const { - type - } = this.state; - if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) { - return this.state.containsEsc; - } - return super.isExportDefaultSpecifier(); - } - parseExportDefaultExpression() { - if (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(void 0, void 0)); - 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 node2 = stack.pop(); - if (node2.type === "ArrowFunctionExpression") { - if (node2.typeParameters || !node2.returnType) { - this.finishArrowValidation(node2); - } else { - arrows.push(node2); - } - if (node2.body.type !== "BlockStatement") { - stack.push(node2.body); - } - } else if (node2.type === "ConditionalExpression") { - stack.push(node2.consequent); - stack.push(node2.alternate); - } - } - if (disallowInvalid) { - arrows.forEach((node2) => this.finishArrowValidation(node2)); - return [arrows, []]; - } - return partition(arrows, (node2) => node2.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(514 | 4); - super.checkParams(node, false, true); - this.scope.exit(); - } - forwardNoArrowParamsConversionAt(node, parse2) { - let result; - if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { - this.state.noArrowParamsConversionAt.push(this.state.start); - result = parse2(); - this.state.noArrowParamsConversionAt.pop(); - } else { - result = parse2(); - } - return result; - } - parseParenItem(node, startLoc) { - const newNode = super.parseParenItem(node, startLoc); - if (this.eat(17)) { - newNode.optional = true; - this.resetEndLocation(node); - } - if (this.match(14)) { - const typeCastNode = this.startNodeAt(startLoc); - typeCastNode.expression = newNode; - typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); - return this.finishNode(typeCastNode, "TypeCastExpression"); - } - return newNode; - } - 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.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(code2) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (code2 === 123 && next === 124) { - this.finishOp(6, 2); - } else if (this.state.inType && (code2 === 62 || code2 === 60)) { - this.finishOp(code2 === 62 ? 48 : 47, 1); - } else if (this.state.inType && code2 === 63) { - if (next === 46) { - this.finishOp(18, 2); - } else { - this.finishOp(17, 1); - } - } else if (isIteratorStart(code2, next, this.input.charCodeAt(this.state.pos + 2))) { - this.state.pos += 2; - this.readIterator(); - } else { - super.getTokenFromCode(code2); - } - } - 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, isTuple, refExpressionErrors) { - const node = super.parseArrayLike(close, isTuple, refExpressionErrors); - if (refExpressionErrors != null && !this.state.maybeInArrowParameters) { - this.toReferencedList(node.elements); - } - return node; - } - isValidLVal(type, disallowCallExpression, isParenthesized, binding) { - return type === "TypeCastExpression" || super.isValidLVal(type, disallowCallExpression, 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) || this.match(51))) { - node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression(); - } - if (this.isContextual(113)) { - this.next(); - const implemented = node.implements = []; - do { - const node2 = this.startNode(); - node2.id = this.flowParseRestrictedIdentifier(true); - if (this.match(47)) { - node2.typeParameters = this.flowParseTypeParameterInstantiation(); - } else { - node2.typeParameters = null; - } - implemented.push(this.finishNode(node2, "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; - } - parseFunctionParamType(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 = this.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 = this.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 jsx2; - if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) { - state = this.state.clone(); - jsx2 = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); - if (!jsx2.error) return jsx2.node; - const { - context - } = this.state; - const currentContext = context[context.length - 1]; - if (currentContext === types.j_oTag || currentContext === types.j_expr) { - context.pop(); - } - } - if ((_jsx = jsx2) != 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 arrowExpression2 = this.forwardNoArrowParamsConversionAt(typeParameters, () => { - const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); - this.resetStartLocationFromNode(result, typeParameters); - return result; - }); - if ((_arrowExpression$extr = arrowExpression2.extra) != null && _arrowExpression$extr.parenthesized) abort(); - const expr = this.maybeUnwrapTypeCastExpression(arrowExpression2); - if (expr.type !== "ArrowFunctionExpression") abort(); - expr.typeParameters = typeParameters; - this.resetStartLocationFromNode(expr, typeParameters); - return arrowExpression2; - }, 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 = jsx2) != null && _jsx2.node) { - this.state = jsx2.failState; - return jsx2.node; - } - if (arrowExpression) { - this.state = arrow.failState; - return arrowExpression; - } - if ((_jsx3 = jsx2) != null && _jsx3.thrown) throw jsx2.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.includes(this.offsetToSourcePos(node.start))) { - node.params = params; - } else { - super.setArrowFunctionParameters(node, params); - } - } - checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { - if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) { - 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.includes(this.sourceToOffsetPos(this.state.start))); - } - parseSubscripts(base, startLoc, noCalls) { - if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) { - this.next(); - const node = this.startNodeAt(startLoc); - node.callee = base; - node.arguments = super.parseCallExpressionArguments(); - 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.flowParseTypeParameterInstantiationInExpression(); - this.expect(10); - node.arguments = this.parseCallExpressionArguments(); - node.optional = true; - return this.finishCallExpression(node, true); - } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) { - const node = this.startNodeAt(startLoc); - node.callee = base; - const result = this.tryParse(() => { - node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); - this.expect(10); - node.arguments = super.parseCallExpressionArguments(); - 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, void 0, true); - } - readToken_mult_modulo(code2) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (code2 === 42 && next === 47 && this.state.hasFlowComment) { - this.state.hasFlowComment = false; - this.state.pos += 2; - this.nextToken(); - return; - } - super.readToken_mult_modulo(code2); - } - readToken_pipe_amp(code2) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (code2 === 124 && next === 125) { - this.finishOp(9, 2); - return; - } - super.readToken_pipe_amp(code2); - } - 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 135: { - const literal = this.parseNumericLiteral(this.state.value); - if (endOfInit()) { - return { - type: "number", - loc: literal.loc.start, - value: literal - }; - } - return { - type: "invalid", - loc: startLoc - }; - } - case 134: { - 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 = /* @__PURE__ */ 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"); - } - jsxParseOpeningElementAfterName(node) { - if (this.shouldParseTypes()) { - if (this.match(47) || this.match(51)) { - node.typeArguments = this.flowParseTypeParameterInstantiationInExpression(); - } - } - return super.jsxParseOpeningElementAfterName(node); - } - 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; - } - 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; - } - maybeUnwrapTypeCastExpression(node) { - return node.type === "TypeCastExpression" ? node.expression : node; - } - }; - var entities = { - __proto__: null, - quot: '"', - amp: "&", - apos: "'", - lt: "<", - gt: ">", - nbsp: "\xA0", - iexcl: "\xA1", - cent: "\xA2", - pound: "\xA3", - curren: "\xA4", - yen: "\xA5", - brvbar: "\xA6", - sect: "\xA7", - uml: "\xA8", - copy: "\xA9", - ordf: "\xAA", - laquo: "\xAB", - not: "\xAC", - shy: "\xAD", - reg: "\xAE", - macr: "\xAF", - deg: "\xB0", - plusmn: "\xB1", - sup2: "\xB2", - sup3: "\xB3", - acute: "\xB4", - micro: "\xB5", - para: "\xB6", - middot: "\xB7", - cedil: "\xB8", - sup1: "\xB9", - ordm: "\xBA", - raquo: "\xBB", - frac14: "\xBC", - frac12: "\xBD", - frac34: "\xBE", - iquest: "\xBF", - Agrave: "\xC0", - Aacute: "\xC1", - Acirc: "\xC2", - Atilde: "\xC3", - Auml: "\xC4", - Aring: "\xC5", - AElig: "\xC6", - Ccedil: "\xC7", - Egrave: "\xC8", - Eacute: "\xC9", - Ecirc: "\xCA", - Euml: "\xCB", - Igrave: "\xCC", - Iacute: "\xCD", - Icirc: "\xCE", - Iuml: "\xCF", - ETH: "\xD0", - Ntilde: "\xD1", - Ograve: "\xD2", - Oacute: "\xD3", - Ocirc: "\xD4", - Otilde: "\xD5", - Ouml: "\xD6", - times: "\xD7", - Oslash: "\xD8", - Ugrave: "\xD9", - Uacute: "\xDA", - Ucirc: "\xDB", - Uuml: "\xDC", - Yacute: "\xDD", - THORN: "\xDE", - szlig: "\xDF", - agrave: "\xE0", - aacute: "\xE1", - acirc: "\xE2", - atilde: "\xE3", - auml: "\xE4", - aring: "\xE5", - aelig: "\xE6", - ccedil: "\xE7", - egrave: "\xE8", - eacute: "\xE9", - ecirc: "\xEA", - euml: "\xEB", - igrave: "\xEC", - iacute: "\xED", - icirc: "\xEE", - iuml: "\xEF", - eth: "\xF0", - ntilde: "\xF1", - ograve: "\xF2", - oacute: "\xF3", - ocirc: "\xF4", - otilde: "\xF5", - ouml: "\xF6", - divide: "\xF7", - oslash: "\xF8", - ugrave: "\xF9", - uacute: "\xFA", - ucirc: "\xFB", - uuml: "\xFC", - yacute: "\xFD", - thorn: "\xFE", - yuml: "\xFF", - 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" - }; - var lineBreak = /\r\n|[\r\n\u2028\u2029]/; - var lineBreakG = new RegExp(lineBreak.source, "g"); - function isNewLine(code2) { - switch (code2) { - case 10: - case 13: - case 8232: - case 8233: - return true; - default: - return false; - } - } - function hasNewLine(input, start, end) { - for (let i = start; i < end; i++) { - if (isNewLine(input.charCodeAt(i))) { - return true; - } - } - return false; - } - var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - var skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g; - function isWhitespace(code2) { - switch (code2) { - case 9: - case 11: - case 12: - case 32: - case 160: - case 5760: - case 8192: - case 8193: - case 8194: - case 8195: - case 8196: - case 8197: - case 8198: - case 8199: - case 8200: - case 8201: - case 8202: - case 8239: - case 8287: - case 12288: - case 65279: - return true; - default: - return false; - } - } - var 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(143); - } else { - super.getTokenFromCode(ch); - } - return; - } - out += this.input.slice(chunkStart, this.state.pos); - this.finishToken(142, 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(134, 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, void 0, 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(141, this.input.slice(start, this.state.pos)); - } - jsxParseIdentifier() { - const node = this.startNode(); - if (this.match(141)) { - 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.brace); - this.next(); - node = this.jsxParseExpressionContainer(node, types.j_oTag); - if (node.expression.type === "JSXEmptyExpression") { - this.raise(JsxErrors.AttributeIsEmpty, node); - } - return node; - case 143: - case 134: - 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.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.brace); - this.next(); - this.expect(21); - node.argument = this.parseMaybeAssignAllowIn(); - this.setContext(types.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(144)) { - return this.finishNode(node, "JSXOpeningFragment"); - } - node.name = this.jsxParseElementName(); - return this.jsxParseOpeningElementAfterName(node); - } - jsxParseOpeningElementAfterName(node) { - const attributes = []; - while (!this.match(56) && !this.match(144)) { - attributes.push(this.jsxParseAttribute()); - } - node.attributes = attributes; - node.selfClosing = this.eat(56); - this.expect(144); - return this.finishNode(node, "JSXOpeningElement"); - } - jsxParseClosingElementAt(startLoc) { - const node = this.startNodeAt(startLoc); - if (this.eat(144)) { - return this.finishNode(node, "JSXClosingFragment"); - } - node.name = this.jsxParseElementName(); - this.expect(144); - 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 143: - startLoc = this.state.startLoc; - this.next(); - if (this.eat(56)) { - closingElement = this.jsxParseClosingElementAt(startLoc); - break contents; - } - children.push(this.jsxParseElementAt(startLoc)); - break; - case 142: - children.push(this.parseLiteral(this.state.value, "JSXText")); - break; - case 5: { - const node2 = this.startNode(); - this.setContext(types.brace); - this.next(); - if (this.match(21)) { - children.push(this.jsxParseSpreadChild(node2)); - } else { - children.push(this.jsxParseExpressionContainer(node2, types.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(143)) { - return this.jsxParseElement(); - } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) { - this.replaceToken(143); - return this.jsxParseElement(); - } else { - return super.parseExprAtom(refExpressionErrors); - } - } - skipSpace() { - const curContext = this.curContext(); - if (!curContext.preserveSpace) super.skipSpace(); - } - getTokenFromCode(code2) { - const context = this.curContext(); - if (context === types.j_expr) { - this.jsxReadToken(); - return; - } - if (context === types.j_oTag || context === types.j_cTag) { - if (isIdentifierStart(code2)) { - this.jsxReadWord(); - return; - } - if (code2 === 62) { - ++this.state.pos; - this.finishToken(144); - return; - } - if ((code2 === 34 || code2 === 39) && context === types.j_oTag) { - this.jsxReadString(code2); - return; - } - } - if (code2 === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) { - ++this.state.pos; - this.finishToken(143); - return; - } - super.getTokenFromCode(code2); - } - updateContext(prevType) { - const { - context, - type - } = this.state; - if (type === 56 && prevType === 143) { - context.splice(-2, 2, types.j_cTag); - this.state.canStartJSXElement = false; - } else if (type === 143) { - context.push(types.j_oTag); - } else if (type === 144) { - const out = context[context.length - 1]; - if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) { - context.pop(); - this.state.canStartJSXElement = context[context.length - 1] === types.j_expr; - } else { - this.setContext(types.j_expr); - this.state.canStartJSXElement = true; - } - } else { - this.state.canStartJSXElement = tokenComesBeforeExpression(type); - } - } - }; - var TypeScriptScope = class extends Scope { - constructor(...args) { - super(...args); - this.tsNames = /* @__PURE__ */ new Map(); - } - }; - var TypeScriptScopeHandler = class extends ScopeHandler { - constructor(...args) { - super(...args); - this.importsStack = []; - } - createScope(flags) { - this.importsStack.push(/* @__PURE__ */ new Set()); - return new TypeScriptScope(flags); - } - enter(flags) { - if (flags === 1024) { - this.importsStack.push(/* @__PURE__ */ new Set()); - } - super.enter(flags); - } - exit() { - const flags = super.exit(); - if (flags === 1024) { - 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); - } - }; - var ProductionParameterHandler = class { - 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); - } - var BaseParser = class { - constructor() { - this.sawUnambiguousESM = false; - this.ambiguousScriptDifferentAst = false; - } - sourceToOffsetPos(sourcePos) { - return sourcePos + this.startIndex; - } - offsetToSourcePos(offsetPos) { - return offsetPos - this.startIndex; - } - 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 === void 0) { - node.trailingComments = comments; - } else { - node.trailingComments.unshift(...comments); - } - } - function setLeadingComments(node, comments) { - if (node.leadingComments === void 0) { - node.leadingComments = comments; - } else { - node.leadingComments.unshift(...comments); - } - } - function setInnerComments(node, comments) { - if (node.innerComments === void 0) { - 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); - } - } - var CommentsParser = class 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) { - var _node$options; - 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 node = commentWS.containingNode; - const commentStart = commentWS.start; - if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) { - switch (node.type) { - case "ObjectExpression": - case "ObjectPattern": - adjustInnerComments(node, node.properties, commentWS); - break; - case "CallExpression": - case "NewExpression": - case "OptionalCallExpression": - adjustInnerComments(node, node.arguments, commentWS); - break; - case "ImportExpression": - adjustInnerComments(node, [node.source, (_node$options = node.options) != null ? _node$options : null], commentWS); - break; - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - case "ObjectMethod": - case "ClassMethod": - case "ClassPrivateMethod": - case "TSTypeParameterDeclaration": - adjustInnerComments(node, node.params, commentWS); - break; - case "ArrayExpression": - case "ArrayPattern": - adjustInnerComments(node, node.elements, commentWS); - break; - case "ExportNamedDeclaration": - case "ImportDeclaration": - adjustInnerComments(node, node.specifiers, commentWS); - break; - case "TSEnumDeclaration": - adjustInnerComments(node, node.members, commentWS); - break; - case "TSEnumBody": - adjustInnerComments(node, node.members, commentWS); - break; - case "TSInterfaceBody": - adjustInnerComments(node, node.body, commentWS); - break; - default: { - if (node.type === "RecordExpression") { - adjustInnerComments(node, node.properties, commentWS); - break; - } - if (node.type === "TupleExpression") { - adjustInnerComments(node, node.elements, commentWS); - break; - } - 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; - } - } - 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; - } - } - } - }; - var State = class _State { - constructor() { - this.flags = 1024; - this.startIndex = void 0; - 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 = 140; - this.value = null; - this.start = 0; - this.end = 0; - this.lastTokEndLoc = null; - this.lastTokStartLoc = null; - this.context = [types.brace]; - this.firstInvalidTemplateEscapePos = null; - this.strictErrors = /* @__PURE__ */ new Map(); - this.tokensLength = 0; - } - get strict() { - return (this.flags & 1) > 0; - } - set strict(v) { - if (v) this.flags |= 1; - else this.flags &= -2; - } - init({ - strictMode, - sourceType, - startIndex, - startLine, - startColumn - }) { - this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; - this.startIndex = startIndex; - this.curLine = startLine; - this.lineStart = -startColumn; - this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex); - } - get maybeInArrowParameters() { - return (this.flags & 2) > 0; - } - set maybeInArrowParameters(v) { - if (v) this.flags |= 2; - else this.flags &= -3; - } - get inType() { - return (this.flags & 4) > 0; - } - set inType(v) { - if (v) this.flags |= 4; - else this.flags &= -5; - } - get noAnonFunctionType() { - return (this.flags & 8) > 0; - } - set noAnonFunctionType(v) { - if (v) this.flags |= 8; - else this.flags &= -9; - } - get hasFlowComment() { - return (this.flags & 16) > 0; - } - set hasFlowComment(v) { - if (v) this.flags |= 16; - else this.flags &= -17; - } - get isAmbientContext() { - return (this.flags & 32) > 0; - } - set isAmbientContext(v) { - if (v) this.flags |= 32; - else this.flags &= -33; - } - get inAbstractClass() { - return (this.flags & 64) > 0; - } - set inAbstractClass(v) { - if (v) this.flags |= 64; - else this.flags &= -65; - } - get inDisallowConditionalTypesContext() { - return (this.flags & 128) > 0; - } - set inDisallowConditionalTypesContext(v) { - if (v) this.flags |= 128; - else this.flags &= -129; - } - get soloAwait() { - return (this.flags & 256) > 0; - } - set soloAwait(v) { - if (v) this.flags |= 256; - else this.flags &= -257; - } - get inFSharpPipelineDirectBody() { - return (this.flags & 512) > 0; - } - set inFSharpPipelineDirectBody(v) { - if (v) this.flags |= 512; - else this.flags &= -513; - } - get canStartJSXElement() { - return (this.flags & 1024) > 0; - } - set canStartJSXElement(v) { - if (v) this.flags |= 1024; - else this.flags &= -1025; - } - get containsEsc() { - return (this.flags & 2048) > 0; - } - set containsEsc(v) { - if (v) this.flags |= 2048; - else this.flags &= -2049; - } - get hasTopLevelAwait() { - return (this.flags & 4096) > 0; - } - set hasTopLevelAwait(v) { - if (v) this.flags |= 4096; - else this.flags &= -4097; - } - curPosition() { - return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex); - } - clone() { - const state = new _State(); - state.flags = this.flags; - state.startIndex = this.startIndex; - 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(code2) { - return code2 >= 48 && code2 <= 57; - }; - var forbiddenNumericSeparatorSiblings = { - decBinOct: /* @__PURE__ */ new Set([46, 66, 69, 79, 95, 98, 101, 111]), - hex: /* @__PURE__ */ new Set([46, 88, 95, 120]) - }; - var 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 = (ch2) => ({ - pos, - ch: ch2, - lineStart, - curLine - }); - const ch = input.charCodeAt(pos++); - switch (ch) { - case 110: - return res("\n"); - case 114: - return res("\r"); - case 120: { - let code2; - ({ - code: code2, - pos - } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); - return res(code2 === null ? null : String.fromCharCode(code2)); - } - case 117: { - let code2; - ({ - code: code2, - pos - } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); - return res(code2 === null ? null : String.fromCodePoint(code2)); - } - case 116: - return res(" "); - case 98: - return res("\b"); - case 118: - return res("\v"); - 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 = /^[0-7]+/.exec(input.slice(startPos, pos + 2)); - 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 code2 = input.charCodeAt(pos); - let val; - if (code2 === 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 (code2 >= 97) { - val = code2 - 97 + 10; - } else if (code2 >= 65) { - val = code2 - 65 + 10; - } else if (_isDigit(code2)) { - val = code2 - 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 code2; - if (ch === 123) { - ++pos; - ({ - code: code2, - pos - } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); - ++pos; - if (code2 !== null && code2 > 1114111) { - if (throwOnInvalid) { - errors.invalidCodePoint(pos, lineStart, curLine); - } else { - return { - code: null, - pos - }; - } - } - } else { - ({ - code: code2, - pos - } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); - } - return { - code: code2, - pos - }; - } - function buildPosition(pos, lineStart, curLine) { - return new Position(curLine, pos - lineStart, pos); - } - var VALID_REGEX_FLAGS = /* @__PURE__ */ new Set([103, 109, 115, 105, 121, 117, 100, 118]); - var Token = class { - constructor(state) { - const startIndex = state.startIndex || 0; - this.type = state.type; - this.value = state.value; - this.start = startIndex + state.start; - this.end = startIndex + state.end; - this.loc = new SourceLocation(state.startLoc, state.endLoc); - } - }; - var Tokenizer = class extends CommentsParser { - constructor(options, input) { - super(); - this.isLookahead = void 0; - this.tokens = []; - this.errorHandlers_readInt = { - invalidDigit: (pos, lineStart, curLine, radix) => { - if (!(this.optionFlags & 2048)) 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.optionFlags & 256) { - 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.lookaheadCharCodeSince(this.state.pos); - } - lookaheadCharCodeSince(pos) { - return this.input.charCodeAt(this.nextTokenStartSince(pos)); - } - 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 & 64512) === 55296 && ++pos < this.input.length) { - const trail = this.input.charCodeAt(pos); - if ((trail & 64512) === 56320) { - cp = 65536 + ((cp & 1023) << 10) + (trail & 1023); - } - } - 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(140); - 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: this.sourceToOffsetPos(start), - end: this.sourceToOffsetPos(end + commentEnd.length), - loc: new SourceLocation(startLoc, this.state.curPosition()) - }; - if (this.optionFlags & 256) 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: this.sourceToOffsetPos(start), - end: this.sourceToOffsetPos(end), - loc: new SourceLocation(startLoc, this.state.curPosition()) - }; - if (this.optionFlags & 256) this.pushToken(comment); - return comment; - } - skipSpace() { - const spaceStart = this.state.pos; - const comments = this.optionFlags & 4096 ? [] : null; - 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 !== void 0) { - this.addComment(comment); - comments == null || comments.push(comment); - } - break; - } - case 47: { - const comment = this.skipLineComment(2); - if (comment !== void 0) { - this.addComment(comment); - comments == null || comments.push(comment); - } - break; - } - default: - break loop; - } - break; - default: - if (isWhitespace(ch)) { - ++this.state.pos; - } else if (ch === 45 && !this.inModule && this.optionFlags & 8192) { - 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 !== void 0) { - this.addComment(comment); - comments == null || comments.push(comment); - } - } else { - break loop; - } - } else if (ch === 60 && !this.inModule && this.optionFlags & 8192) { - 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 !== void 0) { - this.addComment(comment); - comments == null || comments.push(comment); - } - } else { - break loop; - } - } else { - break loop; - } - } - } - if ((comments == null ? void 0 : comments.length) > 0) { - const end = this.state.pos; - const commentWhitespace = { - start: this.sourceToOffsetPos(spaceStart), - end: this.sourceToOffsetPos(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(139, this.readWord1(next)); - } else if (next === 92) { - ++this.state.pos; - this.finishToken(139, 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(code2) { - let type = code2 === 42 ? 55 : 54; - let width = 1; - let next = this.input.charCodeAt(this.state.pos + 1); - if (code2 === 42 && next === 42) { - width++; - next = this.input.charCodeAt(this.state.pos + 2); - type = 57; - } - if (next === 61 && !this.state.inType) { - width++; - type = code2 === 37 ? 33 : 30; - } - this.finishOp(type, width); - } - readToken_pipe_amp(code2) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === code2) { - if (this.input.charCodeAt(this.state.pos + 2) === 61) { - this.finishOp(30, 3); - } else { - this.finishOp(code2 === 124 ? 41 : 42, 2); - } - return; - } - if (code2 === 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(code2 === 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(code2) { - const next = this.input.charCodeAt(this.state.pos + 1); - if (next === code2) { - 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(code2) { - 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 (code2 === 61 && next === 62) { - this.state.pos += 2; - this.finishToken(19); - return; - } - this.finishOp(code2 === 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(code2) { - switch (code2) { - 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(code2); - return; - case 47: - this.readToken_slash(); - return; - case 37: - case 42: - this.readToken_mult_modulo(code2); - return; - case 124: - case 38: - this.readToken_pipe_amp(code2); - return; - case 94: - this.readToken_caret(); - return; - case 43: - case 45: - this.readToken_plus_min(code2); - return; - case 60: - this.readToken_lt(); - return; - case 62: - this.readToken_gt(); - return; - case 61: - case 33: - this.readToken_eq_excl(code2); - 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(code2)) { - this.readWord(code2); - return; - } - } - throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), { - unexpected: String.fromCodePoint(code2) - }); - } - 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(138, { - 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 start = this.state.pos; - 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(start, this.state.pos).replace(/[_n]/g, ""); - this.finishToken(136, str); - return; - } - this.finishToken(135, val); - } - readNumber(startsWithDot) { - const start = this.state.pos; - const startLoc = this.state.curPosition(); - let isFloat = false; - let isBigInt = 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; - var 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(136, str); - return; - } - if (isDecimal) { - this.finishToken(137, str); - return; - } - const val = isOctal ? parseInt(str, 8) : parseFloat(str); - this.finishToken(135, val); - } - readCodePoint(throwOnInvalid) { - const { - code: code2, - pos - } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint); - this.state.pos = pos; - return code2; - } - 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(134, 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, this.sourceToOffsetPos(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 !== void 0) { - this.state.pos += firstCode <= 65535 ? 1 : 2; - } - while (this.state.pos < this.length) { - const ch = this.codePointAtPos(this.state.pos); - if (isIdentifierChar(ch)) { - this.state.pos += ch <= 65535 ? 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 !== void 0) { - 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.optionFlags & 2048)) 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)); - }; - } - }; - var ClassScope = class { - constructor() { - this.privateNames = /* @__PURE__ */ new Set(); - this.loneAccessors = /* @__PURE__ */ new Map(); - this.undefinedPrivateNames = /* @__PURE__ */ new Map(); - } - }; - var ClassScopeHandler = class { - constructor(parser) { - this.parser = void 0; - this.stack = []; - this.undefinedPrivateNames = /* @__PURE__ */ 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 - }); - } - } - }; - var ExpressionScope = class { - constructor(type = 0) { - this.type = type; - } - canBeArrowParameterDeclaration() { - return this.type === 2 || this.type === 1; - } - isCertainlyParameterDeclaration() { - return this.type === 3; - } - }; - var ArrowHeadParsingScope = class extends ExpressionScope { - constructor(type) { - super(type); - this.declarationErrors = /* @__PURE__ */ 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); - } - }; - var ExpressionScopeHandler = class { - 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(); - } - var UtilParser = class extends Tokenizer { - addExtra(node, key, value, enumerable = true) { - if (!node) return; - let { - extra - } = node; - if (extra == null) { - extra = {}; - node.extra = 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) { - if (this.input.startsWith(name, nameStart)) { - const nextCh = this.input.charCodeAt(nameStart + name.length); - return !(isIdentifierChar(nextCh) || (nextCh & 64512) === 55296); - } - 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(140) || this.match(8) || this.hasPrecedingLineBreak(); - } - hasPrecedingLineBreak() { - return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start); - } - hasFollowingLineBreak() { - return hasNewLine(this.input, this.state.end, this.nextTokenStart()); - } - 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) { - if (!this.eat(type)) { - this.unexpected(loc, type); - } - } - tryParse(fn, oldState = this.state.clone()) { - const abortSignal = { - node: null - }; - try { - const node = fn((node2 = null) => { - abortSignal.node = node2; - 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, - voidPatternLoc - } = refExpressionErrors; - const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc || !!voidPatternLoc; - 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); - } - if (voidPatternLoc != null) { - this.raise(Errors.InvalidCoverDiscardElement, voidPatternLoc); - } - } - 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 = /* @__PURE__ */ new Set(); - const oldInModule = this.inModule; - this.inModule = inModule; - const oldScope = this.scope; - const ScopeHandler2 = this.getScopeHandler(); - this.scope = new ScopeHandler2(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 || this.optionFlags & 1) { - paramFlags |= 2; - } - if (this.optionFlags & 32) { - paramFlags |= 1; - } - const isCommonJS = !this.inModule && this.options.sourceType === "commonjs"; - if (isCommonJS || this.optionFlags & 2) { - paramFlags |= 4; - } - this.prodParam.enter(paramFlags); - let scopeFlags = isCommonJS ? 514 : 1; - if (this.optionFlags & 4) { - scopeFlags |= 512; - } - this.scope.enter(scopeFlags); - } - checkDestructuringPrivate(refExpressionErrors) { - const { - privateKeyLoc - } = refExpressionErrors; - if (privateKeyLoc !== null) { - this.expectPlugin("destructuringPrivate", privateKeyLoc); - } - } - }; - var ExpressionErrors = class { - constructor() { - this.shorthandAssignLoc = null; - this.doubleProtoLoc = null; - this.privateKeyLoc = null; - this.optionalParametersLoc = null; - this.voidPatternLoc = null; - } - }; - var Node2 = class { - constructor(parser, pos, loc) { - this.type = ""; - this.start = pos; - this.end = 0; - this.loc = new SourceLocation(loc); - if ((parser == null ? void 0 : parser.optionFlags) & 128) this.range = [pos, 0]; - if (parser != null && parser.filename) this.loc.filename = parser.filename; - } - }; - var NodePrototype = Node2.prototype; - NodePrototype.__clone = function() { - const newNode = new Node2(void 0, 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; - }; - var NodeUtils = class extends UtilParser { - startNode() { - const loc = this.state.startLoc; - return new Node2(this, loc.index, loc); - } - startNodeAt(loc) { - return new Node2(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.optionFlags & 128) node.range[1] = endLoc.index; - if (this.optionFlags & 4096) { - this.processComment(node); - } - return node; - } - resetStartLocation(node, startLoc) { - node.start = startLoc.index; - node.loc.start = startLoc; - if (this.optionFlags & 128) node.range[0] = startLoc.index; - } - resetEndLocation(node, endLoc = this.state.lastTokEndLoc) { - node.end = endLoc.index; - node.loc.end = endLoc; - if (this.optionFlags & 128) node.range[1] = endLoc.index; - } - resetStartLocationFromNode(node, locationNode) { - this.resetStartLocation(node, locationNode.loc.start); - } - castNodeTo(node, type) { - node.type = type; - return node; - } - cloneIdentifier(node) { - const { - type, - start, - end, - loc, - range, - name - } = node; - const cloned = Object.create(NodePrototype); - cloned.type = type; - cloned.start = start; - cloned.end = end; - cloned.loc = loc; - cloned.range = range; - cloned.name = name; - if (node.extra) cloned.extra = node.extra; - return cloned; - } - cloneStringLiteral(node) { - const { - type, - start, - end, - loc, - range, - extra - } = 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.value = node.value; - return cloned; - } - }; - var unwrapParenthesizedExpression = (node) => { - return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; - }; - var LValParser = class extends NodeUtils { - toAssignable(node, isLHS = false) { - var _node$extra, _node$extra3; - let parenthesized = void 0; - 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 !== "CallExpression" && 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": - case "VoidPattern": - break; - case "ObjectExpression": - this.castNodeTo(node, "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": - this.castNodeTo(node, "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); - } - this.castNodeTo(node, "AssignmentPattern"); - delete node.operator; - if (node.left.type === "VoidPattern") { - this.raise(Errors.VoidPatternInitializer, node.left); - } - 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") { - this.castNodeTo(prop, "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; - this.toAssignableListItem(exprList, i, isLHS); - if (elt.type === "RestElement") { - if (i < end) { - this.raise(Errors.RestTrailingComma, elt); - } else if (trailingCommaLoc) { - this.raise(Errors.RestTrailingComma, trailingCommaLoc); - } - } - } - } - toAssignableListItem(exprList, index, isLHS) { - const node = exprList[index]; - if (node.type === "SpreadElement") { - this.castNodeTo(node, "RestElement"); - const arg = node.argument; - this.checkToRestConversion(arg, true); - this.toAssignable(arg, isLHS); - } else { - this.toAssignable(node, isLHS); - } - } - isAssignable(node, isBinding) { - switch (node.type) { - case "Identifier": - case "ObjectPattern": - case "ArrayPattern": - case "AssignmentPattern": - case "RestElement": - case "VoidPattern": - 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, void 0); - return this.finishNode(node, "SpreadElement"); - } - parseRestBinding() { - const node = this.startNode(); - this.next(); - const argument = this.parseBindingAtom(); - if (argument.type === "VoidPattern") { - this.raise(Errors.UnexpectedVoidPattern, argument); - } - node.argument = argument; - 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); - case 88: - return this.parseVoidPattern(null); - } - 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)) { - let rest = this.parseRestBinding(); - if (this.hasPlugin("flow") || flags & 2) { - rest = this.parseFunctionParamType(rest); - } - elts.push(rest); - if (!this.checkCommaAfterRest(closeCharCode)) { - this.expect(close); - break; - } - } else { - const decorators = []; - if (flags & 2) { - 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.parseBindingElement(flags, decorators)); - } - } - return elts; - } - parseBindingRestProperty(prop) { - this.next(); - if (this.hasPlugin("discardBinding") && this.match(88)) { - prop.argument = this.parseVoidPattern(null); - this.raise(Errors.UnexpectedVoidPattern, prop.argument); - } else { - prop.argument = this.parseIdentifier(); - } - this.checkCommaAfterRest(125); - return this.finishNode(prop, "RestElement"); - } - parseBindingProperty() { - const { - type, - startLoc - } = this.state; - if (type === 21) { - return this.parseBindingRestProperty(this.startNode()); - } - const prop = this.startNode(); - if (type === 139) { - 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); - } - parseBindingElement(flags, decorators) { - const left = this.parseMaybeDefault(); - if (this.hasPlugin("flow") || flags & 2) { - this.parseFunctionParamType(left); - } - if (decorators.length) { - left.decorators = decorators; - this.resetStartLocationFromNode(left, decorators[0]); - } - const elt = this.parseMaybeDefault(left.loc.start, left); - return elt; - } - parseFunctionParamType(param) { - return param; - } - parseMaybeDefault(startLoc, left) { - startLoc != null ? startLoc : startLoc = this.state.startLoc; - left = left != null ? left : this.parseBindingAtom(); - if (!this.eat(29)) return left; - const node = this.startNodeAt(startLoc); - if (left.type === "VoidPattern") { - this.raise(Errors.VoidPatternInitializer, left); - } - node.left = left; - node.right = this.parseMaybeAssignAllowIn(); - return this.finishNode(node, "AssignmentPattern"); - } - isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) { - switch (type) { - case "AssignmentPattern": - return "left"; - case "RestElement": - return "argument"; - case "ObjectProperty": - return "value"; - case "ParenthesizedExpression": - return "expression"; - case "ArrayPattern": - return "elements"; - case "ObjectPattern": - return "properties"; - case "VoidPattern": - return true; - case "CallExpression": - if (!disallowCallExpression && !this.state.strict && this.optionFlags & 8192) { - return true; - } - } - return false; - } - isOptionalMemberExpression(expression) { - return expression.type === "OptionalMemberExpression"; - } - checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false, disallowCallExpression = 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; - } else if (type === "VoidPattern" && ancestor.type === "CatchClause") { - this.raise(Errors.VoidPatternCatchClauseParam, expression); - } - const unwrappedExpression = unwrapParenthesizedExpression(expression); - disallowCallExpression || (disallowCallExpression = unwrappedExpression.type === "CallExpression" && (unwrappedExpression.callee.type === "Import" || unwrappedExpression.callee.type === "Super")); - const validity = this.isValidLVal(type, disallowCallExpression, !(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; - } - let key, isParenthesizedExpression; - if (typeof validity === "string") { - key = validity; - isParenthesizedExpression = type === "ParenthesizedExpression"; - } else { - [key, isParenthesizedExpression] = validity; - } - const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? { - type - } : ancestor; - const val = expression[key]; - if (Array.isArray(val)) { - for (const child of val) { - if (child) { - this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, true); - } - } - } else if (val) { - this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, disallowCallExpression); - } - } - 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; - } - }; - var keywordAndTSRelationalOperator = /in(?:stanceof)?|as|satisfies/y; - function nonNull(x) { - if (x == null) { - throw new Error(`Unexpected ${x} value.`); - } - return x; - } - function assert(x) { - if (!x) { - throw new Error("Assert fail"); - } - } - var 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.`, - AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.", - AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", - AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.", - ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", - ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", - ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "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: '${modifier}'.`, - 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.", - InvalidHeritageClauseType: ({ - token - }) => `'${token}' list can only include identifiers or qualified-names with optional type arguments.`, - InvalidModifierOnAwaitUsingDeclaration: (modifier) => `'${modifier}' modifier cannot appear on an await using declaration.`, - 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.`, - InvalidModifierOnUsingDeclaration: (modifier) => `'${modifier}' modifier cannot appear on a using declaration.`, - 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.", - NonClassMethodPropertyHasAbstractModifier: "'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 `() => ...`.", - ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", - SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", - SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", - SetAccessorCannotHaveReturnType: "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}.`, - UsingDeclarationInAmbientContext: (kind) => `'${kind}' declarations are not allowed in ambient contexts.` - }); - 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 void 0; - } - } - 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(139) || this.isLiteralPropertyName(); - } - tsNextTokenOnSameLineAndCanFollowModifier() { - this.next(); - if (this.hasPrecedingLineBreak()) { - return false; - } - return this.tsTokenCanFollowModifier(); - } - tsNextTokenCanFollowModifier() { - if (this.match(106)) { - this.next(); - return this.tsTokenCanFollowModifier(); - } - return this.tsNextTokenOnSameLineAndCanFollowModifier(); - } - tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) { - if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) { - return void 0; - } - const modifier = this.state.value; - if (allowedModifiers.includes(modifier)) { - if (hasSeenStaticModifier && this.match(106)) { - return void 0; - } - if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { - return void 0; - } - if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { - return modifier; - } - } - return void 0; - } - 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, modified.static); - 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 (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 void 0; - } - result.push(element); - if (this.eat(12)) { - trailingCommaPos = this.state.lastTokStartLoc.index; - continue; - } - if (this.tsIsListTerminator(kind)) { - break; - } - if (expectSuccess) { - this.expect(12); - } - return void 0; - } - 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(134)) { - this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc); - node.argument = super.parseExprAtom(); - } else { - node.argument = this.parseStringLiteral(this.state.value); - } - if (this.eat(12)) { - node.options = this.tsParseImportTypeOptions(); - } else { - node.options = null; - } - this.expect(11); - if (this.eat(16)) { - node.qualifier = this.tsParseEntityName(1 | 2); - } - if (this.match(47)) { - node.typeParameters = this.tsParseTypeArguments(); - } - return this.finishNode(node, "TSImportType"); - } - tsParseImportTypeOptions() { - const node = this.startNode(); - this.expect(5); - const withProperty = this.startNode(); - if (this.isContextual(76)) { - withProperty.method = false; - withProperty.key = this.parseIdentifier(true); - withProperty.computed = false; - withProperty.shorthand = false; - } else { - this.unexpected(null, 76); - } - this.expect(14); - withProperty.value = this.tsParseImportTypeWithPropertyValue(); - node.properties = [this.finishObjectProperty(withProperty)]; - this.eat(12); - this.expect(8); - return this.finishNode(node, "ObjectExpression"); - } - tsParseImportTypeWithPropertyValue() { - const node = this.startNode(); - const properties = []; - this.expect(5); - while (!this.match(8)) { - const type = this.state.type; - if (tokenIsIdentifier(type) || type === 134) { - properties.push(super.parsePropertyDefinition(null)); - } else { - this.unexpected(); - } - this.eat(12); - } - node.properties = properties; - this.next(); - return this.finishNode(node, "ObjectExpression"); - } - tsParseEntityName(flags) { - let entity; - if (flags & 1 && this.match(78)) { - if (flags & 2) { - entity = this.parseIdentifier(true); - } else { - const node = this.startNode(); - this.next(); - entity = this.finishNode(node, "ThisExpression"); - } - } else { - entity = this.parseIdentifier(!!(flags & 1)); - } - while (this.eat(16)) { - const node = this.startNodeAtNode(entity); - node.left = entity; - node.right = this.parseIdentifier(!!(flags & 1)); - entity = this.finishNode(node, "TSQualifiedName"); - } - return entity; - } - tsParseTypeReference() { - const node = this.startNode(); - node.typeName = this.tsParseEntityName(1); - 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(1 | 2); - } - 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(143)) { - 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; - if (this.match(10) || this.match(47)) { - if (readonly) { - this.raise(TSErrors.ReadonlyForMethodSignature, node); - } - const method = node; - if (method.kind && this.match(47)) { - this.raise(TSErrors.AccessorCannotHaveTypeParameters, 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.AccessorCannotDeclareThisParameter, 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.AccessorCannotDeclareThisParameter, this.state.curPosition()); - } - if (firstParameter.type === "Identifier" && firstParameter.optional) { - this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition()); - } - if (firstParameter.type === "RestElement") { - this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition()); - } - } - if (method[returnTypeKey]) { - this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]); - } - } else { - method.kind = "method"; - } - return this.finishNode(method, "TSMethodSignature"); - } else { - const property = node; - 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); - if (!this.match(10) && !this.match(47)) { - this.unexpected(null, 10); - } - } - 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); - } - 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); - const typeParameter = this.startNode(); - typeParameter.name = this.tsParseTypeParameterName(); - typeParameter.constraint = this.tsExpectThenParseType(58); - node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); - 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 restStartLoc = this.state.startLoc; - const rest = this.eat(21); - const { - startLoc - } = this.state; - 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 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.startNodeAt(startLoc); - 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.startNodeAt(startLoc); - 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.startNodeAt(startLoc); - optionalTypeNode.typeAnnotation = type; - type = this.finishNode(optionalTypeNode, "TSOptionalType"); - } - if (rest) { - const restNode = this.startNodeAt(restStartLoc); - 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 135: - case 136: - case 134: - 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 134: - case 135: - case 136: - case 85: - case 86: - return this.tsParseLiteralTypeNode(); - case 53: - if (this.state.value === "-") { - const node = this.startNode(); - const nextToken = this.lookahead(); - if (nextToken.type !== 135 && nextToken.type !== 136) { - 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 !== void 0 && this.lookaheadCharCode() !== 46) { - const node = this.startNode(); - this.next(); - return this.finishNode(node, nodeType); - } - return this.tsParseTypeReference(); - } - } - } - throw this.unexpected(); - } - tsParseArrayTypeOrHigher() { - const { - startLoc - } = this.state; - let type = this.tsParseNonArrayType(); - while (!this.hasPrecedingLineBreak() && this.eat(0)) { - if (this.match(3)) { - const node = this.startNodeAt(startLoc); - node.elementType = type; - this.expect(3); - type = this.finishNode(node, "TSArrayType"); - } else { - const node = this.startNodeAt(startLoc); - 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 types2 = []; - do { - types2.push(parseConstituentType()); - } while (this.eat(operator)); - if (types2.length === 1 && !hasLeadingOperator) { - return types2[0]; - } - node.types = types2; - 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(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.isLookaheadContextual("new"); - } - 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(1 | 2); - 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.lookaheadCharCode() !== 46) { - const node2 = this.startNode(); - this.next(); - return this.finishNode(node2, "TSIntrinsicKeyword"); - } - return this.tsParseType(); - }); - this.semicolon(); - return this.finishNode(node, "TSTypeAliasDeclaration"); - } - tsInTopLevelContext(cb) { - if (this.curContext() !== types.brace) { - const oldContext = this.state.context; - this.state.context = [oldContext[0]]; - try { - return cb(); - } finally { - this.state.context = oldContext; - } - } else { - return cb(); - } - } - 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(134) ? 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"); - } - tsParseEnumBody() { - const node = this.startNode(); - this.expect(5); - node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); - this.expect(8); - return this.finishNode(node, "TSEnumBody"); - } - tsParseModuleBlock() { - const node = this.startNode(); - this.scope.enter(0); - this.expect(5); - super.parseBlockOrModuleBlockBody(node.body = [], void 0, 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(1024); - 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.kind = "global"; - node.global = true; - node.id = this.parseIdentifier(); - } else if (this.match(134)) { - node.kind = "module"; - node.id = super.parseStringLiteral(this.state.value); - } else { - this.unexpected(); - } - if (this.match(5)) { - this.scope.enter(1024); - 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(0); - } - tsParseExternalModuleReference() { - const node = this.startNode(); - this.expectContextual(119); - this.expect(10); - if (!this.match(134)) { - 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 !== void 0 && result !== false) { - return result; - } - this.state = state; - } - tsTryParseDeclare(node) { - if (this.isLineTerminator()) { - return; - } - const startType = this.state.type; - return this.tsInAmbientContext(() => { - switch (startType) { - case 68: - node.declare = true; - return super.parseFunctionStatement(node, false, false); - case 80: - node.declare = true; - return this.parseClass(node, true, false); - case 126: - return this.tsParseEnumDeclaration(node, { - declare: true - }); - case 112: - return this.tsParseAmbientExternalModuleDeclaration(node); - case 100: - if (this.state.containsEsc) { - return; - } - case 75: - case 74: - if (!this.match(75) || !this.isLookaheadContextual("enum")) { - node.declare = true; - return this.parseVarStatement(node, this.state.value, true); - } - this.expect(75); - return this.tsParseEnumDeclaration(node, { - const: true, - declare: true - }); - case 107: - if (this.isUsing()) { - this.raise(TSErrors.InvalidModifierOnUsingDeclaration, this.state.startLoc, "declare"); - node.declare = true; - return this.parseVarStatement(node, "using", true); - } - break; - case 96: - if (this.isAwaitUsing()) { - this.raise(TSErrors.InvalidModifierOnAwaitUsingDeclaration, this.state.startLoc, "declare"); - node.declare = true; - this.next(); - return this.parseVarStatement(node, "await using", true); - } - break; - case 129: { - const result = this.tsParseInterfaceDeclaration(node, { - declare: true - }); - if (result) return result; - } - default: - if (tokenIsIdentifier(startType)) { - return this.tsParseDeclaration(node, this.state.type, true, null); - } - } - }); - } - tsTryParseExportDeclaration() { - return this.tsParseDeclaration(this.startNode(), this.state.type, true, null); - } - tsParseDeclaration(node, type, next, decorators) { - switch (type) { - case 124: - if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) { - return this.tsParseAbstractDeclaration(node, decorators); - } - break; - case 127: - if (this.tsCheckLineTerminator(next)) { - if (this.match(134)) { - return this.tsParseAmbientExternalModuleDeclaration(node); - } else if (tokenIsIdentifier(this.state.type)) { - node.kind = "module"; - return this.tsParseModuleOrNamespaceDeclaration(node); - } - } - break; - case 128: - if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { - node.kind = "namespace"; - return this.tsParseModuleOrNamespaceDeclaration(node); - } - break; - case 130: - 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.tsInTopLevelContext(() => { - 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.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(); - } - parseBindingElement(flags, decorators) { - const startLoc = decorators.length ? decorators[0].loc.start : 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(); - if (flags & 2) { - this.parseFunctionParamType(left); - } - 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" : void 0; - 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, isTuple, refExpressionErrors) { - const node = super.parseArrayLike(close, 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) { - state.stop = true; - 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 result2 = super.parseTaggedTemplateExpression(base, startLoc, state); - result2.typeParameters = typeArguments; - return result2; - } - if (!noCalls && this.eat(10)) { - const node2 = this.startNodeAt(startLoc); - node2.callee = base; - node2.arguments = this.parseCallExpressionArguments(); - this.tsCheckForInvalidTypeCasts(node2.arguments); - node2.typeParameters = typeArguments; - if (state.optionalChainMember) { - node2.optional = isOptionalCall; - } - return this.finishCallExpression(node2, state.optionalChainMember); - } - const tokenType = this.state.type; - if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenType !== 93 && tokenType !== 120 && 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") { - if (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40) { - this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc); - } - if (!this.match(16) && !this.match(18)) { - result.expression = super.stopParseSubscript(base, state); - } - } - 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(134)) { - 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)) { - const nodeImportEquals = node; - this.next(); - let maybeDefaultIdentifier = null; - if (this.isContextual(130) && this.isPotentialImportPhase(false)) { - maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false); - } else { - nodeImportEquals.importKind = "value"; - } - const declaration = this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true); - return declaration; - } 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.isLookaheadContextual("class"); - } - 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; - if (!node.declare && (kind === "using" || kind === "await using")) { - this.raiseOverwrite(TSErrors.UsingDeclarationInAmbientContext, node, kind); - return declaration; - } - for (const { - id, - init - } of declaration.declarations) { - if (!init) continue; - if (kind === "var" || kind === "let" || !!id.typeAnnotation) { - this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init); - } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) { - this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init); - } - } - return declaration; - } - parseStatementContent(flags, decorators) { - if (!this.state.containsEsc) { - switch (this.state.type) { - case 75: { - if (this.isLookaheadContextual("enum")) { - const node = this.startNode(); - this.expect(75); - return this.tsParseEnumDeclaration(node, { - const: true - }); - } - break; - } - case 124: - case 125: { - if (this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()) { - const token = this.state.type; - const node = this.startNode(); - this.next(); - const declaration = token === 125 ? this.tsTryParseDeclare(node) : this.tsParseAbstractDeclaration(node, decorators); - if (declaration) { - if (token === 125) { - declaration.declare = true; - } - return declaration; - } else { - node.expression = this.createIdentifier(this.startNodeAt(node.loc.start), token === 125 ? "declare" : "abstract"); - this.semicolon(false); - return this.finishNode(node, "ExpressionStatement"); - } - } - break; - } - case 126: - return this.tsParseEnumDeclaration(this.startNode()); - case 112: { - const nextCh = this.lookaheadCharCode(); - if (nextCh === 123) { - const node = this.startNode(); - return this.tsParseAmbientExternalModuleDeclaration(node); - } - break; - } - case 129: { - const result = this.tsParseInterfaceDeclaration(this.startNode()); - if (result) return result; - break; - } - case 127: { - if (this.nextTokenIsIdentifierOrStringLiteralOnSameLine()) { - const node = this.startNode(); - this.next(); - return this.tsParseDeclaration(node, 127, false, decorators); - } - break; - } - case 128: { - if (this.nextTokenIsIdentifierOnSameLine()) { - const node = this.startNode(); - this.next(); - return this.tsParseDeclaration(node, 128, false, decorators); - } - break; - } - case 130: { - if (this.nextTokenIsIdentifierOnSameLine()) { - const node = this.startNode(); - this.next(); - return this.tsParseTypeAliasDeclaration(node); - } - break; - } - } - } - 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); - } - } - shouldParseExportDeclaration() { - if (this.tsIsDeclarationStart()) return true; - return super.shouldParseExportDeclaration(); - } - 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; - } - } - return super.parseConditional(expr, startLoc, refExpressionErrors); - } - parseParenItem(node, startLoc) { - const newNode = super.parseParenItem(node, startLoc); - if (this.eat(17)) { - newNode.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 && declaration.type !== "TSImportEqualsDeclaration") { - 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(this.offsetToSourcePos(key.start), this.offsetToSourcePos(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 == null) { - return; - } - super.declareClassPrivateMethodInScope(node, kind); - } - parseClassSuper(node) { - super.parseClassSuper(node); - if (node.superClass) { - if (node.superClass.type === "TSInstantiationExpression") { - const tsInstantiationExpression = node.superClass; - const superClass2 = tsInstantiationExpression.expression; - this.takeSurroundingComments(superClass2, superClass2.start, superClass2.end); - const superTypeArguments = tsInstantiationExpression.typeParameters; - this.takeSurroundingComments(superTypeArguments, superTypeArguments.start, superTypeArguments.end); - node.superClass = superClass2; - node.superTypeParameters = superTypeArguments; - } else if (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 jsx2; - let typeCast; - if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) { - state = this.state.clone(); - jsx2 = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); - if (!jsx2.error) return jsx2.node; - const { - context - } = this.state; - const currentContext = context[context.length - 1]; - if (currentContext === types.j_oTag || currentContext === types.j_expr) { - context.pop(); - } - } - if (!((_jsx = jsx2) != 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 (!jsx2) { - assert(!this.hasPlugin("jsx")); - typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); - if (!typeCast.error) return typeCast.node; - } - if ((_jsx2 = jsx2) != null && _jsx2.node) { - this.state = jsx2.failState; - return jsx2.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 = jsx2) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error); - } - reportReservedArrowTypeParam(node) { - var _node$extra2; - if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra2 = node.extra) != null && _node$extra2.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); - } - parseFunctionParamType(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, disallowCallExpression, isUnparenthesizedInAssign, binding) { - switch (type) { - case "TSTypeCastExpression": - return true; - case "TSParameterProperty": - return "parameter"; - case "TSNonNullExpression": - return "expression"; - case "TSAsExpression": - case "TSSatisfiesExpression": - case "TSTypeAssertion": - return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true]; - default: - return super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding); - } - } - parseBindingAtom() { - if (this.state.type === 78) { - return this.parseIdentifier(true); - } - return super.parseBindingAtom(); - } - parseMaybeDecoratorArguments(expr, startLoc) { - if (this.match(47) || this.match(51)) { - const typeArguments = this.tsParseTypeArgumentsInExpression(); - if (this.match(10)) { - const call = super.parseMaybeDecoratorArguments(expr, startLoc); - call.typeParameters = typeArguments; - return call; - } - this.unexpected(null, 10); - } - return super.parseMaybeDecoratorArguments(expr, startLoc); - } - 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(code2) { - if (this.state.inType) { - if (code2 === 62) { - this.finishOp(48, 1); - return; - } - if (code2 === 60) { - this.finishOp(47, 1); - return; - } - } - super.getTokenFromCode(code2); - } - 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; - } - toAssignableListItem(exprList, index, isLHS) { - const node = exprList[index]; - if (node.type === "TSTypeCastExpression") { - exprList[index] = this.typeCastToParameter(node); - } - super.toAssignableListItem(exprList, index, 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 { - isAmbientContext: oldIsAmbientContext, - strict: oldStrict - } = this.state; - this.state.isAmbientContext = true; - this.state.strict = false; - try { - return cb(); - } finally { - this.state.isAmbientContext = oldIsAmbientContext; - this.state.strict = oldStrict; - } - } - 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.NonClassMethodPropertyHasAbstractModifier, node); - return this.tsParseInterfaceDeclaration(node); - } else { - return null; - } - } - throw 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 || method.type === "TSAbstractMethodDefinition") { - const hasEstreePlugin = this.hasPlugin("estree"); - const methodFn = hasEstreePlugin ? method.value : method; - if (methodFn.body) { - const { - key - } = method; - this.raise(TSErrors.AbstractMethodHasImplementation, method, { - methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(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] = this.cloneIdentifier(node[leftOfAsKey]); - } - if (isImport) { - this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096); - } - } - fillOptionalPropertiesForTSESLint(node) { - var _node$phase, _node$directive, _node$decorators, _node$optional, _node$typeAnnotation, _node$accessibility, _node$decorators2, _node$override, _node$readonly, _node$static, _node$declare, _node$returnType, _node$typeParameters, _node$optional2, _node$optional3, _node$accessibility2, _node$readonly2, _node$static2, _node$declare2, _node$definite, _node$readonly3, _node$typeAnnotation2, _node$accessibility3, _node$decorators3, _node$override2, _node$optional4, _node$id, _node$abstract, _node$declare3, _node$decorators4, _node$implements, _node$superTypeArgume, _node$typeParameters2, _node$declare4, _node$definite2, _node$const, _node$declare5, _node$computed, _node$qualifier, _node$options, _node$declare6, _node$extends, _node$optional5, _node$readonly4, _node$declare7, _node$global, _node$const2, _node$in, _node$out; - switch (node.type) { - case "ImportDeclaration": - (_node$phase = node.phase) != null ? _node$phase : node.phase = null; - return; - case "ExpressionStatement": - (_node$directive = node.directive) != null ? _node$directive : node.directive = void 0; - return; - case "RestElement": - node.value = void 0; - case "Identifier": - case "ArrayPattern": - case "AssignmentPattern": - case "ObjectPattern": - (_node$decorators = node.decorators) != null ? _node$decorators : node.decorators = []; - (_node$optional = node.optional) != null ? _node$optional : node.optional = false; - (_node$typeAnnotation = node.typeAnnotation) != null ? _node$typeAnnotation : node.typeAnnotation = void 0; - return; - case "TSParameterProperty": - (_node$accessibility = node.accessibility) != null ? _node$accessibility : node.accessibility = void 0; - (_node$decorators2 = node.decorators) != null ? _node$decorators2 : node.decorators = []; - (_node$override = node.override) != null ? _node$override : node.override = false; - (_node$readonly = node.readonly) != null ? _node$readonly : node.readonly = false; - (_node$static = node.static) != null ? _node$static : node.static = false; - return; - case "TSEmptyBodyFunctionExpression": - node.body = null; - case "TSDeclareFunction": - case "FunctionDeclaration": - case "FunctionExpression": - case "ClassMethod": - case "ClassPrivateMethod": - (_node$declare = node.declare) != null ? _node$declare : node.declare = false; - (_node$returnType = node.returnType) != null ? _node$returnType : node.returnType = void 0; - (_node$typeParameters = node.typeParameters) != null ? _node$typeParameters : node.typeParameters = void 0; - return; - case "Property": - (_node$optional2 = node.optional) != null ? _node$optional2 : node.optional = false; - return; - case "TSMethodSignature": - case "TSPropertySignature": - (_node$optional3 = node.optional) != null ? _node$optional3 : node.optional = false; - case "TSIndexSignature": - (_node$accessibility2 = node.accessibility) != null ? _node$accessibility2 : node.accessibility = void 0; - (_node$readonly2 = node.readonly) != null ? _node$readonly2 : node.readonly = false; - (_node$static2 = node.static) != null ? _node$static2 : node.static = false; - return; - case "TSAbstractPropertyDefinition": - case "PropertyDefinition": - case "TSAbstractAccessorProperty": - case "AccessorProperty": - (_node$declare2 = node.declare) != null ? _node$declare2 : node.declare = false; - (_node$definite = node.definite) != null ? _node$definite : node.definite = false; - (_node$readonly3 = node.readonly) != null ? _node$readonly3 : node.readonly = false; - (_node$typeAnnotation2 = node.typeAnnotation) != null ? _node$typeAnnotation2 : node.typeAnnotation = void 0; - case "TSAbstractMethodDefinition": - case "MethodDefinition": - (_node$accessibility3 = node.accessibility) != null ? _node$accessibility3 : node.accessibility = void 0; - (_node$decorators3 = node.decorators) != null ? _node$decorators3 : node.decorators = []; - (_node$override2 = node.override) != null ? _node$override2 : node.override = false; - (_node$optional4 = node.optional) != null ? _node$optional4 : node.optional = false; - return; - case "ClassExpression": - (_node$id = node.id) != null ? _node$id : node.id = null; - case "ClassDeclaration": - (_node$abstract = node.abstract) != null ? _node$abstract : node.abstract = false; - (_node$declare3 = node.declare) != null ? _node$declare3 : node.declare = false; - (_node$decorators4 = node.decorators) != null ? _node$decorators4 : node.decorators = []; - (_node$implements = node.implements) != null ? _node$implements : node.implements = []; - (_node$superTypeArgume = node.superTypeArguments) != null ? _node$superTypeArgume : node.superTypeArguments = void 0; - (_node$typeParameters2 = node.typeParameters) != null ? _node$typeParameters2 : node.typeParameters = void 0; - return; - case "TSTypeAliasDeclaration": - case "VariableDeclaration": - (_node$declare4 = node.declare) != null ? _node$declare4 : node.declare = false; - return; - case "VariableDeclarator": - (_node$definite2 = node.definite) != null ? _node$definite2 : node.definite = false; - return; - case "TSEnumDeclaration": - (_node$const = node.const) != null ? _node$const : node.const = false; - (_node$declare5 = node.declare) != null ? _node$declare5 : node.declare = false; - return; - case "TSEnumMember": - (_node$computed = node.computed) != null ? _node$computed : node.computed = false; - return; - case "TSImportType": - (_node$qualifier = node.qualifier) != null ? _node$qualifier : node.qualifier = null; - (_node$options = node.options) != null ? _node$options : node.options = null; - return; - case "TSInterfaceDeclaration": - (_node$declare6 = node.declare) != null ? _node$declare6 : node.declare = false; - (_node$extends = node.extends) != null ? _node$extends : node.extends = []; - return; - case "TSMappedType": - (_node$optional5 = node.optional) != null ? _node$optional5 : node.optional = false; - (_node$readonly4 = node.readonly) != null ? _node$readonly4 : node.readonly = void 0; - return; - case "TSModuleDeclaration": - (_node$declare7 = node.declare) != null ? _node$declare7 : node.declare = false; - (_node$global = node.global) != null ? _node$global : node.global = node.kind === "global"; - return; - case "TSTypeParameter": - (_node$const2 = node.const) != null ? _node$const2 : node.const = false; - (_node$in = node.in) != null ? _node$in : node.in = false; - (_node$out = node.out) != null ? _node$out : node.out = false; - return; - } - } - chStartsBindingIdentifierAndNotRelationalOperator(ch, pos) { - if (isIdentifierStart(ch)) { - keywordAndTSRelationalOperator.lastIndex = pos; - if (keywordAndTSRelationalOperator.test(this.input)) { - const endCh = this.codePointAtPos(keywordAndTSRelationalOperator.lastIndex); - if (!isIdentifierChar(endCh) && endCh !== 92) { - return false; - } - } - return true; - } else if (ch === 92) { - return true; - } else { - return false; - } - } - nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine() { - const next = this.nextTokenInLineStart(); - const nextCh = this.codePointAtPos(next); - return this.chStartsBindingIdentifierAndNotRelationalOperator(nextCh, next); - } - nextTokenIsIdentifierOrStringLiteralOnSameLine() { - const next = this.nextTokenInLineStart(); - const nextCh = this.codePointAtPos(next); - return this.chStartsBindingIdentifier(nextCh, next) || nextCh === 34 || nextCh === 39; - } - }; - 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, estree2) { - var _expression$extra; - const { - type - } = expression; - if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) { - return false; - } - if (estree2) { - 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(expression, estree2) || isNegativeNumber(expression, estree2)) { - return true; - } - if (type === "TemplateLiteral" && expression.expressions.length === 0) { - return true; - } - if (isPossiblyLiteralEnum(expression)) { - return true; - } - return false; - } - function isNumber(expression, estree2) { - if (estree2) { - return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression); - } - return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral"; - } - function isNegativeNumber(expression, estree2) { - if (expression.type === "UnaryExpression") { - const { - operator, - argument - } = expression; - if (operator === "-" && isNumber(argument, estree2)) { - 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); - } - var 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(133)) { - const node = this.startNode(); - this.next(); - this.assertNoSpace(); - node.name = super.parseIdentifier(true); - this.assertNoSpace(); - this.expect(133); - return this.finishPlaceholder(node, expectedNode); - } - } - finishPlaceholder(node, expectedNode) { - let placeholder = node; - if (!placeholder.expectedNode || !placeholder.type) { - placeholder = this.finishNode(placeholder, "Placeholder"); - } - placeholder.expectedNode = expectedNode; - return placeholder; - } - getTokenFromCode(code2) { - if (code2 === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { - this.finishOp(133, 2); - } else { - super.getTokenFromCode(code2); - } - } - 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 !== void 0) { - super.checkReservedWord(word, startLoc, checkKeywords, isBinding); - } - } - cloneIdentifier(node) { - const cloned = super.cloneIdentifier(node); - if (cloned.type === "Placeholder") { - cloned.expectedNode = node.expectedNode; - } - return cloned; - } - cloneStringLiteral(node) { - if (node.type === "Placeholder") { - return this.cloneIdentifier(node); - } - return super.cloneStringLiteral(node); - } - parseBindingAtom() { - return this.parsePlaceholder("Pattern") || super.parseBindingAtom(); - } - isValidLVal(type, disallowCallExpression, isParenthesized, binding) { - return type === "Placeholder" || super.isValidLVal(type, disallowCallExpression, 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 next = this.nextTokenStart(); - if (this.input.charCodeAt(next) === 37 && this.input.charCodeAt(next + 1) === 37) { - return true; - } - return false; - } - verifyBreakContinue(node, isBreak) { - var _node$label; - if (((_node$label = node.label) == null ? void 0 : _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(); - const stmtPlaceholder = node; - stmtPlaceholder.name = expr.name; - return this.finishPlaceholder(stmtPlaceholder, "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(133) || 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); - const node2 = node; - if (!this.isContextual(98) && !this.match(12)) { - node2.specifiers = []; - node2.source = null; - node2.declaration = this.finishPlaceholder(placeholder, "Declaration"); - return this.finishNode(node2, "ExportNamedDeclaration"); - } - this.expectPlugin("exportDefaultFrom"); - const specifier = this.startNode(); - specifier.exported = placeholder; - node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; - return super.parseExport(node2, decorators); - } - isExportDefaultSpecifier() { - if (this.match(65)) { - const next = this.nextTokenStart(); - if (this.isUnparsedContextual(next, "from")) { - if (this.input.startsWith(tokenLabelName(133), 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((node2) => node2.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.offsetToSourcePos(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); - this.castNodeTo(identifier, "V8IntrinsicIdentifier"); - if (this.match(10)) { - return identifier; - } - } - this.unexpected(v8IntrinsicStartLoc); - } - } - parseExprAtom(refExpressionErrors) { - return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors); - } - }; - var PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; - var TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"]; - function validatePlugins(pluginsMap) { - if (pluginsMap.has("decorators")) { - if (pluginsMap.has("decorators-legacy")) { - throw new Error("Cannot use the decorators and decorators-legacy plugin together"); - } - const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport; - if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") { - throw new Error("'decoratorsBeforeExport' must be a boolean, if specified."); - } - const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized; - if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") { - throw new Error("'allowCallParenthesized' must be a boolean."); - } - } - if (pluginsMap.has("flow") && pluginsMap.has("typescript")) { - throw new Error("Cannot combine flow and typescript plugins."); - } - if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) { - throw new Error("Cannot combine placeholders and v8intrinsic plugins."); - } - if (pluginsMap.has("pipelineOperator")) { - var _pluginsMap$get2; - const proposal = pluginsMap.get("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}.`); - } - if (proposal === "hack") { - var _pluginsMap$get; - if (pluginsMap.has("placeholders")) { - throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); - } - if (pluginsMap.has("v8intrinsic")) { - throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); - } - const topicToken = pluginsMap.get("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 === "#" && ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash") { - throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); - } - } else if (proposal === "smart" && ((_pluginsMap$get2 = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get2.syntaxType) === "hash") { - throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`); - } - } - if (pluginsMap.has("moduleAttributes")) { - if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) { - throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins."); - } - const moduleAttributesVersionPluginOption = pluginsMap.get("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 (pluginsMap.has("importAssertions")) { - if (pluginsMap.has("deprecatedImportAssert")) { - throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins."); - } - } - if (pluginsMap.has("deprecatedImportAssert")) ; - else if (pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) { - pluginsMap.set("deprecatedImportAssert", {}); - } - if (pluginsMap.has("recordAndTuple")) { - const syntaxType = pluginsMap.get("recordAndTuple").syntaxType; - if (syntaxType != null) { - const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; - if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(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 (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) { - const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); - error.missingPlugins = "doExpressions"; - throw error; - } - if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("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'."); - } - if (pluginsMap.has("discardBinding") && pluginsMap.get("discardBinding").syntaxType !== "void") { - throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'."); - } - } - var mixinPlugins = { - estree, - jsx, - flow, - typescript, - v8intrinsic, - placeholders - }; - var mixinPluginNames = Object.keys(mixinPlugins); - var ExpressionParser = class extends LValParser { - checkProto(prop, isRecord, sawProto, refExpressionErrors) { - if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { - return sawProto; - } - const key = prop.key; - const name = key.type === "Identifier" ? key.name : key.value; - if (name === "__proto__") { - if (isRecord) { - this.raise(Errors.RecordNoProto, key); - return true; - } - if (sawProto) { - if (refExpressionErrors) { - if (refExpressionErrors.doubleProtoLoc === null) { - refExpressionErrors.doubleProtoLoc = key.loc.start; - } - } else { - this.raise(Errors.DuplicateProto, key); - } - } - return true; - } - return sawProto; - } - shouldExitDescending(expr, potentialArrowAt) { - return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt; - } - getExpression() { - this.enterInitialScopes(); - this.nextToken(); - if (this.match(140)) { - throw this.raise(Errors.ParseExpressionEmptyInput, this.state.startLoc); - } - const expr = this.parseExpression(); - if (!this.match(140)) { - throw this.raise(Errors.ParseExpressionExpectsEOF, this.state.startLoc, { - unexpected: this.input.codePointAt(this.state.start) - }); - } - this.finalizeRemainingComments(); - expr.comments = this.comments; - expr.errors = this.state.errors; - if (this.optionFlags & 256) { - 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) { - refExpressionErrors.optionalParametersLoc = this.state.startLoc; - } - parseMaybeAssign(refExpressionErrors, afterLeftParse) { - const startLoc = this.state.startLoc; - const isYield = this.isContextual(108); - if (isYield) { - if (this.prodParam.hasYield) { - this.next(); - let left2 = this.parseYield(startLoc); - if (afterLeftParse) { - left2 = afterLeftParse.call(this, left2, startLoc); - } - return left2; - } - } - 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; - } - if (refExpressionErrors.voidPatternLoc != null && refExpressionErrors.voidPatternLoc.index >= startIndex) { - refExpressionErrors.voidPatternLoc = null; - } - } else { - node.left = left; - } - this.next(); - node.right = this.parseMaybeAssign(); - this.checkLVal(left, this.finishNode(node, "AssignmentExpression"), void 0, void 0, void 0, void 0, operator === "||=" || operator === "&&=" || operator === "??="); - return node; - } else if (ownExpressionErrors) { - this.checkExpressionErrors(refExpressionErrors, true); - } - if (isYield) { - const { - type: type2 - } = this.state; - const startsExpr2 = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type2) : tokenCanStartExpression(type2) && !this.match(54); - if (startsExpr2 && !this.isAmbiguousPrefixOrIdentifier()) { - this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc); - return this.parseYield(startLoc); - } - } - 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(139) ? 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 "fsharp": - return this.withSoloAwaitPermittingContext(() => { - return this.parseFSharpPipelineBody(prec); - }); - } - if (this.getPluginOption("pipelineOperator", "proposal") === "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); - }); - } - 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.recordAwaitIfAllowed()) { - this.next(); - const expr2 = this.parseAwait(startLoc); - if (!sawUnary) this.checkExponentialAfterUnary(expr2); - return expr2; - } - 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 startsExpr2 = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54); - if (startsExpr2 && !this.isAmbiguousPrefixOrIdentifier()) { - this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc); - return this.parseAwait(startLoc); - } - } - return expr; - } - parseUpdate(node, update, refExpressionErrors) { - if (update) { - const updateExpressionNode = node; - this.checkLVal(updateExpressionNode.argument, 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 node2 = this.startNodeAt(startLoc); - node2.operator = this.state.value; - node2.prefix = false; - node2.argument = expr; - this.next(); - this.checkLVal(expr, expr = this.finishNode(node2, "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, 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) { - return this.stopParseSubscript(base, state); - } - } - 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 { - return this.stopParseSubscript(base, state); - } - } - } - stopParseSubscript(base, state) { - 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(139)) { - 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, state) { - const node = this.startNodeAt(startLoc); - node.object = base; - this.next(); - const isImport = this.match(83); - const callee = this.parseNoCallExpr(); - if (callee.type === "Super" || isImport && callee.type === "ImportExpression" || callee.type === "Import") { - throw this.raise(Errors.UnsupportedBindRHS, callee); - } - node.callee = callee; - state.stop = true; - return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, false); - } - 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(); - } else { - node.arguments = this.parseCallExpressionArguments(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 && this.offsetToSourcePos(base.start) === this.state.potentialArrowAt; - } - finishCallExpression(node, optional) { - if (node.callee.type === "Import") { - if (node.arguments.length === 0 || node.arguments.length > 2) { - this.raise(Errors.ImportCallArity, node); - } else { - for (const arg of node.arguments) { - if (arg.type === "SpreadElement") { - this.raise(Errors.ImportCallSpreadArgument, arg); - } - } - } - } - return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); - } - parseCallExpressionArguments(allowPlaceholder, nodeForExtra, refExpressionErrors) { - const elts = []; - let first = true; - const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; - this.state.inFSharpPipelineDirectBody = false; - while (!this.eat(11)) { - if (first) { - first = false; - } else { - this.expect(12); - if (this.match(11)) { - if (nodeForExtra) { - this.addTrailingCommaExtraToNode(nodeForExtra); - } - this.next(); - break; - } - } - elts.push(this.parseExprListItem(11, 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.parseImportMetaPropertyOrPhaseCall(node); - } - if (this.match(10)) { - if (this.optionFlags & 512) { - 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 135: - return this.parseNumericLiteral(this.state.value); - case 136: - return this.parseBigIntLiteral(this.state.value); - case 134: - 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 0: { - return this.parseArrayLike(3, false, refExpressionErrors); - } - 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 139: { - 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); - } - throw this.unexpected(); - } - case 47: { - const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); - if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { - throw this.expectOnePlugin(["jsx", "flow", "typescript"]); - } - throw this.unexpected(); - } - default: - if (type === 137) { - return this.parseDecimalLiteral(this.state.value); - } else if (type === 2 || type === 1) { - return this.parseArrayLike(this.state.type === 2 ? 4 : 3, true); - } else if (type === 6 || type === 7) { - return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true); - } - 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: type2 - } = this.state; - if (type2 === 68) { - this.resetPreviousNodeTrailingComments(id); - this.next(); - return this.parseAsyncFunctionExpression(this.startNodeAtNode(id)); - } else if (tokenIsIdentifier(type2)) { - if (canBeArrow && this.lookaheadCharCode() === 61) { - return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); - } else { - return id; - } - } else if (type2 === 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 { - throw 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); - } - throw 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)) { - if (pipeProposal === "hack") { - if (!this.topicReferenceIsAllowedInCurrentContext()) { - this.raise(Errors.PipeTopicUnbound, startLoc); - } - this.registerTopicReference(); - return this.finishNode(node, "TopicReference"); - } else { - if (!this.topicReferenceIsAllowedInCurrentContext()) { - this.raise(Errors.PrimaryTopicNotAllowed, startLoc); - } - this.registerTopicReference(); - return this.finishNode(node, "PipelinePrimaryTopicReference"); - } - } 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) { - if (!(this.optionFlags & 16)) { - this.raise(Errors.SuperNotAllowed, node); - } - } else if (!this.scope.allowSuper) { - if (!(this.optionFlags & 16)) { - 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"); - } - parseImportMetaPropertyOrPhaseCall(node) { - this.next(); - if (this.isContextual(105) || this.isContextual(97)) { - const isSource = this.isContextual(105); - this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation"); - this.next(); - node.phase = isSource ? "source" : "defer"; - return this.parseImportCall(node); - } else { - const id = this.createIdentifierAt(this.startNodeAtNode(node), "import", this.state.lastTokStartLoc); - if (this.isContextual(101)) { - if (!this.inModule) { - this.raise(Errors.ImportMetaOutsideModule, id); - } - this.sawUnambiguousESM = true; - } - return this.parseMetaProperty(node, id, "meta"); - } - } - parseLiteralAtNode(value, type, node) { - this.addExtra(node, "rawValue", value); - this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(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.startNode(); - this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end)); - node.pattern = value.pattern; - node.flags = value.flags; - this.next(); - return this.finishNode(node, "RegExpLiteral"); - } - 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.parseMaybeAssignAllowInOrVoidPattern(11, 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.optionFlags & 1024)) { - 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.allowNewTarget) { - 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 === "ImportExpression" || callee.type === "Import") { - this.raise(Errors.ImportCallNotNewExpression, callee); - } - if (callee.type === "Super") { - this.raise(Errors.SuperCallNotNewExpression, 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(); - let curElt = this.parseTemplateElement(isTagged); - const quasis = [curElt]; - const substitutions = []; - while (!curElt.tail) { - substitutions.push(this.parseTemplateSubstitution()); - this.readTemplateContinuation(); - quasis.push(curElt = this.parseTemplateElement(isTagged)); - } - node.expressions = substitutions; - node.quasis = quasis; - 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; - let sawProto = false; - 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); - sawProto = this.checkProto(prop, isRecord, sawProto, 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; - this.parsePropertyName(prop, refExpressionErrors); - if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { - const { - key - } = 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.parseMaybeAssignAllowInOrVoidPattern(8, refExpressionErrors); - return this.finishObjectProperty(prop); - } - 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, this.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, this.cloneIdentifier(prop.key)); - } else { - prop.value = this.cloneIdentifier(prop.key); - } - prop.shorthand = true; - return this.finishObjectProperty(prop); - } - } - finishObjectProperty(node) { - return this.finishNode(node, "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 135: - key = this.parseNumericLiteral(value); - break; - case 134: - key = this.parseStringLiteral(value); - break; - case 136: - key = this.parseBigIntLiteral(value); - break; - case 139: { - 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: - if (type === 137) { - key = this.parseDecimalLiteral(value); - break; - } - this.unexpected(); - } - } - prop.key = key; - if (type !== 139) { - prop.computed = false; - } - } - } - 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(514 | 16 | (inClassScope ? 576 : 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, 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(514 | 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 && /* @__PURE__ */ new Set(); - const formalParameters = { - type: "FormalParameters" - }; - for (const param of node.params) { - this.checkLVal(param, formalParameters, 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(close, allowEmpty, refExpressionErrors)); - } - return elts; - } - parseExprListItem(close, 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.parseMaybeAssignAllowInOrVoidPattern(close, 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"); - } - createIdentifierAt(node, name, endLoc) { - node.name = name; - node.loc.identifierName = name; - return this.finishNodeAt(node, "Identifier", endLoc); - } - parseIdentifierName(liberal) { - let name; - const { - startLoc, - type - } = this.state; - if (tokenIsKeywordOrIdentifier(type)) { - name = this.state.value; - } else { - this.unexpected(); - } - const tokenIsKeyword2 = tokenKeywordOrIdentifierIsKeyword(type); - if (liberal) { - if (tokenIsKeyword2) { - this.replaceToken(132); - } - } else { - this.checkReservedWord(name, startLoc, tokenIsKeyword2, 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; - } - } - } - recordAwaitIfAllowed() { - const isAwaitAllowed = this.prodParam.hasAwait; - if (isAwaitAllowed && !this.scope.inFunction) { - this.state.hasTopLevelAwait = true; - } - return isAwaitAllowed; - } - 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.optionFlags & 1)) { - if (this.isAmbiguousPrefixOrIdentifier()) { - this.ambiguousScriptDifferentAst = true; - } else { - this.sawUnambiguousESM = true; - } - } - if (!this.state.soloAwait) { - node.argument = this.parseMaybeUnary(null, true); - } - return this.finishNode(node, "AwaitExpression"); - } - isAmbiguousPrefixOrIdentifier() { - if (this.hasPrecedingLineBreak()) return true; - const { - type - } = this.state; - return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54; - } - parseYield(startLoc) { - const node = this.startNodeAt(startLoc); - this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node); - let delegating = false; - let argument = null; - if (!this.hasPrecedingLineBreak()) { - delegating = this.eat(55); - switch (this.state.type) { - case 13: - case 140: - 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(); - node.options = null; - if (this.eat(12)) { - if (!this.match(11)) { - node.options = this.parseMaybeAssignAllowIn(); - if (this.eat(12)) { - this.addTrailingCommaExtraToNode(node.options); - if (!this.match(11)) { - do { - this.parseMaybeAssignAllowIn(); - } while (this.eat(12) && !this.match(11)); - this.raise(Errors.ImportCallArity, node); - } - } - } else { - this.addTrailingCommaExtraToNode(node.source); - } - } - 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"); - } - parseVoidPattern(refExpressionErrors) { - this.expectPlugin("discardBinding"); - const node = this.startNode(); - if (refExpressionErrors != null) { - refExpressionErrors.voidPatternLoc = this.state.startLoc; - } - this.next(); - return this.finishNode(node, "VoidPattern"); - } - parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, afterLeftParse) { - if (refExpressionErrors != null && this.match(88)) { - const nextCode = this.lookaheadCharCode(); - if (nextCode === 44 || nextCode === (close === 3 ? 93 : close === 8 ? 125 : 41) || nextCode === 61) { - return this.parseMaybeDefault(this.state.startLoc, this.parseVoidPattern(refExpressionErrors)); - } - } - return this.parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse); - } - parsePropertyNamePrefixOperator(prop) { - } - }; - var loopLabel = { - kind: 1 - }; - var switchLabel = { - kind: 2 - }; - var loneSurrogate = /[\uD800-\uDFFF]/u; - var keywordRelationalOperator = /in(?:stanceof)?/y; - function babel7CompatTokens(tokens, input, startIndex) { - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - const { - type - } = token; - if (typeof type === "number") { - if (type === 139) { - 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, - end: hashEndPos, - startLoc: loc.start, - endLoc: hashEndLoc - }), new Token({ - type: getExportedToken(132), - value, - start: hashEndPos, - 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 - startIndex) === 96) { - startToken = new Token({ - type: getExportedToken(22), - value: "`", - start, - end: backquoteEnd, - startLoc: loc.start, - endLoc: backquoteEndLoc - }); - } else { - startToken = new Token({ - type: getExportedToken(8), - value: "}", - 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, - 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, - 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; - } - var StatementParser = class extends ExpressionParser { - parseTopLevel(file, program) { - file.program = this.parseProgram(program, 140, this.options.sourceType === "module" ? "module" : "script"); - file.comments = this.comments; - if (this.optionFlags & 256) { - file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex); - } - return this.finishNode(file, "File"); - } - parseProgram(program, end, sourceType) { - program.sourceType = sourceType; - program.interpreter = this.parseInterpreterDirective(); - this.parseBlockBody(program, true, true, end); - if (this.inModule) { - if (!(this.optionFlags & 64) && this.scope.undefinedExports.size > 0) { - for (const [localName, at] of Array.from(this.scope.undefinedExports)) { - this.raise(Errors.ModuleExportUndefined, at, { - localName - }); - } - } - this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait); - } - let finishedProgram; - if (end === 140) { - finishedProgram = this.finishNode(program, "Program"); - } else { - finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1)); - } - return finishedProgram; - } - stmtToDirective(stmt) { - const directive = this.castNodeTo(stmt, "Directive"); - const directiveLiteral = this.castNodeTo(stmt.expression, "DirectiveLiteral"); - const expressionValue = directiveLiteral.value; - const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(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); - directive.value = directiveLiteral; - delete stmt.expression; - 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(); - } - isUsing() { - if (!this.isContextual(107)) { - return false; - } - return this.nextTokenIsIdentifierOnSameLine(); - } - isForUsing() { - if (!this.isContextual(107)) { - return false; - } - const next = this.nextTokenInLineStart(); - const nextCh = this.codePointAtPos(next); - if (this.isUnparsedContextual(next, "of")) { - const nextCharAfterOf = this.lookaheadCharCodeSince(next + 2); - if (nextCharAfterOf !== 61 && nextCharAfterOf !== 58 && nextCharAfterOf !== 59) { - return false; - } - } - if (this.chStartsBindingIdentifier(nextCh, next) || this.isUnparsedContextual(next, "void")) { - return true; - } - return false; - } - nextTokenIsIdentifierOnSameLine() { - const next = this.nextTokenInLineStart(); - const nextCh = this.codePointAtPos(next); - return this.chStartsBindingIdentifier(nextCh, next); - } - isAwaitUsing() { - if (!this.isContextual(96)) { - return false; - } - let next = this.nextTokenInLineStart(); - if (this.isUnparsedContextual(next, "using")) { - next = this.nextTokenInLineStartSince(next + 5); - const nextCh = this.codePointAtPos(next); - if (this.chStartsBindingIdentifier(nextCh, next)) { - return true; - } - } - return false; - } - 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); - } - hasInLineFollowingBindingIdentifierOrBrace() { - const next = this.nextTokenInLineStart(); - const nextCh = this.codePointAtPos(next); - return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next); - } - allowsUsing() { - return (this.scope.inModule || !this.scope.inTopLevel) && !this.scope.inBareCaseStatement; - } - 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.isAwaitUsing()) { - if (!this.allowsUsing()) { - this.raise(Errors.UnexpectedUsingDeclaration, node); - } else if (!allowDeclaration) { - this.raise(Errors.UnexpectedLexicalDeclaration, node); - } else if (!this.recordAwaitIfAllowed()) { - this.raise(Errors.AwaitUsingNotInAsyncContext, node); - } - this.next(); - return this.parseVarStatement(node, "await using"); - } - break; - case 107: - if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) { - break; - } - if (!this.allowsUsing()) { - 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.optionFlags & 8) && !topLevel) { - this.raise(Errors.UnexpectedImportExport, this.state.startLoc); - } - this.next(); - let result; - if (startType === 83) { - result = this.parseImport(node); - } else { - result = this.parseExport(node, decorators); - } - 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.optionFlags & 8) && !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) { - var _classNode$decorators; - if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) { - 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 startLoc2 = this.state.startLoc; - this.next(); - expr = this.parseExpression(); - this.expect(11); - expr = this.wrapParenthesis(startLoc2, expr); - const paramsStartLoc = this.state.startLoc; - node.expression = this.parseMaybeDecoratorArguments(expr, startLoc2); - if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) { - this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc); - } - } else { - expr = this.parseIdentifier(false); - while (this.eat(16)) { - const node2 = this.startNodeAt(startLoc); - node2.object = expr; - if (this.match(139)) { - this.classScope.usePrivateName(this.state.value, this.state.startLoc); - node2.property = this.parsePrivateName(); - } else { - node2.property = this.parseIdentifier(true); - } - node2.computed = false; - expr = this.finishNode(node2, "MemberExpression"); - } - node.expression = this.parseMaybeDecoratorArguments(expr, startLoc); - } - } else { - node.expression = this.parseExprSubscripts(); - } - return this.finishNode(node, "Decorator"); - } - parseMaybeDecoratorArguments(expr, startLoc) { - if (this.eat(10)) { - const node = this.startNodeAt(startLoc); - node.callee = expr; - node.arguments = this.parseCallExpressionArguments(); - 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.isContextual(96) && this.recordAwaitIfAllowed()) { - awaitAt = this.state.startLoc; - this.next(); - } - 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.isAwaitUsing(); - const starsWithUsingDeclaration = startsWithAwaitUsing || this.isForUsing(); - 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.recordAwaitIfAllowed()) { - this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc); - } - this.next(); - } else { - kind = this.state.value; - } - this.next(); - this.parseVar(initNode, true, kind); - const init2 = this.finishNode(initNode, "VariableDeclaration"); - const isForIn = this.match(58); - if (isForIn && starsWithUsingDeclaration) { - this.raise(Errors.ForInUsing, init2); - } - if ((isForIn || this.isContextual(102)) && init2.declarations.length === 1) { - return this.parseForIn(node, init2, awaitAt); - } - if (awaitAt !== null) { - this.unexpected(awaitAt); - } - return this.parseFor(node, init2); - } - } - 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, { - 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.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(256); - 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, { - type: "CatchClause" - }, 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.sourceToOffsetPos(this.state.start); - label.kind = kind; - } else { - break; - } - } - this.state.labels.push({ - name: maybeName, - kind, - statementStart: this.sourceToOffsetPos(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 : void 0, 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" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) { - this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, { - kind - }); - } - } - declarations.push(this.finishNode(decl, "VariableDeclarator")); - if (!this.eat(12)) break; - } - return node; - } - parseVarId(decl, kind) { - const id = this.parseBindingAtom(); - if (kind === "using" || kind === "await using") { - if (id.type === "ArrayPattern" || id.type === "ObjectPattern") { - this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start); - } - } else { - if (id.type === "VoidPattern") { - this.raise(Errors.UnexpectedVoidPattern, id.loc.start); - } - } - this.checkLVal(id, { - type: "VariableDeclarator" - }, 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(514); - 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); - } - nameIsConstructor(key) { - return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor"; - } - isNonstaticConstructor(method) { - return !method.computed && !method.static && this.nameIsConstructor(method.key); - } - 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(139); - this.parseClassElementName(method); - this.parsePostMemberNameModifiers(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 = !this.state.containsEsc && tokenIsIdentifier(this.state.type); - const key = this.parseClassElementName(member); - const maybeContextualKw = isContextual ? key.name : null; - const isPrivate = this.isPrivateName(key); - 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 (maybeContextualKw === "async" && !this.isLineTerminator()) { - this.resetPreviousNodeTrailingComments(key); - const isGenerator = this.eat(55); - if (publicMember.optional) { - this.unexpected(maybeQuestionTokenStartLoc); - } - method.kind = "method"; - const isPrivate2 = this.match(139); - this.parseClassElementName(method); - this.parsePostMemberNameModifiers(publicMember); - if (isPrivate2) { - 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 ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) { - this.resetPreviousNodeTrailingComments(key); - method.kind = maybeContextualKw; - const isPrivate2 = this.match(139); - this.parseClassElementName(publicMethod); - if (isPrivate2) { - 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 (maybeContextualKw === "accessor" && !this.isLineTerminator()) { - this.expectPlugin("decoratorAutoAccessors"); - this.resetPreviousNodeTrailingComments(key); - const isPrivate2 = this.match(139); - this.parseClassElementName(publicProp); - this.pushClassAccessorProperty(classBody, accessorProp, isPrivate2); - } 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 === 134) && member.static && value === "prototype") { - this.raise(Errors.StaticPrototype, this.state.startLoc); - } - if (type === 139) { - if (value === "constructor") { - this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc); - } - const key = this.parsePrivateName(); - member.key = key; - return key; - } - this.parsePropertyName(member); - return member.key; - } - parseClassStaticBlock(classBody, member) { - var _member$decorators; - this.scope.enter(576 | 128 | 16); - const oldLabels = this.state.labels; - this.state.labels = []; - this.prodParam.enter(0); - const body = member.body = []; - this.parseBlockOrModuleBlockBody(body, void 0, 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 && this.nameIsConstructor(prop.key)) { - 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 && this.nameIsConstructor(prop.key)) { - this.raise(Errors.ConstructorClassField, prop.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(576 | 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); - this.sawUnambiguousESM = 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); - } - this.sawUnambiguousESM = true; - 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); - this.sawUnambiguousESM = true; - return this.finishNode(node2, "ExportDefaultDeclaration"); - } - throw 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)) { - var _ref, _ref$specifiers; - (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.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)) { - const node2 = node; - if (!node2.specifiers) node2.specifiers = []; - const isTypeExport = node2.exportKind === "type"; - node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport)); - node2.source = null; - if (this.hasPlugin("importAssertions")) { - node2.assertions = []; - } else { - node2.attributes = []; - } - node2.declaration = null; - return true; - } - return false; - } - maybeParseExportDeclaration(node) { - if (this.shouldParseExportDeclaration()) { - node.specifiers = []; - node.source = null; - if (this.hasPlugin("importAssertions")) { - node.assertions = []; - } else { - node.attributes = []; - } - 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() || this.isUsing() || this.isAwaitUsing()) { - throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc); - } - const res = this.parseMaybeAssignAllowIn(); - this.semicolon(); - return res; - } - parseExportDeclaration(node) { - if (this.match(80)) { - const node2 = this.parseClass(this.startNode(), true, false); - return node2; - } - 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 next2 = this.nextTokenStart(); - const nextChar = this.input.charCodeAt(next2); - if (nextChar === 123 || this.chStartsBindingIdentifier(nextChar, next2) && !this.input.startsWith("from", next2)) { - 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; - } - } - if (this.isUsing()) { - this.raise(Errors.UsingDeclarationExport, this.state.startLoc); - return true; - } - if (this.isAwaitUsing()) { - this.raise(Errors.UsingDeclarationExport, 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) { - const decl = node.declaration; - if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") { - const { - id - } = decl; - if (!id) throw new Error("Assertion failure"); - this.checkDuplicateExports(node, id.name); - } else if (decl.type === "VariableDeclaration") { - for (const declaration of decl.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(134); - 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 = this.cloneStringLiteral(node.local); - } else if (!node.exported) { - node.exported = this.cloneIdentifier(node.local); - } - return this.finishNode(node, "ExportSpecifier"); - } - parseModuleExportName() { - if (this.match(134)) { - const result = this.parseStringLiteral(this.state.value); - const surrogate = loneSurrogate.exec(result.value); - 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 !== void 0) { - return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default"; - } - }); - if (nonDefaultNamedSpecifier !== void 0) { - 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.startNode(); - const phaseIdentifierName = this.parseIdentifierName(true); - const { - type - } = this.state; - const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; - if (isImportPhase) { - this.applyImportPhase(node, isExport, phaseIdentifierName, phaseIdentifier.loc.start); - return null; - } else { - this.applyImportPhase(node, isExport, null); - return this.createIdentifier(phaseIdentifier, phaseIdentifierName); - } - } - isPrecedingIdImportPhase(phase) { - const { - type - } = this.state; - return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12; - } - parseImport(node) { - if (this.match(134)) { - 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(); - this.sawUnambiguousESM = true; - return this.finishNode(node, "ImportDeclaration"); - } - parseImportSource() { - if (!this.match(134)) 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, { - type - }, bindingType); - return this.finishNode(specifier, type); - } - parseImportAttributes() { - this.expect(5); - const attrs = []; - const attrNames = /* @__PURE__ */ 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(134)) { - node.key = this.parseStringLiteral(keyName); - } else { - node.key = this.parseIdentifier(true); - } - this.expect(14); - if (!this.match(134)) { - 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 = /* @__PURE__ */ 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(134)) { - 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; - var useWith = false; - if (this.match(76)) { - if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) { - return; - } - this.next(); - if (this.hasPlugin("moduleAttributes")) { - attributes = this.parseModuleAttributes(); - this.addExtra(node, "deprecatedWithLegacySyntax", true); - } else { - attributes = this.parseImportAttributes(); - } - useWith = true; - } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) { - if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) { - this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc); - } - if (!this.hasPlugin("importAssertions")) { - this.addExtra(node, "deprecatedAssertSyntax", true); - } - this.next(); - attributes = this.parseImportAttributes(); - } else { - attributes = []; - } - 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(134); - const isMaybeTypeOnly = this.isContextual(130); - specifier.imported = this.parseModuleExportName(); - const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, void 0); - 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 = this.cloneIdentifier(imported); - } - } - return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType); - } - isThisParam(param) { - return param.type === "Identifier" && param.name === "this"; - } - }; - var Parser = class extends StatementParser { - constructor(options, input, pluginsMap) { - const normalizedOptions = getOptions(options); - super(normalizedOptions, input); - this.options = normalizedOptions; - this.initializeScopes(); - this.plugins = pluginsMap; - this.filename = normalizedOptions.sourceFilename; - this.startIndex = normalizedOptions.startIndex; - let optionFlags = 0; - if (normalizedOptions.allowAwaitOutsideFunction) { - optionFlags |= 1; - } - if (normalizedOptions.allowReturnOutsideFunction) { - optionFlags |= 2; - } - if (normalizedOptions.allowImportExportEverywhere) { - optionFlags |= 8; - } - if (normalizedOptions.allowSuperOutsideMethod) { - optionFlags |= 16; - } - if (normalizedOptions.allowUndeclaredExports) { - optionFlags |= 64; - } - if (normalizedOptions.allowNewTargetOutsideFunction) { - optionFlags |= 4; - } - if (normalizedOptions.allowYieldOutsideFunction) { - optionFlags |= 32; - } - if (normalizedOptions.ranges) { - optionFlags |= 128; - } - if (normalizedOptions.tokens) { - optionFlags |= 256; - } - if (normalizedOptions.createImportExpressions) { - optionFlags |= 512; - } - if (normalizedOptions.createParenthesizedExpressions) { - optionFlags |= 1024; - } - if (normalizedOptions.errorRecovery) { - optionFlags |= 2048; - } - if (normalizedOptions.attachComment) { - optionFlags |= 4096; - } - if (normalizedOptions.annexB) { - optionFlags |= 8192; - } - this.optionFlags = optionFlags; - } - getScopeHandler() { - return ScopeHandler; - } - parse() { - this.enterInitialScopes(); - const file = this.startNode(); - const program = this.startNode(); - this.nextToken(); - file.errors = null; - const result = this.parseTopLevel(file, program); - result.errors = this.state.errors; - result.comments.length = this.state.commentsLen; - return result; - } - }; - function parse(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 tokenTypes2 = {}; - for (const typeName of Object.keys(internalTokenTypes)) { - tokenTypes2[typeName] = getExportedToken(internalTokenTypes[typeName]); - } - return tokenTypes2; - } - var tokTypes = generateExportedTokenTypes(tt); - function getParser(options, input) { - let cls = Parser; - const pluginsMap = /* @__PURE__ */ new Map(); - if (options != null && options.plugins) { - for (const plugin of options.plugins) { - let name, opts; - if (typeof plugin === "string") { - name = plugin; - } else { - [name, opts] = plugin; - } - if (!pluginsMap.has(name)) { - pluginsMap.set(name, opts || {}); - } - } - validatePlugins(pluginsMap); - cls = getParserClass(pluginsMap); - } - return new cls(options, input, pluginsMap); - } - var parserClassCache = /* @__PURE__ */ new Map(); - function getParserClass(pluginsMap) { - const pluginList = []; - for (const name of mixinPluginNames) { - if (pluginsMap.has(name)) { - pluginList.push(name); - } - } - const key = pluginList.join("|"); - let cls = parserClassCache.get(key); - if (!cls) { - cls = Parser; - for (const plugin of pluginList) { - cls = mixinPlugins[plugin](cls); - } - parserClassCache.set(key, cls); - } - return cls; - } - exports2.parse = parse; - exports2.parseExpression = parseExpression; - exports2.tokTypes = tokTypes; - } -}); - -// intern-log/node_modules/.pnpm/estree-walker@2.0.2/node_modules/estree-walker/dist/umd/estree-walker.js -var require_estree_walker = __commonJS({ - "intern-log/node_modules/.pnpm/estree-walker@2.0.2/node_modules/estree-walker/dist/umd/estree-walker.js"(exports2, module2) { - (function(global2, factory) { - typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = global2 || self, factory(global2.estreeWalker = {})); - })(exports2, function(exports3) { - "use strict"; - class WalkerBase { - constructor() { - this.should_skip = false; - this.should_remove = false; - this.replacement = null; - 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]; - } - } - } - } - class SyncWalker extends WalkerBase { - /** - * - * @param {SyncHandler} enter - * @param {SyncHandler} leave - */ - constructor(enter, leave) { - super(); - this.enter = enter; - 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)) { - 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; - } - } - class AsyncWalker extends WalkerBase { - /** - * - * @param {AsyncHandler} enter - * @param {AsyncHandler} leave - */ - constructor(enter, leave) { - super(); - this.enter = enter; - this.leave = leave; - } - /** - * - * @param {BaseNode} node - * @param {BaseNode} parent - * @param {string} [prop] - * @param {number} [index] - * @returns {Promise} - */ - async 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; - await 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 (!await this.visit(value[i], node, key, i)) { - i--; - } - } - } - } else if (value !== null && typeof value.type === "string") { - await 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; - await 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; - } - } - function walk(ast, { enter, leave }) { - const instance = new SyncWalker(enter, leave); - return instance.visit(ast, null); - } - async function asyncWalk(ast, { enter, leave }) { - const instance = new AsyncWalker(enter, leave); - return await instance.visit(ast, null); - } - exports3.asyncWalk = asyncWalk; - exports3.walk = walk; - Object.defineProperty(exports3, "__esModule", { value: true }); - }); - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/base64.js -var require_base64 = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/base64.js"(exports2) { - var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); - exports2.encode = function(number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); - }; - exports2.decode = function(charCode) { - var bigA = 65; - var bigZ = 90; - var littleA = 97; - var littleZ = 122; - var zero = 48; - var nine = 57; - var plus = 43; - var slash = 47; - var littleOffset = 26; - var numberOffset = 52; - if (bigA <= charCode && charCode <= bigZ) { - return charCode - bigA; - } - if (littleA <= charCode && charCode <= littleZ) { - return charCode - littleA + littleOffset; - } - if (zero <= charCode && charCode <= nine) { - return charCode - zero + numberOffset; - } - if (charCode == plus) { - return 62; - } - if (charCode == slash) { - return 63; - } - return -1; - }; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/base64-vlq.js -var require_base64_vlq = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/base64-vlq.js"(exports2) { - var base64 = require_base64(); - var VLQ_BASE_SHIFT = 5; - var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - var VLQ_BASE_MASK = VLQ_BASE - 1; - var VLQ_CONTINUATION_BIT = VLQ_BASE; - function toVLQSigned(aValue) { - return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; - } - function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative ? -shifted : shifted; - } - exports2.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) { - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - return encoded; - }; - exports2.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; - }; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/util.js -var require_util = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/util.js"(exports2) { - 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.'); - } - } - exports2.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] - }; - } - exports2.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; - } - exports2.urlGenerate = urlGenerate; - var MAX_CACHED_INPUTS = 32; - 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; - }; - } - var normalize = lruMemoize(function normalize2(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports2.isAbsolute(path); - 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 === "") { - 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; - }); - exports2.normalize = normalize; - function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || "/"; - } - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - 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; - } - exports2.join = join; - exports2.isAbsolute = function(aPath) { - return aPath.charAt(0) === "/" || urlRegexp.test(aPath); - }; - function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - aRoot = aRoot.replace(/\/$/, ""); - var level = 0; - while (aPath.indexOf(aRoot + "/") !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - ++level; - } - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); - } - exports2.relative = relative; - var supportsNullProto = function() { - var obj = /* @__PURE__ */ Object.create(null); - return !("__proto__" in obj); - }(); - function identity(s) { - return s; - } - function toSetString(aStr) { - if (isProtoString(aStr)) { - return "$" + aStr; - } - return aStr; - } - exports2.toSetString = supportsNullProto ? identity : toSetString; - function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - return aStr; - } - exports2.fromSetString = supportsNullProto ? identity : fromSetString; - function isProtoString(s) { - if (!s) { - return false; - } - var length = s.length; - if (length < 9) { - return false; - } - if (s.charCodeAt(length - 1) !== 95 || s.charCodeAt(length - 2) !== 95 || s.charCodeAt(length - 3) !== 111 || s.charCodeAt(length - 4) !== 116 || s.charCodeAt(length - 5) !== 111 || s.charCodeAt(length - 6) !== 114 || s.charCodeAt(length - 7) !== 112 || 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; - } - function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp3 = strcmp(mappingA.source, mappingB.source); - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalLine - mappingB.originalLine; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalColumn - mappingB.originalColumn; - if (cmp3 !== 0 || onlyCompareOriginal) { - return cmp3; - } - cmp3 = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.generatedLine - mappingB.generatedLine; - if (cmp3 !== 0) { - return cmp3; - } - return strcmp(mappingA.name, mappingB.name); - } - exports2.compareByOriginalPositions = compareByOriginalPositions; - function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { - var cmp3; - cmp3 = mappingA.originalLine - mappingB.originalLine; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalColumn - mappingB.originalColumn; - if (cmp3 !== 0 || onlyCompareOriginal) { - return cmp3; - } - cmp3 = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.generatedLine - mappingB.generatedLine; - if (cmp3 !== 0) { - return cmp3; - } - return strcmp(mappingA.name, mappingB.name); - } - exports2.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; - function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp3 = mappingA.generatedLine - mappingB.generatedLine; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp3 !== 0 || onlyCompareGenerated) { - return cmp3; - } - cmp3 = strcmp(mappingA.source, mappingB.source); - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalLine - mappingB.originalLine; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalColumn - mappingB.originalColumn; - if (cmp3 !== 0) { - return cmp3; - } - return strcmp(mappingA.name, mappingB.name); - } - exports2.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { - var cmp3 = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp3 !== 0 || onlyCompareGenerated) { - return cmp3; - } - cmp3 = strcmp(mappingA.source, mappingB.source); - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalLine - mappingB.originalLine; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalColumn - mappingB.originalColumn; - if (cmp3 !== 0) { - return cmp3; - } - return strcmp(mappingA.name, mappingB.name); - } - exports2.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; - function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - if (aStr1 === null) { - return 1; - } - if (aStr2 === null) { - return -1; - } - if (aStr1 > aStr2) { - return 1; - } - return -1; - } - function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp3 = mappingA.generatedLine - mappingB.generatedLine; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = strcmp(mappingA.source, mappingB.source); - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalLine - mappingB.originalLine; - if (cmp3 !== 0) { - return cmp3; - } - cmp3 = mappingA.originalColumn - mappingB.originalColumn; - if (cmp3 !== 0) { - return cmp3; - } - return strcmp(mappingA.name, mappingB.name); - } - exports2.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - function parseSourceMapInput(str) { - return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, "")); - } - exports2.parseSourceMapInput = parseSourceMapInput; - function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { - sourceURL = sourceURL || ""; - if (sourceRoot) { - if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { - sourceRoot += "/"; - } - sourceURL = sourceRoot + sourceURL; - } - if (sourceMapURL) { - var parsed = urlParse(sourceMapURL); - if (!parsed) { - throw new Error("sourceMapURL could not be parsed"); - } - if (parsed.path) { - var index = parsed.path.lastIndexOf("/"); - if (index >= 0) { - parsed.path = parsed.path.substring(0, index + 1); - } - } - sourceURL = join(urlGenerate(parsed), sourceURL); - } - return normalize(sourceURL); - } - exports2.computeSourceURL = computeSourceURL; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/array-set.js -var require_array_set = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/array-set.js"(exports2) { - var util = require_util(); - var has = Object.prototype.hasOwnProperty; - var hasNativeMap = typeof Map !== "undefined"; - function ArraySet() { - this._array = []; - this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null); - } - ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; - }; - ArraySet.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; - }; - ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util.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; - } - } - }; - ArraySet.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); - } - }; - ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - throw new Error('"' + aStr + '" is not in the set.'); - }; - ArraySet.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); - }; - ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); - }; - exports2.ArraySet = ArraySet; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/mapping-list.js -var require_mapping_list = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/mapping-list.js"(exports2) { - var util = require_util(); - function generatedPositionAfter(mappingA, mappingB) { - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; - } - function MappingList() { - this._array = []; - this._sorted = true; - this._last = { generatedLine: -1, generatedColumn: 0 }; - } - MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - MappingList.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); - } - }; - MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; - }; - exports2.MappingList = MappingList; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/source-map-generator.js -var require_source_map_generator = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/source-map-generator.js"(exports2) { - var base64VLQ = require_base64_vlq(); - var util = require_util(); - var ArraySet = require_array_set().ArraySet; - var MappingList = require_mapping_list().MappingList; - function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, "file", null); - this._sourceRoot = util.getArg(aArgs, "sourceRoot", null); - this._skipValidation = util.getArg(aArgs, "skipValidation", false); - this._ignoreInvalidMapping = util.getArg(aArgs, "ignoreInvalidMapping", false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; - } - SourceMapGenerator.prototype._version = 3; - SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, { - file: aSourceMapConsumer.file, - 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.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.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; - }; - SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, "generated"); - var original = util.getArg(aArgs, "original", null); - var source = util.getArg(aArgs, "source", null); - var name = util.getArg(aArgs, "name", null); - if (!this._skipValidation) { - if (this._validateMapping(generated, original, source, name) === false) { - return; - } - } - 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, - name - }); - }; - SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - if (aSourceContent != null) { - if (!this._sourcesContents) { - this._sourcesContents = /* @__PURE__ */ Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - 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; - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - var newSources = new ArraySet(); - var newNames = new ArraySet(); - this._mappings.unsortedForEach(function(mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source); - } - if (sourceRoot != null) { - mapping.source = util.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; - aSourceMapConsumer.sources.forEach(function(sourceFile2) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile2); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile2 = util.join(aSourceMapPath, sourceFile2); - } - if (sourceRoot != null) { - sourceFile2 = util.relative(sourceRoot, sourceFile2); - } - this.setSourceContent(sourceFile2, content); - } - }, this); - }; - SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { - if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { - var message = "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 (this._ignoreInvalidMapping) { - if (typeof console !== "undefined" && console.warn) { - console.warn(message); - } - return false; - } else { - throw new Error(message); - } - } - if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { - 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) { - return; - } else { - var message = "Invalid mapping: " + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - }); - if (this._ignoreInvalidMapping) { - if (typeof console !== "undefined" && console.warn) { - console.warn(message); - } - return false; - } else { - throw new Error(message); - } - } - }; - SourceMapGenerator.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; - var lineDelta = mapping.generatedLine - previousGeneratedLine; - next += lineDelta === 1 ? ";" : ";".repeat(lineDelta); - previousGeneratedLine = mapping.generatedLine; - } else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ","; - } - } - next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - result += next; - } - return result; - }; - SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function(source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; - }, this); - }; - SourceMapGenerator.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; - }; - SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - exports2.SourceMapGenerator = SourceMapGenerator; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/binary-search.js -var require_binary_search = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/binary-search.js"(exports2) { - exports2.GREATEST_LOWER_BOUND = 1; - exports2.LEAST_UPPER_BOUND = 2; - function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp3 = aCompare(aNeedle, aHaystack[mid], true); - if (cmp3 === 0) { - return mid; - } else if (cmp3 > 0) { - if (aHigh - mid > 1) { - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - if (aBias == exports2.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } else { - if (mid - aLow > 1) { - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - if (aBias == exports2.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } - } - exports2.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - var index = recursiveSearch( - -1, - aHaystack.length, - aNeedle, - aHaystack, - aCompare, - aBias || exports2.GREATEST_LOWER_BOUND - ); - if (index < 0) { - return -1; - } - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - return index; - }; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/quick-sort.js -var require_quick_sort = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/quick-sort.js"(exports2) { - function SortTemplate(comparator) { - function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; - } - function randomIntInRange(low, high) { - return Math.round(low + Math.random() * (high - low)); - } - function doQuickSort(ary, comparator2, p, r) { - if (p < r) { - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - swap(ary, pivotIndex, r); - var pivot = ary[r]; - for (var j = p; j < r; j++) { - if (comparator2(ary[j], pivot, false) <= 0) { - i += 1; - swap(ary, i, j); - } - } - swap(ary, i + 1, j); - var q = i + 1; - doQuickSort(ary, comparator2, p, q - 1); - doQuickSort(ary, comparator2, q + 1, r); - } - } - return doQuickSort; - } - function cloneSort(comparator) { - let template = SortTemplate.toString(); - let templateFn = new Function(`return ${template}`)(); - return templateFn(comparator); - } - var isEvalAllowed = function() { - try { - new Function("return 0")(); - return true; - } catch { - return false; - } - }(); - var sortCache = /* @__PURE__ */ new WeakMap(); - exports2.quickSort = function(ary, comparator, start = 0) { - let doQuickSort = isEvalAllowed ? sortCache.get(comparator) : SortTemplate(comparator); - if (doQuickSort === void 0) { - doQuickSort = cloneSort(comparator); - sortCache.set(comparator, doQuickSort); - } - doQuickSort(ary, comparator, start, ary.length - 1); - }; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/source-map-consumer.js -var require_source_map_consumer = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/source-map-consumer.js"(exports2) { - var util = require_util(); - var binarySearch = require_binary_search(); - var ArraySet = require_array_set().ArraySet; - var base64VLQ = require_base64_vlq(); - var quickSort = require_quick_sort().quickSort; - var MAX_SECTION_OFFSET_LINE = 1e7; - function SourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === "string") { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); - } - SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); - }; - SourceMapConsumer.prototype._version = 3; - SourceMapConsumer.prototype.__generatedMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", { - configurable: true, - enumerable: true, - get: function() { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - return this.__generatedMappings; - } - }); - SourceMapConsumer.prototype.__originalMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", { - configurable: true, - enumerable: true, - get: function() { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - return this.__originalMappings; - } - }); - SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - SourceMapConsumer.GENERATED_ORDER = 1; - SourceMapConsumer.ORIGINAL_ORDER = 2; - SourceMapConsumer.GREATEST_LOWER_BOUND = 1; - SourceMapConsumer.LEAST_UPPER_BOUND = 2; - SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.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); - if (source !== null) { - source = util.computeSourceURL(sourceRoot, source, sourceMapURL); - } - boundCallback({ - source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : names.at(mapping.name) - }); - } - }; - SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, "line"); - var needle = { - source: util.getArg(aArgs, "source"), - originalLine: line, - originalColumn: util.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.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND - ); - if (index >= 0) { - var mapping = this._originalMappings[index]; - if (aArgs.column === void 0) { - var originalLine = mapping.originalLine; - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, "generatedLine", null), - column: util.getArg(mapping, "generatedColumn", null), - lastColumn: util.getArg(mapping, "lastGeneratedColumn", null) - }); - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, "generatedLine", null), - column: util.getArg(mapping, "generatedColumn", null), - lastColumn: util.getArg(mapping, "lastGeneratedColumn", null) - }); - mapping = this._originalMappings[++index]; - } - } - } - return mappings; - }; - exports2.SourceMapConsumer = SourceMapConsumer; - function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === "string") { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - var version = util.getArg(sourceMap, "version"); - var sources = util.getArg(sourceMap, "sources"); - var names = util.getArg(sourceMap, "names", []); - var sourceRoot = util.getArg(sourceMap, "sourceRoot", null); - var sourcesContent = util.getArg(sourceMap, "sourcesContent", null); - var mappings = util.getArg(sourceMap, "mappings"); - var file = util.getArg(sourceMap, "file", null); - if (version != this._version) { - throw new Error("Unsupported version: " + version); - } - if (sourceRoot) { - sourceRoot = util.normalize(sourceRoot); - } - sources = sources.map(String).map(util.normalize).map(function(source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; - }); - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - this._absoluteSources = this._sources.toArray().map(function(s) { - return util.computeSourceURL(sourceRoot, s, aSourceMapURL); - }); - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this._sourceMapURL = aSourceMapURL; - this.file = file; - } - BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); - BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - var i; - for (i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } - return -1; - }; - 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.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); - }); - 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.compareByOriginalPositions); - return smc; - }; - BasicSourceMapConsumer.prototype._version = 3; - Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", { - get: function() { - return this._absoluteSources.slice(); - } - }); - function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; - } - var compareGenerated = util.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(array, compareGenerated, start); - } - } - 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; - 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(); - mapping.generatedLine = generatedLine; - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - 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"); - } - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - if (segment.length > 1) { - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - mapping.originalLine += 1; - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - if (segment.length > 4) { - 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(originalMappings[i], util.compareByOriginalPositionsNoSource); - } - } - this.__originalMappings = [].concat(...originalMappings); - }; - BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { - 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); - }; - BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - mapping.lastGeneratedColumn = Infinity; - } - }; - BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, "line"), - generatedColumn: util.getArg(aArgs, "column") - }; - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - if (index >= 0) { - var mapping = this._generatedMappings[index]; - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, "source", null); - if (source !== null) { - source = this._sources.at(source); - source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - var name = util.getArg(mapping, "name", null); - if (name !== null) { - name = this._names.at(name); - } - return { - source, - line: util.getArg(mapping, "originalLine", null), - column: util.getArg(mapping, "originalColumn", null), - name - }; - } - } - return { - source: null, - line: null, - column: null, - name: null - }; - }; - 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; - }); - }; - 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.relative(this.sourceRoot, relativeSource); - } - var url; - if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { - 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)]; - } - } - if (nullOnMissing) { - return null; - } else { - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - }; - BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, "source"); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - var needle = { - source, - originalLine: util.getArg(aArgs, "line"), - originalColumn: util.getArg(aArgs, "column") - }; - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - if (index >= 0) { - var mapping = this._originalMappings[index]; - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, "generatedLine", null), - column: util.getArg(mapping, "generatedColumn", null), - lastColumn: util.getArg(mapping, "lastGeneratedColumn", null) - }; - } - } - return { - line: null, - column: null, - lastColumn: null - }; - }; - exports2.BasicSourceMapConsumer = BasicSourceMapConsumer; - function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === "string") { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - var version = util.getArg(sourceMap, "version"); - var sections = util.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 - }; - var maxOffsetLine = 0; - this._sections = sections.map(function(s) { - if (s.url) { - throw new Error("Support for url field in sections not implemented."); - } - var offset = util.getArg(s, "offset"); - var offsetLine = util.getArg(offset, "line"); - var offsetColumn = util.getArg(offset, "column"); - if (!isValidOffset(offsetLine) || !isValidOffset(offsetColumn)) { - throw new Error("Section offset line and column must be non-negative integers."); - } - if (offsetLine > MAX_SECTION_OFFSET_LINE) { - throw new Error("Section offset line must not exceed " + MAX_SECTION_OFFSET_LINE + "."); - } - if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) { - throw new Error("Section offsets must be ordered and non-overlapping."); - } - lastOffset = offset; - var consumer = new SourceMapConsumer(util.getArg(s, "map"), aSourceMapURL); - var totalOffsetLine = offsetLine + (consumer._maxOffsetLine || 0); - if (totalOffsetLine > MAX_SECTION_OFFSET_LINE) { - throw new Error("Section offset line must not exceed " + MAX_SECTION_OFFSET_LINE + ", including offsets of nested sections."); - } - if (totalOffsetLine > maxOffsetLine) { - maxOffsetLine = totalOffsetLine; - } - 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 - }; - }); - this._maxOffsetLine = maxOffsetLine; - } - function isValidOffset(aValue) { - return typeof aValue === "number" && aValue >= 0 && aValue <= 9007199254740991 && // Number.MAX_SAFE_INTEGER - Math.floor(aValue) === aValue; - } - IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); - IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - IndexedSourceMapConsumer.prototype._version = 3; - Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", { - get: function() { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - var sectionSources = this._sections[i].consumer.sources; - for (var j = 0; j < sectionSources.length; j++) { - sources.push(sectionSources[j]); - } - } - return sources; - } - }); - IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, "line"), - generatedColumn: util.getArg(aArgs, "column") - }; - var sectionIndex = binarySearch.search( - needle, - this._sections, - function(needle2, section2) { - var cmp3 = needle2.generatedLine - section2.generatedOffset.generatedLine; - if (cmp3) { - return cmp3; - } - return needle2.generatedColumn - section2.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 - }); - }; - IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function(s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - 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 || content === "") { - return content; - } - } - if (nullOnMissing) { - return null; - } else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - if (section.consumer._findSourceIndex(util.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 - }; - }; - 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); - if (source !== null) { - source = util.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); - } - var adjustedMapping = { - 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 - }; - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === "number") { - this.__originalMappings.push(adjustedMapping); - } - } - } - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - exports2.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/source-node.js -var require_source_node = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/lib/source-node.js"(exports2) { - var SourceMapGenerator = require_source_map_generator().SourceMapGenerator; - var util = require_util(); - var REGEX_NEWLINE = /(\r?\n)/; - var NEWLINE_CODE = 10; - var isSourceNode = "$$$isSourceNode$$$"; - 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); - } - SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - var node = new SourceNode(); - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - var newLine = getNextLine() || ""; - return lineContents + newLine; - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0; - } - }; - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - var lastMapping = null; - aSourceMapConsumer.eachMapping(function(mapping) { - if (lastMapping !== null) { - if (lastGeneratedLine < mapping.generatedLine) { - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - } else { - 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); - lastMapping = mapping; - return; - } - } - while (lastGeneratedLine < mapping.generatedLine) { - if (remainingLinesIndex >= remainingLines.length) { - lastGeneratedLine = mapping.generatedLine; - break; - } - 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); - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - addMappingWithCode(lastMapping, shiftNextLine()); - } - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - 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 === void 0) { - 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 - )); - } - } - }; - 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; - }; - 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; - }; - 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 - }); - } - } - } - }; - 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; - }; - 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; - }; - SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - 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]]); - } - }; - SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function(chunk) { - str += chunk; - }); - return str; - }; - SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(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; - 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 }; - }; - exports2.SourceNode = SourceNode; - } -}); - -// intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/source-map.js -var require_source_map = __commonJS({ - "intern-log/node_modules/.pnpm/source-map-js@1.2.2/node_modules/source-map-js/source-map.js"(exports2) { - exports2.SourceMapGenerator = require_source_map_generator().SourceMapGenerator; - exports2.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer; - exports2.SourceNode = require_source_node().SourceNode; - } -}); - -// intern-log/node_modules/.pnpm/@vue+compiler-core@3.5.44/node_modules/@vue/compiler-core/dist/compiler-core.cjs.prod.js -var require_compiler_core_cjs_prod = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+compiler-core@3.5.44/node_modules/@vue/compiler-core/dist/compiler-core.cjs.prod.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var shared = require_shared(); - var decode = require_decode(); - var parser = require_lib(); - var estreeWalker = require_estree_walker(); - var sourceMapJs = require_source_map(); - var FRAGMENT = /* @__PURE__ */ Symbol(``); - var TELEPORT = /* @__PURE__ */ Symbol(``); - var SUSPENSE = /* @__PURE__ */ Symbol(``); - var KEEP_ALIVE = /* @__PURE__ */ Symbol(``); - var BASE_TRANSITION = /* @__PURE__ */ Symbol( - `` - ); - var OPEN_BLOCK = /* @__PURE__ */ Symbol(``); - var CREATE_BLOCK = /* @__PURE__ */ Symbol(``); - var CREATE_ELEMENT_BLOCK = /* @__PURE__ */ Symbol( - `` - ); - var CREATE_VNODE = /* @__PURE__ */ Symbol(``); - var CREATE_ELEMENT_VNODE = /* @__PURE__ */ Symbol( - `` - ); - var CREATE_COMMENT = /* @__PURE__ */ Symbol( - `` - ); - var CREATE_TEXT = /* @__PURE__ */ Symbol( - `` - ); - var CREATE_STATIC = /* @__PURE__ */ Symbol( - `` - ); - var RESOLVE_COMPONENT = /* @__PURE__ */ Symbol( - `` - ); - var RESOLVE_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol( - `` - ); - var RESOLVE_DIRECTIVE = /* @__PURE__ */ Symbol( - `` - ); - var RESOLVE_FILTER = /* @__PURE__ */ Symbol( - `` - ); - var WITH_DIRECTIVES = /* @__PURE__ */ Symbol( - `` - ); - var RENDER_LIST = /* @__PURE__ */ Symbol(``); - var RENDER_SLOT = /* @__PURE__ */ Symbol(``); - var CREATE_SLOTS = /* @__PURE__ */ Symbol(``); - var TO_DISPLAY_STRING = /* @__PURE__ */ Symbol( - `` - ); - var MERGE_PROPS = /* @__PURE__ */ Symbol(``); - var NORMALIZE_CLASS = /* @__PURE__ */ Symbol( - `` - ); - var NORMALIZE_STYLE = /* @__PURE__ */ Symbol( - `` - ); - var NORMALIZE_PROPS = /* @__PURE__ */ Symbol( - `` - ); - var GUARD_REACTIVE_PROPS = /* @__PURE__ */ Symbol( - `` - ); - var TO_HANDLERS = /* @__PURE__ */ Symbol(``); - var CAMELIZE = /* @__PURE__ */ Symbol(``); - var CAPITALIZE = /* @__PURE__ */ Symbol(``); - var TO_HANDLER_KEY = /* @__PURE__ */ Symbol( - `` - ); - var SET_BLOCK_TRACKING = /* @__PURE__ */ Symbol( - `` - ); - var PUSH_SCOPE_ID = /* @__PURE__ */ Symbol(``); - var POP_SCOPE_ID = /* @__PURE__ */ Symbol(``); - var WITH_CTX = /* @__PURE__ */ Symbol(``); - var UNREF = /* @__PURE__ */ Symbol(``); - var IS_REF = /* @__PURE__ */ Symbol(``); - var WITH_MEMO = /* @__PURE__ */ Symbol(``); - var IS_MEMO_SAME = /* @__PURE__ */ Symbol(``); - var 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]; - }); - } - var Namespaces = { - "HTML": 0, - "0": "HTML", - "SVG": 1, - "1": "SVG", - "MATH_ML": 2, - "2": "MATH_ML" - }; - var 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" - }; - var ElementTypes = { - "ELEMENT": 0, - "0": "ELEMENT", - "COMPONENT": 1, - "1": "COMPONENT", - "SLOT": 2, - "2": "SLOT", - "TEMPLATE": 3, - "3": "TEMPLATE" - }; - var ConstantTypes = { - "NOT_CONSTANT": 0, - "0": "NOT_CONSTANT", - "CAN_SKIP_PATCH": 1, - "1": "CAN_SKIP_PATCH", - "CAN_CACHE": 2, - "2": "CAN_CACHE", - "CAN_STRINGIFY": 3, - "3": "CAN_STRINGIFY" - }; - var 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: [], - temps: 0, - codegenNode: void 0, - loc: locStub - }; - } - function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent2 = false, loc = locStub) { - if (context) { - if (isBlock) { - context.helper(OPEN_BLOCK); - context.helper(getVNodeBlockHelper(context.inSSR, isComponent2)); - } else { - context.helper(getVNodeHelper(context.inSSR, isComponent2)); - } - if (directives) { - context.helper(WITH_DIRECTIVES); - } - } - return { - type: 13, - tag, - props, - children, - patchFlag, - dynamicProps, - directives, - isBlock, - disableTracking, - isComponent: isComponent2, - 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: shared.isString(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: shared.isString(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, needPauseTracking = false, inVOnce = false) { - return { - type: 20, - index, - value, - needPauseTracking, - inVOnce, - needArraySpread: false, - 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, isComponent2) { - return ssr || isComponent2 ? CREATE_VNODE : CREATE_ELEMENT_VNODE; - } - function getVNodeBlockHelper(ssr, isComponent2) { - return ssr || isComponent2 ? 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)); - } - } - var defaultDelimitersOpen = new Uint8Array([123, 123]); - var defaultDelimitersClose = new Uint8Array([125, 125]); - function isTagStartChar(c) { - return c >= 97 && c <= 122 || c >= 65 && c <= 90; - } - function isWhitespace(c) { - return c === 32 || c === 10 || c === 9 || c === 12 || c === 13; - } - function isEndOfTagSection(c) { - return c === 47 || c === 62 || isWhitespace(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; - } - var 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; - const length = this.newlines.length; - let j = -1; - if (length > 100) { - let l = -1; - let r = length; - while (l + 1 < r) { - const m = l + r >>> 1; - this.newlines[m] < index ? l = m : r = m; - } - j = l; - } else { - for (let i = length - 1; i >= 0; i--) { - if (index > this.newlines[i]) { - j = i; - break; - } - } - } - if (j >= 0) { - line = j + 2; - column = index - this.newlines[j]; - } - 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(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 (!this.inVPre && 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(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(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(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(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(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(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(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 ? decode.DecodingMode.Legacy : decode.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.state !== 33) { - 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( - decode.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( - decode.fromCodePoint(cp), - this.entityStart, - this.sectionStart - ); - } - } - } - }; - var 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" - }; - var 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); - 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) { - } - function createCompilerError(code, loc, messages2, additionalMessage) { - const msg = (messages2 || errorMessages)[code] + (additionalMessage || ``); - const error = new SyntaxError(String(msg)); - error.code = code; - error.loc = loc; - return error; - } - var 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_V_MODEL_ON_CONST": 45, - "45": "X_V_MODEL_ON_CONST", - "X_INVALID_EXPRESSION": 46, - "46": "X_INVALID_EXPRESSION", - "X_KEEP_ALIVE_INVALID_CHILDREN": 47, - "47": "X_KEEP_ALIVE_INVALID_CHILDREN", - "X_PREFIX_ID_NOT_SUPPORTED": 48, - "48": "X_PREFIX_ID_NOT_SUPPORTED", - "X_MODULE_MODE_NOT_SUPPORTED": 49, - "49": "X_MODULE_MODE_NOT_SUPPORTED", - "X_CACHE_HANDLER_NOT_SUPPORTED": 50, - "50": "X_CACHE_HANDLER_NOT_SUPPORTED", - "X_SCOPE_ID_NOT_SUPPORTED": 51, - "51": "X_SCOPE_ID_NOT_SUPPORTED", - "X_VNODE_HOOKS": 52, - "52": "X_VNODE_HOOKS", - "X_V_BIND_INVALID_SAME_NAME_ARGUMENT": 53, - "53": "X_V_BIND_INVALID_SAME_NAME_ARGUMENT", - "__EXTEND_POINT__": 54, - "54": "__EXTEND_POINT__" - }; - var errorMessages = { - // 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.`, - [53]: `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. -For props declared with defineModel(), assign the returned ref to a variable and use v-model on that variable.`, - [45]: `v-model cannot be used on a const binding because it is not writable.`, - [46]: `Error parsing JavaScript expression: `, - [47]: `<KeepAlive> expects exactly one child component.`, - [52]: `@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 - [48]: `"prefixIdentifiers" option is not supported in this build of compiler.`, - [49]: `ES module mode is not supported in this build of compiler.`, - [50]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`, - [51]: `"scopeId" option is only supported in module mode.`, - // just to fulfill types - [54]: `` - }; - 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; - estreeWalker.walk(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" && // eslint-disable-next-line no-restricted-syntax - (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) - ); - } - } else if (node.type === "SwitchStatement") { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - walkSwitchStatement( - node, - false, - (id) => markScopeIdentifier(node, id, knownIds) - ); - } - } else if (node.type === "CatchClause" && node.param) { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - for (const id of extractIdentifiers(node.param)) { - markScopeIdentifier(node, id, knownIds); - } - } - } else if (isForStatement(node)) { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - walkForStatement( - node, - false, - (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, parentStack[parentStack.length - 2])) { - return true; - } - switch (parent.type) { - case "AssignmentExpression": - case "AssignmentPattern": - return true; - case "ObjectProperty": - return parent.key !== id && isInDestructureAssignment(parent, parentStack); - 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(p)) { - onIdent(id); - } - } - } - function walkBlockDeclarations(block, onIdent) { - const body = block.type === "SwitchCase" ? block.consequent : block.body; - for (const stmt of body) { - if (stmt.type === "VariableDeclaration") { - if (stmt.declare) continue; - for (const decl of stmt.declarations) { - for (const id of extractIdentifiers(decl.id)) { - onIdent(id); - } - } - } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") { - if (stmt.declare || !stmt.id) continue; - onIdent(stmt.id); - } else if (isForStatement(stmt)) { - walkForStatement(stmt, true, onIdent); - } else if (stmt.type === "SwitchStatement") { - walkSwitchStatement(stmt, true, onIdent); - } - } - } - function isForStatement(stmt) { - return stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement"; - } - function walkForStatement(stmt, isVar, onIdent) { - const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left; - if (variable && variable.type === "VariableDeclaration" && (variable.kind === "var" ? isVar : !isVar)) { - for (const decl of variable.declarations) { - for (const id of extractIdentifiers(decl.id)) { - onIdent(id); - } - } - } - } - function walkSwitchStatement(stmt, isVar, onIdent) { - for (const cs of stmt.cases) { - for (const stmt2 of cs.consequent) { - if (stmt2.type === "VariableDeclaration" && (stmt2.kind === "var" ? isVar : !isVar)) { - for (const decl of stmt2.declarations) { - for (const id of extractIdentifiers(decl.id)) { - onIdent(id); - } - } - } - } - walkBlockDeclarations(cs, onIdent); - } - } - function extractIdentifiers(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(prop.argument, nodes); - } else { - extractIdentifiers(prop.value, nodes); - } - } - break; - case "ArrayPattern": - param.elements.forEach((element) => { - if (element) extractIdentifiers(element, nodes); - }); - break; - case "RestElement": - extractIdentifiers(param.argument, nodes); - break; - case "AssignmentPattern": - extractIdentifiers(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); - } - var isFunctionType = (node) => { - return /Function(?:Expression|Declaration)$|Method$/.test(node.type); - }; - var isStaticProperty = (node) => node && (node.type === "ObjectProperty" || node.type === "ObjectMethod") && !node.computed; - var 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; - } - var 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; - } - } - var 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; - } - } - var nonIdentifierRE = /^$|^\d|[^\$\w\xA0-\uFFFF]/; - var isSimpleIdentifier = (name) => !nonIdentifierRE.test(name); - var validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/; - var validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/; - var whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g; - var getExpSource = (exp) => exp.type === 4 ? exp.content : exp.loc.source; - var isMemberExpressionBrowser = (exp) => { - const path = getExpSource(exp).trim().replace(whitespaceRE, (s) => s.trim()); - let state = 0; - 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: - if (char === "[") { - stateStack.push(state); - state = 1; - currentOpenBracketCount++; - } else if (char === "(") { - stateStack.push(state); - state = 2; - currentOpenParensCount++; - } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) { - return false; - } - break; - case 1: - if (char === `'` || char === `"` || char === "`") { - stateStack.push(state); - state = 3; - currentStringType = char; - } else if (char === `[`) { - currentOpenBracketCount++; - } else if (char === `]`) { - if (!--currentOpenBracketCount) { - state = stateStack.pop(); - } - } - break; - case 2: - if (char === `'` || char === `"` || char === "`") { - stateStack.push(state); - state = 3; - currentStringType = char; - } else if (char === `(`) { - currentOpenParensCount++; - } else if (char === `)`) { - if (i === path.length - 1) { - return false; - } - if (!--currentOpenParensCount) { - state = stateStack.pop(); - } - } - break; - case 3: - if (char === currentStringType) { - state = stateStack.pop(); - currentStringType = null; - } - break; - } - } - return !currentOpenBracketCount && !currentOpenParensCount; - }; - var isMemberExpressionNode = (exp, context) => { - try { - let ret = exp.ast || parser.parseExpression(getExpSource(exp), { - plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"] - }); - ret = unwrapTSNode(ret); - return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier" && ret.name !== "undefined"; - } catch (e) { - return false; - } - }; - var isMemberExpression = isMemberExpressionNode; - var fnExpRE = /^\s*(?:async\s*)?(?:\([^)]*?\)|[\w$_]+)\s*(?::[^=]+)?=>|^\s*(?:async\s+)?function(?:\s+[\w$]+)?\s*\(/; - var isFnExpressionBrowser = (exp) => fnExpRE.test(getExpSource(exp)); - var isFnExpressionNode = (exp, context) => { - try { - let ret = exp.ast || parser.parseExpression(getExpSource(exp), { - plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"] - }); - if (ret.type === "Program") { - ret = ret.body[0]; - if (ret.type === "ExpressionStatement") { - ret = ret.expression; - } - } - ret = unwrapTSNode(ret); - return ret.type === "FunctionExpression" || ret.type === "ArrowFunctionExpression"; - } catch (e) { - return false; - } - }; - var isFnExpression = isFnExpressionNode; - 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) && (shared.isString(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 isVPre(p) { - return p.type === 7 && p.name === "pre"; - } - 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; - } - var propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]); - function getUnnormalizedProps(props, callPath = []) { - if (props && !shared.isString(props) && props.type === 14) { - const callee = props.callee; - if (!shared.isString(callee) && propsHelperSet.has(callee)) { - return getUnnormalizedProps( - props.arguments[0], - callPath.concat(props) - ); - } - } - return [props, callPath]; - } - function injectProp(node, prop, context) { - if (node.type !== 13 && injectSlotKey(node, prop)) { - return; - } - let propsWithInjection; - let props = node.type === 13 ? node.props : node.arguments[2]; - let callPath = []; - let parentCall; - if (props && !shared.isString(props) && props.type === 14) { - const ret = getUnnormalizedProps(props); - props = ret[0]; - callPath = ret[1]; - parentCall = callPath[callPath.length - 1]; - } - if (props == null || shared.isString(props)) { - propsWithInjection = createObjectExpression([prop]); - } else if (props.type === 14) { - const first = props.arguments[0]; - if (!shared.isString(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 injectSlotKey(node, prop) { - var _a, _b, _c; - if (prop.key.type !== 4 || prop.key.content !== "key") { - return false; - } - const props = node.arguments[2]; - if (props && !shared.isString(props)) { - const [unnormalizedProps] = getUnnormalizedProps(props); - if (unnormalizedProps && !shared.isString(unnormalizedProps) && unnormalizedProps.type === 15 && hasProp(prop, unnormalizedProps)) { - return true; - } - } - (_a = node.arguments)[2] || (_a[2] = "{}"); - (_b = node.arguments)[3] || (_b[3] = "undefined"); - (_c = node.arguments)[4] || (_c[4] = "undefined"); - node.arguments[5] = prop.value; - return true; - } - 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) => shared.isObject(c) && hasScopeRef(c, ids)); - case 5: - case 12: - return hasScopeRef(node.content, ids); - case 2: - case 3: - case 20: - return false; - default: - return false; - } - } - function getMemoedVNodeCall(node) { - if (node.type === 14 && node.callee === WITH_MEMO) { - return node.arguments[1].returns; - } else { - return node; - } - } - var forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/; - function isAllWhitespace(str) { - for (let i = 0; i < str.length; i++) { - if (!isWhitespace(str.charCodeAt(i))) { - return false; - } - } - return true; - } - function isWhitespaceText(node) { - return node.type === 2 && isAllWhitespace(node.content) || node.type === 12 && isWhitespaceText(node.content); - } - function isCommentOrWhitespace(node) { - return node.type === 3 || isWhitespaceText(node); - } - var defaultParserOptions = { - parseMode: "base", - ns: 0, - delimiters: [`{{`, `}}`], - getNamespace: () => 0, - isVoidTag: shared.NO, - isPreTag: shared.NO, - isIgnoreNewlineTag: shared.NO, - isCustomElement: shared.NO, - onError: defaultOnError, - onWarn: defaultOnWarn, - comments: false, - prefixIdentifiers: false - }; - var currentOptions = defaultParserOptions; - var currentRoot = null; - var currentInput = ""; - var currentOpenTag = null; - var currentProp = null; - var currentAttrValue = ""; - var currentAttrStartIndex = -1; - var currentAttrEndIndex = -1; - var inPre = 0; - var inVPre = false; - var currentVPreBoundary = null; - var stack = []; - var tokenizer = new Tokenizer(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.delimiterOpen.length; - let innerEnd = end - tokenizer.delimiterClose.length; - while (isWhitespace(currentInput.charCodeAt(innerStart))) { - innerStart++; - } - while (isWhitespace(currentInput.charCodeAt(innerEnd - 1))) { - innerEnd--; - } - let exp = getSlice(innerStart, innerEnd); - if (exp.includes("&")) { - { - exp = decode.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) { - const name = currentOpenTag.tag; - currentOpenTag.isSelfClosing = true; - endOpenTag(end); - if (stack[0] && stack[0].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 === "." ? [createSimpleExpression("prop")] : [], - loc: getLoc(start) - }; - if (name === "pre") { - inVPre = tokenizer.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 && !isVPre(currentProp)) { - 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 && !isVPre(currentProp)) { - 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 { - const exp = createSimpleExpression(mod, true, getLoc(start, end)); - currentProp.modifiers.push(exp); - } - }, - 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.inSFCRoot && currentOpenTag.tag === "template" && currentProp.name === "lang" && currentAttrValue && currentAttrValue !== "html") { - tokenizer.enterRCDATA(toCharCodes(`</template`), 0); - } - } else { - let expParseMode = 0; - { - if (currentProp.name === "for") { - expParseMode = 3; - } else if (currentProp.name === "slot") { - expParseMode = 1; - } else if (currentProp.name === "on" && currentAttrValue.includes(";")) { - expParseMode = 2; - } - } - currentProp.exp = createExp( - currentAttrValue, - false, - getLoc(currentAttrStartIndex, currentAttrEndIndex), - 0, - expParseMode - ); - if (currentProp.name === "for") { - currentProp.forParseResult = parseForExpression(currentProp.exp); - } - let syncIndex = -1; - if (currentProp.name === "bind" && (syncIndex = currentProp.modifiers.findIndex( - (mod) => mod.content === "sync" - )) > -1 && checkCompatEnabled( - "COMPILER_V_BIND_SYNC", - currentOptions, - currentProp.loc, - currentProp.arg.loc.source - )) { - currentProp.name = "model"; - currentProp.modifiers.splice(syncIndex, 1); - } - } - } - 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.state !== 1) { - switch (tokenizer.state) { - case 5: - case 8: - emitError(5, end); - break; - case 3: - case 4: - emitError( - 25, - tokenizer.sectionStart - ); - break; - case 28: - if (tokenizer.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] ? stack[0].ns : currentOptions.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 - ); - } - } - }); - var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; - var 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 : 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.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.inXML = true; - } - } - currentOpenTag = null; - } - function onText(content, start, end) { - const parent = stack[0] || currentRoot; - const lastNode = parent.children[parent.children.length - 1]; - if (lastNode && 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, lookAhead(end, 62) + 1); - } - if (tokenizer.inSFCRoot) { - if (el.children.length) { - el.innerLoc.end = shared.extend({}, el.children[el.children.length - 1].loc.end); - } else { - el.innerLoc.end = shared.extend({}, el.innerLoc.start); - } - el.innerLoc.source = getSlice( - el.innerLoc.start.offset, - el.innerLoc.end.offset - ); - } - const { tag, ns, children } = 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.inRCDATA) { - el.children = condenseWhitespace(children); - } - if (ns === 0 && currentOptions.isIgnoreNewlineTag(tag)) { - const first = children[0]; - if (first && first.type === 2) { - first.content = first.content.replace(/^\r?\n/, ""); - } - } - if (ns === 0 && currentOptions.isPreTag(tag)) { - inPre--; - } - if (currentVPreBoundary === el) { - inVPre = tokenizer.inVPre = false; - currentVPreBoundary = null; - } - if (tokenizer.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) { - tokenizer.inXML = false; - } - { - const props = el.props; - if (!tokenizer.inSFCRoot && isCompatEnabled( - "COMPILER_NATIVE_TEMPLATE", - currentOptions - ) && el.tag === "template" && !isFragmentTemplate(el)) { - const parent = stack[0] || currentRoot; - const index = parent.children.indexOf(el); - parent.children.splice(index, 1, ...el.children); - } - const inlineTemplateProp = props.find( - (p) => p.type === 6 && p.name === "inline-template" - ); - if (inlineTemplateProp && checkCompatEnabled( - "COMPILER_INLINE_TEMPLATE", - currentOptions, - inlineTemplateProp.loc - ) && el.children.length) { - inlineTemplateProp.value = { - type: 2, - content: getSlice( - el.children[0].loc.start.offset, - el.children[el.children.length - 1].loc.end.offset - ), - loc: inlineTemplateProp.loc - }; - } - } - } - function lookAhead(index, c) { - let i = index; - while (currentInput.charCodeAt(i) !== c && i < currentInput.length - 1) i++; - return i; - } - function backTrack(index, c) { - let i = index; - while (currentInput.charCodeAt(i) !== c && i >= 0) i--; - return i; - } - var 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 }) { - if (currentOptions.isCustomElement(tag)) { - return false; - } - if (tag === "component" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || currentOptions.isBuiltInComponent && currentOptions.isBuiltInComponent(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; - } else if (checkCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - currentOptions, - p.loc - )) { - return true; - } - } - } else if ( - // :is on plain element - only treat as component in compat mode - p.name === "bind" && isStaticArgOf(p.arg, "is") && checkCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - currentOptions, - p.loc - ) - ) { - return true; - } - } - return false; - } - function isUpperCase(c) { - return c > 64 && c < 91; - } - var windowsNewlineRE = /\r\n/g; - function condenseWhitespace(nodes) { - 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 = nodes[i - 1] && nodes[i - 1].type; - const next = nodes[i + 1] && nodes[i + 1].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"); - } - } - } - return removedWhitespace ? nodes.filter(Boolean) : nodes; - } - 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(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.getPos(start), - // @ts-expect-error allow late attachment - end: end == null ? end : tokenizer.getPos(end), - // @ts-expect-error allow late attachment - source: end == null ? end : getSlice(start, end) - }; - } - function cloneLoc(loc) { - return getLoc(loc.start.offset, loc.end.offset); - } - function setLocEnd(loc, end) { - loc.end = tokenizer.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) { - const exp = createSimpleExpression(content, isStatic, loc, constType); - if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 && 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) { - exp.ast = parser.parse(` ${content} `, options).program; - } else if (parseMode === 1) { - exp.ast = parser.parseExpression(`(${content})=>{}`, options); - } else { - exp.ast = parser.parseExpression(`(${content})`, options); - } - } catch (e) { - exp.ast = false; - emitError(46, 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.reset(); - currentOpenTag = null; - currentProp = null; - currentAttrValue = ""; - currentAttrStartIndex = -1; - currentAttrEndIndex = -1; - stack.length = 0; - } - function baseParse(input, options) { - reset(); - currentInput = input; - currentOptions = shared.extend({}, defaultParserOptions); - if (options) { - let key; - for (key in options) { - if (options[key] != null) { - currentOptions[key] = options[key]; - } - } - } - tokenizer.mode = currentOptions.parseMode === "html" ? 1 : currentOptions.parseMode === "sfc" ? 2 : 0; - tokenizer.inXML = currentOptions.ns === 1 || currentOptions.ns === 2; - const delimiters = options && options.delimiters; - if (delimiters) { - tokenizer.delimiterOpen = toCharCodes(delimiters[0]); - tokenizer.delimiterClose = toCharCodes(delimiters[1]); - } - const root = currentRoot = createRoot([], input); - tokenizer.parse(currentInput); - root.loc = getLoc(0, input.length); - root.children = condenseWhitespace(root.children); - currentRoot = null; - return root; - } - function cacheStatic(root, context) { - walk( - root, - void 0, - context, - // Root node is unfortunately non-hoistable due to potential parent - // fallthrough attributes. - !!getSingleElementRoot(root) - ); - } - function getSingleElementRoot(root) { - const children = root.children.filter((x) => x.type !== 3); - return children.length === 1 && children[0].type === 1 && !isSlotOutlet(children[0]) ? children[0] : null; - } - function walk(node, parent, context, doNotHoistNode = false, inFor = false) { - const { children } = node; - const toCache = []; - 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; - toCache.push(child); - continue; - } - } else { - const codegenNode = child.codegenNode; - if (codegenNode.type === 13) { - const flag = codegenNode.patchFlag; - if ((flag === void 0 || 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); - } - } - } - } else if (child.type === 12) { - const constantType = doNotHoistNode ? 0 : getConstantType(child, context); - if (constantType >= 2) { - if (child.codegenNode.type === 14 && child.codegenNode.arguments.length > 0) { - child.codegenNode.arguments.push( - `-1` - ); - } - toCache.push(child); - continue; - } - } - if (child.type === 1) { - const isComponent2 = child.tagType === 1; - if (isComponent2) { - context.scopes.vSlot++; - } - walk(child, node, context, false, inFor); - if (isComponent2) { - context.scopes.vSlot--; - } - } else if (child.type === 11) { - walk(child, node, context, child.children.length === 1, true); - } else if (child.type === 9) { - for (let i2 = 0; i2 < child.branches.length; i2++) { - walk( - child.branches[i2], - node, - context, - child.branches[i2].children.length === 1, - inFor - ); - } - } - } - let cachedAsArray = false; - if (toCache.length === children.length && node.type === 1) { - if (node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && shared.isArray(node.codegenNode.children)) { - node.codegenNode.children = getCacheExpression( - createArrayExpression(node.codegenNode.children) - ); - cachedAsArray = true; - } else if (node.tagType === 1 && node.codegenNode && node.codegenNode.type === 13 && node.codegenNode.children && !shared.isArray(node.codegenNode.children) && node.codegenNode.children.type === 15) { - const slot = getSlotNode(node.codegenNode, "default"); - if (slot) { - slot.returns = getCacheExpression( - createArrayExpression(slot.returns) - ); - cachedAsArray = true; - } - } else if (node.tagType === 3 && parent && parent.type === 1 && parent.tagType === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 15) { - const slotName = findDir(node, "slot", true); - const slot = slotName && slotName.arg && getSlotNode(parent.codegenNode, slotName.arg); - if (slot) { - slot.returns = getCacheExpression( - createArrayExpression(slot.returns) - ); - cachedAsArray = true; - } - } - } - if (!cachedAsArray) { - for (const child of toCache) { - child.codegenNode = context.cache(child.codegenNode); - } - } - function getCacheExpression(value) { - const exp = context.cache(value); - exp.needArraySpread = true; - return exp; - } - function getSlotNode(node2, name) { - if (node2.children && !shared.isArray(node2.children) && node2.children.type === 15) { - const slot = node2.children.properties.find( - (p) => p.key === name || p.key.content === name - ); - return slot && slot.value; - } - } - if (toCache.length && context.transformHoist) { - context.transformHoist(children, context, node); - } - } - 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" && node.tag !== "math") { - return 0; - } - if (codegenNode.patchFlag === void 0) { - 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 (shared.isString(child) || shared.isSymbol(child)) { - continue; - } - const childType = getConstantType(child, context); - if (childType === 0) { - return 0; - } else if (childType < returnType) { - returnType = childType; - } - } - return returnType; - case 20: - return 2; - default: - return 0; - } - } - var allowHoistedHelperSet = /* @__PURE__ */ new Set([ - NORMALIZE_CLASS, - NORMALIZE_STYLE, - NORMALIZE_PROPS, - GUARD_REACTIVE_PROPS - ]); - function getConstantTypeOfHelperCall(value, context) { - if (value.type === 14 && !shared.isString(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 createTransformContext(root, { - filename = "", - prefixIdentifiers = false, - hoistStatic = false, - hmr = false, - cacheHandlers = false, - nodeTransforms = [], - directiveTransforms = {}, - transformHoist = null, - isBuiltInComponent = shared.NOOP, - isCustomElement = shared.NOOP, - expressionPlugins = [], - scopeId = null, - slotted = true, - ssr = false, - inSSR = false, - ssrCssVars = ``, - bindingMetadata = shared.EMPTY_OBJ, - inline = false, - isTS = false, - onError = defaultOnError, - onWarn = defaultOnWarn, - compatConfig - }) { - const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/); - const context = { - // options - filename, - selfName: nameMatch && shared.capitalize(shared.camelize(nameMatch[1])), - prefixIdentifiers, - hoistStatic, - 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: [], - cached: [], - constantCache: /* @__PURE__ */ new WeakMap(), - vForMemoKeyedNodes: /* @__PURE__ */ new WeakSet(), - temps: 0, - identifiers: /* @__PURE__ */ Object.create(null), - scopes: { - vFor: 0, - vSlot: 0, - vPre: 0, - vOnce: 0 - }, - parent: null, - grandParent: 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) { - context.parent.children[context.childIndex] = context.currentNode = node; - }, - removeNode(node) { - const list = context.parent.children; - const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1; - 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: shared.NOOP, - addIdentifiers(exp) { - { - if (shared.isString(exp)) { - addId(exp); - } else if (exp.identifiers) { - exp.identifiers.forEach(addId); - } else if (exp.type === 4) { - addId(exp.content); - } - } - }, - removeIdentifiers(exp) { - { - if (shared.isString(exp)) { - removeId(exp); - } else if (exp.identifiers) { - exp.identifiers.forEach(removeId); - } else if (exp.type === 4) { - removeId(exp.content); - } - } - }, - hoist(exp) { - if (shared.isString(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, inVOnce = false) { - const cacheExp = createCacheExpression( - context.cached.length, - exp, - isVNode, - inVOnce - ); - context.cached.push(cacheExp); - return cacheExp; - } - }; - { - context.filters = /* @__PURE__ */ new Set(); - } - 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) { - cacheStatic(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; - { - root.filters = [...context.filters]; - } - } - function createRootCodegen(root, context) { - const { helper } = context; - const { children } = root; - if (children.length === 1) { - const singleElementRootChild = getSingleElementRoot(root); - if (singleElementRootChild && singleElementRootChild.codegenNode) { - const codegenNode = singleElementRootChild.codegenNode; - if (codegenNode.type === 13) { - convertToBlock(codegenNode, context); - } - root.codegenNode = codegenNode; - } else { - root.codegenNode = children[0]; - } - } else if (children.length > 1) { - let patchFlag = 64; - root.codegenNode = createVNodeCall( - context, - helper(FRAGMENT), - void 0, - root.children, - patchFlag, - 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 (shared.isString(child)) continue; - context.grandParent = context.parent; - 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 (shared.isArray(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 = shared.isString(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 PURE_ANNOTATION = `/*@__PURE__*/`; - var 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, 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; - } - } - if (node.loc.source) { - addMapping(node.loc.start, name); - } - } - if (newlineIndex === -3) { - advancePositionWithMutation(context, code); - } else { - context.offset += code.length; - if (newlineIndex === -2) { - context.column += code.length; - } else { - if (newlineIndex === -1) { - newlineIndex = code.length - 1; - } - context.line++; - context.column = code.length - newlineIndex; - } - } - if (node && node.loc !== locStub && node.loc.source) { - 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, - name - }); - } - if (sourceMap) { - context.map = new sourceMapJs.SourceMapGenerator(); - 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.filters && ast.filters.length) { - newline(); - genAssets(ast.filters, "filter", context); - 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 (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 === "filter" ? RESOLVE_FILTER : 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 } = context; - newline(); - for (let i = 0; i < hoists.length; i++) { - const exp = hoists[i]; - if (exp) { - push(`const _hoisted_${i + 1} = `); - genNode(exp, context); - 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 shared.isString(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) => shared.isArray(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 (shared.isString(node)) { - push( - node, - -3 - /* Unknown */ - ); - } else if (shared.isArray(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 (shared.isString(node)) { - context.push( - node, - -3 - /* Unknown */ - ); - return; - } - if (shared.isSymbol(node)) { - context.push(context.helper(node)); - return; - } - switch (node.type) { - case 1: - case 9: - case 11: - 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; - } - } - function genText(node, context) { - context.push(JSON.stringify(node.content), -3, node); - } - function genExpression(node, context) { - const { content, isStatic } = node; - context.push( - isStatic ? JSON.stringify(content) : content, - -3, - 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 (shared.isString(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, node); - } else { - push(`[${node.content}]`, -3, node); - } - } - function genComment(node, context) { - const { push, helper, pure } = context; - if (pure) { - push(PURE_ANNOTATION); - } - push( - `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, - -3, - node - ); - } - function genVNodeCall(node, context) { - const { push, helper, pure } = context; - const { - tag, - props, - children, - patchFlag, - dynamicProps, - directives, - isBlock, - disableTracking, - isComponent: isComponent2 - } = node; - let patchFlagString; - if (patchFlag) { - { - patchFlagString = String(patchFlag); - } - } - 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, isComponent2) : getVNodeHelper(context.inSSR, isComponent2); - push(helper(callHelper) + `(`, -2, node); - genNodeList( - genNullableArgs([tag, props, children, patchFlagString, 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 = shared.isString(node.callee) ? node.callee : helper(node.callee); - if (pure) { - push(PURE_ANNOTATION); - } - push(callee + `(`, -2, node); - genNodeList(node.arguments, context); - push(`)`); - } - function genObjectExpression(node, context) { - const { push, indent, deindent, newline } = context; - const { properties } = node; - if (!properties.length) { - push(`{}`, -2, 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, node); - if (shared.isArray(params)) { - genNodeList(params, context); - } else if (params) { - genNode(params, context); - } - push(`) => `); - if (newline || body) { - push(`{`); - indent(); - } - if (returns) { - if (newline) { - push(`return `); - } - if (shared.isArray(returns)) { - genNodeListAsArray(returns, context); - } else { - genNode(returns, context); - } - } else if (body) { - genNode(body, context); - } - if (newline || body) { - deindent(); - push(`}`); - } - if (isSlot) { - if (node.isNonScopedSlot) { - push(`, undefined, true`); - } - 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; - const { needPauseTracking, needArraySpread } = node; - if (needArraySpread) { - push(`[...(`); - } - push(`_cache[${node.index}] || (`); - if (needPauseTracking) { - indent(); - push(`${helper(SET_BLOCK_TRACKING)}(-1`); - if (node.inVOnce) push(`, true`); - push(`),`); - newline(); - push(`(`); - } - push(`_cache[${node.index}] = `); - genNode(node.value, context); - if (needPauseTracking) { - push(`).cacheIndex = ${node.index},`); - newline(); - push(`${helper(SET_BLOCK_TRACKING)}(1),`); - newline(); - push(`_cache[${node.index}]`); - deindent(); - } - push(`)`); - if (needArraySpread) { - 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 (shared.isString(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 (shared.isArray(returns)) { - genNodeListAsArray(returns, context); - } else { - genNode(returns, context); - } - } - var isLiteralWhitelisted = /* @__PURE__ */ shared.makeMap("true,false,null,this"); - var transformExpression = (node, context) => { - if (node.type === 5) { - node.content = processExpression( - node.content, - context - ); - } else if (node.type === 1) { - const memo = findDir(node, "memo"); - 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) && // key has been processed in transformFor(vMemo + vFor) - !(memo && context.vForMemoKeyedNodes.has(node) && arg && arg.type === 4 && arg.content === "key")) { - 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 = shared.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 shared.genPropsAccessExp(raw); - } else if (type === "props-aliased") { - return shared.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; - let ast = node.ast; - if (ast === false) { - return node; - } - if (ast === null || !ast && isSimpleIdentifier(rawExp)) { - const isScopeVarReference = context.identifiers[rawExp]; - const isAllowedGlobal = shared.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 = parser.parseExpression(source, { - sourceType: "module", - plugins: context.expressionPlugins - }); - } catch (e) { - context.onError( - createCompilerError( - 46, - node.loc, - void 0, - e.message - ) - ); - return node; - } - } - const ids = []; - const parentStack = []; - const knownIds = Object.create(context.identifiers); - walkIdentifiers( - ast, - (node2, parent, _, isReferenced2, isLocal) => { - if (isStaticPropertyKey(node2, parent)) { - return; - } - if (node2.name.startsWith("_filter_")) { - return; - } - const needPrefix = isReferenced2 && 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) && (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "MemberExpression")) { - 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 = 3; - } - ret.identifiers = Object.keys(knownIds); - return ret; - } - function canPrefix(id) { - if (shared.isGloballyAllowed(id.name)) { - return false; - } - if (id.name === "require") { - return false; - } - return true; - } - function stringifyExpression(exp) { - if (shared.isString(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"; - } - var 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: cloneLoc(node.loc), - branches: [branch] - }; - context.replaceNode(ifNode); - if (processCodegen) { - return processCodegen(ifNode, branch, true); - } - } else { - const siblings = context.parent.children; - let i = siblings.indexOf(node); - while (i-- >= -1) { - const sibling = siblings[i]; - if (sibling && isCommentOrWhitespace(sibling)) { - context.removeNode(sibling); - continue; - } - if (sibling && sibling.type === 9) { - if ((dir.name === "else-if" || dir.name === "else") && sibling.branches[sibling.branches.length - 1].condition === void 0) { - context.onError( - createCompilerError(30, node.loc) - ); - } - context.removeNode(); - const branch = createIfBranch(node, dir); - { - 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), [ - '""', - "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; - return createVNodeCall( - context, - helper(FRAGMENT), - createObjectExpression([keyProperty]), - children, - patchFlag, - 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; - } - } - } - var 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`, false, true); - const isDirKey = keyProp && keyProp.type === 7; - let keyExp = keyProp && (keyProp.type === 6 ? keyProp.value ? createSimpleExpression(keyProp.value.content, true) : void 0 : keyProp.exp); - const keyProperty = keyExp ? createObjectProperty(`key`, keyExp) : null; - { - if (isTemplate && memo) { - memo.exp = processExpression( - memo.exp, - context - ); - } - if ((isTemplate || memo) && keyProperty && isDirKey) { - keyExp = keyProp.exp = keyProperty.value = processExpression( - keyProperty.value, - context - ); - if (memo) { - context.vForMemoKeyedNodes.add(node); - } - } - } - 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, - void 0, - void 0, - true, - !isStableFragment, - false, - node.loc - ); - return () => { - var _a; - 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, - void 0, - void 0, - true, - void 0, - false - ); - } else { - childBlock = children[0].codegenNode; - if (isTemplate && keyProperty) { - injectProp(childBlock, keyProperty, context); - } - const shouldUseBlock = !isStableFragment || childBlock.isBlockRequired === true; - if (childBlock.isBlock !== shouldUseBlock) { - if (childBlock.isBlock) { - removeHelper(OPEN_BLOCK); - removeHelper( - getVNodeBlockHelper(context.inSSR, childBlock.isComponent) - ); - } else { - removeHelper( - getVNodeHelper(context.inSSR, childBlock.isComponent) - ); - } - } - childBlock.isBlock = shouldUseBlock; - if (childBlock.isBlock) { - helper(OPEN_BLOCK); - helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent)); - } else { - helper(getVNodeHelper(context.inSSR, childBlock.isComponent)); - if (childBlock.needsPatch) { - childBlock.patchFlag = ((_a = childBlock.patchFlag) != null ? _a : 0) | 512; - } - } - } - if (memo) { - const loop = createFunctionExpression( - createForLoopParams(forNode.parseResult, [ - createSimpleExpression(`_cached`) - ]) - ); - loop.body = createBlockStatement([ - createCompoundExpression([`const _memo = (`, memo.exp, `)`]), - createCompoundExpression([ - `if (_cached && _cached.el`, - ...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.length)) - ); - context.cached.push(null); - } 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)); - } - var defaultFallback = createSimpleExpression(`undefined`, false); - var 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--; - }; - } - } - }; - var 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); - }; - } - } - }; - var 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 = node.props.some( - (prop) => isVSlot(prop) && (hasScopeRef(prop.arg, context.identifiers) || hasScopeRef(prop.exp, context.identifiers)) - ) || children.some((child) => hasScopeRef(child, 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 (!isCommentOrWhitespace(prev)) { - break; - } - } - if (prev && isTemplateNode(prev) && findDir(prev, /^(?:else-)?if$/)) { - 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); - if (context.compatConfig) { - fn.isNonScopedSlot = true; - } - 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.every(isWhitespaceText)) { - 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 + ``, - 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; - } - var directiveImportMap = /* @__PURE__ */ new WeakMap(); - var 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 isComponent2 = node.tagType === 1; - let vnodeTag = isComponent2 ? resolveComponentType(node, context) : `"${tag}"`; - const isDynamicComponent = shared.isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT; - let vnodeProps; - let vnodeChildren; - let patchFlag = 0; - let vnodeDynamicProps; - let dynamicPropNames; - let vnodeDirectives; - let needsPatch = false; - let isBlockRequired = false; - let shouldUseBlock = ( - // dynamic component may resolve to plain elements - isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent2 && // <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" || tag === "math") - ); - if (props.length > 0) { - const propsBuildResult = buildProps( - node, - context, - void 0, - isComponent2, - isDynamicComponent - ); - vnodeProps = propsBuildResult.props; - patchFlag = propsBuildResult.patchFlag; - dynamicPropNames = propsBuildResult.dynamicPropNames; - needsPatch = propsBuildResult.needsPatch; - isBlockRequired = propsBuildResult.isBlockRequired; - 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; - } - const shouldBuildAsSlots = isComponent2 && // 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 (dynamicPropNames && dynamicPropNames.length) { - vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames); - } - const vnodeCall = node.codegenNode = createVNodeCall( - context, - vnodeTag, - vnodeProps, - vnodeChildren, - patchFlag === 0 ? void 0 : patchFlag, - vnodeDynamicProps, - vnodeDirectives, - !!shouldUseBlock, - false, - isComponent2, - node.loc - ); - needsPatch = needsPatch && (patchFlag === 0 || patchFlag === 32); - if (needsPatch) { - vnodeCall.needsPatch = true; - } - if (isBlockRequired) { - vnodeCall.isBlockRequired = true; - } - }; - }; - function resolveComponentType(node, context, ssr = false) { - let { tag } = node; - const isExplicitDynamic = isComponentTag(tag); - const isProp = findProp( - node, - "is", - false, - true - /* allow empty */ - ); - if (isProp) { - if (isExplicitDynamic || isCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - context - )) { - let exp; - if (isProp.type === 6) { - exp = isProp.value && createSimpleExpression(isProp.value.content, true); - } else { - exp = isProp.exp; - if (!exp) { - exp = createSimpleExpression(`is`, false, isProp.arg.loc); - { - exp = isProp.exp = processExpression(exp, context); - } - } - } - 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 && shared.capitalize(shared.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 = shared.camelize(name); - const PascalName = shared.capitalize(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, isComponent2, isDynamicComponent, ssr = false) { - const { tag, loc: elementLoc, children } = node; - let properties = []; - const mergeArgs = []; - const runtimeDirectives = []; - const hasChildren = children.length > 0; - let shouldUseBlock = false; - let isBlockRequired = 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 pushRefVForMarker = () => { - if (context.scopes.vFor > 0) { - properties.push( - createObjectProperty( - createSimpleExpression("ref_for", true), - createSimpleExpression("true") - ) - ); - } - }; - const analyzePatchFlag = ({ key, value }) => { - if (isStaticExp(key)) { - const name = key.content; - const isEventHandler = shared.isOn(name); - if (isEventHandler && (!isComponent2 || 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 - !shared.isReservedProp(name)) { - hasHydrationEventBinding = true; - } - if (isEventHandler && shared.isReservedProp(name)) { - hasVnodeHook = true; - } - if (name === "ref") { - hasRef = 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 === "class") { - hasClassBinding = true; - } else if (name === "style") { - hasStyleBinding = true; - } else if (name !== "ref" && name !== "key" && !dynamicPropNames.includes(name)) { - dynamicPropNames.push(name); - } - if (isComponent2 && (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; - pushRefVForMarker(); - 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:") || isCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - context - ))) { - 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 (!isComponent2) { - context.onError( - createCompilerError(40, loc) - ); - } - continue; - } - if (name === "once" || name === "memo") { - continue; - } - if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag) || isCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - context - ))) { - continue; - } - if (isVOn && ssr) { - continue; - } - if (isVBind && isStaticArgOf(arg, "key")) { - shouldUseBlock = true; - } - if (isVOn && hasChildren && arg && isStaticExp(arg) && shared.camelize(arg.content) === "vue:beforeUpdate") { - shouldUseBlock = true; - isBlockRequired = true; - } - if (isVBind && isStaticArgOf(arg, "ref")) { - pushRefVForMarker(); - } - if (!arg && (isVBind || isVOn)) { - hasDynamicKeys = true; - if (exp) { - if (isVBind) { - { - pushMergeArg(); - if (isCompatEnabled( - "COMPILER_V_BIND_OBJECT_ORDER", - context - )) { - mergeArgs.unshift(exp); - continue; - } - } - pushRefVForMarker(); - pushMergeArg(); - mergeArgs.push(exp); - } else { - pushMergeArg({ - type: 14, - loc, - callee: context.helper(TO_HANDLERS), - arguments: isComponent2 ? [exp] : [exp, `true`] - }); - } - } else { - context.onError( - createCompilerError( - isVBind ? 34 : 35, - loc - ) - ); - } - continue; - } - if (isVBind && modifiers.some((mod) => mod.content === "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 (shared.isSymbol(needRuntime)) { - directiveImportMap.set(prop, needRuntime); - } - } - } else if (!shared.isBuiltInDirective(name)) { - runtimeDirectives.push(prop); - if (hasChildren) { - shouldUseBlock = true; - isBlockRequired = 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 && !isComponent2) { - patchFlag |= 2; - } - if (hasStyleBinding && !isComponent2) { - patchFlag |= 4; - } - if (dynamicPropNames.length) { - patchFlag |= 8; - } - if (hasHydrationEventBinding) { - patchFlag |= 32; - } - } - const needsPatch = (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0); - if (!shouldUseBlock && needsPatch) { - 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, - needsPatch, - isBlockRequired - }; - } - 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" || shared.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"; - } - var 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 = shared.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 = shared.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 = shared.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 - }; - } - var transformOn = (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("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 - shared.toHandlerKey(shared.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, context); - const isInlineStatement = !(isMemberExp || isFnExpression(exp, context)); - 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; - }; - var 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 (arg.type !== 4) { - arg.children.unshift(`(`); - arg.children.push(`) || ""`); - } else if (!arg.isStatic) { - arg.content = arg.content ? `${arg.content} || ""` : `""`; - } - if (modifiers.some((mod) => mod.content === "camel")) { - if (arg.type === 4) { - if (arg.isStatic) { - arg.content = shared.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.some((mod) => mod.content === "prop")) { - injectPrefix(arg, "."); - } - if (modifiers.some((mod) => mod.content === "attr")) { - injectPrefix(arg, "^"); - } - } - return { - props: [createObjectProperty(arg, exp)] - }; - }; - var 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(`)`); - } - }; - var 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. - !(node.tag === "template"))) { - 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` - ); - } - children[i] = { - type: 12, - content: child, - loc: child.loc, - codegenNode: createCallExpression( - context.helper(CREATE_TEXT), - callArgs - ) - }; - } - } - }; - } - }; - var seen$1 = /* @__PURE__ */ new WeakSet(); - var 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, - true - ); - } - }; - } - }; - var transformModel = (dir, node, context) => { - const { exp, arg } = dir; - if (!exp) { - context.onError( - createCompilerError(41, dir.loc) - ); - return createTransformProps(); - } - const rawExp = exp.loc.source.trim(); - 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(); - } - if (bindingType === "literal-const" || bindingType === "setup-const") { - context.onError(createCompilerError(45, exp.loc)); - return createTransformProps(); - } - const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref"); - if (!expString.trim() || !isMemberExpression(exp, 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:${shared.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) => m.content).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 }; - } - var validDivisionCharRE = /[\w).+\-_$\]]/; - var transformFilter = (node, context) => { - if (!isCompatEnabled("COMPILER_FILTERS", context)) { - return; - } - if (node.type === 5) { - rewriteFilter(node.content, context); - } else if (node.type === 1) { - node.props.forEach((prop) => { - if (prop.type === 7 && prop.name !== "for" && prop.exp) { - rewriteFilter(prop.exp, context); - } - }); - } - }; - function rewriteFilter(node, context) { - if (node.type === 4) { - parseFilter(node, context); - } else { - for (let i = 0; i < node.children.length; i++) { - const child = node.children[i]; - if (typeof child !== "object") continue; - if (child.type === 4) { - parseFilter(child, context); - } else if (child.type === 8) { - rewriteFilter(child, context); - } else if (child.type === 5) { - rewriteFilter(child.content, context); - } - } - } - } - function parseFilter(node, context) { - const exp = node.content; - let inSingle = false; - let inDouble = false; - let inTemplateString = false; - let inRegex = false; - let curly = 0; - let square = 0; - let paren = 0; - let lastFilterIndex = 0; - let c, prev, i, expression, filters = []; - for (i = 0; i < exp.length; i++) { - prev = c; - c = exp.charCodeAt(i); - if (inSingle) { - if (c === 39 && prev !== 92) inSingle = false; - } else if (inDouble) { - if (c === 34 && prev !== 92) inDouble = false; - } else if (inTemplateString) { - if (c === 96 && prev !== 92) inTemplateString = false; - } else if (inRegex) { - if (c === 47 && prev !== 92) inRegex = false; - } else if (c === 124 && // pipe - exp.charCodeAt(i + 1) !== 124 && exp.charCodeAt(i - 1) !== 124 && !curly && !square && !paren) { - if (expression === void 0) { - lastFilterIndex = i + 1; - expression = exp.slice(0, i).trim(); - } else { - pushFilter(); - } - } else { - switch (c) { - case 34: - inDouble = true; - break; - case 39: - inSingle = true; - break; - case 96: - inTemplateString = true; - break; - case 40: - paren++; - break; - case 41: - paren--; - break; - case 91: - square++; - break; - case 93: - square--; - break; - case 123: - curly++; - break; - case 125: - curly--; - break; - } - if (c === 47) { - let j = i - 1; - let p; - for (; j >= 0; j--) { - p = exp.charAt(j); - if (p !== " ") break; - } - if (!p || !validDivisionCharRE.test(p)) { - inRegex = true; - } - } - } - } - if (expression === void 0) { - expression = exp.slice(0, i).trim(); - } else if (lastFilterIndex !== 0) { - pushFilter(); - } - function pushFilter() { - filters.push(exp.slice(lastFilterIndex, i).trim()); - lastFilterIndex = i + 1; - } - if (filters.length) { - for (i = 0; i < filters.length; i++) { - expression = wrapFilter(expression, filters[i], context); - } - node.content = expression; - node.ast = void 0; - } - } - function wrapFilter(exp, filter, context) { - context.helper(RESOLVE_FILTER); - const i = filter.indexOf("("); - if (i < 0) { - context.filters.add(filter); - return `${toValidAssetId(filter, "filter")}(${exp})`; - } else { - const name = filter.slice(0, i); - const args = filter.slice(i + 1); - context.filters.add(name); - return `${toValidAssetId(name, "filter")}(${exp}${args !== ")" ? "," + args : args}`; - } - } - var seen = /* @__PURE__ */ new WeakSet(); - var transformMemo = (node, context) => { - if (node.type === 1) { - const dir = findDir(node, "memo"); - if (!dir || seen.has(node) || context.inSSR) { - 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.length) - ]); - context.cached.push(null); - } - }; - } - }; - var transformVBindShorthand = (node, context) => { - if (node.type === 1) { - for (const prop of node.props) { - if (prop.type === 7 && prop.name === "bind" && (!prop.exp || // #13930 :foo in in-DOM templates will be parsed into :foo="" by browser - false) && prop.arg) { - const arg = prop.arg; - if (arg.type !== 4 || !arg.isStatic) { - context.onError( - createCompilerError( - 53, - arg.loc - ) - ); - prop.exp = createSimpleExpression("", true, arg.loc); - } else { - const propName = shared.camelize(arg.content); - if (validFirstIdentCharRE.test(propName[0]) || // allow hyphen first char for https://github.com/vuejs/language-tools/pull/3424 - propName[0] === "-") { - prop.exp = createSimpleExpression(propName, false, arg.loc); - } - } - } - } - } - }; - function getBaseTransformPreset(prefixIdentifiers) { - return [ - [ - transformVBindShorthand, - transformOnce, - transformIf, - transformMemo, - transformFor, - ...[transformFilter], - ...prefixIdentifiers ? [ - // order is important - trackVForSlotScopes, - transformExpression - ] : [], - transformSlotOutlet, - transformElement, - trackSlotScopes, - transformText - ], - { - on: transformOn, - bind: transformBind, - model: transformModel - } - ]; - } - 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(50)); - } - if (options.scopeId && !isModuleMode) { - onError(createCompilerError(51)); - } - const resolvedOptions = shared.extend({}, options, { - prefixIdentifiers - }); - const ast = shared.isString(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, - shared.extend({}, resolvedOptions, { - nodeTransforms: [ - ...nodeTransforms, - ...options.nodeTransforms || [] - // user transforms - ], - directiveTransforms: shared.extend( - {}, - directiveTransforms, - options.directiveTransforms || {} - // user transforms - ) - }) - ); - return generate(ast, resolvedOptions); - } - var 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" - }; - var noopDirectiveTransform = () => ({ props: [] }); - exports2.generateCodeFrame = shared.generateCodeFrame; - exports2.BASE_TRANSITION = BASE_TRANSITION; - exports2.BindingTypes = BindingTypes; - exports2.CAMELIZE = CAMELIZE; - exports2.CAPITALIZE = CAPITALIZE; - exports2.CREATE_BLOCK = CREATE_BLOCK; - exports2.CREATE_COMMENT = CREATE_COMMENT; - exports2.CREATE_ELEMENT_BLOCK = CREATE_ELEMENT_BLOCK; - exports2.CREATE_ELEMENT_VNODE = CREATE_ELEMENT_VNODE; - exports2.CREATE_SLOTS = CREATE_SLOTS; - exports2.CREATE_STATIC = CREATE_STATIC; - exports2.CREATE_TEXT = CREATE_TEXT; - exports2.CREATE_VNODE = CREATE_VNODE; - exports2.CompilerDeprecationTypes = CompilerDeprecationTypes; - exports2.ConstantTypes = ConstantTypes; - exports2.ElementTypes = ElementTypes; - exports2.ErrorCodes = ErrorCodes; - exports2.FRAGMENT = FRAGMENT; - exports2.GUARD_REACTIVE_PROPS = GUARD_REACTIVE_PROPS; - exports2.IS_MEMO_SAME = IS_MEMO_SAME; - exports2.IS_REF = IS_REF; - exports2.KEEP_ALIVE = KEEP_ALIVE; - exports2.MERGE_PROPS = MERGE_PROPS; - exports2.NORMALIZE_CLASS = NORMALIZE_CLASS; - exports2.NORMALIZE_PROPS = NORMALIZE_PROPS; - exports2.NORMALIZE_STYLE = NORMALIZE_STYLE; - exports2.Namespaces = Namespaces; - exports2.NodeTypes = NodeTypes; - exports2.OPEN_BLOCK = OPEN_BLOCK; - exports2.POP_SCOPE_ID = POP_SCOPE_ID; - exports2.PUSH_SCOPE_ID = PUSH_SCOPE_ID; - exports2.RENDER_LIST = RENDER_LIST; - exports2.RENDER_SLOT = RENDER_SLOT; - exports2.RESOLVE_COMPONENT = RESOLVE_COMPONENT; - exports2.RESOLVE_DIRECTIVE = RESOLVE_DIRECTIVE; - exports2.RESOLVE_DYNAMIC_COMPONENT = RESOLVE_DYNAMIC_COMPONENT; - exports2.RESOLVE_FILTER = RESOLVE_FILTER; - exports2.SET_BLOCK_TRACKING = SET_BLOCK_TRACKING; - exports2.SUSPENSE = SUSPENSE; - exports2.TELEPORT = TELEPORT; - exports2.TO_DISPLAY_STRING = TO_DISPLAY_STRING; - exports2.TO_HANDLERS = TO_HANDLERS; - exports2.TO_HANDLER_KEY = TO_HANDLER_KEY; - exports2.TS_NODE_TYPES = TS_NODE_TYPES; - exports2.UNREF = UNREF; - exports2.WITH_CTX = WITH_CTX; - exports2.WITH_DIRECTIVES = WITH_DIRECTIVES; - exports2.WITH_MEMO = WITH_MEMO; - exports2.advancePositionWithClone = advancePositionWithClone; - exports2.advancePositionWithMutation = advancePositionWithMutation; - exports2.assert = assert; - exports2.baseCompile = baseCompile; - exports2.baseParse = baseParse; - exports2.buildDirectiveArgs = buildDirectiveArgs; - exports2.buildProps = buildProps; - exports2.buildSlots = buildSlots; - exports2.checkCompatEnabled = checkCompatEnabled; - exports2.convertToBlock = convertToBlock; - exports2.createArrayExpression = createArrayExpression; - exports2.createAssignmentExpression = createAssignmentExpression; - exports2.createBlockStatement = createBlockStatement; - exports2.createCacheExpression = createCacheExpression; - exports2.createCallExpression = createCallExpression; - exports2.createCompilerError = createCompilerError; - exports2.createCompoundExpression = createCompoundExpression; - exports2.createConditionalExpression = createConditionalExpression; - exports2.createForLoopParams = createForLoopParams; - exports2.createFunctionExpression = createFunctionExpression; - exports2.createIfStatement = createIfStatement; - exports2.createInterpolation = createInterpolation; - exports2.createObjectExpression = createObjectExpression; - exports2.createObjectProperty = createObjectProperty; - exports2.createReturnStatement = createReturnStatement; - exports2.createRoot = createRoot; - exports2.createSequenceExpression = createSequenceExpression; - exports2.createSimpleExpression = createSimpleExpression; - exports2.createStructuralDirectiveTransform = createStructuralDirectiveTransform; - exports2.createTemplateLiteral = createTemplateLiteral; - exports2.createTransformContext = createTransformContext; - exports2.createVNodeCall = createVNodeCall; - exports2.errorMessages = errorMessages; - exports2.extractIdentifiers = extractIdentifiers; - exports2.findDir = findDir; - exports2.findProp = findProp; - exports2.forAliasRE = forAliasRE; - exports2.generate = generate; - exports2.getBaseTransformPreset = getBaseTransformPreset; - exports2.getConstantType = getConstantType; - exports2.getMemoedVNodeCall = getMemoedVNodeCall; - exports2.getVNodeBlockHelper = getVNodeBlockHelper; - exports2.getVNodeHelper = getVNodeHelper; - exports2.hasDynamicKeyVBind = hasDynamicKeyVBind; - exports2.hasScopeRef = hasScopeRef; - exports2.helperNameMap = helperNameMap; - exports2.injectProp = injectProp; - exports2.isAllWhitespace = isAllWhitespace; - exports2.isCommentOrWhitespace = isCommentOrWhitespace; - exports2.isCoreComponent = isCoreComponent; - exports2.isFnExpression = isFnExpression; - exports2.isFnExpressionBrowser = isFnExpressionBrowser; - exports2.isFnExpressionNode = isFnExpressionNode; - exports2.isFunctionType = isFunctionType; - exports2.isInDestructureAssignment = isInDestructureAssignment; - exports2.isInNewExpression = isInNewExpression; - exports2.isMemberExpression = isMemberExpression; - exports2.isMemberExpressionBrowser = isMemberExpressionBrowser; - exports2.isMemberExpressionNode = isMemberExpressionNode; - exports2.isReferencedIdentifier = isReferencedIdentifier; - exports2.isSimpleIdentifier = isSimpleIdentifier; - exports2.isSlotOutlet = isSlotOutlet; - exports2.isStaticArgOf = isStaticArgOf; - exports2.isStaticExp = isStaticExp; - exports2.isStaticProperty = isStaticProperty; - exports2.isStaticPropertyKey = isStaticPropertyKey; - exports2.isTemplateNode = isTemplateNode; - exports2.isText = isText$1; - exports2.isVPre = isVPre; - exports2.isVSlot = isVSlot; - exports2.isWhitespaceText = isWhitespaceText; - exports2.locStub = locStub; - exports2.noopDirectiveTransform = noopDirectiveTransform; - exports2.processExpression = processExpression; - exports2.processFor = processFor; - exports2.processIf = processIf; - exports2.processSlotOutlet = processSlotOutlet; - exports2.registerRuntimeHelpers = registerRuntimeHelpers; - exports2.resolveComponentType = resolveComponentType; - exports2.stringifyExpression = stringifyExpression; - exports2.toValidAssetId = toValidAssetId; - exports2.trackSlotScopes = trackSlotScopes; - exports2.trackVForSlotScopes = trackVForSlotScopes; - exports2.transform = transform; - exports2.transformBind = transformBind; - exports2.transformElement = transformElement; - exports2.transformExpression = transformExpression; - exports2.transformModel = transformModel; - exports2.transformOn = transformOn; - exports2.transformVBindShorthand = transformVBindShorthand; - exports2.traverseNode = traverseNode; - exports2.unwrapTSNode = unwrapTSNode; - exports2.validFirstIdentCharRE = validFirstIdentCharRE; - exports2.walkBlockDeclarations = walkBlockDeclarations; - exports2.walkFunctionParams = walkFunctionParams; - exports2.walkIdentifiers = walkIdentifiers; - exports2.warnDeprecation = warnDeprecation; - } -}); - -// intern-log/node_modules/.pnpm/@vue+compiler-core@3.5.44/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js -var require_compiler_core_cjs = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+compiler-core@3.5.44/node_modules/@vue/compiler-core/dist/compiler-core.cjs.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var shared = require_shared(); - var decode = require_decode(); - var parser = require_lib(); - var estreeWalker = require_estree_walker(); - var sourceMapJs = require_source_map(); - var FRAGMENT = /* @__PURE__ */ Symbol(`Fragment`); - var TELEPORT = /* @__PURE__ */ Symbol(`Teleport`); - var SUSPENSE = /* @__PURE__ */ Symbol(`Suspense`); - var KEEP_ALIVE = /* @__PURE__ */ Symbol(`KeepAlive`); - var BASE_TRANSITION = /* @__PURE__ */ Symbol( - `BaseTransition` - ); - var OPEN_BLOCK = /* @__PURE__ */ Symbol(`openBlock`); - var CREATE_BLOCK = /* @__PURE__ */ Symbol(`createBlock`); - var CREATE_ELEMENT_BLOCK = /* @__PURE__ */ Symbol( - `createElementBlock` - ); - var CREATE_VNODE = /* @__PURE__ */ Symbol(`createVNode`); - var CREATE_ELEMENT_VNODE = /* @__PURE__ */ Symbol( - `createElementVNode` - ); - var CREATE_COMMENT = /* @__PURE__ */ Symbol( - `createCommentVNode` - ); - var CREATE_TEXT = /* @__PURE__ */ Symbol( - `createTextVNode` - ); - var CREATE_STATIC = /* @__PURE__ */ Symbol( - `createStaticVNode` - ); - var RESOLVE_COMPONENT = /* @__PURE__ */ Symbol( - `resolveComponent` - ); - var RESOLVE_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol( - `resolveDynamicComponent` - ); - var RESOLVE_DIRECTIVE = /* @__PURE__ */ Symbol( - `resolveDirective` - ); - var RESOLVE_FILTER = /* @__PURE__ */ Symbol( - `resolveFilter` - ); - var WITH_DIRECTIVES = /* @__PURE__ */ Symbol( - `withDirectives` - ); - var RENDER_LIST = /* @__PURE__ */ Symbol(`renderList`); - var RENDER_SLOT = /* @__PURE__ */ Symbol(`renderSlot`); - var CREATE_SLOTS = /* @__PURE__ */ Symbol(`createSlots`); - var TO_DISPLAY_STRING = /* @__PURE__ */ Symbol( - `toDisplayString` - ); - var MERGE_PROPS = /* @__PURE__ */ Symbol(`mergeProps`); - var NORMALIZE_CLASS = /* @__PURE__ */ Symbol( - `normalizeClass` - ); - var NORMALIZE_STYLE = /* @__PURE__ */ Symbol( - `normalizeStyle` - ); - var NORMALIZE_PROPS = /* @__PURE__ */ Symbol( - `normalizeProps` - ); - var GUARD_REACTIVE_PROPS = /* @__PURE__ */ Symbol( - `guardReactiveProps` - ); - var TO_HANDLERS = /* @__PURE__ */ Symbol(`toHandlers`); - var CAMELIZE = /* @__PURE__ */ Symbol(`camelize`); - var CAPITALIZE = /* @__PURE__ */ Symbol(`capitalize`); - var TO_HANDLER_KEY = /* @__PURE__ */ Symbol( - `toHandlerKey` - ); - var SET_BLOCK_TRACKING = /* @__PURE__ */ Symbol( - `setBlockTracking` - ); - var PUSH_SCOPE_ID = /* @__PURE__ */ Symbol(`pushScopeId`); - var POP_SCOPE_ID = /* @__PURE__ */ Symbol(`popScopeId`); - var WITH_CTX = /* @__PURE__ */ Symbol(`withCtx`); - var UNREF = /* @__PURE__ */ Symbol(`unref`); - var IS_REF = /* @__PURE__ */ Symbol(`isRef`); - var WITH_MEMO = /* @__PURE__ */ Symbol(`withMemo`); - var IS_MEMO_SAME = /* @__PURE__ */ Symbol(`isMemoSame`); - var 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]; - }); - } - var Namespaces = { - "HTML": 0, - "0": "HTML", - "SVG": 1, - "1": "SVG", - "MATH_ML": 2, - "2": "MATH_ML" - }; - var 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" - }; - var ElementTypes = { - "ELEMENT": 0, - "0": "ELEMENT", - "COMPONENT": 1, - "1": "COMPONENT", - "SLOT": 2, - "2": "SLOT", - "TEMPLATE": 3, - "3": "TEMPLATE" - }; - var ConstantTypes = { - "NOT_CONSTANT": 0, - "0": "NOT_CONSTANT", - "CAN_SKIP_PATCH": 1, - "1": "CAN_SKIP_PATCH", - "CAN_CACHE": 2, - "2": "CAN_CACHE", - "CAN_STRINGIFY": 3, - "3": "CAN_STRINGIFY" - }; - var 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: [], - temps: 0, - codegenNode: void 0, - loc: locStub - }; - } - function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent2 = false, loc = locStub) { - if (context) { - if (isBlock) { - context.helper(OPEN_BLOCK); - context.helper(getVNodeBlockHelper(context.inSSR, isComponent2)); - } else { - context.helper(getVNodeHelper(context.inSSR, isComponent2)); - } - if (directives) { - context.helper(WITH_DIRECTIVES); - } - } - return { - type: 13, - tag, - props, - children, - patchFlag, - dynamicProps, - directives, - isBlock, - disableTracking, - isComponent: isComponent2, - 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: shared.isString(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: shared.isString(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, needPauseTracking = false, inVOnce = false) { - return { - type: 20, - index, - value, - needPauseTracking, - inVOnce, - needArraySpread: false, - 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, isComponent2) { - return ssr || isComponent2 ? CREATE_VNODE : CREATE_ELEMENT_VNODE; - } - function getVNodeBlockHelper(ssr, isComponent2) { - return ssr || isComponent2 ? 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)); - } - } - var defaultDelimitersOpen = new Uint8Array([123, 123]); - var defaultDelimitersClose = new Uint8Array([125, 125]); - function isTagStartChar(c) { - return c >= 97 && c <= 122 || c >= 65 && c <= 90; - } - function isWhitespace(c) { - return c === 32 || c === 10 || c === 9 || c === 12 || c === 13; - } - function isEndOfTagSection(c) { - return c === 47 || c === 62 || isWhitespace(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; - } - var 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 - }; - var Tokenizer = class { - constructor(stack2, cbs) { - this.stack = stack2; - this.cbs = cbs; - this.state = 1; - this.buffer = ""; - this.sectionStart = 0; - this.index = 0; - this.entityStart = 0; - this.baseState = 1; - this.inRCDATA = false; - this.inXML = false; - this.inVPre = false; - this.newlines = []; - this.mode = 0; - this.delimiterOpen = defaultDelimitersOpen; - this.delimiterClose = defaultDelimitersClose; - this.delimiterIndex = -1; - this.currentSequence = void 0; - this.sequenceIndex = 0; - { - this.entityDecoder = new decode.EntityDecoder( - decode.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; - const length = this.newlines.length; - let j = -1; - if (length > 100) { - let l = -1; - let r = length; - while (l + 1 < r) { - const m = l + r >>> 1; - this.newlines[m] < index ? l = m : r = m; - } - j = l; - } else { - for (let i = length - 1; i >= 0; i--) { - if (index > this.newlines[i]) { - j = i; - break; - } - } - } - if (j >= 0) { - line = j + 2; - column = index - this.newlines[j]; - } - 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(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 (!this.inVPre && 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(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(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(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(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(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(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(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 ? decode.DecodingMode.Legacy : decode.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.state !== 33) { - 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( - decode.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( - decode.fromCodePoint(cp), - this.entityStart, - this.sectionStart - ); - } - } - } - }; - var 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" - }; - var 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, messages2, additionalMessage) { - const msg = (messages2 || errorMessages)[code] + (additionalMessage || ``); - const error = new SyntaxError(String(msg)); - error.code = code; - error.loc = loc; - return error; - } - var 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_V_MODEL_ON_CONST": 45, - "45": "X_V_MODEL_ON_CONST", - "X_INVALID_EXPRESSION": 46, - "46": "X_INVALID_EXPRESSION", - "X_KEEP_ALIVE_INVALID_CHILDREN": 47, - "47": "X_KEEP_ALIVE_INVALID_CHILDREN", - "X_PREFIX_ID_NOT_SUPPORTED": 48, - "48": "X_PREFIX_ID_NOT_SUPPORTED", - "X_MODULE_MODE_NOT_SUPPORTED": 49, - "49": "X_MODULE_MODE_NOT_SUPPORTED", - "X_CACHE_HANDLER_NOT_SUPPORTED": 50, - "50": "X_CACHE_HANDLER_NOT_SUPPORTED", - "X_SCOPE_ID_NOT_SUPPORTED": 51, - "51": "X_SCOPE_ID_NOT_SUPPORTED", - "X_VNODE_HOOKS": 52, - "52": "X_VNODE_HOOKS", - "X_V_BIND_INVALID_SAME_NAME_ARGUMENT": 53, - "53": "X_V_BIND_INVALID_SAME_NAME_ARGUMENT", - "__EXTEND_POINT__": 54, - "54": "__EXTEND_POINT__" - }; - var errorMessages = { - // 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.`, - [53]: `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. -For props declared with defineModel(), assign the returned ref to a variable and use v-model on that variable.`, - [45]: `v-model cannot be used on a const binding because it is not writable.`, - [46]: `Error parsing JavaScript expression: `, - [47]: `<KeepAlive> expects exactly one child component.`, - [52]: `@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 - [48]: `"prefixIdentifiers" option is not supported in this build of compiler.`, - [49]: `ES module mode is not supported in this build of compiler.`, - [50]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`, - [51]: `"scopeId" option is only supported in module mode.`, - // just to fulfill types - [54]: `` - }; - 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; - estreeWalker.walk(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" && // eslint-disable-next-line no-restricted-syntax - (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) - ); - } - } else if (node.type === "SwitchStatement") { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - walkSwitchStatement( - node, - false, - (id) => markScopeIdentifier(node, id, knownIds) - ); - } - } else if (node.type === "CatchClause" && node.param) { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - for (const id of extractIdentifiers(node.param)) { - markScopeIdentifier(node, id, knownIds); - } - } - } else if (isForStatement(node)) { - if (node.scopeIds) { - node.scopeIds.forEach((id) => markKnownIds(id, knownIds)); - } else { - walkForStatement( - node, - false, - (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, parentStack[parentStack.length - 2])) { - return true; - } - switch (parent.type) { - case "AssignmentExpression": - case "AssignmentPattern": - return true; - case "ObjectProperty": - return parent.key !== id && isInDestructureAssignment(parent, parentStack); - 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(p)) { - onIdent(id); - } - } - } - function walkBlockDeclarations(block, onIdent) { - const body = block.type === "SwitchCase" ? block.consequent : block.body; - for (const stmt of body) { - if (stmt.type === "VariableDeclaration") { - if (stmt.declare) continue; - for (const decl of stmt.declarations) { - for (const id of extractIdentifiers(decl.id)) { - onIdent(id); - } - } - } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") { - if (stmt.declare || !stmt.id) continue; - onIdent(stmt.id); - } else if (isForStatement(stmt)) { - walkForStatement(stmt, true, onIdent); - } else if (stmt.type === "SwitchStatement") { - walkSwitchStatement(stmt, true, onIdent); - } - } - } - function isForStatement(stmt) { - return stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement"; - } - function walkForStatement(stmt, isVar, onIdent) { - const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left; - if (variable && variable.type === "VariableDeclaration" && (variable.kind === "var" ? isVar : !isVar)) { - for (const decl of variable.declarations) { - for (const id of extractIdentifiers(decl.id)) { - onIdent(id); - } - } - } - } - function walkSwitchStatement(stmt, isVar, onIdent) { - for (const cs of stmt.cases) { - for (const stmt2 of cs.consequent) { - if (stmt2.type === "VariableDeclaration" && (stmt2.kind === "var" ? isVar : !isVar)) { - for (const decl of stmt2.declarations) { - for (const id of extractIdentifiers(decl.id)) { - onIdent(id); - } - } - } - } - walkBlockDeclarations(cs, onIdent); - } - } - function extractIdentifiers(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(prop.argument, nodes); - } else { - extractIdentifiers(prop.value, nodes); - } - } - break; - case "ArrayPattern": - param.elements.forEach((element) => { - if (element) extractIdentifiers(element, nodes); - }); - break; - case "RestElement": - extractIdentifiers(param.argument, nodes); - break; - case "AssignmentPattern": - extractIdentifiers(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); - } - var isFunctionType = (node) => { - return /Function(?:Expression|Declaration)$|Method$/.test(node.type); - }; - var isStaticProperty = (node) => node && (node.type === "ObjectProperty" || node.type === "ObjectMethod") && !node.computed; - var 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; - } - var 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; - } - } - var 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; - } - } - var nonIdentifierRE = /^$|^\d|[^\$\w\xA0-\uFFFF]/; - var isSimpleIdentifier = (name) => !nonIdentifierRE.test(name); - var validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/; - var validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/; - var whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g; - var getExpSource = (exp) => exp.type === 4 ? exp.content : exp.loc.source; - var isMemberExpressionBrowser = (exp) => { - const path = getExpSource(exp).trim().replace(whitespaceRE, (s) => s.trim()); - let state = 0; - 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: - if (char === "[") { - stateStack.push(state); - state = 1; - currentOpenBracketCount++; - } else if (char === "(") { - stateStack.push(state); - state = 2; - currentOpenParensCount++; - } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) { - return false; - } - break; - case 1: - if (char === `'` || char === `"` || char === "`") { - stateStack.push(state); - state = 3; - currentStringType = char; - } else if (char === `[`) { - currentOpenBracketCount++; - } else if (char === `]`) { - if (!--currentOpenBracketCount) { - state = stateStack.pop(); - } - } - break; - case 2: - if (char === `'` || char === `"` || char === "`") { - stateStack.push(state); - state = 3; - currentStringType = char; - } else if (char === `(`) { - currentOpenParensCount++; - } else if (char === `)`) { - if (i === path.length - 1) { - return false; - } - if (!--currentOpenParensCount) { - state = stateStack.pop(); - } - } - break; - case 3: - if (char === currentStringType) { - state = stateStack.pop(); - currentStringType = null; - } - break; - } - } - return !currentOpenBracketCount && !currentOpenParensCount; - }; - var isMemberExpressionNode = (exp, context) => { - try { - let ret = exp.ast || parser.parseExpression(getExpSource(exp), { - plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"] - }); - ret = unwrapTSNode(ret); - return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier" && ret.name !== "undefined"; - } catch (e) { - return false; - } - }; - var isMemberExpression = isMemberExpressionNode; - var fnExpRE = /^\s*(?:async\s*)?(?:\([^)]*?\)|[\w$_]+)\s*(?::[^=]+)?=>|^\s*(?:async\s+)?function(?:\s+[\w$]+)?\s*\(/; - var isFnExpressionBrowser = (exp) => fnExpRE.test(getExpSource(exp)); - var isFnExpressionNode = (exp, context) => { - try { - let ret = exp.ast || parser.parseExpression(getExpSource(exp), { - plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"] - }); - if (ret.type === "Program") { - ret = ret.body[0]; - if (ret.type === "ExpressionStatement") { - ret = ret.expression; - } - } - ret = unwrapTSNode(ret); - return ret.type === "FunctionExpression" || ret.type === "ArrowFunctionExpression"; - } catch (e) { - return false; - } - }; - var isFnExpression = isFnExpressionNode; - 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) && (shared.isString(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 isVPre(p) { - return p.type === 7 && p.name === "pre"; - } - 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; - } - var propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]); - function getUnnormalizedProps(props, callPath = []) { - if (props && !shared.isString(props) && props.type === 14) { - const callee = props.callee; - if (!shared.isString(callee) && propsHelperSet.has(callee)) { - return getUnnormalizedProps( - props.arguments[0], - callPath.concat(props) - ); - } - } - return [props, callPath]; - } - function injectProp(node, prop, context) { - if (node.type !== 13 && injectSlotKey(node, prop)) { - return; - } - let propsWithInjection; - let props = node.type === 13 ? node.props : node.arguments[2]; - let callPath = []; - let parentCall; - if (props && !shared.isString(props) && props.type === 14) { - const ret = getUnnormalizedProps(props); - props = ret[0]; - callPath = ret[1]; - parentCall = callPath[callPath.length - 1]; - } - if (props == null || shared.isString(props)) { - propsWithInjection = createObjectExpression([prop]); - } else if (props.type === 14) { - const first = props.arguments[0]; - if (!shared.isString(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 injectSlotKey(node, prop) { - var _a, _b, _c; - if (prop.key.type !== 4 || prop.key.content !== "key") { - return false; - } - const props = node.arguments[2]; - if (props && !shared.isString(props)) { - const [unnormalizedProps] = getUnnormalizedProps(props); - if (unnormalizedProps && !shared.isString(unnormalizedProps) && unnormalizedProps.type === 15 && hasProp(prop, unnormalizedProps)) { - return true; - } - } - (_a = node.arguments)[2] || (_a[2] = "{}"); - (_b = node.arguments)[3] || (_b[3] = "undefined"); - (_c = node.arguments)[4] || (_c[4] = "undefined"); - node.arguments[5] = prop.value; - return true; - } - 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) => shared.isObject(c) && hasScopeRef(c, ids)); - case 5: - case 12: - return hasScopeRef(node.content, ids); - case 2: - case 3: - case 20: - return false; - default: - return false; - } - } - function getMemoedVNodeCall(node) { - if (node.type === 14 && node.callee === WITH_MEMO) { - return node.arguments[1].returns; - } else { - return node; - } - } - var forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/; - function isAllWhitespace(str) { - for (let i = 0; i < str.length; i++) { - if (!isWhitespace(str.charCodeAt(i))) { - return false; - } - } - return true; - } - function isWhitespaceText(node) { - return node.type === 2 && isAllWhitespace(node.content) || node.type === 12 && isWhitespaceText(node.content); - } - function isCommentOrWhitespace(node) { - return node.type === 3 || isWhitespaceText(node); - } - var defaultParserOptions = { - parseMode: "base", - ns: 0, - delimiters: [`{{`, `}}`], - getNamespace: () => 0, - isVoidTag: shared.NO, - isPreTag: shared.NO, - isIgnoreNewlineTag: shared.NO, - isCustomElement: shared.NO, - onError: defaultOnError, - onWarn: defaultOnWarn, - comments: true, - prefixIdentifiers: false - }; - var currentOptions = defaultParserOptions; - var currentRoot = null; - var currentInput = ""; - var currentOpenTag = null; - var currentProp = null; - var currentAttrValue = ""; - var currentAttrStartIndex = -1; - var currentAttrEndIndex = -1; - var inPre = 0; - var inVPre = false; - var currentVPreBoundary = null; - var stack = []; - var tokenizer = new Tokenizer(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.delimiterOpen.length; - let innerEnd = end - tokenizer.delimiterClose.length; - while (isWhitespace(currentInput.charCodeAt(innerStart))) { - innerStart++; - } - while (isWhitespace(currentInput.charCodeAt(innerEnd - 1))) { - innerEnd--; - } - let exp = getSlice(innerStart, innerEnd); - if (exp.includes("&")) { - { - exp = decode.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) { - const name = currentOpenTag.tag; - currentOpenTag.isSelfClosing = true; - endOpenTag(end); - if (stack[0] && stack[0].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 === "." ? [createSimpleExpression("prop")] : [], - loc: getLoc(start) - }; - if (name === "pre") { - inVPre = tokenizer.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 && !isVPre(currentProp)) { - 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 && !isVPre(currentProp)) { - 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 { - const exp = createSimpleExpression(mod, true, getLoc(start, end)); - currentProp.modifiers.push(exp); - } - }, - 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.inSFCRoot && currentOpenTag.tag === "template" && currentProp.name === "lang" && currentAttrValue && currentAttrValue !== "html") { - tokenizer.enterRCDATA(toCharCodes(`</template`), 0); - } - } else { - let expParseMode = 0; - { - if (currentProp.name === "for") { - expParseMode = 3; - } else if (currentProp.name === "slot") { - expParseMode = 1; - } else if (currentProp.name === "on" && currentAttrValue.includes(";")) { - expParseMode = 2; - } - } - currentProp.exp = createExp( - currentAttrValue, - false, - getLoc(currentAttrStartIndex, currentAttrEndIndex), - 0, - expParseMode - ); - if (currentProp.name === "for") { - currentProp.forParseResult = parseForExpression(currentProp.exp); - } - let syncIndex = -1; - if (currentProp.name === "bind" && (syncIndex = currentProp.modifiers.findIndex( - (mod) => mod.content === "sync" - )) > -1 && checkCompatEnabled( - "COMPILER_V_BIND_SYNC", - currentOptions, - currentProp.loc, - currentProp.arg.loc.source - )) { - currentProp.name = "model"; - currentProp.modifiers.splice(syncIndex, 1); - } - } - } - 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.state !== 1) { - switch (tokenizer.state) { - case 5: - case 8: - emitError(5, end); - break; - case 3: - case 4: - emitError( - 25, - tokenizer.sectionStart - ); - break; - case 28: - if (tokenizer.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] ? stack[0].ns : currentOptions.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 - ); - } - } - }); - var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; - var 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 : 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.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.inXML = true; - } - } - currentOpenTag = null; - } - function onText(content, start, end) { - const parent = stack[0] || currentRoot; - const lastNode = parent.children[parent.children.length - 1]; - if (lastNode && 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, lookAhead(end, 62) + 1); - } - if (tokenizer.inSFCRoot) { - if (el.children.length) { - el.innerLoc.end = shared.extend({}, el.children[el.children.length - 1].loc.end); - } else { - el.innerLoc.end = shared.extend({}, el.innerLoc.start); - } - el.innerLoc.source = getSlice( - el.innerLoc.start.offset, - el.innerLoc.end.offset - ); - } - const { tag, ns, children } = 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.inRCDATA) { - el.children = condenseWhitespace(children); - } - if (ns === 0 && currentOptions.isIgnoreNewlineTag(tag)) { - const first = children[0]; - if (first && first.type === 2) { - first.content = first.content.replace(/^\r?\n/, ""); - } - } - if (ns === 0 && currentOptions.isPreTag(tag)) { - inPre--; - } - if (currentVPreBoundary === el) { - inVPre = tokenizer.inVPre = false; - currentVPreBoundary = null; - } - if (tokenizer.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) { - tokenizer.inXML = false; - } - { - const props = el.props; - if (isCompatEnabled( - "COMPILER_V_IF_V_FOR_PRECEDENCE", - currentOptions - )) { - let hasIf = false; - let hasFor = false; - for (let i = 0; i < props.length; i++) { - const p = props[i]; - if (p.type === 7) { - if (p.name === "if") { - hasIf = true; - } else if (p.name === "for") { - hasFor = true; - } - } - if (hasIf && hasFor) { - warnDeprecation( - "COMPILER_V_IF_V_FOR_PRECEDENCE", - currentOptions, - el.loc - ); - break; - } - } - } - if (!tokenizer.inSFCRoot && isCompatEnabled( - "COMPILER_NATIVE_TEMPLATE", - currentOptions - ) && el.tag === "template" && !isFragmentTemplate(el)) { - warnDeprecation( - "COMPILER_NATIVE_TEMPLATE", - currentOptions, - el.loc - ); - const parent = stack[0] || currentRoot; - const index = parent.children.indexOf(el); - parent.children.splice(index, 1, ...el.children); - } - const inlineTemplateProp = props.find( - (p) => p.type === 6 && p.name === "inline-template" - ); - if (inlineTemplateProp && checkCompatEnabled( - "COMPILER_INLINE_TEMPLATE", - currentOptions, - inlineTemplateProp.loc - ) && el.children.length) { - inlineTemplateProp.value = { - type: 2, - content: getSlice( - el.children[0].loc.start.offset, - el.children[el.children.length - 1].loc.end.offset - ), - loc: inlineTemplateProp.loc - }; - } - } - } - function lookAhead(index, c) { - let i = index; - while (currentInput.charCodeAt(i) !== c && i < currentInput.length - 1) i++; - return i; - } - function backTrack(index, c) { - let i = index; - while (currentInput.charCodeAt(i) !== c && i >= 0) i--; - return i; - } - var 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 }) { - if (currentOptions.isCustomElement(tag)) { - return false; - } - if (tag === "component" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || currentOptions.isBuiltInComponent && currentOptions.isBuiltInComponent(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; - } else if (checkCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - currentOptions, - p.loc - )) { - return true; - } - } - } else if ( - // :is on plain element - only treat as component in compat mode - p.name === "bind" && isStaticArgOf(p.arg, "is") && checkCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - currentOptions, - p.loc - ) - ) { - return true; - } - } - return false; - } - function isUpperCase(c) { - return c > 64 && c < 91; - } - var windowsNewlineRE = /\r\n/g; - function condenseWhitespace(nodes) { - 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 = nodes[i - 1] && nodes[i - 1].type; - const next = nodes[i + 1] && nodes[i + 1].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"); - } - } - } - return removedWhitespace ? nodes.filter(Boolean) : nodes; - } - 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(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.getPos(start), - // @ts-expect-error allow late attachment - end: end == null ? end : tokenizer.getPos(end), - // @ts-expect-error allow late attachment - source: end == null ? end : getSlice(start, end) - }; - } - function cloneLoc(loc) { - return getLoc(loc.start.offset, loc.end.offset); - } - function setLocEnd(loc, end) { - loc.end = tokenizer.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) { - const exp = createSimpleExpression(content, isStatic, loc, constType); - if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 && 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) { - exp.ast = parser.parse(` ${content} `, options).program; - } else if (parseMode === 1) { - exp.ast = parser.parseExpression(`(${content})=>{}`, options); - } else { - exp.ast = parser.parseExpression(`(${content})`, options); - } - } catch (e) { - exp.ast = false; - emitError(46, 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.reset(); - currentOpenTag = null; - currentProp = null; - currentAttrValue = ""; - currentAttrStartIndex = -1; - currentAttrEndIndex = -1; - stack.length = 0; - } - function baseParse(input, options) { - reset(); - currentInput = input; - currentOptions = shared.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.mode = currentOptions.parseMode === "html" ? 1 : currentOptions.parseMode === "sfc" ? 2 : 0; - tokenizer.inXML = currentOptions.ns === 1 || currentOptions.ns === 2; - const delimiters = options && options.delimiters; - if (delimiters) { - tokenizer.delimiterOpen = toCharCodes(delimiters[0]); - tokenizer.delimiterClose = toCharCodes(delimiters[1]); - } - const root = currentRoot = createRoot([], input); - tokenizer.parse(currentInput); - root.loc = getLoc(0, input.length); - root.children = condenseWhitespace(root.children); - currentRoot = null; - return root; - } - function cacheStatic(root, context) { - walk( - root, - void 0, - context, - // Root node is unfortunately non-hoistable due to potential parent - // fallthrough attributes. - !!getSingleElementRoot(root) - ); - } - function getSingleElementRoot(root) { - const children = root.children.filter((x) => x.type !== 3); - return children.length === 1 && children[0].type === 1 && !isSlotOutlet(children[0]) ? children[0] : null; - } - function walk(node, parent, context, doNotHoistNode = false, inFor = false) { - const { children } = node; - const toCache = []; - 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; - toCache.push(child); - continue; - } - } else { - const codegenNode = child.codegenNode; - if (codegenNode.type === 13) { - const flag = codegenNode.patchFlag; - if ((flag === void 0 || 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); - } - } - } - } else if (child.type === 12) { - const constantType = doNotHoistNode ? 0 : getConstantType(child, context); - if (constantType >= 2) { - if (child.codegenNode.type === 14 && child.codegenNode.arguments.length > 0) { - child.codegenNode.arguments.push( - `-1 /* ${shared.PatchFlagNames[-1]} */` - ); - } - toCache.push(child); - continue; - } - } - if (child.type === 1) { - const isComponent2 = child.tagType === 1; - if (isComponent2) { - context.scopes.vSlot++; - } - walk(child, node, context, false, inFor); - if (isComponent2) { - context.scopes.vSlot--; - } - } else if (child.type === 11) { - walk(child, node, context, child.children.length === 1, true); - } else if (child.type === 9) { - for (let i2 = 0; i2 < child.branches.length; i2++) { - walk( - child.branches[i2], - node, - context, - child.branches[i2].children.length === 1, - inFor - ); - } - } - } - let cachedAsArray = false; - if (toCache.length === children.length && node.type === 1) { - if (node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && shared.isArray(node.codegenNode.children)) { - node.codegenNode.children = getCacheExpression( - createArrayExpression(node.codegenNode.children) - ); - cachedAsArray = true; - } else if (node.tagType === 1 && node.codegenNode && node.codegenNode.type === 13 && node.codegenNode.children && !shared.isArray(node.codegenNode.children) && node.codegenNode.children.type === 15) { - const slot = getSlotNode(node.codegenNode, "default"); - if (slot) { - slot.returns = getCacheExpression( - createArrayExpression(slot.returns) - ); - cachedAsArray = true; - } - } else if (node.tagType === 3 && parent && parent.type === 1 && parent.tagType === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 15) { - const slotName = findDir(node, "slot", true); - const slot = slotName && slotName.arg && getSlotNode(parent.codegenNode, slotName.arg); - if (slot) { - slot.returns = getCacheExpression( - createArrayExpression(slot.returns) - ); - cachedAsArray = true; - } - } - } - if (!cachedAsArray) { - for (const child of toCache) { - child.codegenNode = context.cache(child.codegenNode); - } - } - function getCacheExpression(value) { - const exp = context.cache(value); - exp.needArraySpread = true; - return exp; - } - function getSlotNode(node2, name) { - if (node2.children && !shared.isArray(node2.children) && node2.children.type === 15) { - const slot = node2.children.properties.find( - (p) => p.key === name || p.key.content === name - ); - return slot && slot.value; - } - } - if (toCache.length && context.transformHoist) { - context.transformHoist(children, context, node); - } - } - 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" && node.tag !== "math") { - return 0; - } - if (codegenNode.patchFlag === void 0) { - 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 (shared.isString(child) || shared.isSymbol(child)) { - continue; - } - const childType = getConstantType(child, context); - if (childType === 0) { - return 0; - } else if (childType < returnType) { - returnType = childType; - } - } - return returnType; - case 20: - return 2; - default: - return 0; - } - } - var allowHoistedHelperSet = /* @__PURE__ */ new Set([ - NORMALIZE_CLASS, - NORMALIZE_STYLE, - NORMALIZE_PROPS, - GUARD_REACTIVE_PROPS - ]); - function getConstantTypeOfHelperCall(value, context) { - if (value.type === 14 && !shared.isString(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 createTransformContext(root, { - filename = "", - prefixIdentifiers = false, - hoistStatic = false, - hmr = false, - cacheHandlers = false, - nodeTransforms = [], - directiveTransforms = {}, - transformHoist = null, - isBuiltInComponent = shared.NOOP, - isCustomElement = shared.NOOP, - expressionPlugins = [], - scopeId = null, - slotted = true, - ssr = false, - inSSR = false, - ssrCssVars = ``, - bindingMetadata = shared.EMPTY_OBJ, - inline = false, - isTS = false, - onError = defaultOnError, - onWarn = defaultOnWarn, - compatConfig - }) { - const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/); - const context = { - // options - filename, - selfName: nameMatch && shared.capitalize(shared.camelize(nameMatch[1])), - prefixIdentifiers, - hoistStatic, - 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: [], - cached: [], - constantCache: /* @__PURE__ */ new WeakMap(), - vForMemoKeyedNodes: /* @__PURE__ */ new WeakSet(), - temps: 0, - identifiers: /* @__PURE__ */ Object.create(null), - scopes: { - vFor: 0, - vSlot: 0, - vPre: 0, - vOnce: 0 - }, - parent: null, - grandParent: 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: shared.NOOP, - addIdentifiers(exp) { - { - if (shared.isString(exp)) { - addId(exp); - } else if (exp.identifiers) { - exp.identifiers.forEach(addId); - } else if (exp.type === 4) { - addId(exp.content); - } - } - }, - removeIdentifiers(exp) { - { - if (shared.isString(exp)) { - removeId(exp); - } else if (exp.identifiers) { - exp.identifiers.forEach(removeId); - } else if (exp.type === 4) { - removeId(exp.content); - } - } - }, - hoist(exp) { - if (shared.isString(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, inVOnce = false) { - const cacheExp = createCacheExpression( - context.cached.length, - exp, - isVNode, - inVOnce - ); - context.cached.push(cacheExp); - return cacheExp; - } - }; - { - context.filters = /* @__PURE__ */ new Set(); - } - 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) { - cacheStatic(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; - { - root.filters = [...context.filters]; - } - } - function createRootCodegen(root, context) { - const { helper } = context; - const { children } = root; - if (children.length === 1) { - const singleElementRootChild = getSingleElementRoot(root); - if (singleElementRootChild && singleElementRootChild.codegenNode) { - const codegenNode = singleElementRootChild.codegenNode; - if (codegenNode.type === 13) { - convertToBlock(codegenNode, context); - } - root.codegenNode = codegenNode; - } else { - root.codegenNode = children[0]; - } - } else if (children.length > 1) { - let patchFlag = 64; - if (children.filter((c) => c.type !== 3).length === 1) { - patchFlag |= 2048; - } - root.codegenNode = createVNodeCall( - context, - helper(FRAGMENT), - void 0, - root.children, - patchFlag, - 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 (shared.isString(child)) continue; - context.grandParent = context.parent; - 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 (shared.isArray(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 = shared.isString(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 PURE_ANNOTATION = `/*@__PURE__*/`; - var 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, 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; - } - } - if (node.loc.source) { - addMapping(node.loc.start, name); - } - } - if (newlineIndex === -3) { - advancePositionWithMutation(context, code); - } else { - context.offset += code.length; - if (newlineIndex === -2) { - context.column += code.length; - } else { - if (newlineIndex === -1) { - newlineIndex = code.length - 1; - } - context.line++; - context.column = code.length - newlineIndex; - } - } - if (node && node.loc !== locStub && node.loc.source) { - 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, - name - }); - } - if (sourceMap) { - context.map = new sourceMapJs.SourceMapGenerator(); - 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.filters && ast.filters.length) { - newline(); - genAssets(ast.filters, "filter", context); - 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 (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 === "filter" ? RESOLVE_FILTER : 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 } = context; - newline(); - for (let i = 0; i < hoists.length; i++) { - const exp = hoists[i]; - if (exp) { - push(`const _hoisted_${i + 1} = `); - genNode(exp, context); - 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 shared.isString(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) => shared.isArray(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 (shared.isString(node)) { - push( - node, - -3 - /* Unknown */ - ); - } else if (shared.isArray(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 (shared.isString(node)) { - context.push( - node, - -3 - /* Unknown */ - ); - return; - } - if (shared.isSymbol(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, node); - } - function genExpression(node, context) { - const { content, isStatic } = node; - context.push( - isStatic ? JSON.stringify(content) : content, - -3, - 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 (shared.isString(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, node); - } else { - push(`[${node.content}]`, -3, node); - } - } - function genComment(node, context) { - const { push, helper, pure } = context; - if (pure) { - push(PURE_ANNOTATION); - } - push( - `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, - -3, - node - ); - } - function genVNodeCall(node, context) { - const { push, helper, pure } = context; - const { - tag, - props, - children, - patchFlag, - dynamicProps, - directives, - isBlock, - disableTracking, - isComponent: isComponent2 - } = node; - let patchFlagString; - if (patchFlag) { - { - if (patchFlag < 0) { - patchFlagString = patchFlag + ` /* ${shared.PatchFlagNames[patchFlag]} */`; - } else { - const flagNames = Object.keys(shared.PatchFlagNames).map(Number).filter((n) => n > 0 && patchFlag & n).map((n) => shared.PatchFlagNames[n]).join(`, `); - patchFlagString = patchFlag + ` /* ${flagNames} */`; - } - } - } - 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, isComponent2) : getVNodeHelper(context.inSSR, isComponent2); - push(helper(callHelper) + `(`, -2, node); - genNodeList( - genNullableArgs([tag, props, children, patchFlagString, 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 = shared.isString(node.callee) ? node.callee : helper(node.callee); - if (pure) { - push(PURE_ANNOTATION); - } - push(callee + `(`, -2, node); - genNodeList(node.arguments, context); - push(`)`); - } - function genObjectExpression(node, context) { - const { push, indent, deindent, newline } = context; - const { properties } = node; - if (!properties.length) { - push(`{}`, -2, 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, node); - if (shared.isArray(params)) { - genNodeList(params, context); - } else if (params) { - genNode(params, context); - } - push(`) => `); - if (newline || body) { - push(`{`); - indent(); - } - if (returns) { - if (newline) { - push(`return `); - } - if (shared.isArray(returns)) { - genNodeListAsArray(returns, context); - } else { - genNode(returns, context); - } - } else if (body) { - genNode(body, context); - } - if (newline || body) { - deindent(); - push(`}`); - } - if (isSlot) { - if (node.isNonScopedSlot) { - push(`, undefined, true`); - } - 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; - const { needPauseTracking, needArraySpread } = node; - if (needArraySpread) { - push(`[...(`); - } - push(`_cache[${node.index}] || (`); - if (needPauseTracking) { - indent(); - push(`${helper(SET_BLOCK_TRACKING)}(-1`); - if (node.inVOnce) push(`, true`); - push(`),`); - newline(); - push(`(`); - } - push(`_cache[${node.index}] = `); - genNode(node.value, context); - if (needPauseTracking) { - push(`).cacheIndex = ${node.index},`); - newline(); - push(`${helper(SET_BLOCK_TRACKING)}(1),`); - newline(); - push(`_cache[${node.index}]`); - deindent(); - } - push(`)`); - if (needArraySpread) { - 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 (shared.isString(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 (shared.isArray(returns)) { - genNodeListAsArray(returns, context); - } else { - genNode(returns, context); - } - } - var isLiteralWhitelisted = /* @__PURE__ */ shared.makeMap("true,false,null,this"); - var transformExpression = (node, context) => { - if (node.type === 5) { - node.content = processExpression( - node.content, - context - ); - } else if (node.type === 1) { - const memo = findDir(node, "memo"); - 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) && // key has been processed in transformFor(vMemo + vFor) - !(memo && context.vForMemoKeyedNodes.has(node) && arg && arg.type === 4 && arg.content === "key")) { - 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 = shared.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 shared.genPropsAccessExp(raw); - } else if (type === "props-aliased") { - return shared.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; - let ast = node.ast; - if (ast === false) { - return node; - } - if (ast === null || !ast && isSimpleIdentifier(rawExp)) { - const isScopeVarReference = context.identifiers[rawExp]; - const isAllowedGlobal = shared.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 = parser.parseExpression(source, { - sourceType: "module", - plugins: context.expressionPlugins - }); - } catch (e) { - context.onError( - createCompilerError( - 46, - node.loc, - void 0, - e.message - ) - ); - return node; - } - } - const ids = []; - const parentStack = []; - const knownIds = Object.create(context.identifiers); - walkIdentifiers( - ast, - (node2, parent, _, isReferenced2, isLocal) => { - if (isStaticPropertyKey(node2, parent)) { - return; - } - if (node2.name.startsWith("_filter_")) { - return; - } - const needPrefix = isReferenced2 && 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) && (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "MemberExpression")) { - 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 = 3; - } - ret.identifiers = Object.keys(knownIds); - return ret; - } - function canPrefix(id) { - if (shared.isGloballyAllowed(id.name)) { - return false; - } - if (id.name === "require") { - return false; - } - return true; - } - function stringifyExpression(exp) { - if (shared.isString(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"; - } - var 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: cloneLoc(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 && isCommentOrWhitespace(sibling)) { - context.removeNode(sibling); - if (sibling.type === 3) { - comments.unshift(sibling); - } - continue; - } - if (sibling && sibling.type === 9) { - if ((dir.name === "else-if" || dir.name === "else") && 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; - if (!branch.isTemplateIf && children.filter((c) => c.type !== 3).length === 1) { - patchFlag |= 2048; - } - return createVNodeCall( - context, - helper(FRAGMENT), - createObjectExpression([keyProperty]), - children, - patchFlag, - 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; - } - } - } - var 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`, false, true); - const isDirKey = keyProp && keyProp.type === 7; - let keyExp = keyProp && (keyProp.type === 6 ? keyProp.value ? createSimpleExpression(keyProp.value.content, true) : void 0 : keyProp.exp); - const keyProperty = keyExp ? createObjectProperty(`key`, keyExp) : null; - { - if (isTemplate && memo) { - memo.exp = processExpression( - memo.exp, - context - ); - } - if ((isTemplate || memo) && keyProperty && isDirKey) { - keyExp = keyProp.exp = keyProperty.value = processExpression( - keyProperty.value, - context - ); - if (memo) { - context.vForMemoKeyedNodes.add(node); - } - } - } - 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, - void 0, - void 0, - true, - !isStableFragment, - false, - node.loc - ); - return () => { - var _a; - 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, - void 0, - void 0, - true, - void 0, - false - ); - } else { - childBlock = children[0].codegenNode; - if (isTemplate && keyProperty) { - injectProp(childBlock, keyProperty, context); - } - const shouldUseBlock = !isStableFragment || childBlock.isBlockRequired === true; - if (childBlock.isBlock !== shouldUseBlock) { - if (childBlock.isBlock) { - removeHelper(OPEN_BLOCK); - removeHelper( - getVNodeBlockHelper(context.inSSR, childBlock.isComponent) - ); - } else { - removeHelper( - getVNodeHelper(context.inSSR, childBlock.isComponent) - ); - } - } - childBlock.isBlock = shouldUseBlock; - if (childBlock.isBlock) { - helper(OPEN_BLOCK); - helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent)); - } else { - helper(getVNodeHelper(context.inSSR, childBlock.isComponent)); - if (childBlock.needsPatch) { - childBlock.patchFlag = ((_a = childBlock.patchFlag) != null ? _a : 0) | 512; - } - } - } - if (memo) { - const loop = createFunctionExpression( - createForLoopParams(forNode.parseResult, [ - createSimpleExpression(`_cached`) - ]) - ); - loop.body = createBlockStatement([ - createCompoundExpression([`const _memo = (`, memo.exp, `)`]), - createCompoundExpression([ - `if (_cached && _cached.el`, - ...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.length)) - ); - context.cached.push(null); - } 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)); - } - var defaultFallback = createSimpleExpression(`undefined`, false); - var 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--; - }; - } - } - }; - var 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); - }; - } - } - }; - var 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 = node.props.some( - (prop) => isVSlot(prop) && (hasScopeRef(prop.arg, context.identifiers) || hasScopeRef(prop.exp, context.identifiers)) - ) || children.some((child) => hasScopeRef(child, 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 (!isCommentOrWhitespace(prev)) { - break; - } - } - if (prev && isTemplateNode(prev) && findDir(prev, /^(?:else-)?if$/)) { - 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); - if (context.compatConfig) { - fn.isNonScopedSlot = true; - } - 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.every(isWhitespaceText)) { - 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 + ` /* ${shared.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; - } - var directiveImportMap = /* @__PURE__ */ new WeakMap(); - var 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 isComponent2 = node.tagType === 1; - let vnodeTag = isComponent2 ? resolveComponentType(node, context) : `"${tag}"`; - const isDynamicComponent = shared.isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT; - let vnodeProps; - let vnodeChildren; - let patchFlag = 0; - let vnodeDynamicProps; - let dynamicPropNames; - let vnodeDirectives; - let needsPatch = false; - let isBlockRequired = false; - let shouldUseBlock = ( - // dynamic component may resolve to plain elements - isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent2 && // <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" || tag === "math") - ); - if (props.length > 0) { - const propsBuildResult = buildProps( - node, - context, - void 0, - isComponent2, - isDynamicComponent - ); - vnodeProps = propsBuildResult.props; - patchFlag = propsBuildResult.patchFlag; - dynamicPropNames = propsBuildResult.dynamicPropNames; - needsPatch = propsBuildResult.needsPatch; - isBlockRequired = propsBuildResult.isBlockRequired; - 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(47, { - start: node.children[0].loc.start, - end: node.children[node.children.length - 1].loc.end, - source: "" - }) - ); - } - } - const shouldBuildAsSlots = isComponent2 && // 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 (dynamicPropNames && dynamicPropNames.length) { - vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames); - } - const vnodeCall = node.codegenNode = createVNodeCall( - context, - vnodeTag, - vnodeProps, - vnodeChildren, - patchFlag === 0 ? void 0 : patchFlag, - vnodeDynamicProps, - vnodeDirectives, - !!shouldUseBlock, - false, - isComponent2, - node.loc - ); - needsPatch = needsPatch && (patchFlag === 0 || patchFlag === 32); - if (needsPatch) { - vnodeCall.needsPatch = true; - } - if (isBlockRequired) { - vnodeCall.isBlockRequired = true; - } - }; - }; - function resolveComponentType(node, context, ssr = false) { - let { tag } = node; - const isExplicitDynamic = isComponentTag(tag); - const isProp = findProp( - node, - "is", - false, - true - /* allow empty */ - ); - if (isProp) { - if (isExplicitDynamic || isCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - context - )) { - let exp; - if (isProp.type === 6) { - exp = isProp.value && createSimpleExpression(isProp.value.content, true); - } else { - exp = isProp.exp; - if (!exp) { - exp = createSimpleExpression(`is`, false, isProp.arg.loc); - { - exp = isProp.exp = processExpression(exp, context); - } - } - } - 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 && shared.capitalize(shared.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 = shared.camelize(name); - const PascalName = shared.capitalize(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, isComponent2, isDynamicComponent, ssr = false) { - const { tag, loc: elementLoc, children } = node; - let properties = []; - const mergeArgs = []; - const runtimeDirectives = []; - const hasChildren = children.length > 0; - let shouldUseBlock = false; - let isBlockRequired = 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 pushRefVForMarker = () => { - if (context.scopes.vFor > 0) { - properties.push( - createObjectProperty( - createSimpleExpression("ref_for", true), - createSimpleExpression("true") - ) - ); - } - }; - const analyzePatchFlag = ({ key, value }) => { - if (isStaticExp(key)) { - const name = key.content; - const isEventHandler = shared.isOn(name); - if (isEventHandler && (!isComponent2 || 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 - !shared.isReservedProp(name)) { - hasHydrationEventBinding = true; - } - if (isEventHandler && shared.isReservedProp(name)) { - hasVnodeHook = true; - } - if (name === "ref") { - hasRef = 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 === "class") { - hasClassBinding = true; - } else if (name === "style") { - hasStyleBinding = true; - } else if (name !== "ref" && name !== "key" && !dynamicPropNames.includes(name)) { - dynamicPropNames.push(name); - } - if (isComponent2 && (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; - pushRefVForMarker(); - 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:") || isCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - context - ))) { - 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 (!isComponent2) { - context.onError( - createCompilerError(40, loc) - ); - } - continue; - } - if (name === "once" || name === "memo") { - continue; - } - if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag) || isCompatEnabled( - "COMPILER_IS_ON_ELEMENT", - context - ))) { - continue; - } - if (isVOn && ssr) { - continue; - } - if (isVBind && isStaticArgOf(arg, "key")) { - shouldUseBlock = true; - } - if (isVOn && hasChildren && arg && isStaticExp(arg) && shared.camelize(arg.content) === "vue:beforeUpdate") { - shouldUseBlock = true; - isBlockRequired = true; - } - if (isVBind && isStaticArgOf(arg, "ref")) { - pushRefVForMarker(); - } - if (!arg && (isVBind || isVOn)) { - hasDynamicKeys = true; - if (exp) { - if (isVBind) { - { - pushMergeArg(); - { - const hasOverridableKeys = mergeArgs.some((arg2) => { - if (arg2.type === 15) { - return arg2.properties.some(({ key }) => { - if (key.type !== 4 || !key.isStatic) { - return true; - } - return key.content !== "class" && key.content !== "style" && !shared.isOn(key.content); - }); - } else { - return true; - } - }); - if (hasOverridableKeys) { - checkCompatEnabled( - "COMPILER_V_BIND_OBJECT_ORDER", - context, - loc - ); - } - } - if (isCompatEnabled( - "COMPILER_V_BIND_OBJECT_ORDER", - context - )) { - mergeArgs.unshift(exp); - continue; - } - } - pushRefVForMarker(); - pushMergeArg(); - mergeArgs.push(exp); - } else { - pushMergeArg({ - type: 14, - loc, - callee: context.helper(TO_HANDLERS), - arguments: isComponent2 ? [exp] : [exp, `true`] - }); - } - } else { - context.onError( - createCompilerError( - isVBind ? 34 : 35, - loc - ) - ); - } - continue; - } - if (isVBind && modifiers.some((mod) => mod.content === "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 (shared.isSymbol(needRuntime)) { - directiveImportMap.set(prop, needRuntime); - } - } - } else if (!shared.isBuiltInDirective(name)) { - runtimeDirectives.push(prop); - if (hasChildren) { - shouldUseBlock = true; - isBlockRequired = 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 && !isComponent2) { - patchFlag |= 2; - } - if (hasStyleBinding && !isComponent2) { - patchFlag |= 4; - } - if (dynamicPropNames.length) { - patchFlag |= 8; - } - if (hasHydrationEventBinding) { - patchFlag |= 32; - } - } - const needsPatch = (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0); - if (!shouldUseBlock && needsPatch) { - 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, - needsPatch, - isBlockRequired - }; - } - 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" || shared.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"; - } - var 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 = shared.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 = shared.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 = shared.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 - }; - } - var transformOn = (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(52, 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 - shared.toHandlerKey(shared.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, context); - const isInlineStatement = !(isMemberExp || isFnExpression(exp, context)); - 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; - }; - var 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 (arg.type !== 4) { - arg.children.unshift(`(`); - arg.children.push(`) || ""`); - } else if (!arg.isStatic) { - arg.content = arg.content ? `${arg.content} || ""` : `""`; - } - if (modifiers.some((mod) => mod.content === "camel")) { - if (arg.type === 4) { - if (arg.isStatic) { - arg.content = shared.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.some((mod) => mod.content === "prop")) { - injectPrefix(arg, "."); - } - if (modifiers.some((mod) => mod.content === "attr")) { - injectPrefix(arg, "^"); - } - } - return { - props: [createObjectProperty(arg, exp)] - }; - }; - var 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(`)`); - } - }; - var 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. - !(node.tag === "template"))) { - 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 /* ${shared.PatchFlagNames[1]} */` - ); - } - children[i] = { - type: 12, - content: child, - loc: child.loc, - codegenNode: createCallExpression( - context.helper(CREATE_TEXT), - callArgs - ) - }; - } - } - }; - } - }; - var seen$1 = /* @__PURE__ */ new WeakSet(); - var 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, - true - ); - } - }; - } - }; - var transformModel = (dir, node, context) => { - const { exp, arg } = dir; - if (!exp) { - context.onError( - createCompilerError(41, dir.loc) - ); - return createTransformProps(); - } - const rawExp = exp.loc.source.trim(); - 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(); - } - if (bindingType === "literal-const" || bindingType === "setup-const") { - context.onError(createCompilerError(45, exp.loc)); - return createTransformProps(); - } - const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref"); - if (!expString.trim() || !isMemberExpression(exp, 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:${shared.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) => m.content).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 }; - } - var validDivisionCharRE = /[\w).+\-_$\]]/; - var transformFilter = (node, context) => { - if (!isCompatEnabled("COMPILER_FILTERS", context)) { - return; - } - if (node.type === 5) { - rewriteFilter(node.content, context); - } else if (node.type === 1) { - node.props.forEach((prop) => { - if (prop.type === 7 && prop.name !== "for" && prop.exp) { - rewriteFilter(prop.exp, context); - } - }); - } - }; - function rewriteFilter(node, context) { - if (node.type === 4) { - parseFilter(node, context); - } else { - for (let i = 0; i < node.children.length; i++) { - const child = node.children[i]; - if (typeof child !== "object") continue; - if (child.type === 4) { - parseFilter(child, context); - } else if (child.type === 8) { - rewriteFilter(child, context); - } else if (child.type === 5) { - rewriteFilter(child.content, context); - } - } - } - } - function parseFilter(node, context) { - const exp = node.content; - let inSingle = false; - let inDouble = false; - let inTemplateString = false; - let inRegex = false; - let curly = 0; - let square = 0; - let paren = 0; - let lastFilterIndex = 0; - let c, prev, i, expression, filters = []; - for (i = 0; i < exp.length; i++) { - prev = c; - c = exp.charCodeAt(i); - if (inSingle) { - if (c === 39 && prev !== 92) inSingle = false; - } else if (inDouble) { - if (c === 34 && prev !== 92) inDouble = false; - } else if (inTemplateString) { - if (c === 96 && prev !== 92) inTemplateString = false; - } else if (inRegex) { - if (c === 47 && prev !== 92) inRegex = false; - } else if (c === 124 && // pipe - exp.charCodeAt(i + 1) !== 124 && exp.charCodeAt(i - 1) !== 124 && !curly && !square && !paren) { - if (expression === void 0) { - lastFilterIndex = i + 1; - expression = exp.slice(0, i).trim(); - } else { - pushFilter(); - } - } else { - switch (c) { - case 34: - inDouble = true; - break; - case 39: - inSingle = true; - break; - case 96: - inTemplateString = true; - break; - case 40: - paren++; - break; - case 41: - paren--; - break; - case 91: - square++; - break; - case 93: - square--; - break; - case 123: - curly++; - break; - case 125: - curly--; - break; - } - if (c === 47) { - let j = i - 1; - let p; - for (; j >= 0; j--) { - p = exp.charAt(j); - if (p !== " ") break; - } - if (!p || !validDivisionCharRE.test(p)) { - inRegex = true; - } - } - } - } - if (expression === void 0) { - expression = exp.slice(0, i).trim(); - } else if (lastFilterIndex !== 0) { - pushFilter(); - } - function pushFilter() { - filters.push(exp.slice(lastFilterIndex, i).trim()); - lastFilterIndex = i + 1; - } - if (filters.length) { - warnDeprecation( - "COMPILER_FILTERS", - context, - node.loc - ); - for (i = 0; i < filters.length; i++) { - expression = wrapFilter(expression, filters[i], context); - } - node.content = expression; - node.ast = void 0; - } - } - function wrapFilter(exp, filter, context) { - context.helper(RESOLVE_FILTER); - const i = filter.indexOf("("); - if (i < 0) { - context.filters.add(filter); - return `${toValidAssetId(filter, "filter")}(${exp})`; - } else { - const name = filter.slice(0, i); - const args = filter.slice(i + 1); - context.filters.add(name); - return `${toValidAssetId(name, "filter")}(${exp}${args !== ")" ? "," + args : args}`; - } - } - var seen = /* @__PURE__ */ new WeakSet(); - var transformMemo = (node, context) => { - if (node.type === 1) { - const dir = findDir(node, "memo"); - if (!dir || seen.has(node) || context.inSSR) { - 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.length) - ]); - context.cached.push(null); - } - }; - } - }; - var transformVBindShorthand = (node, context) => { - if (node.type === 1) { - for (const prop of node.props) { - if (prop.type === 7 && prop.name === "bind" && (!prop.exp || // #13930 :foo in in-DOM templates will be parsed into :foo="" by browser - false) && prop.arg) { - const arg = prop.arg; - if (arg.type !== 4 || !arg.isStatic) { - context.onError( - createCompilerError( - 53, - arg.loc - ) - ); - prop.exp = createSimpleExpression("", true, arg.loc); - } else { - const propName = shared.camelize(arg.content); - if (validFirstIdentCharRE.test(propName[0]) || // allow hyphen first char for https://github.com/vuejs/language-tools/pull/3424 - propName[0] === "-") { - prop.exp = createSimpleExpression(propName, false, arg.loc); - } - } - } - } - } - }; - function getBaseTransformPreset(prefixIdentifiers) { - return [ - [ - transformVBindShorthand, - transformOnce, - transformIf, - transformMemo, - transformFor, - ...[transformFilter], - ...prefixIdentifiers ? [ - // order is important - trackVForSlotScopes, - transformExpression - ] : [], - transformSlotOutlet, - transformElement, - trackSlotScopes, - transformText - ], - { - on: transformOn, - bind: transformBind, - model: transformModel - } - ]; - } - 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(50)); - } - if (options.scopeId && !isModuleMode) { - onError(createCompilerError(51)); - } - const resolvedOptions = shared.extend({}, options, { - prefixIdentifiers - }); - const ast = shared.isString(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, - shared.extend({}, resolvedOptions, { - nodeTransforms: [ - ...nodeTransforms, - ...options.nodeTransforms || [] - // user transforms - ], - directiveTransforms: shared.extend( - {}, - directiveTransforms, - options.directiveTransforms || {} - // user transforms - ) - }) - ); - return generate(ast, resolvedOptions); - } - var 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" - }; - var noopDirectiveTransform = () => ({ props: [] }); - exports2.generateCodeFrame = shared.generateCodeFrame; - exports2.BASE_TRANSITION = BASE_TRANSITION; - exports2.BindingTypes = BindingTypes; - exports2.CAMELIZE = CAMELIZE; - exports2.CAPITALIZE = CAPITALIZE; - exports2.CREATE_BLOCK = CREATE_BLOCK; - exports2.CREATE_COMMENT = CREATE_COMMENT; - exports2.CREATE_ELEMENT_BLOCK = CREATE_ELEMENT_BLOCK; - exports2.CREATE_ELEMENT_VNODE = CREATE_ELEMENT_VNODE; - exports2.CREATE_SLOTS = CREATE_SLOTS; - exports2.CREATE_STATIC = CREATE_STATIC; - exports2.CREATE_TEXT = CREATE_TEXT; - exports2.CREATE_VNODE = CREATE_VNODE; - exports2.CompilerDeprecationTypes = CompilerDeprecationTypes; - exports2.ConstantTypes = ConstantTypes; - exports2.ElementTypes = ElementTypes; - exports2.ErrorCodes = ErrorCodes; - exports2.FRAGMENT = FRAGMENT; - exports2.GUARD_REACTIVE_PROPS = GUARD_REACTIVE_PROPS; - exports2.IS_MEMO_SAME = IS_MEMO_SAME; - exports2.IS_REF = IS_REF; - exports2.KEEP_ALIVE = KEEP_ALIVE; - exports2.MERGE_PROPS = MERGE_PROPS; - exports2.NORMALIZE_CLASS = NORMALIZE_CLASS; - exports2.NORMALIZE_PROPS = NORMALIZE_PROPS; - exports2.NORMALIZE_STYLE = NORMALIZE_STYLE; - exports2.Namespaces = Namespaces; - exports2.NodeTypes = NodeTypes; - exports2.OPEN_BLOCK = OPEN_BLOCK; - exports2.POP_SCOPE_ID = POP_SCOPE_ID; - exports2.PUSH_SCOPE_ID = PUSH_SCOPE_ID; - exports2.RENDER_LIST = RENDER_LIST; - exports2.RENDER_SLOT = RENDER_SLOT; - exports2.RESOLVE_COMPONENT = RESOLVE_COMPONENT; - exports2.RESOLVE_DIRECTIVE = RESOLVE_DIRECTIVE; - exports2.RESOLVE_DYNAMIC_COMPONENT = RESOLVE_DYNAMIC_COMPONENT; - exports2.RESOLVE_FILTER = RESOLVE_FILTER; - exports2.SET_BLOCK_TRACKING = SET_BLOCK_TRACKING; - exports2.SUSPENSE = SUSPENSE; - exports2.TELEPORT = TELEPORT; - exports2.TO_DISPLAY_STRING = TO_DISPLAY_STRING; - exports2.TO_HANDLERS = TO_HANDLERS; - exports2.TO_HANDLER_KEY = TO_HANDLER_KEY; - exports2.TS_NODE_TYPES = TS_NODE_TYPES; - exports2.UNREF = UNREF; - exports2.WITH_CTX = WITH_CTX; - exports2.WITH_DIRECTIVES = WITH_DIRECTIVES; - exports2.WITH_MEMO = WITH_MEMO; - exports2.advancePositionWithClone = advancePositionWithClone; - exports2.advancePositionWithMutation = advancePositionWithMutation; - exports2.assert = assert; - exports2.baseCompile = baseCompile; - exports2.baseParse = baseParse; - exports2.buildDirectiveArgs = buildDirectiveArgs; - exports2.buildProps = buildProps; - exports2.buildSlots = buildSlots; - exports2.checkCompatEnabled = checkCompatEnabled; - exports2.convertToBlock = convertToBlock; - exports2.createArrayExpression = createArrayExpression; - exports2.createAssignmentExpression = createAssignmentExpression; - exports2.createBlockStatement = createBlockStatement; - exports2.createCacheExpression = createCacheExpression; - exports2.createCallExpression = createCallExpression; - exports2.createCompilerError = createCompilerError; - exports2.createCompoundExpression = createCompoundExpression; - exports2.createConditionalExpression = createConditionalExpression; - exports2.createForLoopParams = createForLoopParams; - exports2.createFunctionExpression = createFunctionExpression; - exports2.createIfStatement = createIfStatement; - exports2.createInterpolation = createInterpolation; - exports2.createObjectExpression = createObjectExpression; - exports2.createObjectProperty = createObjectProperty; - exports2.createReturnStatement = createReturnStatement; - exports2.createRoot = createRoot; - exports2.createSequenceExpression = createSequenceExpression; - exports2.createSimpleExpression = createSimpleExpression; - exports2.createStructuralDirectiveTransform = createStructuralDirectiveTransform; - exports2.createTemplateLiteral = createTemplateLiteral; - exports2.createTransformContext = createTransformContext; - exports2.createVNodeCall = createVNodeCall; - exports2.errorMessages = errorMessages; - exports2.extractIdentifiers = extractIdentifiers; - exports2.findDir = findDir; - exports2.findProp = findProp; - exports2.forAliasRE = forAliasRE; - exports2.generate = generate; - exports2.getBaseTransformPreset = getBaseTransformPreset; - exports2.getConstantType = getConstantType; - exports2.getMemoedVNodeCall = getMemoedVNodeCall; - exports2.getVNodeBlockHelper = getVNodeBlockHelper; - exports2.getVNodeHelper = getVNodeHelper; - exports2.hasDynamicKeyVBind = hasDynamicKeyVBind; - exports2.hasScopeRef = hasScopeRef; - exports2.helperNameMap = helperNameMap; - exports2.injectProp = injectProp; - exports2.isAllWhitespace = isAllWhitespace; - exports2.isCommentOrWhitespace = isCommentOrWhitespace; - exports2.isCoreComponent = isCoreComponent; - exports2.isFnExpression = isFnExpression; - exports2.isFnExpressionBrowser = isFnExpressionBrowser; - exports2.isFnExpressionNode = isFnExpressionNode; - exports2.isFunctionType = isFunctionType; - exports2.isInDestructureAssignment = isInDestructureAssignment; - exports2.isInNewExpression = isInNewExpression; - exports2.isMemberExpression = isMemberExpression; - exports2.isMemberExpressionBrowser = isMemberExpressionBrowser; - exports2.isMemberExpressionNode = isMemberExpressionNode; - exports2.isReferencedIdentifier = isReferencedIdentifier; - exports2.isSimpleIdentifier = isSimpleIdentifier; - exports2.isSlotOutlet = isSlotOutlet; - exports2.isStaticArgOf = isStaticArgOf; - exports2.isStaticExp = isStaticExp; - exports2.isStaticProperty = isStaticProperty; - exports2.isStaticPropertyKey = isStaticPropertyKey; - exports2.isTemplateNode = isTemplateNode; - exports2.isText = isText$1; - exports2.isVPre = isVPre; - exports2.isVSlot = isVSlot; - exports2.isWhitespaceText = isWhitespaceText; - exports2.locStub = locStub; - exports2.noopDirectiveTransform = noopDirectiveTransform; - exports2.processExpression = processExpression; - exports2.processFor = processFor; - exports2.processIf = processIf; - exports2.processSlotOutlet = processSlotOutlet; - exports2.registerRuntimeHelpers = registerRuntimeHelpers; - exports2.resolveComponentType = resolveComponentType; - exports2.stringifyExpression = stringifyExpression; - exports2.toValidAssetId = toValidAssetId; - exports2.trackSlotScopes = trackSlotScopes; - exports2.trackVForSlotScopes = trackVForSlotScopes; - exports2.transform = transform; - exports2.transformBind = transformBind; - exports2.transformElement = transformElement; - exports2.transformExpression = transformExpression; - exports2.transformModel = transformModel; - exports2.transformOn = transformOn; - exports2.transformVBindShorthand = transformVBindShorthand; - exports2.traverseNode = traverseNode; - exports2.unwrapTSNode = unwrapTSNode; - exports2.validFirstIdentCharRE = validFirstIdentCharRE; - exports2.walkBlockDeclarations = walkBlockDeclarations; - exports2.walkFunctionParams = walkFunctionParams; - exports2.walkIdentifiers = walkIdentifiers; - exports2.warnDeprecation = warnDeprecation; - } -}); - -// intern-log/node_modules/.pnpm/@vue+compiler-core@3.5.44/node_modules/@vue/compiler-core/index.js -var require_compiler_core = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+compiler-core@3.5.44/node_modules/@vue/compiler-core/index.js"(exports2, module2) { - "use strict"; - if (process.env.NODE_ENV === "production") { - module2.exports = require_compiler_core_cjs_prod(); - } else { - module2.exports = require_compiler_core_cjs(); - } - } -}); - -// intern-log/node_modules/.pnpm/@vue+compiler-dom@3.5.44/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.prod.js -var require_compiler_dom_cjs_prod = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+compiler-dom@3.5.44/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.prod.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var compilerCore = require_compiler_core(); - var shared = require_shared(); - var V_MODEL_RADIO = /* @__PURE__ */ Symbol(``); - var V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol( - `` - ); - var V_MODEL_TEXT = /* @__PURE__ */ Symbol(``); - var V_MODEL_SELECT = /* @__PURE__ */ Symbol( - `` - ); - var V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol( - `` - ); - var V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol( - `` - ); - var V_ON_WITH_KEYS = /* @__PURE__ */ Symbol( - `` - ); - var V_SHOW = /* @__PURE__ */ Symbol(``); - var TRANSITION = /* @__PURE__ */ Symbol(``); - var TRANSITION_GROUP = /* @__PURE__ */ Symbol( - `` - ); - compilerCore.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` - }); - var parserOptions = { - parseMode: "html", - isVoidTag: shared.isVoidTag, - isNativeTag: (tag) => shared.isHTMLTag(tag) || shared.isSVGTag(tag) || shared.isMathMLTag(tag), - isPreTag: (tag) => tag === "pre", - isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea", - 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; - } - }; - var 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: compilerCore.createSimpleExpression(`style`, true, p.loc), - exp: parseInlineCSS(p.value.content, p.loc), - modifiers: [], - loc: p.loc - }; - } - }); - } - }; - var parseInlineCSS = (cssText, loc) => { - const normalized = shared.parseStringStyle(cssText); - return compilerCore.createSimpleExpression( - JSON.stringify(normalized), - false, - loc, - 3 - ); - }; - function createDOMCompilerError(code, loc) { - return compilerCore.createCompilerError( - code, - loc, - DOMErrorMessages - ); - } - var DOMErrorCodes = { - "X_V_HTML_NO_EXPRESSION": 54, - "54": "X_V_HTML_NO_EXPRESSION", - "X_V_HTML_WITH_CHILDREN": 55, - "55": "X_V_HTML_WITH_CHILDREN", - "X_V_TEXT_NO_EXPRESSION": 56, - "56": "X_V_TEXT_NO_EXPRESSION", - "X_V_TEXT_WITH_CHILDREN": 57, - "57": "X_V_TEXT_WITH_CHILDREN", - "X_V_MODEL_ON_INVALID_ELEMENT": 58, - "58": "X_V_MODEL_ON_INVALID_ELEMENT", - "X_V_MODEL_ARG_ON_ELEMENT": 59, - "59": "X_V_MODEL_ARG_ON_ELEMENT", - "X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60, - "60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT", - "X_V_MODEL_UNNECESSARY_VALUE": 61, - "61": "X_V_MODEL_UNNECESSARY_VALUE", - "X_V_SHOW_NO_EXPRESSION": 62, - "62": "X_V_SHOW_NO_EXPRESSION", - "X_TRANSITION_INVALID_CHILDREN": 63, - "63": "X_TRANSITION_INVALID_CHILDREN", - "X_IGNORED_SIDE_EFFECT_TAG": 64, - "64": "X_IGNORED_SIDE_EFFECT_TAG", - "__EXTEND_POINT__": 65, - "65": "__EXTEND_POINT__" - }; - var DOMErrorMessages = { - [54]: `v-html is missing expression.`, - [55]: `v-html will override element children.`, - [56]: `v-text is missing expression.`, - [57]: `v-text will override element children.`, - [58]: `v-model can only be used on <input>, <textarea> and <select> elements.`, - [59]: `v-model argument is not supported on plain elements.`, - [60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`, - [61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`, - [62]: `v-show is missing expression.`, - [63]: `<Transition> expects exactly one child element or component.`, - [64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.` - }; - var transformVHtml = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(54, loc) - ); - } - if (node.children.length) { - context.onError( - createDOMCompilerError(55, loc) - ); - node.children.length = 0; - } - return { - props: [ - compilerCore.createObjectProperty( - compilerCore.createSimpleExpression(`innerHTML`, true, loc), - exp || compilerCore.createSimpleExpression("", true) - ) - ] - }; - }; - var transformVText = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(56, loc) - ); - } - if (node.children.length) { - context.onError( - createDOMCompilerError(57, loc) - ); - node.children.length = 0; - } - return { - props: [ - compilerCore.createObjectProperty( - compilerCore.createSimpleExpression(`textContent`, true), - exp ? compilerCore.getConstantType(exp, context) > 0 ? exp : compilerCore.createCallExpression( - context.helperString(compilerCore.TO_DISPLAY_STRING), - [exp], - loc - ) : compilerCore.createSimpleExpression("", true) - ) - ] - }; - }; - var transformModel = (dir, node, context) => { - const baseResult = compilerCore.transformModel(dir, node, context); - if (!baseResult.props.length || node.tagType === 1) { - return baseResult; - } - if (dir.arg) { - context.onError( - createDOMCompilerError( - 59, - dir.arg.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 = compilerCore.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( - 60, - dir.loc - ) - ); - break; - } - } - } else if (compilerCore.hasDynamicKeyVBind(node)) { - directiveToUse = V_MODEL_DYNAMIC; - } else ; - } else if (tag === "select") { - directiveToUse = V_MODEL_SELECT; - } else ; - if (!isInvalidType) { - baseResult.needRuntime = context.helper(directiveToUse); - } - } else { - context.onError( - createDOMCompilerError( - 58, - dir.loc - ) - ); - } - baseResult.props = baseResult.props.filter( - (p) => !(p.key.type === 4 && p.key.content === "modelValue") - ); - return baseResult; - }; - var isEventOptionModifier = /* @__PURE__ */ shared.makeMap(`passive,once,capture`); - var isNonKeyModifier = /* @__PURE__ */ shared.makeMap( - // event propagation management - `stop,prevent,self,ctrl,shift,alt,meta,exact,middle` - ); - var maybeKeyModifier = /* @__PURE__ */ shared.makeMap("left,right"); - var isKeyboardEvent = /* @__PURE__ */ shared.makeMap(`onkeyup,onkeydown,onkeypress`); - var resolveModifiers = (key, modifiers, context, loc) => { - const keyModifiers = []; - const nonKeyModifiers = []; - const eventOptionModifiers = []; - for (let i = 0; i < modifiers.length; i++) { - const modifier = modifiers[i].content; - if (modifier === "native" && compilerCore.checkCompatEnabled( - "COMPILER_V_ON_NATIVE", - context, - loc - )) { - eventOptionModifiers.push(modifier); - } else if (isEventOptionModifier(modifier)) { - eventOptionModifiers.push(modifier); - } else { - if (maybeKeyModifier(modifier)) { - if (compilerCore.isStaticExp(key)) { - if (isKeyboardEvent(key.content.toLowerCase())) { - 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 - }; - }; - var transformClick = (key, event) => { - const isStaticClick = compilerCore.isStaticExp(key) && key.content.toLowerCase() === "onclick"; - return isStaticClick ? compilerCore.createSimpleExpression(event, true) : key.type !== 4 ? compilerCore.createCompoundExpression([ - `(`, - key, - `) === "onClick" ? "${event}" : (`, - key, - `)` - ]) : key; - }; - var transformOn = (dir, node, context) => { - return compilerCore.transformOn(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 = compilerCore.createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [ - handlerExp, - JSON.stringify(nonKeyModifiers) - ]); - } - if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard - (!compilerCore.isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) { - handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_KEYS), [ - handlerExp, - JSON.stringify(keyModifiers) - ]); - } - if (eventOptionModifiers.length) { - const modifierPostfix = eventOptionModifiers.map(shared.capitalize).join(""); - key = compilerCore.isStaticExp(key) ? compilerCore.createSimpleExpression(`${key.content}${modifierPostfix}`, true) : compilerCore.createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]); - } - return { - props: [compilerCore.createObjectProperty(key, handlerExp)] - }; - }); - }; - var transformShow = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(62, loc) - ); - } - return { - props: [], - needRuntime: context.helper(V_SHOW) - }; - }; - var 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; - } - hasMultipleChildren(node); - 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) => !compilerCore.isCommentOrWhitespace(c) - ); - const child = children[0]; - return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren); - } - var expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g; - var stringifyStatic = (children, context, parent) => { - if (context.scopes.vSlot > 0) { - return; - } - const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 20; - let nc = 0; - let ec = 0; - const currentChunk = []; - const stringifyCurrentChunk = (currentIndex) => { - if (nc >= 20 || ec >= 5) { - const staticCall = compilerCore.createCallExpression(context.helper(compilerCore.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) - ]); - const deleteCount = currentChunk.length - 1; - if (isParentCached) { - children.splice( - currentIndex - currentChunk.length, - currentChunk.length, - // @ts-expect-error - staticCall - ); - } else { - currentChunk[0].codegenNode.value = staticCall; - if (currentChunk.length > 1) { - children.splice(currentIndex - currentChunk.length + 1, deleteCount); - const cacheIndex = context.cached.indexOf( - currentChunk[currentChunk.length - 1].codegenNode - ); - if (cacheIndex > -1) { - for (let i2 = cacheIndex; i2 < context.cached.length; i2++) { - const c = context.cached[i2]; - if (c) c.index -= deleteCount; - } - context.cached.splice(cacheIndex - deleteCount + 1, deleteCount); - } - } - } - return deleteCount; - } - return 0; - }; - let i = 0; - for (; i < children.length; i++) { - const child = children[i]; - const isCached = isParentCached || getCachedNode(child); - if (isCached) { - const result = analyzeNode(child); - if (result) { - nc += result[0]; - ec += result[1]; - currentChunk.push(child); - continue; - } - } - i -= stringifyCurrentChunk(i); - nc = 0; - ec = 0; - currentChunk.length = 0; - } - stringifyCurrentChunk(i); - }; - var getCachedNode = (node) => { - if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) { - return node.codegenNode; - } - }; - var dataAriaRE = /^(?:data|aria)-/; - var isStringifiableAttr = (name, ns) => { - return (ns === 0 ? shared.isKnownHtmlAttr(name) : ns === 1 ? shared.isKnownSvgAttr(name) : ns === 2 ? shared.isKnownMathMLAttr(name) : false) || dataAriaRE.test(name); - }; - var isNonStringifiable = /* @__PURE__ */ shared.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 === 1 && compilerCore.findDir(node, "once", true)) { - 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) { - const isOptionTag = node2.tag === "option" && node2.ns === 0; - 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(); - } - if (isOptionTag && compilerCore.isStaticArgOf(p.arg, "value") && p.exp && !p.exp.isStatic) { - 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 (shared.isString(node)) { - return node; - } - if (shared.isSymbol(node)) { - return ``; - } - switch (node.type) { - case 1: - return stringifyElement(node, context); - case 2: - return shared.escapeHtml(node.content); - case 3: - return `<!--${shared.escapeHtml(node.content)}-->`; - case 5: - return shared.escapeHtml(shared.toDisplayString(evaluateConstant(node.content))); - case 8: - return shared.escapeHtml(evaluateConstant(node)); - case 12: - return stringifyNode(node.content, context); - default: - return ""; - } - } - function stringifyElement(node, context) { - var _a; - let res = `<${node.tag}`; - let innerHTML = void 0; - 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 += `="${shared.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 ((shared.isBooleanAttr(p.arg.content) || p.arg.content === "hidden") && exp.content === "false") { - continue; - } - let evaluated = evaluateConstant(exp); - if (evaluated != null) { - const arg = p.arg && p.arg.content; - if (arg === "hidden" && typeof evaluated === "number" && !shared.includeBooleanAttr(evaluated)) { - continue; - } - if (arg === "class") { - evaluated = shared.normalizeClass(evaluated); - } else if (arg === "style") { - evaluated = shared.stringifyStyle(shared.normalizeStyle(evaluated)); - } - res += ` ${p.arg.content}="${shared.escapeHtml( - evaluated - )}"`; - } - } else if (p.name === "html") { - innerHTML = (_a = evaluateConstant(p.exp)) != null ? _a : ""; - } else if (p.name === "text") { - innerHTML = shared.escapeHtml( - shared.toDisplayString(evaluateConstant(p.exp)) - ); - } - } - } - if (context.scopeId) { - res += ` ${context.scopeId}`; - } - res += `>`; - if (innerHTML !== void 0) { - res += innerHTML; - } else { - for (let i = 0; i < node.children.length; i++) { - res += stringifyNode(node.children[i], context); - } - } - if (!shared.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 (shared.isString(c) || shared.isSymbol(c)) { - return; - } - if (c.type === 2) { - res += c.content; - } else if (c.type === 5) { - res += shared.toDisplayString(evaluateConstant(c.content)); - } else { - res += evaluateConstant(c); - } - }); - return res; - } - } - var ignoreSideEffectTags = (node, context) => { - if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) { - context.removeNode(); - } - }; - var DOMNodeTransforms = [ - transformStyle, - transformTransition, - ...[] - ]; - var DOMDirectiveTransforms = { - cloak: compilerCore.noopDirectiveTransform, - html: transformVHtml, - text: transformVText, - model: transformModel, - // override compiler-core - on: transformOn, - // override compiler-core - show: transformShow - }; - function compile(src, options = {}) { - return compilerCore.baseCompile( - src, - shared.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: shared.extend( - {}, - DOMDirectiveTransforms, - options.directiveTransforms || {} - ), - transformHoist: stringifyStatic - }) - ); - } - function parse(template, options = {}) { - return compilerCore.baseParse(template, shared.extend({}, parserOptions, options)); - } - exports2.DOMDirectiveTransforms = DOMDirectiveTransforms; - exports2.DOMErrorCodes = DOMErrorCodes; - exports2.DOMErrorMessages = DOMErrorMessages; - exports2.DOMNodeTransforms = DOMNodeTransforms; - exports2.TRANSITION = TRANSITION; - exports2.TRANSITION_GROUP = TRANSITION_GROUP; - exports2.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX; - exports2.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC; - exports2.V_MODEL_RADIO = V_MODEL_RADIO; - exports2.V_MODEL_SELECT = V_MODEL_SELECT; - exports2.V_MODEL_TEXT = V_MODEL_TEXT; - exports2.V_ON_WITH_KEYS = V_ON_WITH_KEYS; - exports2.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS; - exports2.V_SHOW = V_SHOW; - exports2.compile = compile; - exports2.createDOMCompilerError = createDOMCompilerError; - exports2.parse = parse; - exports2.parserOptions = parserOptions; - exports2.transformStyle = transformStyle; - Object.keys(compilerCore).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports2, k)) exports2[k] = compilerCore[k]; - }); - } -}); - -// intern-log/node_modules/.pnpm/@vue+compiler-dom@3.5.44/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.js -var require_compiler_dom_cjs = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+compiler-dom@3.5.44/node_modules/@vue/compiler-dom/dist/compiler-dom.cjs.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var compilerCore = require_compiler_core(); - var shared = require_shared(); - var V_MODEL_RADIO = /* @__PURE__ */ Symbol(`vModelRadio`); - var V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol( - `vModelCheckbox` - ); - var V_MODEL_TEXT = /* @__PURE__ */ Symbol(`vModelText`); - var V_MODEL_SELECT = /* @__PURE__ */ Symbol( - `vModelSelect` - ); - var V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol( - `vModelDynamic` - ); - var V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol( - `vOnModifiersGuard` - ); - var V_ON_WITH_KEYS = /* @__PURE__ */ Symbol( - `vOnKeysGuard` - ); - var V_SHOW = /* @__PURE__ */ Symbol(`vShow`); - var TRANSITION = /* @__PURE__ */ Symbol(`Transition`); - var TRANSITION_GROUP = /* @__PURE__ */ Symbol( - `TransitionGroup` - ); - compilerCore.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` - }); - var parserOptions = { - parseMode: "html", - isVoidTag: shared.isVoidTag, - isNativeTag: (tag) => shared.isHTMLTag(tag) || shared.isSVGTag(tag) || shared.isMathMLTag(tag), - isPreTag: (tag) => tag === "pre", - isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea", - 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; - } - }; - var 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: compilerCore.createSimpleExpression(`style`, true, p.loc), - exp: parseInlineCSS(p.value.content, p.loc), - modifiers: [], - loc: p.loc - }; - } - }); - } - }; - var parseInlineCSS = (cssText, loc) => { - const normalized = shared.parseStringStyle(cssText); - return compilerCore.createSimpleExpression( - JSON.stringify(normalized), - false, - loc, - 3 - ); - }; - function createDOMCompilerError(code, loc) { - return compilerCore.createCompilerError( - code, - loc, - DOMErrorMessages - ); - } - var DOMErrorCodes = { - "X_V_HTML_NO_EXPRESSION": 54, - "54": "X_V_HTML_NO_EXPRESSION", - "X_V_HTML_WITH_CHILDREN": 55, - "55": "X_V_HTML_WITH_CHILDREN", - "X_V_TEXT_NO_EXPRESSION": 56, - "56": "X_V_TEXT_NO_EXPRESSION", - "X_V_TEXT_WITH_CHILDREN": 57, - "57": "X_V_TEXT_WITH_CHILDREN", - "X_V_MODEL_ON_INVALID_ELEMENT": 58, - "58": "X_V_MODEL_ON_INVALID_ELEMENT", - "X_V_MODEL_ARG_ON_ELEMENT": 59, - "59": "X_V_MODEL_ARG_ON_ELEMENT", - "X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60, - "60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT", - "X_V_MODEL_UNNECESSARY_VALUE": 61, - "61": "X_V_MODEL_UNNECESSARY_VALUE", - "X_V_SHOW_NO_EXPRESSION": 62, - "62": "X_V_SHOW_NO_EXPRESSION", - "X_TRANSITION_INVALID_CHILDREN": 63, - "63": "X_TRANSITION_INVALID_CHILDREN", - "X_IGNORED_SIDE_EFFECT_TAG": 64, - "64": "X_IGNORED_SIDE_EFFECT_TAG", - "__EXTEND_POINT__": 65, - "65": "__EXTEND_POINT__" - }; - var DOMErrorMessages = { - [54]: `v-html is missing expression.`, - [55]: `v-html will override element children.`, - [56]: `v-text is missing expression.`, - [57]: `v-text will override element children.`, - [58]: `v-model can only be used on <input>, <textarea> and <select> elements.`, - [59]: `v-model argument is not supported on plain elements.`, - [60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`, - [61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`, - [62]: `v-show is missing expression.`, - [63]: `<Transition> expects exactly one child element or component.`, - [64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.` - }; - var transformVHtml = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(54, loc) - ); - } - if (node.children.length) { - context.onError( - createDOMCompilerError(55, loc) - ); - node.children.length = 0; - } - return { - props: [ - compilerCore.createObjectProperty( - compilerCore.createSimpleExpression(`innerHTML`, true, loc), - exp || compilerCore.createSimpleExpression("", true) - ) - ] - }; - }; - var transformVText = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(56, loc) - ); - } - if (node.children.length) { - context.onError( - createDOMCompilerError(57, loc) - ); - node.children.length = 0; - } - return { - props: [ - compilerCore.createObjectProperty( - compilerCore.createSimpleExpression(`textContent`, true), - exp ? compilerCore.getConstantType(exp, context) > 0 ? exp : compilerCore.createCallExpression( - context.helperString(compilerCore.TO_DISPLAY_STRING), - [exp], - loc - ) : compilerCore.createSimpleExpression("", true) - ) - ] - }; - }; - var transformModel = (dir, node, context) => { - const baseResult = compilerCore.transformModel(dir, node, context); - if (!baseResult.props.length || node.tagType === 1) { - return baseResult; - } - if (dir.arg) { - context.onError( - createDOMCompilerError( - 59, - dir.arg.loc - ) - ); - } - function checkDuplicatedValue() { - const value = compilerCore.findDir(node, "bind"); - if (value && compilerCore.isStaticArgOf(value.arg, "value")) { - context.onError( - createDOMCompilerError( - 61, - 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 = compilerCore.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( - 60, - dir.loc - ) - ); - break; - default: - checkDuplicatedValue(); - break; - } - } - } else if (compilerCore.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( - 58, - dir.loc - ) - ); - } - baseResult.props = baseResult.props.filter( - (p) => !(p.key.type === 4 && p.key.content === "modelValue") - ); - return baseResult; - }; - var isEventOptionModifier = /* @__PURE__ */ shared.makeMap(`passive,once,capture`); - var isNonKeyModifier = /* @__PURE__ */ shared.makeMap( - // event propagation management - `stop,prevent,self,ctrl,shift,alt,meta,exact,middle` - ); - var maybeKeyModifier = /* @__PURE__ */ shared.makeMap("left,right"); - var isKeyboardEvent = /* @__PURE__ */ shared.makeMap(`onkeyup,onkeydown,onkeypress`); - var resolveModifiers = (key, modifiers, context, loc) => { - const keyModifiers = []; - const nonKeyModifiers = []; - const eventOptionModifiers = []; - for (let i = 0; i < modifiers.length; i++) { - const modifier = modifiers[i].content; - if (modifier === "native" && compilerCore.checkCompatEnabled( - "COMPILER_V_ON_NATIVE", - context, - loc - )) { - eventOptionModifiers.push(modifier); - } else if (isEventOptionModifier(modifier)) { - eventOptionModifiers.push(modifier); - } else { - if (maybeKeyModifier(modifier)) { - if (compilerCore.isStaticExp(key)) { - if (isKeyboardEvent(key.content.toLowerCase())) { - 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 - }; - }; - var transformClick = (key, event) => { - const isStaticClick = compilerCore.isStaticExp(key) && key.content.toLowerCase() === "onclick"; - return isStaticClick ? compilerCore.createSimpleExpression(event, true) : key.type !== 4 ? compilerCore.createCompoundExpression([ - `(`, - key, - `) === "onClick" ? "${event}" : (`, - key, - `)` - ]) : key; - }; - var transformOn = (dir, node, context) => { - return compilerCore.transformOn(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 = compilerCore.createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [ - handlerExp, - JSON.stringify(nonKeyModifiers) - ]); - } - if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard - (!compilerCore.isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) { - handlerExp = compilerCore.createCallExpression(context.helper(V_ON_WITH_KEYS), [ - handlerExp, - JSON.stringify(keyModifiers) - ]); - } - if (eventOptionModifiers.length) { - const modifierPostfix = eventOptionModifiers.map(shared.capitalize).join(""); - key = compilerCore.isStaticExp(key) ? compilerCore.createSimpleExpression(`${key.content}${modifierPostfix}`, true) : compilerCore.createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]); - } - return { - props: [compilerCore.createObjectProperty(key, handlerExp)] - }; - }); - }; - var transformShow = (dir, node, context) => { - const { exp, loc } = dir; - if (!exp) { - context.onError( - createDOMCompilerError(62, loc) - ); - } - return { - props: [], - needRuntime: context.helper(V_SHOW) - }; - }; - var 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; - } - const multipleChildren = hasMultipleChildren(node); - if (multipleChildren) { - context.onError( - createDOMCompilerError( - 63, - { - 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) => !compilerCore.isCommentOrWhitespace(c) - ); - const child = children[0]; - return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren); - } - var expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g; - var stringifyStatic = (children, context, parent) => { - if (context.scopes.vSlot > 0) { - return; - } - const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !shared.isArray(parent.codegenNode.children) && parent.codegenNode.children.type === 20; - let nc = 0; - let ec = 0; - const currentChunk = []; - const stringifyCurrentChunk = (currentIndex) => { - if (nc >= 20 || ec >= 5) { - const staticCall = compilerCore.createCallExpression(context.helper(compilerCore.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) - ]); - const deleteCount = currentChunk.length - 1; - if (isParentCached) { - children.splice( - currentIndex - currentChunk.length, - currentChunk.length, - // @ts-expect-error - staticCall - ); - } else { - currentChunk[0].codegenNode.value = staticCall; - if (currentChunk.length > 1) { - children.splice(currentIndex - currentChunk.length + 1, deleteCount); - const cacheIndex = context.cached.indexOf( - currentChunk[currentChunk.length - 1].codegenNode - ); - if (cacheIndex > -1) { - for (let i2 = cacheIndex; i2 < context.cached.length; i2++) { - const c = context.cached[i2]; - if (c) c.index -= deleteCount; - } - context.cached.splice(cacheIndex - deleteCount + 1, deleteCount); - } - } - } - return deleteCount; - } - return 0; - }; - let i = 0; - for (; i < children.length; i++) { - const child = children[i]; - const isCached = isParentCached || getCachedNode(child); - if (isCached) { - const result = analyzeNode(child); - if (result) { - nc += result[0]; - ec += result[1]; - currentChunk.push(child); - continue; - } - } - i -= stringifyCurrentChunk(i); - nc = 0; - ec = 0; - currentChunk.length = 0; - } - stringifyCurrentChunk(i); - }; - var getCachedNode = (node) => { - if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) { - return node.codegenNode; - } - }; - var dataAriaRE = /^(?:data|aria)-/; - var isStringifiableAttr = (name, ns) => { - return (ns === 0 ? shared.isKnownHtmlAttr(name) : ns === 1 ? shared.isKnownSvgAttr(name) : ns === 2 ? shared.isKnownMathMLAttr(name) : false) || dataAriaRE.test(name); - }; - var isNonStringifiable = /* @__PURE__ */ shared.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 === 1 && compilerCore.findDir(node, "once", true)) { - 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) { - const isOptionTag = node2.tag === "option" && node2.ns === 0; - 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(); - } - if (isOptionTag && compilerCore.isStaticArgOf(p.arg, "value") && p.exp && !p.exp.isStatic) { - 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 (shared.isString(node)) { - return node; - } - if (shared.isSymbol(node)) { - return ``; - } - switch (node.type) { - case 1: - return stringifyElement(node, context); - case 2: - return shared.escapeHtml(node.content); - case 3: - return `<!--${shared.escapeHtml(node.content)}-->`; - case 5: - return shared.escapeHtml(shared.toDisplayString(evaluateConstant(node.content))); - case 8: - return shared.escapeHtml(evaluateConstant(node)); - case 12: - return stringifyNode(node.content, context); - default: - return ""; - } - } - function stringifyElement(node, context) { - var _a; - let res = `<${node.tag}`; - let innerHTML = void 0; - 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 += `="${shared.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 ((shared.isBooleanAttr(p.arg.content) || p.arg.content === "hidden") && exp.content === "false") { - continue; - } - let evaluated = evaluateConstant(exp); - if (evaluated != null) { - const arg = p.arg && p.arg.content; - if (arg === "hidden" && typeof evaluated === "number" && !shared.includeBooleanAttr(evaluated)) { - continue; - } - if (arg === "class") { - evaluated = shared.normalizeClass(evaluated); - } else if (arg === "style") { - evaluated = shared.stringifyStyle(shared.normalizeStyle(evaluated)); - } - res += ` ${p.arg.content}="${shared.escapeHtml( - evaluated - )}"`; - } - } else if (p.name === "html") { - innerHTML = (_a = evaluateConstant(p.exp)) != null ? _a : ""; - } else if (p.name === "text") { - innerHTML = shared.escapeHtml( - shared.toDisplayString(evaluateConstant(p.exp)) - ); - } - } - } - if (context.scopeId) { - res += ` ${context.scopeId}`; - } - res += `>`; - if (innerHTML !== void 0) { - res += innerHTML; - } else { - for (let i = 0; i < node.children.length; i++) { - res += stringifyNode(node.children[i], context); - } - } - if (!shared.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 (shared.isString(c) || shared.isSymbol(c)) { - return; - } - if (c.type === 2) { - res += c.content; - } else if (c.type === 5) { - res += shared.toDisplayString(evaluateConstant(c.content)); - } else { - res += evaluateConstant(c); - } - }); - return res; - } - } - var ignoreSideEffectTags = (node, context) => { - if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) { - context.onError( - createDOMCompilerError( - 64, - node.loc - ) - ); - context.removeNode(); - } - }; - function isValidHTMLNesting(parent, child) { - if (parent === "template") { - return true; - } - if (parent in onlyValidChildren) { - return onlyValidChildren[parent].has(child); - } - if (child in onlyValidParents) { - return onlyValidParents[child].has(parent); - } - if (parent in knownInvalidChildren) { - if (knownInvalidChildren[parent].has(child)) return false; - } - if (child in knownInvalidParents) { - if (knownInvalidParents[child].has(parent)) return false; - } - return true; - } - var headings = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]); - var emptySet = /* @__PURE__ */ new Set([]); - var onlyValidChildren = { - head: /* @__PURE__ */ new Set([ - "base", - "basefront", - "bgsound", - "link", - "meta", - "title", - "noscript", - "noframes", - "style", - "script", - "template" - ]), - optgroup: /* @__PURE__ */ new Set(["option"]), - select: /* @__PURE__ */ new Set(["optgroup", "option", "hr"]), - // table - table: /* @__PURE__ */ new Set(["caption", "colgroup", "tbody", "tfoot", "thead"]), - tr: /* @__PURE__ */ new Set(["td", "th"]), - colgroup: /* @__PURE__ */ new Set(["col"]), - tbody: /* @__PURE__ */ new Set(["tr"]), - thead: /* @__PURE__ */ new Set(["tr"]), - tfoot: /* @__PURE__ */ new Set(["tr"]), - // these elements can not have any children elements - script: emptySet, - iframe: emptySet, - option: emptySet, - textarea: emptySet, - style: emptySet, - title: emptySet - }; - var onlyValidParents = { - // sections - html: emptySet, - body: /* @__PURE__ */ new Set(["html"]), - head: /* @__PURE__ */ new Set(["html"]), - // table - td: /* @__PURE__ */ new Set(["tr"]), - colgroup: /* @__PURE__ */ new Set(["table"]), - caption: /* @__PURE__ */ new Set(["table"]), - tbody: /* @__PURE__ */ new Set(["table"]), - tfoot: /* @__PURE__ */ new Set(["table"]), - col: /* @__PURE__ */ new Set(["colgroup"]), - th: /* @__PURE__ */ new Set(["tr"]), - thead: /* @__PURE__ */ new Set(["table"]), - tr: /* @__PURE__ */ new Set(["tbody", "thead", "tfoot"]), - // data list - dd: /* @__PURE__ */ new Set(["dl", "div"]), - dt: /* @__PURE__ */ new Set(["dl", "div"]), - // other - figcaption: /* @__PURE__ */ new Set(["figure"]), - // li: new Set(["ul", "ol"]), - summary: /* @__PURE__ */ new Set(["details"]), - area: /* @__PURE__ */ new Set(["map"]) - }; - var knownInvalidChildren = { - p: /* @__PURE__ */ new Set([ - "address", - "article", - "aside", - "blockquote", - "center", - "details", - "dialog", - "dir", - "div", - "dl", - "fieldset", - "figure", - "footer", - "form", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "header", - "hgroup", - "hr", - "li", - "main", - "nav", - "menu", - "ol", - "p", - "pre", - "section", - "table", - "ul" - ]), - svg: /* @__PURE__ */ new Set([ - "b", - "blockquote", - "br", - "code", - "dd", - "div", - "dl", - "dt", - "em", - "embed", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "hr", - "i", - "img", - "li", - "menu", - "meta", - "ol", - "p", - "pre", - "ruby", - "s", - "small", - "span", - "strong", - "sub", - "sup", - "table", - "u", - "ul", - "var" - ]) - }; - var knownInvalidParents = { - a: /* @__PURE__ */ new Set(["a"]), - button: /* @__PURE__ */ new Set(["button"]), - dd: /* @__PURE__ */ new Set(["dd", "dt"]), - dt: /* @__PURE__ */ new Set(["dd", "dt"]), - form: /* @__PURE__ */ new Set(["form"]), - li: /* @__PURE__ */ new Set(["li"]), - h1: headings, - h2: headings, - h3: headings, - h4: headings, - h5: headings, - h6: headings - }; - var validateHtmlNesting = (node, context) => { - if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) { - const error = new SyntaxError( - `<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.` - ); - error.loc = node.loc; - context.onWarn(error); - } - }; - var DOMNodeTransforms = [ - transformStyle, - transformTransition, - ...[validateHtmlNesting] - ]; - var DOMDirectiveTransforms = { - cloak: compilerCore.noopDirectiveTransform, - html: transformVHtml, - text: transformVText, - model: transformModel, - // override compiler-core - on: transformOn, - // override compiler-core - show: transformShow - }; - function compile(src, options = {}) { - return compilerCore.baseCompile( - src, - shared.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: shared.extend( - {}, - DOMDirectiveTransforms, - options.directiveTransforms || {} - ), - transformHoist: stringifyStatic - }) - ); - } - function parse(template, options = {}) { - return compilerCore.baseParse(template, shared.extend({}, parserOptions, options)); - } - exports2.DOMDirectiveTransforms = DOMDirectiveTransforms; - exports2.DOMErrorCodes = DOMErrorCodes; - exports2.DOMErrorMessages = DOMErrorMessages; - exports2.DOMNodeTransforms = DOMNodeTransforms; - exports2.TRANSITION = TRANSITION; - exports2.TRANSITION_GROUP = TRANSITION_GROUP; - exports2.V_MODEL_CHECKBOX = V_MODEL_CHECKBOX; - exports2.V_MODEL_DYNAMIC = V_MODEL_DYNAMIC; - exports2.V_MODEL_RADIO = V_MODEL_RADIO; - exports2.V_MODEL_SELECT = V_MODEL_SELECT; - exports2.V_MODEL_TEXT = V_MODEL_TEXT; - exports2.V_ON_WITH_KEYS = V_ON_WITH_KEYS; - exports2.V_ON_WITH_MODIFIERS = V_ON_WITH_MODIFIERS; - exports2.V_SHOW = V_SHOW; - exports2.compile = compile; - exports2.createDOMCompilerError = createDOMCompilerError; - exports2.parse = parse; - exports2.parserOptions = parserOptions; - exports2.transformStyle = transformStyle; - Object.keys(compilerCore).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports2, k)) exports2[k] = compilerCore[k]; - }); - } -}); - -// intern-log/node_modules/.pnpm/@vue+compiler-dom@3.5.44/node_modules/@vue/compiler-dom/index.js -var require_compiler_dom = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+compiler-dom@3.5.44/node_modules/@vue/compiler-dom/index.js"(exports2, module2) { - "use strict"; - if (process.env.NODE_ENV === "production") { - module2.exports = require_compiler_dom_cjs_prod(); - } else { - module2.exports = require_compiler_dom_cjs(); - } - } -}); - -// intern-log/node_modules/.pnpm/@vue+reactivity@3.5.44/node_modules/@vue/reactivity/dist/reactivity.cjs.prod.js -var require_reactivity_cjs_prod = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+reactivity@3.5.44/node_modules/@vue/reactivity/dist/reactivity.cjs.prod.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var shared = require_shared(); - var activeEffectScope; - var EffectScope = class { - // TODO isolatedDeclarations "__v_skip" - constructor(detached = false) { - this.detached = detached; - this._active = true; - this._on = 0; - this.effects = []; - this.cleanups = []; - this._isPaused = false; - this._warnOnRun = true; - this.__v_skip = true; - if (!detached && activeEffectScope) { - if (activeEffectScope.active) { - this.parent = activeEffectScope; - this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( - this - ) - 1; - } else { - this._active = false; - this._warnOnRun = false; - } - } - } - get active() { - return this._active; - } - pause() { - if (this._active) { - this._isPaused = true; - let i, l; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) { - scopes[i].pause(); - } - } - for (i = 0, l = this.effects.length; i < l; i++) { - this.effects[i].pause(); - } - } - } - /** - * Resumes the effect scope, including all child scopes and effects. - */ - resume() { - if (this._active) { - if (this._isPaused) { - this._isPaused = false; - let i, l; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) { - scopes[i].resume(); - } - } - const effects = this.effects.slice(); - for (i = 0, l = effects.length; i < l; i++) { - effects[i].resume(); - } - } - } - } - run(fn) { - if (this._active) { - const currentEffectScope = activeEffectScope; - try { - activeEffectScope = this; - return fn(); - } finally { - activeEffectScope = currentEffectScope; - } - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - on() { - if (++this._on === 1) { - this.prevScope = activeEffectScope; - activeEffectScope = this; - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - off() { - if (this._on > 0 && --this._on === 0) { - if (activeEffectScope === this) { - activeEffectScope = this.prevScope; - } else { - let current = activeEffectScope; - while (current) { - if (current.prevScope === this) { - current.prevScope = this.prevScope; - break; - } - current = current.prevScope; - } - } - this.prevScope = void 0; - } - } - stop(fromParent) { - if (this._active) { - this._active = false; - let i, l; - for (i = 0, l = this.effects.length; i < l; i++) { - this.effects[i].stop(); - } - this.effects.length = 0; - for (i = 0, l = this.cleanups.length; i < l; i++) { - this.cleanups[i](); - } - this.cleanups.length = 0; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) { - scopes[i].stop(true); - } - this.scopes.length = 0; - } - if (!this.detached && this.parent && !fromParent) { - const last = this.parent.scopes.pop(); - if (last && last !== this) { - this.parent.scopes[this.index] = last; - last.index = this.index; - } - } - this.parent = void 0; - } - } - }; - function effectScope(detached) { - return new EffectScope(detached); - } - function getCurrentScope() { - return activeEffectScope; - } - function onScopeDispose(fn, failSilently = false) { - if (activeEffectScope) { - activeEffectScope.cleanups.push(fn); - } - } - var activeSub; - var EffectFlags = { - "ACTIVE": 1, - "1": "ACTIVE", - "RUNNING": 2, - "2": "RUNNING", - "TRACKING": 4, - "4": "TRACKING", - "NOTIFIED": 8, - "8": "NOTIFIED", - "DIRTY": 16, - "16": "DIRTY", - "ALLOW_RECURSE": 32, - "32": "ALLOW_RECURSE", - "PAUSED": 64, - "64": "PAUSED", - "EVALUATED": 128, - "128": "EVALUATED" - }; - var pausedQueueEffects = /* @__PURE__ */ new WeakSet(); - var ReactiveEffect = class { - constructor(fn) { - this.fn = fn; - this.deps = void 0; - this.depsTail = void 0; - this.flags = 1 | 4; - this.next = void 0; - this.cleanup = void 0; - this.scheduler = void 0; - if (activeEffectScope) { - if (activeEffectScope.active) { - activeEffectScope.effects.push(this); - } else { - this.flags &= -2; - } - } - } - pause() { - this.flags |= 64; - } - resume() { - if (this.flags & 64) { - this.flags &= -65; - if (pausedQueueEffects.has(this)) { - pausedQueueEffects.delete(this); - this.trigger(); - } - } - } - /** - * @internal - */ - notify() { - if (this.flags & 2 && !(this.flags & 32)) { - return; - } - if (!(this.flags & 8)) { - batch(this); - } - } - run() { - if (!(this.flags & 1)) { - return this.fn(); - } - this.flags |= 2; - cleanupEffect(this); - prepareDeps(this); - const prevEffect = activeSub; - const prevShouldTrack = shouldTrack; - activeSub = this; - shouldTrack = true; - try { - return this.fn(); - } finally { - cleanupDeps(this); - activeSub = prevEffect; - shouldTrack = prevShouldTrack; - this.flags &= -3; - } - } - stop() { - if (this.flags & 1) { - for (let link = this.deps; link; link = link.nextDep) { - removeSub(link); - } - this.deps = this.depsTail = void 0; - cleanupEffect(this); - this.onStop && this.onStop(); - this.flags &= -2; - } - } - trigger() { - if (this.flags & 64) { - pausedQueueEffects.add(this); - } else if (this.scheduler) { - this.scheduler(); - } else { - this.runIfDirty(); - } - } - /** - * @internal - */ - runIfDirty() { - if (isDirty(this)) { - this.run(); - } - } - get dirty() { - return isDirty(this); - } - }; - var batchDepth = 0; - var batchedSub; - var batchedComputed; - function batch(sub, isComputed = false) { - sub.flags |= 8; - if (isComputed) { - sub.next = batchedComputed; - batchedComputed = sub; - return; - } - sub.next = batchedSub; - batchedSub = sub; - } - function startBatch() { - batchDepth++; - } - function endBatch() { - if (--batchDepth > 0) { - return; - } - if (batchedComputed) { - let e = batchedComputed; - batchedComputed = void 0; - while (e) { - const next = e.next; - e.next = void 0; - e.flags &= -9; - e = next; - } - } - let error; - while (batchedSub) { - let e = batchedSub; - batchedSub = void 0; - while (e) { - const next = e.next; - e.next = void 0; - e.flags &= -9; - if (e.flags & 1) { - try { - ; - e.trigger(); - } catch (err) { - if (!error) error = err; - } - } - e = next; - } - } - if (error) throw error; - } - function prepareDeps(sub) { - for (let link = sub.deps; link; link = link.nextDep) { - link.version = -1; - link.prevActiveLink = link.dep.activeLink; - link.dep.activeLink = link; - } - } - function cleanupDeps(sub) { - let head; - let tail = sub.depsTail; - let link = tail; - while (link) { - const prev = link.prevDep; - if (link.version === -1) { - if (link === tail) tail = prev; - removeSub(link); - removeDep(link); - } else { - head = link; - } - link.dep.activeLink = link.prevActiveLink; - link.prevActiveLink = void 0; - link = prev; - } - sub.deps = head; - sub.depsTail = tail; - } - function isDirty(sub) { - for (let link = sub.deps; link; link = link.nextDep) { - if (link.dep.version !== link.version || link.dep.computed && (refreshComputed(link.dep.computed) || link.dep.version !== link.version)) { - return true; - } - } - if (sub._dirty) { - return true; - } - return false; - } - function refreshComputed(computed2) { - if (computed2.flags & 4 && !(computed2.flags & 16)) { - return; - } - computed2.flags &= -17; - if (computed2.globalVersion === globalVersion) { - return; - } - computed2.globalVersion = globalVersion; - if (!computed2.isSSR && computed2.flags & 128 && (!computed2.deps && !computed2._dirty || !isDirty(computed2))) { - return; - } - computed2.flags |= 2; - const dep = computed2.dep; - const prevSub = activeSub; - const prevShouldTrack = shouldTrack; - activeSub = computed2; - shouldTrack = true; - try { - prepareDeps(computed2); - const value = computed2.fn(computed2._value); - if (dep.version === 0 || shared.hasChanged(value, computed2._value)) { - computed2.flags |= 128; - computed2._value = value; - dep.version++; - } - } catch (err) { - dep.version++; - throw err; - } finally { - activeSub = prevSub; - shouldTrack = prevShouldTrack; - cleanupDeps(computed2); - computed2.flags &= -3; - } - } - function removeSub(link, soft = false) { - const { dep, prevSub, nextSub } = link; - if (prevSub) { - prevSub.nextSub = nextSub; - link.prevSub = void 0; - } - if (nextSub) { - nextSub.prevSub = prevSub; - link.nextSub = void 0; - } - if (dep.subs === link) { - dep.subs = prevSub; - if (!prevSub && dep.computed) { - dep.computed.flags &= -5; - for (let l = dep.computed.deps; l; l = l.nextDep) { - removeSub(l, true); - } - } - } - if (!soft && !--dep.sc && dep.map) { - dep.map.delete(dep.key); - } - } - function removeDep(link) { - const { prevDep, nextDep } = link; - if (prevDep) { - prevDep.nextDep = nextDep; - link.prevDep = void 0; - } - if (nextDep) { - nextDep.prevDep = prevDep; - link.nextDep = void 0; - } - } - function effect(fn, options) { - if (fn.effect instanceof ReactiveEffect) { - fn = fn.effect.fn; - } - const e = new ReactiveEffect(fn); - if (options) { - shared.extend(e, options); - } - try { - e.run(); - } catch (err) { - e.stop(); - throw err; - } - const runner = e.run.bind(e); - runner.effect = e; - return runner; - } - function stop(runner) { - runner.effect.stop(); - } - var shouldTrack = true; - var trackStack = []; - function pauseTracking() { - trackStack.push(shouldTrack); - shouldTrack = false; - } - function enableTracking() { - trackStack.push(shouldTrack); - shouldTrack = true; - } - function resetTracking() { - const last = trackStack.pop(); - shouldTrack = last === void 0 ? true : last; - } - function onEffectCleanup(fn, failSilently = false) { - if (activeSub instanceof ReactiveEffect) { - activeSub.cleanup = fn; - } - } - function cleanupEffect(e) { - const { cleanup } = e; - e.cleanup = void 0; - if (cleanup) { - const prevSub = activeSub; - activeSub = void 0; - try { - cleanup(); - } finally { - activeSub = prevSub; - } - } - } - var globalVersion = 0; - var Link = class { - constructor(sub, dep) { - this.sub = sub; - this.dep = dep; - this.version = dep.version; - this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0; - } - }; - var Dep = class { - // TODO isolatedDeclarations "__v_skip" - constructor(computed2) { - this.computed = computed2; - this.version = 0; - this.activeLink = void 0; - this.subs = void 0; - this.map = void 0; - this.key = void 0; - this.sc = 0; - this.__v_skip = true; - } - track(debugInfo) { - if (!activeSub || !shouldTrack || activeSub === this.computed) { - return; - } - let link = this.activeLink; - if (link === void 0 || link.sub !== activeSub) { - link = this.activeLink = new Link(activeSub, this); - if (!activeSub.deps) { - activeSub.deps = activeSub.depsTail = link; - } else { - link.prevDep = activeSub.depsTail; - activeSub.depsTail.nextDep = link; - activeSub.depsTail = link; - } - addSub(link); - } else if (link.version === -1) { - link.version = this.version; - if (link.nextDep) { - const next = link.nextDep; - next.prevDep = link.prevDep; - if (link.prevDep) { - link.prevDep.nextDep = next; - } - link.prevDep = activeSub.depsTail; - link.nextDep = void 0; - activeSub.depsTail.nextDep = link; - activeSub.depsTail = link; - if (activeSub.deps === link) { - activeSub.deps = next; - } - } - } - return link; - } - trigger(debugInfo) { - this.version++; - globalVersion++; - this.notify(debugInfo); - } - notify(debugInfo) { - startBatch(); - try { - if (false) ; - for (let link = this.subs; link; link = link.prevSub) { - if (link.sub.notify()) { - ; - link.sub.dep.notify(); - } - } - } finally { - endBatch(); - } - } - }; - function addSub(link) { - link.dep.sc++; - if (link.sub.flags & 4) { - const computed2 = link.dep.computed; - if (computed2 && !link.dep.subs) { - computed2.flags |= 4 | 16; - for (let l = computed2.deps; l; l = l.nextDep) { - addSub(l); - } - } - const currentTail = link.dep.subs; - if (currentTail !== link) { - link.prevSub = currentTail; - if (currentTail) currentTail.nextSub = link; - } - link.dep.subs = link; - } - } - var targetMap = /* @__PURE__ */ new WeakMap(); - var ITERATE_KEY = /* @__PURE__ */ Symbol( - "" - ); - var MAP_KEY_ITERATE_KEY = /* @__PURE__ */ Symbol( - "" - ); - var ARRAY_ITERATE_KEY = /* @__PURE__ */ Symbol( - "" - ); - function track(target, type, key) { - if (shouldTrack && activeSub) { - let depsMap = targetMap.get(target); - if (!depsMap) { - targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); - } - let dep = depsMap.get(key); - if (!dep) { - depsMap.set(key, dep = new Dep()); - dep.map = depsMap; - dep.key = key; - } - { - dep.track(); - } - } - } - function trigger(target, type, key, newValue, oldValue, oldTarget) { - const depsMap = targetMap.get(target); - if (!depsMap) { - globalVersion++; - return; - } - const run = (dep) => { - if (dep) { - { - dep.trigger(); - } - } - }; - startBatch(); - if (type === "clear") { - depsMap.forEach(run); - } else { - const targetIsArray = shared.isArray(target); - const isArrayIndex = targetIsArray && shared.isIntegerKey(key); - if (targetIsArray && key === "length") { - const newLength = Number(newValue); - depsMap.forEach((dep, key2) => { - if (key2 === "length" || key2 === ARRAY_ITERATE_KEY || !shared.isSymbol(key2) && key2 >= newLength) { - run(dep); - } - }); - } else { - if (key !== void 0 || depsMap.has(void 0)) { - run(depsMap.get(key)); - } - if (isArrayIndex) { - run(depsMap.get(ARRAY_ITERATE_KEY)); - } - switch (type) { - case "add": - if (!targetIsArray) { - run(depsMap.get(ITERATE_KEY)); - if (shared.isMap(target)) { - run(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } else if (isArrayIndex) { - run(depsMap.get("length")); - } - break; - case "delete": - if (!targetIsArray) { - run(depsMap.get(ITERATE_KEY)); - if (shared.isMap(target)) { - run(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } - break; - case "set": - if (shared.isMap(target)) { - run(depsMap.get(ITERATE_KEY)); - } - break; - } - } - } - endBatch(); - } - function getDepFromReactive(object, key) { - const depMap = targetMap.get(object); - return depMap && depMap.get(key); - } - function reactiveReadArray(array) { - const raw = /* @__PURE__ */ toRaw(array); - if (raw === array) return raw; - track(raw, "iterate", ARRAY_ITERATE_KEY); - if (/* @__PURE__ */ isShallow(array)) return raw; - if (!/* @__PURE__ */ isReadonly(array)) return raw.map(toReactive); - return /* @__PURE__ */ isReactive(array) ? raw.map((item) => toReadonly(toReactive(item))) : raw.map(toReadonly); - } - function shallowReadArray(arr) { - track(arr = /* @__PURE__ */ toRaw(arr), "iterate", ARRAY_ITERATE_KEY); - return arr; - } - function toWrapped(target, item) { - if (/* @__PURE__ */ isReadonly(target)) { - return /* @__PURE__ */ isReactive(target) ? toReadonly(toReactive(item)) : toReadonly(item); - } - return toReactive(item); - } - var arrayInstrumentations = { - __proto__: null, - [Symbol.iterator]() { - return iterator(this, Symbol.iterator, (item) => toWrapped(this, item)); - }, - concat(...args) { - return reactiveReadArray(this).concat( - ...args.map((x) => shared.isArray(x) ? reactiveReadArray(x) : x) - ); - }, - entries() { - return iterator(this, "entries", (value) => { - value[1] = toWrapped(this, value[1]); - return value; - }); - }, - every(fn, thisArg) { - return apply(this, "every", fn, thisArg, void 0, arguments); - }, - filter(fn, thisArg) { - return apply( - this, - "filter", - fn, - thisArg, - (v) => v.map((item) => toWrapped(this, item)), - arguments - ); - }, - find(fn, thisArg) { - return apply( - this, - "find", - fn, - thisArg, - (item) => toWrapped(this, item), - arguments - ); - }, - findIndex(fn, thisArg) { - return apply(this, "findIndex", fn, thisArg, void 0, arguments); - }, - findLast(fn, thisArg) { - return apply( - this, - "findLast", - fn, - thisArg, - (item) => toWrapped(this, item), - arguments - ); - }, - findLastIndex(fn, thisArg) { - return apply(this, "findLastIndex", fn, thisArg, void 0, arguments); - }, - // flat, flatMap could benefit from ARRAY_ITERATE but are not straight-forward to implement - forEach(fn, thisArg) { - return apply(this, "forEach", fn, thisArg, void 0, arguments); - }, - includes(...args) { - return searchProxy(this, "includes", args); - }, - indexOf(...args) { - return searchProxy(this, "indexOf", args); - }, - join(separator) { - return reactiveReadArray(this).join(separator); - }, - // keys() iterator only reads `length`, no optimization required - lastIndexOf(...args) { - return searchProxy(this, "lastIndexOf", args); - }, - map(fn, thisArg) { - return apply(this, "map", fn, thisArg, void 0, arguments); - }, - pop() { - return noTracking(this, "pop"); - }, - push(...args) { - return noTracking(this, "push", args); - }, - reduce(fn, ...args) { - return reduce(this, "reduce", fn, args); - }, - reduceRight(fn, ...args) { - return reduce(this, "reduceRight", fn, args); - }, - shift() { - return noTracking(this, "shift"); - }, - // slice could use ARRAY_ITERATE but also seems to beg for range tracking - some(fn, thisArg) { - return apply(this, "some", fn, thisArg, void 0, arguments); - }, - splice(...args) { - return noTracking(this, "splice", args); - }, - toReversed() { - return reactiveReadArray(this).toReversed(); - }, - toSorted(comparer) { - return reactiveReadArray(this).toSorted(comparer); - }, - toSpliced(...args) { - return reactiveReadArray(this).toSpliced(...args); - }, - unshift(...args) { - return noTracking(this, "unshift", args); - }, - values() { - return iterator(this, "values", (item) => toWrapped(this, item)); - } - }; - function iterator(self2, method, wrapValue) { - const arr = shallowReadArray(self2); - const methodFn = arr[method]; - const iter = methodFn.call(arr); - if (arr !== self2 && !/* @__PURE__ */ isShallow(self2)) { - if (iter[Symbol.toStringTag] === "Array Iterator") { - const wrapped = Object.create(Object.getPrototypeOf(iter)); - wrapped.next = () => wrapResult(iter.next(), wrapValue); - if (methodFn !== arrayProto[method]) { - Object.defineProperties(wrapped, { - return: { - get() { - const fn = iter.return; - return typeof fn === "function" ? fn.bind(iter) : fn; - } - }, - throw: { - get() { - const fn = iter.throw; - return typeof fn === "function" ? fn.bind(iter) : fn; - } - } - }); - } - return wrapped; - } - iter._next = iter.next; - iter.next = () => wrapResult(iter._next(), wrapValue); - } - return iter; - } - function wrapResult(result, wrapValue) { - if (!result.done) { - result.value = wrapValue(result.value); - } - return result; - } - var arrayProto = Array.prototype; - function apply(self2, method, fn, thisArg, wrappedRetFn, args) { - const arr = shallowReadArray(self2); - const needsWrap = arr !== self2 && !/* @__PURE__ */ isShallow(self2); - const methodFn = arr[method]; - if (methodFn !== arrayProto[method]) { - const result2 = methodFn.apply(self2, args); - return needsWrap ? toReactive(result2) : result2; - } - let wrappedFn = fn; - if (arr !== self2) { - if (needsWrap) { - wrappedFn = function(item, index) { - return fn.call(this, toWrapped(self2, item), index, self2); - }; - } else if (fn.length > 2) { - wrappedFn = function(item, index) { - return fn.call(this, item, index, self2); - }; - } - } - const result = methodFn.call(arr, wrappedFn, thisArg); - return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result; - } - function reduce(self2, method, fn, args) { - const arr = shallowReadArray(self2); - const needsWrap = arr !== self2 && !/* @__PURE__ */ isShallow(self2); - let wrappedFn = fn; - let wrapInitialAccumulator = false; - if (arr !== self2) { - if (needsWrap) { - wrapInitialAccumulator = args.length === 0; - wrappedFn = function(acc, item, index) { - if (wrapInitialAccumulator) { - wrapInitialAccumulator = false; - acc = toWrapped(self2, acc); - } - return fn.call(this, acc, toWrapped(self2, item), index, self2); - }; - } else if (fn.length > 3) { - wrappedFn = function(acc, item, index) { - return fn.call(this, acc, item, index, self2); - }; - } - } - const result = arr[method](wrappedFn, ...args); - return wrapInitialAccumulator ? toWrapped(self2, result) : result; - } - function searchProxy(self2, method, args) { - const arr = /* @__PURE__ */ toRaw(self2); - track(arr, "iterate", ARRAY_ITERATE_KEY); - const res = arr[method](...args); - if ((res === -1 || res === false) && /* @__PURE__ */ isProxy(args[0])) { - args[0] = /* @__PURE__ */ toRaw(args[0]); - return arr[method](...args); - } - return res; - } - function noTracking(self2, method, args = []) { - pauseTracking(); - startBatch(); - const res = (/* @__PURE__ */ toRaw(self2))[method].apply(self2, args); - endBatch(); - resetTracking(); - return res; - } - var isNonTrackableKeys = /* @__PURE__ */ shared.makeMap(`__proto__,__v_isRef,__isVue`); - var builtInSymbols = new Set( - /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(shared.isSymbol) - ); - function hasOwnProperty2(key) { - if (!shared.isSymbol(key)) key = String(key); - const obj = /* @__PURE__ */ toRaw(this); - track(obj, "has", key); - return obj.hasOwnProperty(key); - } - var BaseReactiveHandler = class { - constructor(_isReadonly = false, _isShallow = false) { - this._isReadonly = _isReadonly; - this._isShallow = _isShallow; - } - get(target, key, receiver) { - if (key === "__v_skip") return target["__v_skip"]; - const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; - if (key === "__v_isReactive") { - return !isReadonly2; - } else if (key === "__v_isReadonly") { - return isReadonly2; - } else if (key === "__v_isShallow") { - return isShallow2; - } else if (key === "__v_raw") { - if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype - // this means the receiver is a user proxy of the reactive proxy - Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) { - return target; - } - return; - } - const targetIsArray = shared.isArray(target); - if (!isReadonly2) { - let fn; - if (targetIsArray && (fn = arrayInstrumentations[key])) { - return fn; - } - if (key === "hasOwnProperty") { - return hasOwnProperty2; - } - } - const res = Reflect.get( - target, - key, - // if this is a proxy wrapping a ref, return methods using the raw ref - // as receiver so that we don't have to call `toRaw` on the ref in all - // its class methods - /* @__PURE__ */ isRef(target) ? target : receiver - ); - if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { - return res; - } - if (!isReadonly2) { - track(target, "get", key); - } - if (isShallow2) { - return res; - } - if (/* @__PURE__ */ isRef(res)) { - const value = targetIsArray && shared.isIntegerKey(key) ? res : res.value; - return isReadonly2 && shared.isObject(value) ? /* @__PURE__ */ readonly(value) : value; - } - if (shared.isObject(res)) { - return isReadonly2 ? /* @__PURE__ */ readonly(res) : /* @__PURE__ */ reactive(res); - } - return res; - } - }; - var MutableReactiveHandler = class extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(false, isShallow2); - } - set(target, key, value, receiver) { - let oldValue = target[key]; - const isArrayWithIntegerKey = shared.isArray(target) && shared.isIntegerKey(key); - if (!this._isShallow) { - const isOldValueReadonly = /* @__PURE__ */ isReadonly(oldValue); - if (!/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) { - oldValue = /* @__PURE__ */ toRaw(oldValue); - value = /* @__PURE__ */ toRaw(value); - } - if (!isArrayWithIntegerKey && /* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) { - if (isOldValueReadonly) { - return true; - } else { - oldValue.value = value; - return true; - } - } - } - const hadKey = isArrayWithIntegerKey ? Number(key) < target.length : shared.hasOwn(target, key); - const result = Reflect.set( - target, - key, - value, - /* @__PURE__ */ isRef(target) ? target : receiver - ); - if (target === /* @__PURE__ */ toRaw(receiver) && result) { - if (!hadKey) { - trigger(target, "add", key, value); - } else if (shared.hasChanged(value, oldValue)) { - trigger(target, "set", key, value); - } - } - return result; - } - deleteProperty(target, key) { - const hadKey = shared.hasOwn(target, key); - target[key]; - const result = Reflect.deleteProperty(target, key); - if (result && hadKey) { - trigger(target, "delete", key, void 0); - } - return result; - } - has(target, key) { - const result = Reflect.has(target, key); - if (!shared.isSymbol(key) || !builtInSymbols.has(key)) { - track(target, "has", key); - } - return result; - } - ownKeys(target) { - track( - target, - "iterate", - shared.isArray(target) ? "length" : ITERATE_KEY - ); - return Reflect.ownKeys(target); - } - }; - var ReadonlyReactiveHandler = class extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(true, isShallow2); - } - set(target, key) { - return true; - } - deleteProperty(target, key) { - return true; - } - }; - var mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler(); - var readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(); - var shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(true); - var shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true); - var toShallow = (value) => value; - var getProto = (v) => Reflect.getPrototypeOf(v); - function createIterableMethod(method, isReadonly2, isShallow2) { - return function(...args) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const targetIsMap = shared.isMap(rawTarget); - const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; - const isKeyOnly = method === "keys" && targetIsMap; - const innerIterator = target[method](...args); - const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; - !isReadonly2 && track( - rawTarget, - "iterate", - isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY - ); - return shared.extend( - // inheriting all iterator properties - Object.create(innerIterator), - { - // iterator protocol - next() { - const { value, done } = innerIterator.next(); - return done ? { value, done } : { - value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), - done - }; - } - } - ); - }; - } - function createReadonlyMethod(type) { - return function(...args) { - return type === "delete" ? false : type === "clear" ? void 0 : this; - }; - } - function createInstrumentations(readonly2, shallow) { - const instrumentations = { - get(key) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const rawKey = /* @__PURE__ */ toRaw(key); - if (!readonly2) { - if (shared.hasChanged(key, rawKey)) { - track(rawTarget, "get", key); - } - track(rawTarget, "get", rawKey); - } - const { has } = getProto(rawTarget); - const wrap = shallow ? toShallow : readonly2 ? toReadonly : toReactive; - if (has.call(rawTarget, key)) { - return wrap(target.get(key)); - } else if (has.call(rawTarget, rawKey)) { - return wrap(target.get(rawKey)); - } else if (target !== rawTarget) { - target.get(key); - } - }, - get size() { - const target = this["__v_raw"]; - !readonly2 && track(/* @__PURE__ */ toRaw(target), "iterate", ITERATE_KEY); - return target.size; - }, - has(key) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const rawKey = /* @__PURE__ */ toRaw(key); - if (!readonly2) { - if (shared.hasChanged(key, rawKey)) { - track(rawTarget, "has", key); - } - track(rawTarget, "has", rawKey); - } - return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); - }, - forEach(callback, thisArg) { - const observed = this; - const target = observed["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const wrap = shallow ? toShallow : readonly2 ? toReadonly : toReactive; - !readonly2 && track(rawTarget, "iterate", ITERATE_KEY); - return target.forEach((value, key) => { - return callback.call(thisArg, wrap(value), wrap(key), observed); - }); - } - }; - shared.extend( - instrumentations, - readonly2 ? { - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear") - } : { - add(value) { - const target = /* @__PURE__ */ toRaw(this); - const proto = getProto(target); - const rawValue = /* @__PURE__ */ toRaw(value); - const valueToAdd = !shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value) ? rawValue : value; - const hadKey = proto.has.call(target, valueToAdd) || shared.hasChanged(value, valueToAdd) && proto.has.call(target, value) || shared.hasChanged(rawValue, valueToAdd) && proto.has.call(target, rawValue); - if (!hadKey) { - target.add(valueToAdd); - trigger(target, "add", valueToAdd, valueToAdd); - } - return this; - }, - set(key, value) { - if (!shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) { - value = /* @__PURE__ */ toRaw(value); - } - const target = /* @__PURE__ */ toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = /* @__PURE__ */ toRaw(key); - hadKey = has.call(target, key); - } - const oldValue = get.call(target, key); - target.set(key, value); - if (!hadKey) { - trigger(target, "add", key, value); - } else if (shared.hasChanged(value, oldValue)) { - trigger(target, "set", key, value); - } - return this; - }, - delete(key) { - const target = /* @__PURE__ */ toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = /* @__PURE__ */ toRaw(key); - hadKey = has.call(target, key); - } - get ? get.call(target, key) : void 0; - const result = target.delete(key); - if (hadKey) { - trigger(target, "delete", key, void 0); - } - return result; - }, - clear() { - const target = /* @__PURE__ */ toRaw(this); - const hadItems = target.size !== 0; - const result = target.clear(); - if (hadItems) { - trigger( - target, - "clear", - void 0, - void 0 - ); - } - return result; - } - } - ); - const iteratorMethods = [ - "keys", - "values", - "entries", - Symbol.iterator - ]; - iteratorMethods.forEach((method) => { - instrumentations[method] = createIterableMethod(method, readonly2, shallow); - }); - return instrumentations; - } - function createInstrumentationGetter(isReadonly2, shallow) { - const instrumentations = createInstrumentations(isReadonly2, shallow); - return (target, key, receiver) => { - if (key === "__v_isReactive") { - return !isReadonly2; - } else if (key === "__v_isReadonly") { - return isReadonly2; - } else if (key === "__v_isShallow") { - return shallow; - } else if (key === "__v_raw") { - return target; - } - return Reflect.get( - shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target, - key, - receiver - ); - }; - } - var mutableCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, false) - }; - var shallowCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, true) - }; - var readonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, false) - }; - var shallowReadonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, true) - }; - var reactiveMap = /* @__PURE__ */ new WeakMap(); - var shallowReactiveMap = /* @__PURE__ */ new WeakMap(); - var readonlyMap = /* @__PURE__ */ new WeakMap(); - var shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); - function targetTypeMap(rawType) { - switch (rawType) { - case "Object": - case "Array": - return 1; - case "Map": - case "Set": - case "WeakMap": - case "WeakSet": - return 2; - default: - return 0; - } - } - // @__NO_SIDE_EFFECTS__ - function reactive(target) { - if (/* @__PURE__ */ isReadonly(target)) { - return target; - } - return createReactiveObject( - target, - false, - mutableHandlers, - mutableCollectionHandlers, - reactiveMap - ); - } - // @__NO_SIDE_EFFECTS__ - function shallowReactive(target) { - return createReactiveObject( - target, - false, - shallowReactiveHandlers, - shallowCollectionHandlers, - shallowReactiveMap - ); - } - // @__NO_SIDE_EFFECTS__ - function readonly(target) { - return createReactiveObject( - target, - true, - readonlyHandlers, - readonlyCollectionHandlers, - readonlyMap - ); - } - // @__NO_SIDE_EFFECTS__ - function shallowReadonly2(target) { - return createReactiveObject( - target, - true, - shallowReadonlyHandlers, - shallowReadonlyCollectionHandlers, - shallowReadonlyMap - ); - } - function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { - if (!shared.isObject(target)) { - return target; - } - if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { - return target; - } - if (target["__v_skip"] || !Object.isExtensible(target)) { - return target; - } - const existingProxy = proxyMap.get(target); - if (existingProxy) { - return existingProxy; - } - const targetType = targetTypeMap(shared.toRawType(target)); - if (targetType === 0) { - return target; - } - const proxy = new Proxy( - target, - targetType === 2 ? collectionHandlers : baseHandlers - ); - proxyMap.set(target, proxy); - return proxy; - } - // @__NO_SIDE_EFFECTS__ - function isReactive(value) { - if (/* @__PURE__ */ isReadonly(value)) { - return /* @__PURE__ */ isReactive(value["__v_raw"]); - } - return !!(value && value["__v_isReactive"]); - } - // @__NO_SIDE_EFFECTS__ - function isReadonly(value) { - return !!(value && value["__v_isReadonly"]); - } - // @__NO_SIDE_EFFECTS__ - function isShallow(value) { - return !!(value && value["__v_isShallow"]); - } - // @__NO_SIDE_EFFECTS__ - function isProxy(value) { - return value ? !!value["__v_raw"] : false; - } - // @__NO_SIDE_EFFECTS__ - function toRaw(observed) { - const raw = observed && observed["__v_raw"]; - return raw ? /* @__PURE__ */ toRaw(raw) : observed; - } - function markRaw(value) { - if (!shared.hasOwn(value, "__v_skip") && Object.isExtensible(value)) { - shared.def(value, "__v_skip", true); - } - return value; - } - var toReactive = (value) => shared.isObject(value) ? /* @__PURE__ */ reactive(value) : value; - var toReadonly = (value) => shared.isObject(value) ? /* @__PURE__ */ readonly(value) : value; - // @__NO_SIDE_EFFECTS__ - function isRef(r) { - return r ? r["__v_isRef"] === true : false; - } - // @__NO_SIDE_EFFECTS__ - function ref2(value) { - return createRef(value, false); - } - // @__NO_SIDE_EFFECTS__ - function shallowRef(value) { - return createRef(value, true); - } - function createRef(rawValue, shallow) { - if (/* @__PURE__ */ isRef(rawValue)) { - return rawValue; - } - return new RefImpl(rawValue, shallow); - } - var RefImpl = class { - constructor(value, isShallow2) { - this.dep = new Dep(); - this["__v_isRef"] = true; - this["__v_isShallow"] = false; - this._rawValue = isShallow2 ? value : /* @__PURE__ */ toRaw(value); - this._value = isShallow2 ? value : toReactive(value); - this["__v_isShallow"] = isShallow2; - } - get value() { - { - this.dep.track(); - } - return this._value; - } - set value(newValue) { - const oldValue = this._rawValue; - const useDirectValue = this["__v_isShallow"] || /* @__PURE__ */ isShallow(newValue) || /* @__PURE__ */ isReadonly(newValue); - newValue = useDirectValue ? newValue : /* @__PURE__ */ toRaw(newValue); - if (shared.hasChanged(newValue, oldValue)) { - this._rawValue = newValue; - this._value = useDirectValue ? newValue : toReactive(newValue); - { - this.dep.trigger(); - } - } - } - }; - function triggerRef(ref22) { - if (ref22.dep) { - { - ref22.dep.trigger(); - } - } - } - function unref(ref22) { - return /* @__PURE__ */ isRef(ref22) ? ref22.value : ref22; - } - function toValue(source) { - return shared.isFunction(source) ? source() : unref(source); - } - var shallowUnwrapHandlers = { - get: (target, key, receiver) => key === "__v_raw" ? target : unref(Reflect.get(target, key, receiver)), - set: (target, key, value, receiver) => { - const oldValue = target[key]; - if (/* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) { - oldValue.value = value; - return true; - } else { - return Reflect.set(target, key, value, receiver); - } - } - }; - function proxyRefs(objectWithRefs) { - return /* @__PURE__ */ isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); - } - var CustomRefImpl = class { - constructor(factory) { - this["__v_isRef"] = true; - this._value = void 0; - const dep = this.dep = new Dep(); - const { get, set } = factory(dep.track.bind(dep), dep.trigger.bind(dep)); - this._get = get; - this._set = set; - } - get value() { - return this._value = this._get(); - } - set value(newVal) { - this._set(newVal); - } - }; - function customRef(factory) { - return new CustomRefImpl(factory); - } - // @__NO_SIDE_EFFECTS__ - function toRefs(object) { - const ret = shared.isArray(object) ? new Array(object.length) : {}; - for (const key in object) { - ret[key] = propertyToRef(object, key); - } - return ret; - } - var ObjectRefImpl = class { - constructor(_object, key, _defaultValue) { - this._object = _object; - this._defaultValue = _defaultValue; - this["__v_isRef"] = true; - this._value = void 0; - this._key = shared.isSymbol(key) ? key : String(key); - this._raw = /* @__PURE__ */ toRaw(_object); - let shallow = true; - let obj = _object; - if (!shared.isArray(_object) || shared.isSymbol(this._key) || !shared.isIntegerKey(this._key)) { - do { - shallow = !/* @__PURE__ */ isProxy(obj) || /* @__PURE__ */ isShallow(obj); - } while (shallow && (obj = obj["__v_raw"])); - } - this._shallow = shallow; - } - get value() { - let val = this._object[this._key]; - if (this._shallow) { - val = unref(val); - } - return this._value = val === void 0 ? this._defaultValue : val; - } - set value(newVal) { - if (this._shallow && /* @__PURE__ */ isRef(this._raw[this._key])) { - const nestedRef = this._object[this._key]; - if (/* @__PURE__ */ isRef(nestedRef)) { - nestedRef.value = newVal; - return; - } - } - this._object[this._key] = newVal; - } - get dep() { - return getDepFromReactive(this._raw, this._key); - } - }; - var GetterRefImpl = class { - constructor(_getter) { - this._getter = _getter; - this["__v_isRef"] = true; - this["__v_isReadonly"] = true; - this._value = void 0; - } - get value() { - return this._value = this._getter(); - } - }; - // @__NO_SIDE_EFFECTS__ - function toRef(source, key, defaultValue) { - if (/* @__PURE__ */ isRef(source)) { - return source; - } else if (shared.isFunction(source)) { - return new GetterRefImpl(source); - } else if (shared.isObject(source) && arguments.length > 1) { - return propertyToRef(source, key, defaultValue); - } else { - return /* @__PURE__ */ ref2(source); - } - } - function propertyToRef(source, key, defaultValue) { - return new ObjectRefImpl(source, key, defaultValue); - } - var ComputedRefImpl = class { - constructor(fn, setter, isSSR) { - this.fn = fn; - this.setter = setter; - this._value = void 0; - this.dep = new Dep(this); - this.__v_isRef = true; - this.deps = void 0; - this.depsTail = void 0; - this.flags = 16; - this.globalVersion = globalVersion - 1; - this.next = void 0; - this.effect = this; - this["__v_isReadonly"] = !setter; - this.isSSR = isSSR; - } - /** - * @internal - */ - notify() { - this.flags |= 16; - if (!(this.flags & 8) && // avoid infinite self recursion - activeSub !== this) { - batch(this, true); - return true; - } - } - get value() { - const link = this.dep.track(); - refreshComputed(this); - if (link) { - link.version = this.dep.version; - } - return this._value; - } - set value(newValue) { - if (this.setter) { - this.setter(newValue); - } - } - }; - // @__NO_SIDE_EFFECTS__ - function computed(getterOrOptions, debugOptions, isSSR = false) { - let getter; - let setter; - if (shared.isFunction(getterOrOptions)) { - getter = getterOrOptions; - } else { - getter = getterOrOptions.get; - setter = getterOrOptions.set; - } - const cRef = new ComputedRefImpl(getter, setter, isSSR); - return cRef; - } - var TrackOpTypes = { - "GET": "get", - "HAS": "has", - "ITERATE": "iterate" - }; - var TriggerOpTypes = { - "SET": "set", - "ADD": "add", - "DELETE": "delete", - "CLEAR": "clear" - }; - var ReactiveFlags = { - "SKIP": "__v_skip", - "IS_REACTIVE": "__v_isReactive", - "IS_READONLY": "__v_isReadonly", - "IS_SHALLOW": "__v_isShallow", - "RAW": "__v_raw", - "IS_REF": "__v_isRef" - }; - var WatchErrorCodes = { - "WATCH_GETTER": 2, - "2": "WATCH_GETTER", - "WATCH_CALLBACK": 3, - "3": "WATCH_CALLBACK", - "WATCH_CLEANUP": 4, - "4": "WATCH_CLEANUP" - }; - var INITIAL_WATCHER_VALUE = {}; - var cleanupMap = /* @__PURE__ */ new WeakMap(); - var activeWatcher = void 0; - function getCurrentWatcher() { - return activeWatcher; - } - function onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) { - if (owner) { - let cleanups = cleanupMap.get(owner); - if (!cleanups) cleanupMap.set(owner, cleanups = []); - cleanups.push(cleanupFn); - } - } - function watch(source, cb, options = shared.EMPTY_OBJ) { - const { immediate, deep, once, scheduler: scheduler2, augmentJob, call } = options; - const reactiveGetter = (source2) => { - if (deep) return source2; - if (/* @__PURE__ */ isShallow(source2) || deep === false || deep === 0) - return traverse(source2, 1); - return traverse(source2); - }; - let effect2; - let getter; - let cleanup; - let boundCleanup; - let forceTrigger = false; - let isMultiSource = false; - if (/* @__PURE__ */ isRef(source)) { - getter = () => source.value; - forceTrigger = /* @__PURE__ */ isShallow(source); - } else if (/* @__PURE__ */ isReactive(source)) { - getter = () => reactiveGetter(source); - forceTrigger = true; - } else if (shared.isArray(source)) { - isMultiSource = true; - forceTrigger = source.some((s) => /* @__PURE__ */ isReactive(s) || /* @__PURE__ */ isShallow(s)); - getter = () => source.map((s) => { - if (/* @__PURE__ */ isRef(s)) { - return s.value; - } else if (/* @__PURE__ */ isReactive(s)) { - return reactiveGetter(s); - } else if (shared.isFunction(s)) { - return call ? call(s, 2) : s(); - } else ; - }); - } else if (shared.isFunction(source)) { - if (cb) { - getter = call ? () => call(source, 2) : source; - } else { - getter = () => { - if (cleanup) { - pauseTracking(); - try { - cleanup(); - } finally { - resetTracking(); - } - } - const currentEffect = activeWatcher; - activeWatcher = effect2; - try { - return call ? call(source, 3, [boundCleanup]) : source(boundCleanup); - } finally { - activeWatcher = currentEffect; - } - }; - } - } else { - getter = shared.NOOP; - } - if (cb && deep) { - const baseGetter = getter; - const depth = deep === true ? Infinity : deep; - getter = () => traverse(baseGetter(), depth); - } - const scope = getCurrentScope(); - const watchHandle = () => { - effect2.stop(); - if (scope && scope.active) { - shared.remove(scope.effects, effect2); - } - }; - if (once && cb) { - const _cb = cb; - cb = (...args) => { - try { - return _cb(...args); - } finally { - watchHandle(); - } - }; - } - let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE; - const job = (immediateFirstRun) => { - if (!(effect2.flags & 1) || !effect2.dirty && !immediateFirstRun) { - return; - } - if (cb) { - const newValue = effect2.run(); - if (immediateFirstRun || deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => shared.hasChanged(v, oldValue[i])) : shared.hasChanged(newValue, oldValue))) { - const currentWatcher = activeWatcher; - pauseTracking(); - try { - if (cleanup) { - cleanup(); - } - activeWatcher = effect2; - const args = [ - newValue, - // pass undefined as the old value when it's changed for the first time - oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue, - boundCleanup - ]; - oldValue = newValue; - call ? call(cb, 3, args) : ( - // @ts-expect-error - cb(...args) - ); - } finally { - activeWatcher = currentWatcher; - resetTracking(); - } - } - } else { - effect2.run(); - } - }; - if (augmentJob) { - augmentJob(job); - } - effect2 = new ReactiveEffect(getter); - effect2.scheduler = scheduler2 ? () => scheduler2(job, false) : job; - boundCleanup = (fn) => onWatcherCleanup(fn, false, effect2); - cleanup = effect2.onStop = () => { - const cleanups = cleanupMap.get(effect2); - if (cleanups) { - if (call) { - call(cleanups, 4); - } else { - for (const cleanup2 of cleanups) cleanup2(); - } - cleanupMap.delete(effect2); - } - }; - if (cb) { - if (immediate) { - job(true); - } else { - oldValue = effect2.run(); - } - } else if (scheduler2) { - scheduler2(job.bind(null, true), true); - } else { - effect2.run(); - } - watchHandle.pause = effect2.pause.bind(effect2); - watchHandle.resume = effect2.resume.bind(effect2); - watchHandle.stop = watchHandle; - return watchHandle; - } - function traverse(value, depth = Infinity, seen) { - if (depth <= 0 || !shared.isObject(value) || value["__v_skip"]) { - return value; - } - seen = seen || /* @__PURE__ */ new Map(); - if ((seen.get(value) || 0) >= depth) { - return value; - } - seen.set(value, depth); - depth--; - if (/* @__PURE__ */ isRef(value)) { - traverse(value.value, depth, seen); - } else if (shared.isArray(value)) { - for (let i = 0; i < value.length; i++) { - traverse(value[i], depth, seen); - } - } else if (shared.isSet(value) || shared.isMap(value)) { - value.forEach((v) => { - traverse(v, depth, seen); - }); - } else if (shared.isPlainObject(value)) { - for (const key in value) { - traverse(value[key], depth, seen); - } - for (const key of Object.getOwnPropertySymbols(value)) { - if (Object.prototype.propertyIsEnumerable.call(value, key)) { - traverse(value[key], depth, seen); - } - } - } - return value; - } - exports2.ARRAY_ITERATE_KEY = ARRAY_ITERATE_KEY; - exports2.EffectFlags = EffectFlags; - exports2.EffectScope = EffectScope; - exports2.ITERATE_KEY = ITERATE_KEY; - exports2.MAP_KEY_ITERATE_KEY = MAP_KEY_ITERATE_KEY; - exports2.ReactiveEffect = ReactiveEffect; - exports2.ReactiveFlags = ReactiveFlags; - exports2.TrackOpTypes = TrackOpTypes; - exports2.TriggerOpTypes = TriggerOpTypes; - exports2.WatchErrorCodes = WatchErrorCodes; - exports2.computed = computed; - exports2.customRef = customRef; - exports2.effect = effect; - exports2.effectScope = effectScope; - exports2.enableTracking = enableTracking; - exports2.getCurrentScope = getCurrentScope; - exports2.getCurrentWatcher = getCurrentWatcher; - exports2.isProxy = isProxy; - exports2.isReactive = isReactive; - exports2.isReadonly = isReadonly; - exports2.isRef = isRef; - exports2.isShallow = isShallow; - exports2.markRaw = markRaw; - exports2.onEffectCleanup = onEffectCleanup; - exports2.onScopeDispose = onScopeDispose; - exports2.onWatcherCleanup = onWatcherCleanup; - exports2.pauseTracking = pauseTracking; - exports2.proxyRefs = proxyRefs; - exports2.reactive = reactive; - exports2.reactiveReadArray = reactiveReadArray; - exports2.readonly = readonly; - exports2.ref = ref2; - exports2.resetTracking = resetTracking; - exports2.shallowReactive = shallowReactive; - exports2.shallowReadArray = shallowReadArray; - exports2.shallowReadonly = shallowReadonly2; - exports2.shallowRef = shallowRef; - exports2.stop = stop; - exports2.toRaw = toRaw; - exports2.toReactive = toReactive; - exports2.toReadonly = toReadonly; - exports2.toRef = toRef; - exports2.toRefs = toRefs; - exports2.toValue = toValue; - exports2.track = track; - exports2.traverse = traverse; - exports2.trigger = trigger; - exports2.triggerRef = triggerRef; - exports2.unref = unref; - exports2.watch = watch; - } -}); - -// intern-log/node_modules/.pnpm/@vue+reactivity@3.5.44/node_modules/@vue/reactivity/dist/reactivity.cjs.js -var require_reactivity_cjs = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+reactivity@3.5.44/node_modules/@vue/reactivity/dist/reactivity.cjs.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var shared = require_shared(); - function warn2(msg, ...args) { - console.warn(`[Vue warn] ${msg}`, ...args); - } - var activeEffectScope; - var EffectScope = class { - // TODO isolatedDeclarations "__v_skip" - constructor(detached = false) { - this.detached = detached; - this._active = true; - this._on = 0; - this.effects = []; - this.cleanups = []; - this._isPaused = false; - this._warnOnRun = true; - this.__v_skip = true; - if (!detached && activeEffectScope) { - if (activeEffectScope.active) { - this.parent = activeEffectScope; - this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( - this - ) - 1; - } else { - this._active = false; - this._warnOnRun = false; - } - } - } - get active() { - return this._active; - } - pause() { - if (this._active) { - this._isPaused = true; - let i, l; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) { - scopes[i].pause(); - } - } - for (i = 0, l = this.effects.length; i < l; i++) { - this.effects[i].pause(); - } - } - } - /** - * Resumes the effect scope, including all child scopes and effects. - */ - resume() { - if (this._active) { - if (this._isPaused) { - this._isPaused = false; - let i, l; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) { - scopes[i].resume(); - } - } - const effects = this.effects.slice(); - for (i = 0, l = effects.length; i < l; i++) { - effects[i].resume(); - } - } - } - } - run(fn) { - if (this._active) { - const currentEffectScope = activeEffectScope; - try { - activeEffectScope = this; - return fn(); - } finally { - activeEffectScope = currentEffectScope; - } - } else if (this._warnOnRun) { - warn2(`cannot run an inactive effect scope.`); - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - on() { - if (++this._on === 1) { - this.prevScope = activeEffectScope; - activeEffectScope = this; - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - off() { - if (this._on > 0 && --this._on === 0) { - if (activeEffectScope === this) { - activeEffectScope = this.prevScope; - } else { - let current = activeEffectScope; - while (current) { - if (current.prevScope === this) { - current.prevScope = this.prevScope; - break; - } - current = current.prevScope; - } - } - this.prevScope = void 0; - } - } - stop(fromParent) { - if (this._active) { - this._active = false; - let i, l; - for (i = 0, l = this.effects.length; i < l; i++) { - this.effects[i].stop(); - } - this.effects.length = 0; - for (i = 0, l = this.cleanups.length; i < l; i++) { - this.cleanups[i](); - } - this.cleanups.length = 0; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) { - scopes[i].stop(true); - } - this.scopes.length = 0; - } - if (!this.detached && this.parent && !fromParent) { - const last = this.parent.scopes.pop(); - if (last && last !== this) { - this.parent.scopes[this.index] = last; - last.index = this.index; - } - } - this.parent = void 0; - } - } - }; - function effectScope(detached) { - return new EffectScope(detached); - } - function getCurrentScope() { - return activeEffectScope; - } - function onScopeDispose(fn, failSilently = false) { - if (activeEffectScope) { - activeEffectScope.cleanups.push(fn); - } else if (!failSilently) { - warn2( - `onScopeDispose() is called when there is no active effect scope to be associated with.` - ); - } - } - var activeSub; - var EffectFlags = { - "ACTIVE": 1, - "1": "ACTIVE", - "RUNNING": 2, - "2": "RUNNING", - "TRACKING": 4, - "4": "TRACKING", - "NOTIFIED": 8, - "8": "NOTIFIED", - "DIRTY": 16, - "16": "DIRTY", - "ALLOW_RECURSE": 32, - "32": "ALLOW_RECURSE", - "PAUSED": 64, - "64": "PAUSED", - "EVALUATED": 128, - "128": "EVALUATED" - }; - var pausedQueueEffects = /* @__PURE__ */ new WeakSet(); - var ReactiveEffect = class { - constructor(fn) { - this.fn = fn; - this.deps = void 0; - this.depsTail = void 0; - this.flags = 1 | 4; - this.next = void 0; - this.cleanup = void 0; - this.scheduler = void 0; - if (activeEffectScope) { - if (activeEffectScope.active) { - activeEffectScope.effects.push(this); - } else { - this.flags &= -2; - } - } - } - pause() { - this.flags |= 64; - } - resume() { - if (this.flags & 64) { - this.flags &= -65; - if (pausedQueueEffects.has(this)) { - pausedQueueEffects.delete(this); - this.trigger(); - } - } - } - /** - * @internal - */ - notify() { - if (this.flags & 2 && !(this.flags & 32)) { - return; - } - if (!(this.flags & 8)) { - batch(this); - } - } - run() { - if (!(this.flags & 1)) { - return this.fn(); - } - this.flags |= 2; - cleanupEffect(this); - prepareDeps(this); - const prevEffect = activeSub; - const prevShouldTrack = shouldTrack; - activeSub = this; - shouldTrack = true; - try { - return this.fn(); - } finally { - if (activeSub !== this) { - warn2( - "Active effect was not restored correctly - this is likely a Vue internal bug." - ); - } - cleanupDeps(this); - activeSub = prevEffect; - shouldTrack = prevShouldTrack; - this.flags &= -3; - } - } - stop() { - if (this.flags & 1) { - for (let link = this.deps; link; link = link.nextDep) { - removeSub(link); - } - this.deps = this.depsTail = void 0; - cleanupEffect(this); - this.onStop && this.onStop(); - this.flags &= -2; - } - } - trigger() { - if (this.flags & 64) { - pausedQueueEffects.add(this); - } else if (this.scheduler) { - this.scheduler(); - } else { - this.runIfDirty(); - } - } - /** - * @internal - */ - runIfDirty() { - if (isDirty(this)) { - this.run(); - } - } - get dirty() { - return isDirty(this); - } - }; - var batchDepth = 0; - var batchedSub; - var batchedComputed; - function batch(sub, isComputed = false) { - sub.flags |= 8; - if (isComputed) { - sub.next = batchedComputed; - batchedComputed = sub; - return; - } - sub.next = batchedSub; - batchedSub = sub; - } - function startBatch() { - batchDepth++; - } - function endBatch() { - if (--batchDepth > 0) { - return; - } - if (batchedComputed) { - let e = batchedComputed; - batchedComputed = void 0; - while (e) { - const next = e.next; - e.next = void 0; - e.flags &= -9; - e = next; - } - } - let error; - while (batchedSub) { - let e = batchedSub; - batchedSub = void 0; - while (e) { - const next = e.next; - e.next = void 0; - e.flags &= -9; - if (e.flags & 1) { - try { - ; - e.trigger(); - } catch (err) { - if (!error) error = err; - } - } - e = next; - } - } - if (error) throw error; - } - function prepareDeps(sub) { - for (let link = sub.deps; link; link = link.nextDep) { - link.version = -1; - link.prevActiveLink = link.dep.activeLink; - link.dep.activeLink = link; - } - } - function cleanupDeps(sub) { - let head; - let tail = sub.depsTail; - let link = tail; - while (link) { - const prev = link.prevDep; - if (link.version === -1) { - if (link === tail) tail = prev; - removeSub(link); - removeDep(link); - } else { - head = link; - } - link.dep.activeLink = link.prevActiveLink; - link.prevActiveLink = void 0; - link = prev; - } - sub.deps = head; - sub.depsTail = tail; - } - function isDirty(sub) { - for (let link = sub.deps; link; link = link.nextDep) { - if (link.dep.version !== link.version || link.dep.computed && (refreshComputed(link.dep.computed) || link.dep.version !== link.version)) { - return true; - } - } - if (sub._dirty) { - return true; - } - return false; - } - function refreshComputed(computed2) { - if (computed2.flags & 4 && !(computed2.flags & 16)) { - return; - } - computed2.flags &= -17; - if (computed2.globalVersion === globalVersion) { - return; - } - computed2.globalVersion = globalVersion; - if (!computed2.isSSR && computed2.flags & 128 && (!computed2.deps && !computed2._dirty || !isDirty(computed2))) { - return; - } - computed2.flags |= 2; - const dep = computed2.dep; - const prevSub = activeSub; - const prevShouldTrack = shouldTrack; - activeSub = computed2; - shouldTrack = true; - try { - prepareDeps(computed2); - const value = computed2.fn(computed2._value); - if (dep.version === 0 || shared.hasChanged(value, computed2._value)) { - computed2.flags |= 128; - computed2._value = value; - dep.version++; - } - } catch (err) { - dep.version++; - throw err; - } finally { - activeSub = prevSub; - shouldTrack = prevShouldTrack; - cleanupDeps(computed2); - computed2.flags &= -3; - } - } - function removeSub(link, soft = false) { - const { dep, prevSub, nextSub } = link; - if (prevSub) { - prevSub.nextSub = nextSub; - link.prevSub = void 0; - } - if (nextSub) { - nextSub.prevSub = prevSub; - link.nextSub = void 0; - } - if (dep.subsHead === link) { - dep.subsHead = nextSub; - } - if (dep.subs === link) { - dep.subs = prevSub; - if (!prevSub && dep.computed) { - dep.computed.flags &= -5; - for (let l = dep.computed.deps; l; l = l.nextDep) { - removeSub(l, true); - } - } - } - if (!soft && !--dep.sc && dep.map) { - dep.map.delete(dep.key); - } - } - function removeDep(link) { - const { prevDep, nextDep } = link; - if (prevDep) { - prevDep.nextDep = nextDep; - link.prevDep = void 0; - } - if (nextDep) { - nextDep.prevDep = prevDep; - link.nextDep = void 0; - } - } - function effect(fn, options) { - if (fn.effect instanceof ReactiveEffect) { - fn = fn.effect.fn; - } - const e = new ReactiveEffect(fn); - if (options) { - shared.extend(e, options); - } - try { - e.run(); - } catch (err) { - e.stop(); - throw err; - } - const runner = e.run.bind(e); - runner.effect = e; - return runner; - } - function stop(runner) { - runner.effect.stop(); - } - var shouldTrack = true; - var trackStack = []; - function pauseTracking() { - trackStack.push(shouldTrack); - shouldTrack = false; - } - function enableTracking() { - trackStack.push(shouldTrack); - shouldTrack = true; - } - function resetTracking() { - const last = trackStack.pop(); - shouldTrack = last === void 0 ? true : last; - } - function onEffectCleanup(fn, failSilently = false) { - if (activeSub instanceof ReactiveEffect) { - activeSub.cleanup = fn; - } else if (!failSilently) { - warn2( - `onEffectCleanup() was called when there was no active effect to associate with.` - ); - } - } - function cleanupEffect(e) { - const { cleanup } = e; - e.cleanup = void 0; - if (cleanup) { - const prevSub = activeSub; - activeSub = void 0; - try { - cleanup(); - } finally { - activeSub = prevSub; - } - } - } - var globalVersion = 0; - var Link = class { - constructor(sub, dep) { - this.sub = sub; - this.dep = dep; - this.version = dep.version; - this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0; - } - }; - var Dep = class { - // TODO isolatedDeclarations "__v_skip" - constructor(computed2) { - this.computed = computed2; - this.version = 0; - this.activeLink = void 0; - this.subs = void 0; - this.map = void 0; - this.key = void 0; - this.sc = 0; - this.__v_skip = true; - { - this.subsHead = void 0; - } - } - track(debugInfo) { - if (!activeSub || !shouldTrack || activeSub === this.computed) { - return; - } - let link = this.activeLink; - if (link === void 0 || link.sub !== activeSub) { - link = this.activeLink = new Link(activeSub, this); - if (!activeSub.deps) { - activeSub.deps = activeSub.depsTail = link; - } else { - link.prevDep = activeSub.depsTail; - activeSub.depsTail.nextDep = link; - activeSub.depsTail = link; - } - addSub(link); - } else if (link.version === -1) { - link.version = this.version; - if (link.nextDep) { - const next = link.nextDep; - next.prevDep = link.prevDep; - if (link.prevDep) { - link.prevDep.nextDep = next; - } - link.prevDep = activeSub.depsTail; - link.nextDep = void 0; - activeSub.depsTail.nextDep = link; - activeSub.depsTail = link; - if (activeSub.deps === link) { - activeSub.deps = next; - } - } - } - if (activeSub.onTrack) { - activeSub.onTrack( - shared.extend( - { - effect: activeSub - }, - debugInfo - ) - ); - } - return link; - } - trigger(debugInfo) { - this.version++; - globalVersion++; - this.notify(debugInfo); - } - notify(debugInfo) { - startBatch(); - try { - if (true) { - for (let head = this.subsHead; head; head = head.nextSub) { - if (head.sub.onTrigger && !(head.sub.flags & 8)) { - head.sub.onTrigger( - shared.extend( - { - effect: head.sub - }, - debugInfo - ) - ); - } - } - } - for (let link = this.subs; link; link = link.prevSub) { - if (link.sub.notify()) { - ; - link.sub.dep.notify(); - } - } - } finally { - endBatch(); - } - } - }; - function addSub(link) { - link.dep.sc++; - if (link.sub.flags & 4) { - const computed2 = link.dep.computed; - if (computed2 && !link.dep.subs) { - computed2.flags |= 4 | 16; - for (let l = computed2.deps; l; l = l.nextDep) { - addSub(l); - } - } - const currentTail = link.dep.subs; - if (currentTail !== link) { - link.prevSub = currentTail; - if (currentTail) currentTail.nextSub = link; - } - if (link.dep.subsHead === void 0) { - link.dep.subsHead = link; - } - link.dep.subs = link; - } - } - var targetMap = /* @__PURE__ */ new WeakMap(); - var ITERATE_KEY = /* @__PURE__ */ Symbol( - "Object iterate" - ); - var MAP_KEY_ITERATE_KEY = /* @__PURE__ */ Symbol( - "Map keys iterate" - ); - var ARRAY_ITERATE_KEY = /* @__PURE__ */ Symbol( - "Array iterate" - ); - function track(target, type, key) { - if (shouldTrack && activeSub) { - let depsMap = targetMap.get(target); - if (!depsMap) { - targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); - } - let dep = depsMap.get(key); - if (!dep) { - depsMap.set(key, dep = new Dep()); - dep.map = depsMap; - dep.key = key; - } - { - dep.track({ - target, - type, - key - }); - } - } - } - function trigger(target, type, key, newValue, oldValue, oldTarget) { - const depsMap = targetMap.get(target); - if (!depsMap) { - globalVersion++; - return; - } - const run = (dep) => { - if (dep) { - { - dep.trigger({ - target, - type, - key, - newValue, - oldValue, - oldTarget - }); - } - } - }; - startBatch(); - if (type === "clear") { - depsMap.forEach(run); - } else { - const targetIsArray = shared.isArray(target); - const isArrayIndex = targetIsArray && shared.isIntegerKey(key); - if (targetIsArray && key === "length") { - const newLength = Number(newValue); - depsMap.forEach((dep, key2) => { - if (key2 === "length" || key2 === ARRAY_ITERATE_KEY || !shared.isSymbol(key2) && key2 >= newLength) { - run(dep); - } - }); - } else { - if (key !== void 0 || depsMap.has(void 0)) { - run(depsMap.get(key)); - } - if (isArrayIndex) { - run(depsMap.get(ARRAY_ITERATE_KEY)); - } - switch (type) { - case "add": - if (!targetIsArray) { - run(depsMap.get(ITERATE_KEY)); - if (shared.isMap(target)) { - run(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } else if (isArrayIndex) { - run(depsMap.get("length")); - } - break; - case "delete": - if (!targetIsArray) { - run(depsMap.get(ITERATE_KEY)); - if (shared.isMap(target)) { - run(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } - break; - case "set": - if (shared.isMap(target)) { - run(depsMap.get(ITERATE_KEY)); - } - break; - } - } - } - endBatch(); - } - function getDepFromReactive(object, key) { - const depMap = targetMap.get(object); - return depMap && depMap.get(key); - } - function reactiveReadArray(array) { - const raw = /* @__PURE__ */ toRaw(array); - if (raw === array) return raw; - track(raw, "iterate", ARRAY_ITERATE_KEY); - if (/* @__PURE__ */ isShallow(array)) return raw; - if (!/* @__PURE__ */ isReadonly(array)) return raw.map(toReactive); - return /* @__PURE__ */ isReactive(array) ? raw.map((item) => toReadonly(toReactive(item))) : raw.map(toReadonly); - } - function shallowReadArray(arr) { - track(arr = /* @__PURE__ */ toRaw(arr), "iterate", ARRAY_ITERATE_KEY); - return arr; - } - function toWrapped(target, item) { - if (/* @__PURE__ */ isReadonly(target)) { - return /* @__PURE__ */ isReactive(target) ? toReadonly(toReactive(item)) : toReadonly(item); - } - return toReactive(item); - } - var arrayInstrumentations = { - __proto__: null, - [Symbol.iterator]() { - return iterator(this, Symbol.iterator, (item) => toWrapped(this, item)); - }, - concat(...args) { - return reactiveReadArray(this).concat( - ...args.map((x) => shared.isArray(x) ? reactiveReadArray(x) : x) - ); - }, - entries() { - return iterator(this, "entries", (value) => { - value[1] = toWrapped(this, value[1]); - return value; - }); - }, - every(fn, thisArg) { - return apply(this, "every", fn, thisArg, void 0, arguments); - }, - filter(fn, thisArg) { - return apply( - this, - "filter", - fn, - thisArg, - (v) => v.map((item) => toWrapped(this, item)), - arguments - ); - }, - find(fn, thisArg) { - return apply( - this, - "find", - fn, - thisArg, - (item) => toWrapped(this, item), - arguments - ); - }, - findIndex(fn, thisArg) { - return apply(this, "findIndex", fn, thisArg, void 0, arguments); - }, - findLast(fn, thisArg) { - return apply( - this, - "findLast", - fn, - thisArg, - (item) => toWrapped(this, item), - arguments - ); - }, - findLastIndex(fn, thisArg) { - return apply(this, "findLastIndex", fn, thisArg, void 0, arguments); - }, - // flat, flatMap could benefit from ARRAY_ITERATE but are not straight-forward to implement - forEach(fn, thisArg) { - return apply(this, "forEach", fn, thisArg, void 0, arguments); - }, - includes(...args) { - return searchProxy(this, "includes", args); - }, - indexOf(...args) { - return searchProxy(this, "indexOf", args); - }, - join(separator) { - return reactiveReadArray(this).join(separator); - }, - // keys() iterator only reads `length`, no optimization required - lastIndexOf(...args) { - return searchProxy(this, "lastIndexOf", args); - }, - map(fn, thisArg) { - return apply(this, "map", fn, thisArg, void 0, arguments); - }, - pop() { - return noTracking(this, "pop"); - }, - push(...args) { - return noTracking(this, "push", args); - }, - reduce(fn, ...args) { - return reduce(this, "reduce", fn, args); - }, - reduceRight(fn, ...args) { - return reduce(this, "reduceRight", fn, args); - }, - shift() { - return noTracking(this, "shift"); - }, - // slice could use ARRAY_ITERATE but also seems to beg for range tracking - some(fn, thisArg) { - return apply(this, "some", fn, thisArg, void 0, arguments); - }, - splice(...args) { - return noTracking(this, "splice", args); - }, - toReversed() { - return reactiveReadArray(this).toReversed(); - }, - toSorted(comparer) { - return reactiveReadArray(this).toSorted(comparer); - }, - toSpliced(...args) { - return reactiveReadArray(this).toSpliced(...args); - }, - unshift(...args) { - return noTracking(this, "unshift", args); - }, - values() { - return iterator(this, "values", (item) => toWrapped(this, item)); - } - }; - function iterator(self2, method, wrapValue) { - const arr = shallowReadArray(self2); - const methodFn = arr[method]; - const iter = methodFn.call(arr); - if (arr !== self2 && !/* @__PURE__ */ isShallow(self2)) { - if (iter[Symbol.toStringTag] === "Array Iterator") { - const wrapped = Object.create(Object.getPrototypeOf(iter)); - wrapped.next = () => wrapResult(iter.next(), wrapValue); - if (methodFn !== arrayProto[method]) { - Object.defineProperties(wrapped, { - return: { - get() { - const fn = iter.return; - return typeof fn === "function" ? fn.bind(iter) : fn; - } - }, - throw: { - get() { - const fn = iter.throw; - return typeof fn === "function" ? fn.bind(iter) : fn; - } - } - }); - } - return wrapped; - } - iter._next = iter.next; - iter.next = () => wrapResult(iter._next(), wrapValue); - } - return iter; - } - function wrapResult(result, wrapValue) { - if (!result.done) { - result.value = wrapValue(result.value); - } - return result; - } - var arrayProto = Array.prototype; - function apply(self2, method, fn, thisArg, wrappedRetFn, args) { - const arr = shallowReadArray(self2); - const needsWrap = arr !== self2 && !/* @__PURE__ */ isShallow(self2); - const methodFn = arr[method]; - if (methodFn !== arrayProto[method]) { - const result2 = methodFn.apply(self2, args); - return needsWrap ? toReactive(result2) : result2; - } - let wrappedFn = fn; - if (arr !== self2) { - if (needsWrap) { - wrappedFn = function(item, index) { - return fn.call(this, toWrapped(self2, item), index, self2); - }; - } else if (fn.length > 2) { - wrappedFn = function(item, index) { - return fn.call(this, item, index, self2); - }; - } - } - const result = methodFn.call(arr, wrappedFn, thisArg); - return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result; - } - function reduce(self2, method, fn, args) { - const arr = shallowReadArray(self2); - const needsWrap = arr !== self2 && !/* @__PURE__ */ isShallow(self2); - let wrappedFn = fn; - let wrapInitialAccumulator = false; - if (arr !== self2) { - if (needsWrap) { - wrapInitialAccumulator = args.length === 0; - wrappedFn = function(acc, item, index) { - if (wrapInitialAccumulator) { - wrapInitialAccumulator = false; - acc = toWrapped(self2, acc); - } - return fn.call(this, acc, toWrapped(self2, item), index, self2); - }; - } else if (fn.length > 3) { - wrappedFn = function(acc, item, index) { - return fn.call(this, acc, item, index, self2); - }; - } - } - const result = arr[method](wrappedFn, ...args); - return wrapInitialAccumulator ? toWrapped(self2, result) : result; - } - function searchProxy(self2, method, args) { - const arr = /* @__PURE__ */ toRaw(self2); - track(arr, "iterate", ARRAY_ITERATE_KEY); - const res = arr[method](...args); - if ((res === -1 || res === false) && /* @__PURE__ */ isProxy(args[0])) { - args[0] = /* @__PURE__ */ toRaw(args[0]); - return arr[method](...args); - } - return res; - } - function noTracking(self2, method, args = []) { - pauseTracking(); - startBatch(); - const res = (/* @__PURE__ */ toRaw(self2))[method].apply(self2, args); - endBatch(); - resetTracking(); - return res; - } - var isNonTrackableKeys = /* @__PURE__ */ shared.makeMap(`__proto__,__v_isRef,__isVue`); - var builtInSymbols = new Set( - /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(shared.isSymbol) - ); - function hasOwnProperty2(key) { - if (!shared.isSymbol(key)) key = String(key); - const obj = /* @__PURE__ */ toRaw(this); - track(obj, "has", key); - return obj.hasOwnProperty(key); - } - var BaseReactiveHandler = class { - constructor(_isReadonly = false, _isShallow = false) { - this._isReadonly = _isReadonly; - this._isShallow = _isShallow; - } - get(target, key, receiver) { - if (key === "__v_skip") return target["__v_skip"]; - const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; - if (key === "__v_isReactive") { - return !isReadonly2; - } else if (key === "__v_isReadonly") { - return isReadonly2; - } else if (key === "__v_isShallow") { - return isShallow2; - } else if (key === "__v_raw") { - if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype - // this means the receiver is a user proxy of the reactive proxy - Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) { - return target; - } - return; - } - const targetIsArray = shared.isArray(target); - if (!isReadonly2) { - let fn; - if (targetIsArray && (fn = arrayInstrumentations[key])) { - return fn; - } - if (key === "hasOwnProperty") { - return hasOwnProperty2; - } - } - const res = Reflect.get( - target, - key, - // if this is a proxy wrapping a ref, return methods using the raw ref - // as receiver so that we don't have to call `toRaw` on the ref in all - // its class methods - /* @__PURE__ */ isRef(target) ? target : receiver - ); - if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { - return res; - } - if (!isReadonly2) { - track(target, "get", key); - } - if (isShallow2) { - return res; - } - if (/* @__PURE__ */ isRef(res)) { - const value = targetIsArray && shared.isIntegerKey(key) ? res : res.value; - return isReadonly2 && shared.isObject(value) ? /* @__PURE__ */ readonly(value) : value; - } - if (shared.isObject(res)) { - return isReadonly2 ? /* @__PURE__ */ readonly(res) : /* @__PURE__ */ reactive(res); - } - return res; - } - }; - var MutableReactiveHandler = class extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(false, isShallow2); - } - set(target, key, value, receiver) { - let oldValue = target[key]; - const isArrayWithIntegerKey = shared.isArray(target) && shared.isIntegerKey(key); - if (!this._isShallow) { - const isOldValueReadonly = /* @__PURE__ */ isReadonly(oldValue); - if (!/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) { - oldValue = /* @__PURE__ */ toRaw(oldValue); - value = /* @__PURE__ */ toRaw(value); - } - if (!isArrayWithIntegerKey && /* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) { - if (isOldValueReadonly) { - { - warn2( - `Set operation on key "${String(key)}" failed: target is readonly.`, - target[key] - ); - } - return true; - } else { - oldValue.value = value; - return true; - } - } - } - const hadKey = isArrayWithIntegerKey ? Number(key) < target.length : shared.hasOwn(target, key); - const result = Reflect.set( - target, - key, - value, - /* @__PURE__ */ isRef(target) ? target : receiver - ); - if (target === /* @__PURE__ */ toRaw(receiver) && result) { - if (!hadKey) { - trigger(target, "add", key, value); - } else if (shared.hasChanged(value, oldValue)) { - trigger(target, "set", key, value, oldValue); - } - } - return result; - } - deleteProperty(target, key) { - const hadKey = shared.hasOwn(target, key); - const oldValue = target[key]; - const result = Reflect.deleteProperty(target, key); - if (result && hadKey) { - trigger(target, "delete", key, void 0, oldValue); - } - return result; - } - has(target, key) { - const result = Reflect.has(target, key); - if (!shared.isSymbol(key) || !builtInSymbols.has(key)) { - track(target, "has", key); - } - return result; - } - ownKeys(target) { - track( - target, - "iterate", - shared.isArray(target) ? "length" : ITERATE_KEY - ); - return Reflect.ownKeys(target); - } - }; - var ReadonlyReactiveHandler = class extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(true, isShallow2); - } - set(target, key) { - { - warn2( - `Set operation on key "${String(key)}" failed: target is readonly.`, - target - ); - } - return true; - } - deleteProperty(target, key) { - { - warn2( - `Delete operation on key "${String(key)}" failed: target is readonly.`, - target - ); - } - return true; - } - }; - var mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler(); - var readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(); - var shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(true); - var shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true); - var toShallow = (value) => value; - var getProto = (v) => Reflect.getPrototypeOf(v); - function createIterableMethod(method, isReadonly2, isShallow2) { - return function(...args) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const targetIsMap = shared.isMap(rawTarget); - const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; - const isKeyOnly = method === "keys" && targetIsMap; - const innerIterator = target[method](...args); - const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; - !isReadonly2 && track( - rawTarget, - "iterate", - isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY - ); - return shared.extend( - // inheriting all iterator properties - Object.create(innerIterator), - { - // iterator protocol - next() { - const { value, done } = innerIterator.next(); - return done ? { value, done } : { - value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), - done - }; - } - } - ); - }; - } - function createReadonlyMethod(type) { - return function(...args) { - { - const key = args[0] ? `on key "${args[0]}" ` : ``; - warn2( - `${shared.capitalize(type)} operation ${key}failed: target is readonly.`, - /* @__PURE__ */ toRaw(this) - ); - } - return type === "delete" ? false : type === "clear" ? void 0 : this; - }; - } - function createInstrumentations(readonly2, shallow) { - const instrumentations = { - get(key) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const rawKey = /* @__PURE__ */ toRaw(key); - if (!readonly2) { - if (shared.hasChanged(key, rawKey)) { - track(rawTarget, "get", key); - } - track(rawTarget, "get", rawKey); - } - const { has } = getProto(rawTarget); - const wrap = shallow ? toShallow : readonly2 ? toReadonly : toReactive; - if (has.call(rawTarget, key)) { - return wrap(target.get(key)); - } else if (has.call(rawTarget, rawKey)) { - return wrap(target.get(rawKey)); - } else if (target !== rawTarget) { - target.get(key); - } - }, - get size() { - const target = this["__v_raw"]; - !readonly2 && track(/* @__PURE__ */ toRaw(target), "iterate", ITERATE_KEY); - return target.size; - }, - has(key) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const rawKey = /* @__PURE__ */ toRaw(key); - if (!readonly2) { - if (shared.hasChanged(key, rawKey)) { - track(rawTarget, "has", key); - } - track(rawTarget, "has", rawKey); - } - return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); - }, - forEach(callback, thisArg) { - const observed = this; - const target = observed["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const wrap = shallow ? toShallow : readonly2 ? toReadonly : toReactive; - !readonly2 && track(rawTarget, "iterate", ITERATE_KEY); - return target.forEach((value, key) => { - return callback.call(thisArg, wrap(value), wrap(key), observed); - }); - } - }; - shared.extend( - instrumentations, - readonly2 ? { - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear") - } : { - add(value) { - const target = /* @__PURE__ */ toRaw(this); - const proto = getProto(target); - const rawValue = /* @__PURE__ */ toRaw(value); - const valueToAdd = !shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value) ? rawValue : value; - const hadKey = proto.has.call(target, valueToAdd) || shared.hasChanged(value, valueToAdd) && proto.has.call(target, value) || shared.hasChanged(rawValue, valueToAdd) && proto.has.call(target, rawValue); - if (!hadKey) { - target.add(valueToAdd); - trigger(target, "add", valueToAdd, valueToAdd); - } - return this; - }, - set(key, value) { - if (!shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) { - value = /* @__PURE__ */ toRaw(value); - } - const target = /* @__PURE__ */ toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = /* @__PURE__ */ toRaw(key); - hadKey = has.call(target, key); - } else { - checkIdentityKeys(target, has, key); - } - const oldValue = get.call(target, key); - target.set(key, value); - if (!hadKey) { - trigger(target, "add", key, value); - } else if (shared.hasChanged(value, oldValue)) { - trigger(target, "set", key, value, oldValue); - } - return this; - }, - delete(key) { - const target = /* @__PURE__ */ toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = /* @__PURE__ */ toRaw(key); - hadKey = has.call(target, key); - } else { - checkIdentityKeys(target, has, key); - } - const oldValue = get ? get.call(target, key) : void 0; - const result = target.delete(key); - if (hadKey) { - trigger(target, "delete", key, void 0, oldValue); - } - return result; - }, - clear() { - const target = /* @__PURE__ */ toRaw(this); - const hadItems = target.size !== 0; - const oldTarget = shared.isMap(target) ? new Map(target) : new Set(target); - const result = target.clear(); - if (hadItems) { - trigger( - target, - "clear", - void 0, - void 0, - oldTarget - ); - } - return result; - } - } - ); - const iteratorMethods = [ - "keys", - "values", - "entries", - Symbol.iterator - ]; - iteratorMethods.forEach((method) => { - instrumentations[method] = createIterableMethod(method, readonly2, shallow); - }); - return instrumentations; - } - function createInstrumentationGetter(isReadonly2, shallow) { - const instrumentations = createInstrumentations(isReadonly2, shallow); - return (target, key, receiver) => { - if (key === "__v_isReactive") { - return !isReadonly2; - } else if (key === "__v_isReadonly") { - return isReadonly2; - } else if (key === "__v_isShallow") { - return shallow; - } else if (key === "__v_raw") { - return target; - } - return Reflect.get( - shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target, - key, - receiver - ); - }; - } - var mutableCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, false) - }; - var shallowCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, true) - }; - var readonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, false) - }; - var shallowReadonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, true) - }; - function checkIdentityKeys(target, has, key) { - const rawKey = /* @__PURE__ */ toRaw(key); - if (rawKey !== key && has.call(target, rawKey)) { - const type = shared.toRawType(target); - warn2( - `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.` - ); - } - } - var reactiveMap = /* @__PURE__ */ new WeakMap(); - var shallowReactiveMap = /* @__PURE__ */ new WeakMap(); - var readonlyMap = /* @__PURE__ */ new WeakMap(); - var shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); - function targetTypeMap(rawType) { - switch (rawType) { - case "Object": - case "Array": - return 1; - case "Map": - case "Set": - case "WeakMap": - case "WeakSet": - return 2; - default: - return 0; - } - } - // @__NO_SIDE_EFFECTS__ - function reactive(target) { - if (/* @__PURE__ */ isReadonly(target)) { - return target; - } - return createReactiveObject( - target, - false, - mutableHandlers, - mutableCollectionHandlers, - reactiveMap - ); - } - // @__NO_SIDE_EFFECTS__ - function shallowReactive(target) { - return createReactiveObject( - target, - false, - shallowReactiveHandlers, - shallowCollectionHandlers, - shallowReactiveMap - ); - } - // @__NO_SIDE_EFFECTS__ - function readonly(target) { - return createReactiveObject( - target, - true, - readonlyHandlers, - readonlyCollectionHandlers, - readonlyMap - ); - } - // @__NO_SIDE_EFFECTS__ - function shallowReadonly2(target) { - return createReactiveObject( - target, - true, - shallowReadonlyHandlers, - shallowReadonlyCollectionHandlers, - shallowReadonlyMap - ); - } - function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { - if (!shared.isObject(target)) { - { - warn2( - `value cannot be made ${isReadonly2 ? "readonly" : "reactive"}: ${String( - target - )}` - ); - } - return target; - } - if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { - return target; - } - if (target["__v_skip"] || !Object.isExtensible(target)) { - return target; - } - const existingProxy = proxyMap.get(target); - if (existingProxy) { - return existingProxy; - } - const targetType = targetTypeMap(shared.toRawType(target)); - if (targetType === 0) { - return target; - } - const proxy = new Proxy( - target, - targetType === 2 ? collectionHandlers : baseHandlers - ); - proxyMap.set(target, proxy); - return proxy; - } - // @__NO_SIDE_EFFECTS__ - function isReactive(value) { - if (/* @__PURE__ */ isReadonly(value)) { - return /* @__PURE__ */ isReactive(value["__v_raw"]); - } - return !!(value && value["__v_isReactive"]); - } - // @__NO_SIDE_EFFECTS__ - function isReadonly(value) { - return !!(value && value["__v_isReadonly"]); - } - // @__NO_SIDE_EFFECTS__ - function isShallow(value) { - return !!(value && value["__v_isShallow"]); - } - // @__NO_SIDE_EFFECTS__ - function isProxy(value) { - return value ? !!value["__v_raw"] : false; - } - // @__NO_SIDE_EFFECTS__ - function toRaw(observed) { - const raw = observed && observed["__v_raw"]; - return raw ? /* @__PURE__ */ toRaw(raw) : observed; - } - function markRaw(value) { - if (!shared.hasOwn(value, "__v_skip") && Object.isExtensible(value)) { - shared.def(value, "__v_skip", true); - } - return value; - } - var toReactive = (value) => shared.isObject(value) ? /* @__PURE__ */ reactive(value) : value; - var toReadonly = (value) => shared.isObject(value) ? /* @__PURE__ */ readonly(value) : value; - // @__NO_SIDE_EFFECTS__ - function isRef(r) { - return r ? r["__v_isRef"] === true : false; - } - // @__NO_SIDE_EFFECTS__ - function ref2(value) { - return createRef(value, false); - } - // @__NO_SIDE_EFFECTS__ - function shallowRef(value) { - return createRef(value, true); - } - function createRef(rawValue, shallow) { - if (/* @__PURE__ */ isRef(rawValue)) { - return rawValue; - } - return new RefImpl(rawValue, shallow); - } - var RefImpl = class { - constructor(value, isShallow2) { - this.dep = new Dep(); - this["__v_isRef"] = true; - this["__v_isShallow"] = false; - this._rawValue = isShallow2 ? value : /* @__PURE__ */ toRaw(value); - this._value = isShallow2 ? value : toReactive(value); - this["__v_isShallow"] = isShallow2; - } - get value() { - { - this.dep.track({ - target: this, - type: "get", - key: "value" - }); - } - return this._value; - } - set value(newValue) { - const oldValue = this._rawValue; - const useDirectValue = this["__v_isShallow"] || /* @__PURE__ */ isShallow(newValue) || /* @__PURE__ */ isReadonly(newValue); - newValue = useDirectValue ? newValue : /* @__PURE__ */ toRaw(newValue); - if (shared.hasChanged(newValue, oldValue)) { - this._rawValue = newValue; - this._value = useDirectValue ? newValue : toReactive(newValue); - { - this.dep.trigger({ - target: this, - type: "set", - key: "value", - newValue, - oldValue - }); - } - } - } - }; - function triggerRef(ref22) { - if (ref22.dep) { - { - ref22.dep.trigger({ - target: ref22, - type: "set", - key: "value", - newValue: ref22._value - }); - } - } - } - function unref(ref22) { - return /* @__PURE__ */ isRef(ref22) ? ref22.value : ref22; - } - function toValue(source) { - return shared.isFunction(source) ? source() : unref(source); - } - var shallowUnwrapHandlers = { - get: (target, key, receiver) => key === "__v_raw" ? target : unref(Reflect.get(target, key, receiver)), - set: (target, key, value, receiver) => { - const oldValue = target[key]; - if (/* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) { - oldValue.value = value; - return true; - } else { - return Reflect.set(target, key, value, receiver); - } - } - }; - function proxyRefs(objectWithRefs) { - return /* @__PURE__ */ isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); - } - var CustomRefImpl = class { - constructor(factory) { - this["__v_isRef"] = true; - this._value = void 0; - const dep = this.dep = new Dep(); - const { get, set } = factory(dep.track.bind(dep), dep.trigger.bind(dep)); - this._get = get; - this._set = set; - } - get value() { - return this._value = this._get(); - } - set value(newVal) { - this._set(newVal); - } - }; - function customRef(factory) { - return new CustomRefImpl(factory); - } - // @__NO_SIDE_EFFECTS__ - function toRefs(object) { - if (!/* @__PURE__ */ isProxy(object)) { - warn2(`toRefs() expects a reactive object but received a plain one.`); - } - const ret = shared.isArray(object) ? new Array(object.length) : {}; - for (const key in object) { - ret[key] = propertyToRef(object, key); - } - return ret; - } - var ObjectRefImpl = class { - constructor(_object, key, _defaultValue) { - this._object = _object; - this._defaultValue = _defaultValue; - this["__v_isRef"] = true; - this._value = void 0; - this._key = shared.isSymbol(key) ? key : String(key); - this._raw = /* @__PURE__ */ toRaw(_object); - let shallow = true; - let obj = _object; - if (!shared.isArray(_object) || shared.isSymbol(this._key) || !shared.isIntegerKey(this._key)) { - do { - shallow = !/* @__PURE__ */ isProxy(obj) || /* @__PURE__ */ isShallow(obj); - } while (shallow && (obj = obj["__v_raw"])); - } - this._shallow = shallow; - } - get value() { - let val = this._object[this._key]; - if (this._shallow) { - val = unref(val); - } - return this._value = val === void 0 ? this._defaultValue : val; - } - set value(newVal) { - if (this._shallow && /* @__PURE__ */ isRef(this._raw[this._key])) { - const nestedRef = this._object[this._key]; - if (/* @__PURE__ */ isRef(nestedRef)) { - nestedRef.value = newVal; - return; - } - } - this._object[this._key] = newVal; - } - get dep() { - return getDepFromReactive(this._raw, this._key); - } - }; - var GetterRefImpl = class { - constructor(_getter) { - this._getter = _getter; - this["__v_isRef"] = true; - this["__v_isReadonly"] = true; - this._value = void 0; - } - get value() { - return this._value = this._getter(); - } - }; - // @__NO_SIDE_EFFECTS__ - function toRef(source, key, defaultValue) { - if (/* @__PURE__ */ isRef(source)) { - return source; - } else if (shared.isFunction(source)) { - return new GetterRefImpl(source); - } else if (shared.isObject(source) && arguments.length > 1) { - return propertyToRef(source, key, defaultValue); - } else { - return /* @__PURE__ */ ref2(source); - } - } - function propertyToRef(source, key, defaultValue) { - return new ObjectRefImpl(source, key, defaultValue); - } - var ComputedRefImpl = class { - constructor(fn, setter, isSSR) { - this.fn = fn; - this.setter = setter; - this._value = void 0; - this.dep = new Dep(this); - this.__v_isRef = true; - this.deps = void 0; - this.depsTail = void 0; - this.flags = 16; - this.globalVersion = globalVersion - 1; - this.next = void 0; - this.effect = this; - this["__v_isReadonly"] = !setter; - this.isSSR = isSSR; - } - /** - * @internal - */ - notify() { - this.flags |= 16; - if (!(this.flags & 8) && // avoid infinite self recursion - activeSub !== this) { - batch(this, true); - return true; - } - } - get value() { - const link = this.dep.track({ - target: this, - type: "get", - key: "value" - }); - refreshComputed(this); - if (link) { - link.version = this.dep.version; - } - return this._value; - } - set value(newValue) { - if (this.setter) { - this.setter(newValue); - } else { - warn2("Write operation failed: computed value is readonly"); - } - } - }; - // @__NO_SIDE_EFFECTS__ - function computed(getterOrOptions, debugOptions, isSSR = false) { - let getter; - let setter; - if (shared.isFunction(getterOrOptions)) { - getter = getterOrOptions; - } else { - getter = getterOrOptions.get; - setter = getterOrOptions.set; - } - const cRef = new ComputedRefImpl(getter, setter, isSSR); - if (debugOptions && !isSSR) { - cRef.onTrack = debugOptions.onTrack; - cRef.onTrigger = debugOptions.onTrigger; - } - return cRef; - } - var TrackOpTypes = { - "GET": "get", - "HAS": "has", - "ITERATE": "iterate" - }; - var TriggerOpTypes = { - "SET": "set", - "ADD": "add", - "DELETE": "delete", - "CLEAR": "clear" - }; - var ReactiveFlags = { - "SKIP": "__v_skip", - "IS_REACTIVE": "__v_isReactive", - "IS_READONLY": "__v_isReadonly", - "IS_SHALLOW": "__v_isShallow", - "RAW": "__v_raw", - "IS_REF": "__v_isRef" - }; - var WatchErrorCodes = { - "WATCH_GETTER": 2, - "2": "WATCH_GETTER", - "WATCH_CALLBACK": 3, - "3": "WATCH_CALLBACK", - "WATCH_CLEANUP": 4, - "4": "WATCH_CLEANUP" - }; - var INITIAL_WATCHER_VALUE = {}; - var cleanupMap = /* @__PURE__ */ new WeakMap(); - var activeWatcher = void 0; - function getCurrentWatcher() { - return activeWatcher; - } - function onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) { - if (owner) { - let cleanups = cleanupMap.get(owner); - if (!cleanups) cleanupMap.set(owner, cleanups = []); - cleanups.push(cleanupFn); - } else if (!failSilently) { - warn2( - `onWatcherCleanup() was called when there was no active watcher to associate with.` - ); - } - } - function watch(source, cb, options = shared.EMPTY_OBJ) { - const { immediate, deep, once, scheduler: scheduler2, augmentJob, call } = options; - const warnInvalidSource = (s) => { - (options.onWarn || warn2)( - `Invalid watch source: `, - s, - `A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.` - ); - }; - const reactiveGetter = (source2) => { - if (deep) return source2; - if (/* @__PURE__ */ isShallow(source2) || deep === false || deep === 0) - return traverse(source2, 1); - return traverse(source2); - }; - let effect2; - let getter; - let cleanup; - let boundCleanup; - let forceTrigger = false; - let isMultiSource = false; - if (/* @__PURE__ */ isRef(source)) { - getter = () => source.value; - forceTrigger = /* @__PURE__ */ isShallow(source); - } else if (/* @__PURE__ */ isReactive(source)) { - getter = () => reactiveGetter(source); - forceTrigger = true; - } else if (shared.isArray(source)) { - isMultiSource = true; - forceTrigger = source.some((s) => /* @__PURE__ */ isReactive(s) || /* @__PURE__ */ isShallow(s)); - getter = () => source.map((s) => { - if (/* @__PURE__ */ isRef(s)) { - return s.value; - } else if (/* @__PURE__ */ isReactive(s)) { - return reactiveGetter(s); - } else if (shared.isFunction(s)) { - return call ? call(s, 2) : s(); - } else { - warnInvalidSource(s); - } - }); - } else if (shared.isFunction(source)) { - if (cb) { - getter = call ? () => call(source, 2) : source; - } else { - getter = () => { - if (cleanup) { - pauseTracking(); - try { - cleanup(); - } finally { - resetTracking(); - } - } - const currentEffect = activeWatcher; - activeWatcher = effect2; - try { - return call ? call(source, 3, [boundCleanup]) : source(boundCleanup); - } finally { - activeWatcher = currentEffect; - } - }; - } - } else { - getter = shared.NOOP; - warnInvalidSource(source); - } - if (cb && deep) { - const baseGetter = getter; - const depth = deep === true ? Infinity : deep; - getter = () => traverse(baseGetter(), depth); - } - const scope = getCurrentScope(); - const watchHandle = () => { - effect2.stop(); - if (scope && scope.active) { - shared.remove(scope.effects, effect2); - } - }; - if (once && cb) { - const _cb = cb; - cb = (...args) => { - try { - return _cb(...args); - } finally { - watchHandle(); - } - }; - } - let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE; - const job = (immediateFirstRun) => { - if (!(effect2.flags & 1) || !effect2.dirty && !immediateFirstRun) { - return; - } - if (cb) { - const newValue = effect2.run(); - if (immediateFirstRun || deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => shared.hasChanged(v, oldValue[i])) : shared.hasChanged(newValue, oldValue))) { - const currentWatcher = activeWatcher; - pauseTracking(); - try { - if (cleanup) { - cleanup(); - } - activeWatcher = effect2; - const args = [ - newValue, - // pass undefined as the old value when it's changed for the first time - oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue, - boundCleanup - ]; - oldValue = newValue; - call ? call(cb, 3, args) : ( - // @ts-expect-error - cb(...args) - ); - } finally { - activeWatcher = currentWatcher; - resetTracking(); - } - } - } else { - effect2.run(); - } - }; - if (augmentJob) { - augmentJob(job); - } - effect2 = new ReactiveEffect(getter); - effect2.scheduler = scheduler2 ? () => scheduler2(job, false) : job; - boundCleanup = (fn) => onWatcherCleanup(fn, false, effect2); - cleanup = effect2.onStop = () => { - const cleanups = cleanupMap.get(effect2); - if (cleanups) { - if (call) { - call(cleanups, 4); - } else { - for (const cleanup2 of cleanups) cleanup2(); - } - cleanupMap.delete(effect2); - } - }; - { - effect2.onTrack = options.onTrack; - effect2.onTrigger = options.onTrigger; - } - if (cb) { - if (immediate) { - job(true); - } else { - oldValue = effect2.run(); - } - } else if (scheduler2) { - scheduler2(job.bind(null, true), true); - } else { - effect2.run(); - } - watchHandle.pause = effect2.pause.bind(effect2); - watchHandle.resume = effect2.resume.bind(effect2); - watchHandle.stop = watchHandle; - return watchHandle; - } - function traverse(value, depth = Infinity, seen) { - if (depth <= 0 || !shared.isObject(value) || value["__v_skip"]) { - return value; - } - seen = seen || /* @__PURE__ */ new Map(); - if ((seen.get(value) || 0) >= depth) { - return value; - } - seen.set(value, depth); - depth--; - if (/* @__PURE__ */ isRef(value)) { - traverse(value.value, depth, seen); - } else if (shared.isArray(value)) { - for (let i = 0; i < value.length; i++) { - traverse(value[i], depth, seen); - } - } else if (shared.isSet(value) || shared.isMap(value)) { - value.forEach((v) => { - traverse(v, depth, seen); - }); - } else if (shared.isPlainObject(value)) { - for (const key in value) { - traverse(value[key], depth, seen); - } - for (const key of Object.getOwnPropertySymbols(value)) { - if (Object.prototype.propertyIsEnumerable.call(value, key)) { - traverse(value[key], depth, seen); - } - } - } - return value; - } - exports2.ARRAY_ITERATE_KEY = ARRAY_ITERATE_KEY; - exports2.EffectFlags = EffectFlags; - exports2.EffectScope = EffectScope; - exports2.ITERATE_KEY = ITERATE_KEY; - exports2.MAP_KEY_ITERATE_KEY = MAP_KEY_ITERATE_KEY; - exports2.ReactiveEffect = ReactiveEffect; - exports2.ReactiveFlags = ReactiveFlags; - exports2.TrackOpTypes = TrackOpTypes; - exports2.TriggerOpTypes = TriggerOpTypes; - exports2.WatchErrorCodes = WatchErrorCodes; - exports2.computed = computed; - exports2.customRef = customRef; - exports2.effect = effect; - exports2.effectScope = effectScope; - exports2.enableTracking = enableTracking; - exports2.getCurrentScope = getCurrentScope; - exports2.getCurrentWatcher = getCurrentWatcher; - exports2.isProxy = isProxy; - exports2.isReactive = isReactive; - exports2.isReadonly = isReadonly; - exports2.isRef = isRef; - exports2.isShallow = isShallow; - exports2.markRaw = markRaw; - exports2.onEffectCleanup = onEffectCleanup; - exports2.onScopeDispose = onScopeDispose; - exports2.onWatcherCleanup = onWatcherCleanup; - exports2.pauseTracking = pauseTracking; - exports2.proxyRefs = proxyRefs; - exports2.reactive = reactive; - exports2.reactiveReadArray = reactiveReadArray; - exports2.readonly = readonly; - exports2.ref = ref2; - exports2.resetTracking = resetTracking; - exports2.shallowReactive = shallowReactive; - exports2.shallowReadArray = shallowReadArray; - exports2.shallowReadonly = shallowReadonly2; - exports2.shallowRef = shallowRef; - exports2.stop = stop; - exports2.toRaw = toRaw; - exports2.toReactive = toReactive; - exports2.toReadonly = toReadonly; - exports2.toRef = toRef; - exports2.toRefs = toRefs; - exports2.toValue = toValue; - exports2.track = track; - exports2.traverse = traverse; - exports2.trigger = trigger; - exports2.triggerRef = triggerRef; - exports2.unref = unref; - exports2.watch = watch; - } -}); - -// intern-log/node_modules/.pnpm/@vue+reactivity@3.5.44/node_modules/@vue/reactivity/index.js -var require_reactivity = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+reactivity@3.5.44/node_modules/@vue/reactivity/index.js"(exports2, module2) { - "use strict"; - if (process.env.NODE_ENV === "production") { - module2.exports = require_reactivity_cjs_prod(); - } else { - module2.exports = require_reactivity_cjs(); - } - } -}); - -// intern-log/node_modules/.pnpm/@vue+runtime-core@3.5.44/node_modules/@vue/runtime-core/dist/runtime-core.cjs.prod.js -var require_runtime_core_cjs_prod = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+runtime-core@3.5.44/node_modules/@vue/runtime-core/dist/runtime-core.cjs.prod.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var reactivity = require_reactivity(); - var shared = require_shared(); - function pushWarningContext(vnode) { - } - function popWarningContext() { - } - function assertNumber(val, type) { - return; - } - var ErrorCodes = { - "SETUP_FUNCTION": 0, - "0": "SETUP_FUNCTION", - "RENDER_FUNCTION": 1, - "1": "RENDER_FUNCTION", - "NATIVE_EVENT_HANDLER": 5, - "5": "NATIVE_EVENT_HANDLER", - "COMPONENT_EVENT_HANDLER": 6, - "6": "COMPONENT_EVENT_HANDLER", - "VNODE_HOOK": 7, - "7": "VNODE_HOOK", - "DIRECTIVE_HOOK": 8, - "8": "DIRECTIVE_HOOK", - "TRANSITION_HOOK": 9, - "9": "TRANSITION_HOOK", - "APP_ERROR_HANDLER": 10, - "10": "APP_ERROR_HANDLER", - "APP_WARN_HANDLER": 11, - "11": "APP_WARN_HANDLER", - "FUNCTION_REF": 12, - "12": "FUNCTION_REF", - "ASYNC_COMPONENT_LOADER": 13, - "13": "ASYNC_COMPONENT_LOADER", - "SCHEDULER": 14, - "14": "SCHEDULER", - "COMPONENT_UPDATE": 15, - "15": "COMPONENT_UPDATE", - "APP_UNMOUNT_CLEANUP": 16, - "16": "APP_UNMOUNT_CLEANUP" - }; - var ErrorTypeStrings$1 = { - ["sp"]: "serverPrefetch hook", - ["bc"]: "beforeCreate hook", - ["c"]: "created hook", - ["bm"]: "beforeMount hook", - ["m"]: "mounted hook", - ["bu"]: "beforeUpdate hook", - ["u"]: "updated", - ["bum"]: "beforeUnmount hook", - ["um"]: "unmounted hook", - ["a"]: "activated hook", - ["da"]: "deactivated hook", - ["ec"]: "errorCaptured hook", - ["rtc"]: "renderTracked hook", - ["rtg"]: "renderTriggered hook", - [0]: "setup function", - [1]: "render function", - [2]: "watcher getter", - [3]: "watcher callback", - [4]: "watcher cleanup function", - [5]: "native event handler", - [6]: "component event handler", - [7]: "vnode hook", - [8]: "directive hook", - [9]: "transition hook", - [10]: "app errorHandler", - [11]: "app warnHandler", - [12]: "ref function", - [13]: "async component loader", - [14]: "scheduler flush", - [15]: "component update", - [16]: "app unmount cleanup function" - }; - function callWithErrorHandling(fn, instance, type, args) { - try { - return args ? fn(...args) : fn(); - } catch (err) { - handleError(err, instance, type); - } - } - function callWithAsyncErrorHandling(fn, instance, type, args) { - if (shared.isFunction(fn)) { - const res = callWithErrorHandling(fn, instance, type, args); - if (res && shared.isPromise(res)) { - res.catch((err) => { - handleError(err, instance, type); - }); - } - return res; - } - if (shared.isArray(fn)) { - const values = []; - for (let i = 0; i < fn.length; i++) { - values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)); - } - return values; - } - } - function handleError(err, instance, type, throwInDev = true) { - const contextVNode = instance ? instance.vnode : null; - const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || shared.EMPTY_OBJ; - if (instance) { - let cur = instance.parent; - const exposedInstance = instance.proxy; - const errorInfo = `https://vuejs.org/error-reference/#runtime-${type}`; - while (cur) { - const errorCapturedHooks = cur.ec; - if (errorCapturedHooks) { - for (let i = 0; i < errorCapturedHooks.length; i++) { - if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) { - return; - } - } - } - cur = cur.parent; - } - if (errorHandler) { - reactivity.pauseTracking(); - callWithErrorHandling(errorHandler, null, 10, [ - err, - exposedInstance, - errorInfo - ]); - reactivity.resetTracking(); - return; - } - } - logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction); - } - function logError(err, type, contextVNode, throwInDev = true, throwInProd = false) { - if (throwInProd) { - throw err; - } else { - console.error(err); - } - } - var queue = []; - var flushIndex = -1; - var pendingPostFlushCbs = []; - var activePostFlushCbs = null; - var postFlushIndex = 0; - var resolvedPromise = /* @__PURE__ */ Promise.resolve(); - var currentFlushPromise = null; - function nextTick(fn) { - const p = currentFlushPromise || resolvedPromise; - return fn ? p.then(this ? fn.bind(this) : fn) : p; - } - function findInsertionIndex(id) { - let start = flushIndex + 1; - let end = queue.length; - while (start < end) { - const middle = start + end >>> 1; - const middleJob = queue[middle]; - const middleJobId = getId(middleJob); - if (middleJobId < id || middleJobId === id && middleJob.flags & 2) { - start = middle + 1; - } else { - end = middle; - } - } - return start; - } - function queueJob(job) { - if (!(job.flags & 1)) { - const jobId = getId(job); - const lastJob = queue[queue.length - 1]; - if (!lastJob || // fast path when the job id is larger than the tail - !(job.flags & 2) && jobId >= getId(lastJob)) { - queue.push(job); - } else { - queue.splice(findInsertionIndex(jobId), 0, job); - } - job.flags |= 1; - queueFlush(); - } - } - function queueFlush() { - if (!currentFlushPromise) { - currentFlushPromise = resolvedPromise.then(flushJobs); - } - } - function queuePostFlushCb(cb) { - if (!shared.isArray(cb)) { - if (activePostFlushCbs && cb.id === -1) { - activePostFlushCbs.splice(postFlushIndex + 1, 0, cb); - } else if (!(cb.flags & 1)) { - pendingPostFlushCbs.push(cb); - cb.flags |= 1; - } - } else { - for (let i = 0; i < cb.length; i++) { - pendingPostFlushCbs.push(cb[i]); - } - } - queueFlush(); - } - function flushPreFlushCbs(instance, minUid, seen, i = flushIndex + 1) { - for (; i < queue.length; i++) { - const cb = queue[i]; - if (cb && cb.flags & 2) { - if (instance && cb.id !== instance.uid || minUid !== void 0 && !(cb.id >= minUid)) { - continue; - } - queue.splice(i, 1); - i = instance ? i - 1 : flushIndex; - if (cb.flags & 4) { - cb.flags &= -2; - } - cb(); - if (!(cb.flags & 4)) { - cb.flags &= -2; - } - } - } - } - function flushPostFlushCbs(seen, skip, minUid = 0) { - if (pendingPostFlushCbs.length) { - let cbs = pendingPostFlushCbs; - let kept = 0; - if (skip) { - cbs = []; - for (let i = 0; i < pendingPostFlushCbs.length; i++) { - const cb = pendingPostFlushCbs[i]; - if (cb.i !== void 0 ? !cb.i || cb.i.uid < minUid : skip.has(cb)) { - pendingPostFlushCbs[kept++] = cb; - } else { - cbs.push(cb); - } - } - } - const deduped = [...new Set(cbs)].sort((a, b) => getId(a) - getId(b)); - pendingPostFlushCbs.length = kept; - if (activePostFlushCbs) { - for (let i = 0; i < deduped.length; i++) { - activePostFlushCbs.push(deduped[i]); - } - return; - } - activePostFlushCbs = deduped; - for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { - const cb = activePostFlushCbs[postFlushIndex]; - if (cb.flags & 4) { - cb.flags &= -2; - } - if (!(cb.flags & 8)) cb(); - cb.flags &= -2; - } - activePostFlushCbs = null; - postFlushIndex = 0; - } - } - var isFlushing = false; - function flushOnAppMount(fn, minUid) { - if (isFlushing) { - fn(); - return; - } - const queued = minUid === void 0 ? void 0 : new Set(pendingPostFlushCbs); - fn(); - isFlushing = true; - try { - flushPreFlushCbs(void 0, minUid); - flushPostFlushCbs(void 0, queued, minUid); - } finally { - isFlushing = false; - } - } - var getId = (job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id; - function flushJobs(seen) { - try { - for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job && !(job.flags & 8)) { - if (false) ; - if (job.flags & 4) { - job.flags &= ~1; - } - callWithErrorHandling( - job, - job.i, - job.i ? 15 : 14 - ); - if (!(job.flags & 4)) { - job.flags &= ~1; - } - } - } - } finally { - for (; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job) { - job.flags &= -2; - } - } - flushIndex = -1; - queue.length = 0; - flushPostFlushCbs(); - currentFlushPromise = null; - if (queue.length || pendingPostFlushCbs.length) { - flushJobs(); - } - } - } - var currentRenderingInstance = null; - var currentScopeId = null; - function setCurrentRenderingInstance(instance) { - const prev = currentRenderingInstance; - currentRenderingInstance = instance; - currentScopeId = instance && instance.type.__scopeId || null; - return prev; - } - function pushScopeId(id) { - currentScopeId = id; - } - function popScopeId() { - currentScopeId = null; - } - var withScopeId = (_id) => withCtx; - function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { - if (!ctx) return fn; - if (fn._n) { - return fn; - } - const renderFnWithContext = (...args) => { - if (renderFnWithContext._d) { - setBlockTracking(-1); - } - const prevInstance = setCurrentRenderingInstance(ctx); - const prevStackSize = blockStack.length; - let res; - try { - res = fn(...args); - } finally { - for (let i = blockStack.length; i > prevStackSize; i--) closeBlock(); - setCurrentRenderingInstance(prevInstance); - if (renderFnWithContext._d) { - setBlockTracking(1); - } - } - return res; - }; - renderFnWithContext._n = true; - renderFnWithContext._c = true; - renderFnWithContext._d = true; - return renderFnWithContext; - } - function withDirectives(vnode, directives) { - if (currentRenderingInstance === null) { - return vnode; - } - const instance = getComponentPublicInstance(currentRenderingInstance); - const bindings = vnode.dirs || (vnode.dirs = []); - for (let i = 0; i < directives.length; i++) { - let [dir, value, arg, modifiers = shared.EMPTY_OBJ] = directives[i]; - if (dir) { - if (shared.isFunction(dir)) { - dir = { - mounted: dir, - updated: dir - }; - } - if (dir.deep) { - reactivity.traverse(value); - } - bindings.push({ - dir, - instance, - value, - oldValue: void 0, - arg, - modifiers - }); - } - } - return vnode; - } - function invokeDirectiveHook(vnode, prevVNode, instance, name) { - const bindings = vnode.dirs; - const oldBindings = prevVNode && prevVNode.dirs; - for (let i = 0; i < bindings.length; i++) { - const binding = bindings[i]; - if (oldBindings) { - binding.oldValue = oldBindings[i].value; - } - let hook = binding.dir[name]; - if (hook) { - reactivity.pauseTracking(); - callWithAsyncErrorHandling(hook, instance, 8, [ - vnode.el, - binding, - vnode, - prevVNode - ]); - reactivity.resetTracking(); - } - } - } - function provide(key, value) { - if (currentInstance) { - let provides = currentInstance.provides; - const parentProvides = currentInstance.parent && currentInstance.parent.provides; - if (parentProvides === provides) { - provides = currentInstance.provides = Object.create(parentProvides); - } - provides[key] = value; - } - } - function inject(key, defaultValue, treatDefaultAsFactory = false) { - const instance = getCurrentInstance(); - if (instance || currentApp) { - let provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null || instance.ce ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0; - if (provides && key in provides) { - return provides[key]; - } else if (arguments.length > 1) { - return treatDefaultAsFactory && shared.isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue; - } else ; - } - } - function hasInjectionContext() { - return !!(getCurrentInstance() || currentApp); - } - var ssrContextKey = /* @__PURE__ */ Symbol.for("v-scx"); - var useSSRContext = () => { - { - const ctx = inject(ssrContextKey); - return ctx; - } - }; - function watchEffect(effect, options) { - return doWatch(effect, null, options); - } - function watchPostEffect(effect, options) { - return doWatch( - effect, - null, - { flush: "post" } - ); - } - function watchSyncEffect(effect, options) { - return doWatch( - effect, - null, - { flush: "sync" } - ); - } - function watch(source, cb, options) { - return doWatch(source, cb, options); - } - function doWatch(source, cb, options = shared.EMPTY_OBJ) { - const { immediate, deep, flush, once } = options; - const baseWatchOptions = shared.extend({}, options); - const runsImmediately = cb && immediate || !cb && flush !== "post"; - let ssrCleanup; - if (isInSSRComponentSetup) { - if (flush === "sync") { - const ctx = useSSRContext(); - ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []); - } else if (!runsImmediately) { - const watchStopHandle = () => { - }; - watchStopHandle.stop = shared.NOOP; - watchStopHandle.resume = shared.NOOP; - watchStopHandle.pause = shared.NOOP; - return watchStopHandle; - } - } - const instance = currentInstance; - baseWatchOptions.call = (fn, type, args) => callWithAsyncErrorHandling(fn, instance, type, args); - let isPre = false; - if (flush === "post") { - baseWatchOptions.scheduler = (job) => { - job.i = instance; - queuePostRenderEffect(job, instance && instance.suspense); - }; - } else if (flush !== "sync") { - isPre = true; - baseWatchOptions.scheduler = (job, isFirstRun) => { - if (isFirstRun) { - job(); - } else { - queueJob(job); - } - }; - } - baseWatchOptions.augmentJob = (job) => { - if (cb) { - job.flags |= 4; - } - if (isPre) { - job.flags |= 2; - if (instance) { - job.id = instance.uid; - job.i = instance; - } - } - }; - const watchHandle = reactivity.watch(source, cb, baseWatchOptions); - if (isInSSRComponentSetup) { - if (ssrCleanup) { - ssrCleanup.push(watchHandle); - } else if (runsImmediately) { - watchHandle(); - } - } - return watchHandle; - } - function instanceWatch(source, value, options) { - const publicThis = this.proxy; - const getter = shared.isString(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); - let cb; - if (shared.isFunction(value)) { - cb = value; - } else { - cb = value.handler; - options = value; - } - const reset = setCurrentInstance(this); - const res = doWatch(getter, cb.bind(publicThis), options); - reset(); - return res; - } - function createPathGetter(ctx, path) { - const segments = path.split("."); - return () => { - let cur = ctx; - for (let i = 0; i < segments.length && cur; i++) { - cur = cur[segments[i]]; - } - return cur; - }; - } - var pendingMounts = /* @__PURE__ */ new WeakMap(); - var TeleportEndKey = /* @__PURE__ */ Symbol("_vte"); - var isTeleport = (type) => type.__isTeleport; - var isTeleportDisabled = (props) => props && (props.disabled || props.disabled === ""); - var isTeleportDeferred = (props) => props && (props.defer || props.defer === ""); - var isTargetSVG = (target) => typeof SVGElement !== "undefined" && target instanceof SVGElement; - var isTargetMathML = (target) => typeof MathMLElement === "function" && target instanceof MathMLElement; - var resolveTarget = (props, select) => { - const targetSelector = props && props.to; - if (shared.isString(targetSelector)) { - if (!select) { - return null; - } else { - const target = select(targetSelector); - return target; - } - } else { - return targetSelector; - } - }; - var TeleportImpl = { - name: "Teleport", - __isTeleport: true, - process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals) { - const { - mc: mountChildren, - pc: patchChildren, - pbc: patchBlockChildren, - o: { insert, querySelector, createText, createComment, parentNode } - } = internals; - const disabled = isTeleportDisabled(n2.props); - let { dynamicChildren } = n2; - const mount = (vnode, container2, anchor2) => { - if (vnode.shapeFlag & 16) { - mountChildren( - vnode.children, - container2, - anchor2, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - }; - const mountToTarget = (vnode = n2) => { - const disabled2 = isTeleportDisabled(vnode.props); - const target = vnode.target = resolveTarget(vnode.props, querySelector); - const targetAnchor = prepareAnchor(target, vnode, createText, insert); - if (target) { - if (namespace !== "svg" && isTargetSVG(target)) { - namespace = "svg"; - } else if (namespace !== "mathml" && isTargetMathML(target)) { - namespace = "mathml"; - } - if (parentComponent && parentComponent.isCE) { - (parentComponent.ce._teleportTargets || (parentComponent.ce._teleportTargets = /* @__PURE__ */ new Set())).add(target); - } - if (!disabled2) { - mount(vnode, target, targetAnchor); - updateCssVars(vnode, false); - } - } - }; - const queuePendingMount = (vnode) => { - const mountJob = () => { - if (pendingMounts.get(vnode) !== mountJob) return; - pendingMounts.delete(vnode); - if (isTeleportDisabled(vnode.props)) { - const mountContainer = parentNode(vnode.el) || container; - mount(vnode, mountContainer, vnode.anchor); - updateCssVars(vnode, true); - } - mountToTarget(vnode); - }; - pendingMounts.set(vnode, mountJob); - queuePostRenderEffect(mountJob, parentSuspense); - }; - if (n1 == null) { - const placeholder = n2.el = createText(""); - const mainAnchor = n2.anchor = createText(""); - insert(placeholder, container, anchor); - insert(mainAnchor, container, anchor); - if (isTeleportDeferred(n2.props) || parentSuspense && parentSuspense.pendingBranch) { - queuePendingMount(n2); - return; - } - if (disabled) { - mount(n2, container, mainAnchor); - updateCssVars(n2, true); - } - mountToTarget(); - } else { - n2.el = n1.el; - const mainAnchor = n2.anchor = n1.anchor; - const pendingMount = pendingMounts.get(n1); - if (pendingMount) { - pendingMount.flags |= 8; - pendingMounts.delete(n1); - queuePendingMount(n2); - return; - } - n2.targetStart = n1.targetStart; - const target = n2.target = n1.target; - const targetAnchor = n2.targetAnchor = n1.targetAnchor; - const wasDisabled = isTeleportDisabled(n1.props); - const currentContainer = wasDisabled ? container : target; - const currentAnchor = wasDisabled ? mainAnchor : targetAnchor; - if (namespace === "svg" || isTargetSVG(target)) { - namespace = "svg"; - } else if (namespace === "mathml" || isTargetMathML(target)) { - namespace = "mathml"; - } - if (dynamicChildren) { - patchBlockChildren( - n1.dynamicChildren, - dynamicChildren, - currentContainer, - parentComponent, - parentSuspense, - namespace, - slotScopeIds - ); - traverseStaticChildren(n1, n2, true); - } else if (!optimized) { - patchChildren( - n1, - n2, - currentContainer, - currentAnchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - false - ); - } - if (disabled) { - if (!wasDisabled) { - moveTeleport( - n2, - container, - mainAnchor, - internals, - 1 - ); - } else { - if (n2.props && n1.props && n2.props.to !== n1.props.to) { - n2.props.to = n1.props.to; - } - } - } else { - if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) { - const nextTarget = resolveTarget(n2.props, querySelector); - if (nextTarget) { - n2.target = nextTarget; - moveTeleport( - n2, - nextTarget, - null, - internals, - 0 - ); - } - } else if (wasDisabled) { - moveTeleport( - n2, - target, - targetAnchor, - internals, - 1 - ); - } - } - updateCssVars(n2, disabled); - } - }, - remove(vnode, parentComponent, parentSuspense, { um: unmount, o: { remove: hostRemove } }, doRemove) { - const { - shapeFlag, - children, - anchor, - targetStart, - targetAnchor, - target, - props - } = vnode; - const disabled = isTeleportDisabled(props); - const shouldRemove = doRemove || !disabled; - const pendingMount = pendingMounts.get(vnode); - if (pendingMount) { - pendingMount.flags |= 8; - pendingMounts.delete(vnode); - } - if (target) { - hostRemove(targetStart); - hostRemove(targetAnchor); - } - doRemove && hostRemove(anchor); - if (!pendingMount && (disabled || target) && shapeFlag & 16) { - for (let i = 0; i < children.length; i++) { - const child = children[i]; - unmount( - child, - parentComponent, - parentSuspense, - shouldRemove, - !!child.dynamicChildren - ); - } - } - }, - move: moveTeleport, - hydrate: hydrateTeleport - }; - function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2) { - if (moveType === 0) { - if (vnode.targetStart) { - insert(vnode.targetStart, container, parentAnchor); - } - insert(vnode.targetAnchor, container, parentAnchor); - parentAnchor = vnode.targetAnchor; - } - const { el, anchor, shapeFlag, children, props } = vnode; - const isReorder = moveType === 2; - if (isReorder) { - insert(el, container, parentAnchor); - } - if (!pendingMounts.has(vnode) && (!isReorder || isTeleportDisabled(props))) { - if (shapeFlag & 16) { - for (let i = 0; i < children.length; i++) { - move( - children[i], - container, - parentAnchor, - 2 - ); - } - } - } - if (isReorder) { - insert(anchor, container, parentAnchor); - } - } - function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { - o: { nextSibling, parentNode, querySelector, insert, createText } - }, hydrateChildren) { - function hydrateAnchor(target2, targetNode) { - let targetAnchor = targetNode; - while (targetAnchor) { - if (targetAnchor && targetAnchor.nodeType === 8) { - if (targetAnchor.data === "teleport start anchor") { - vnode.targetStart = targetAnchor; - } else if (targetAnchor.data === "teleport anchor") { - vnode.targetAnchor = targetAnchor; - target2._lpa = vnode.targetAnchor && nextSibling(vnode.targetAnchor); - break; - } - } - targetAnchor = nextSibling(targetAnchor); - } - } - function hydrateDisabledTeleport(node2, vnode2) { - vnode2.anchor = hydrateChildren( - nextSibling(node2), - vnode2, - parentNode(node2), - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - const target = vnode.target = resolveTarget( - vnode.props, - querySelector - ); - const disabled = isTeleportDisabled(vnode.props); - if (target) { - const targetNode = target._lpa || target.firstChild; - if (vnode.shapeFlag & 16) { - if (disabled) { - hydrateDisabledTeleport(node, vnode); - hydrateAnchor(target, targetNode); - if (!vnode.targetAnchor) { - prepareAnchor( - target, - vnode, - createText, - insert, - // if target is the same as the main view, insert anchors before current node - // to avoid hydrating mismatch - parentNode(node) === target ? node : null - ); - } - } else { - vnode.anchor = nextSibling(node); - hydrateAnchor(target, targetNode); - if (!vnode.targetAnchor) { - prepareAnchor(target, vnode, createText, insert); - } - hydrateChildren( - targetNode && nextSibling(targetNode), - vnode, - target, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - } - updateCssVars(vnode, disabled); - } else if (disabled) { - if (vnode.shapeFlag & 16) { - hydrateDisabledTeleport(node, vnode); - vnode.targetStart = node; - vnode.targetAnchor = nextSibling(node); - } - } - return vnode.anchor && nextSibling(vnode.anchor); - } - var Teleport = TeleportImpl; - function updateCssVars(vnode, isDisabled) { - const ctx = vnode.ctx; - if (ctx && ctx.ut) { - let node, anchor; - if (isDisabled) { - node = vnode.el; - anchor = vnode.anchor; - } else { - node = vnode.targetStart; - anchor = vnode.targetAnchor; - } - while (node && node !== anchor) { - if (node.nodeType === 1) node.setAttribute("data-v-owner", ctx.uid); - node = node.nextSibling; - } - ctx.ut(); - } - } - function prepareAnchor(target, vnode, createText, insert, anchor = null) { - const targetStart = vnode.targetStart = createText(""); - const targetAnchor = vnode.targetAnchor = createText(""); - targetStart[TeleportEndKey] = targetAnchor; - if (target) { - insert(targetStart, target, anchor); - insert(targetAnchor, target, anchor); - } - return targetAnchor; - } - var leaveCbKey = /* @__PURE__ */ Symbol("_leaveCb"); - var enterCbKey = /* @__PURE__ */ Symbol("_enterCb"); - function useTransitionState() { - const state = { - isMounted: false, - isLeaving: false, - isUnmounting: false, - leavingVNodes: /* @__PURE__ */ new Map() - }; - onMounted(() => { - state.isMounted = true; - }); - onBeforeUnmount(() => { - state.isUnmounting = true; - }); - return state; - } - var TransitionHookValidator = [Function, Array]; - var BaseTransitionPropsValidators = { - mode: String, - appear: Boolean, - persisted: Boolean, - // enter - onBeforeEnter: TransitionHookValidator, - onEnter: TransitionHookValidator, - onAfterEnter: TransitionHookValidator, - onEnterCancelled: TransitionHookValidator, - // leave - onBeforeLeave: TransitionHookValidator, - onLeave: TransitionHookValidator, - onAfterLeave: TransitionHookValidator, - onLeaveCancelled: TransitionHookValidator, - // appear - onBeforeAppear: TransitionHookValidator, - onAppear: TransitionHookValidator, - onAfterAppear: TransitionHookValidator, - onAppearCancelled: TransitionHookValidator - }; - var BaseTransitionImpl = { - name: `BaseTransition`, - props: BaseTransitionPropsValidators, - setup(props, { slots }) { - const instance = getCurrentInstance(); - const state = useTransitionState(); - return () => { - const children = slots.default && getTransitionRawChildren(slots.default(), true); - const child = children && children.length ? findNonCommentChild(children) : ( - // Keep explicit default-slot conditionals on the same transition path - // as regular v-if branches, which render a comment placeholder. - instance.subTree ? createCommentVNode() : void 0 - ); - if (!child) { - return; - } - const rawProps = reactivity.toRaw(props); - const { mode } = rawProps; - if (state.isLeaving) { - return emptyPlaceholder(child); - } - const innerChild = getInnerChild$1(child); - if (!innerChild) { - return emptyPlaceholder(child); - } - let enterHooks = resolveTransitionHooks( - innerChild, - rawProps, - state, - instance, - // #11061, ensure enterHooks is fresh after clone - (hooks) => enterHooks = hooks - ); - if (innerChild.type !== Comment) { - setTransitionHooks(innerChild, enterHooks); - } - let oldInnerChild = instance.subTree && getInnerChild$1(instance.subTree); - if (oldInnerChild && oldInnerChild.type !== Comment && !isSameVNodeType(oldInnerChild, innerChild) && getTransitionRoot(instance.subTree)) { - let leavingHooks = resolveTransitionHooks( - oldInnerChild, - rawProps, - state, - instance - ); - setTransitionHooks(oldInnerChild, leavingHooks); - if (mode === "out-in" && innerChild.type !== Comment) { - state.isLeaving = true; - leavingHooks.afterLeave = () => { - state.isLeaving = false; - if (!(instance.job.flags & 8)) { - instance.update(); - } - delete leavingHooks.afterLeave; - oldInnerChild = void 0; - }; - return emptyPlaceholder(child); - } else if (mode === "in-out" && innerChild.type !== Comment) { - leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => { - const leavingVNodesCache = getLeavingNodesForType( - state, - oldInnerChild - ); - leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild; - el[leaveCbKey] = () => { - earlyRemove(); - el[leaveCbKey] = void 0; - delete enterHooks.delayedLeave; - oldInnerChild = void 0; - }; - enterHooks.delayedLeave = () => { - delayedLeave(); - delete enterHooks.delayedLeave; - oldInnerChild = void 0; - }; - }; - } else { - oldInnerChild = void 0; - } - } else if (oldInnerChild) { - oldInnerChild = void 0; - } - return child; - }; - } - }; - function findNonCommentChild(children) { - let child = children[0]; - if (children.length > 1) { - for (const c of children) { - if (c.type !== Comment) { - child = c; - break; - } - } - } - return child; - } - var BaseTransition = BaseTransitionImpl; - function getLeavingNodesForType(state, vnode) { - const { leavingVNodes } = state; - let leavingVNodesCache = leavingVNodes.get(vnode.type); - if (!leavingVNodesCache) { - leavingVNodesCache = /* @__PURE__ */ Object.create(null); - leavingVNodes.set(vnode.type, leavingVNodesCache); - } - return leavingVNodesCache; - } - function resolveTransitionHooks(vnode, props, state, instance, postClone) { - const { - appear, - mode, - persisted = false, - onBeforeEnter, - onEnter, - onAfterEnter, - onEnterCancelled, - onBeforeLeave, - onLeave, - onAfterLeave, - onLeaveCancelled, - onBeforeAppear, - onAppear, - onAfterAppear, - onAppearCancelled - } = props; - const key = String(vnode.key); - const leavingVNodesCache = getLeavingNodesForType(state, vnode); - const callHook2 = (hook, args) => { - hook && callWithAsyncErrorHandling( - hook, - instance, - 9, - args - ); - }; - const callAsyncHook = (hook, args) => { - const done = args[1]; - callHook2(hook, args); - if (shared.isArray(hook)) { - if (hook.every((hook2) => hook2.length <= 1)) done(); - } else if (hook.length <= 1) { - done(); - } - }; - const hooks = { - mode, - persisted, - beforeEnter(el) { - let hook = onBeforeEnter; - if (!state.isMounted) { - if (appear) { - hook = onBeforeAppear || onBeforeEnter; - } else { - return; - } - } - if (el[leaveCbKey]) { - el[leaveCbKey]( - true - /* cancelled */ - ); - } - const leavingVNode = leavingVNodesCache[key]; - if (leavingVNode && isSameVNodeType(vnode, leavingVNode)) { - let leavingCb = leavingVNode.el[leaveCbKey]; - if (!leavingCb) { - const leavingRoot = getTransitionRoot(leavingVNode); - leavingCb = leavingRoot && leavingRoot.el[leaveCbKey]; - } - if (leavingCb) { - leavingCb(); - } - } - callHook2(hook, [el]); - }, - enter(el) { - if (leavingVNodesCache[key] === vnode) return; - let hook = onEnter; - let afterHook = onAfterEnter; - let cancelHook = onEnterCancelled; - if (!state.isMounted) { - if (appear) { - hook = onAppear || onEnter; - afterHook = onAfterAppear || onAfterEnter; - cancelHook = onAppearCancelled || onEnterCancelled; - } else { - return; - } - } - let called = false; - el[enterCbKey] = (cancelled) => { - if (called) return; - called = true; - if (cancelled) { - callHook2(cancelHook, [el]); - } else { - callHook2(afterHook, [el]); - } - if (hooks.delayedLeave) { - hooks.delayedLeave(); - } - el[enterCbKey] = void 0; - }; - const done = el[enterCbKey].bind(null, false); - if (hook) { - callAsyncHook(hook, [el, done]); - } else { - done(); - } - }, - leave(el, remove2) { - const key2 = String(vnode.key); - if (el[enterCbKey]) { - el[enterCbKey]( - true - /* cancelled */ - ); - } - if (state.isUnmounting) { - return remove2(); - } - callHook2(onBeforeLeave, [el]); - let called = false; - el[leaveCbKey] = (cancelled) => { - if (called) return; - called = true; - remove2(); - if (cancelled) { - callHook2(onLeaveCancelled, [el]); - } else { - callHook2(onAfterLeave, [el]); - } - el[leaveCbKey] = void 0; - if (leavingVNodesCache[key2] === vnode) { - delete leavingVNodesCache[key2]; - } - }; - const done = el[leaveCbKey].bind(null, false); - leavingVNodesCache[key2] = vnode; - if (onLeave) { - callAsyncHook(onLeave, [el, done]); - } else { - done(); - } - }, - clone(vnode2) { - const hooks2 = resolveTransitionHooks( - vnode2, - props, - state, - instance, - postClone - ); - if (postClone) postClone(hooks2); - return hooks2; - } - }; - return hooks; - } - function emptyPlaceholder(vnode) { - if (isKeepAlive(vnode)) { - vnode = cloneVNode(vnode); - vnode.children = null; - return vnode; - } - } - function getInnerChild$1(vnode) { - if (!isKeepAlive(vnode)) { - if (isTeleport(vnode.type) && vnode.children) { - return findNonCommentChild(vnode.children); - } - return vnode; - } - if (vnode.component) { - return vnode.component.subTree; - } - const { shapeFlag, children } = vnode; - if (children) { - if (shapeFlag & 16) { - return children[0]; - } - if (shapeFlag & 32 && shared.isFunction(children.default)) { - return children.default(); - } - } - } - function setTransitionHooks(vnode, hooks) { - if (vnode.shapeFlag & 6 && vnode.component) { - vnode.transition = hooks; - const subTree = vnode.component.subTree; - setTransitionHooks( - isTeleport(subTree.type) ? getInnerChild$1(subTree) || subTree : subTree, - hooks - ); - } else if (vnode.shapeFlag & 128) { - vnode.ssContent.transition = hooks.clone(vnode.ssContent); - vnode.ssFallback.transition = hooks.clone(vnode.ssFallback); - } else { - vnode.transition = hooks; - if (vnode.type === Fragment && shared.isArray(vnode.children)) { - const child = filterSingleRoot(vnode.children, false); - if (child) { - setTransitionHooks(child, hooks); - } - } - } - } - function getTransitionRawChildren(children, keepComment = false, parentKey) { - let ret = []; - let keyedFragmentCount = 0; - for (let i = 0; i < children.length; i++) { - let child = children[i]; - const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i); - if (child.type === Fragment) { - if (child.patchFlag & 128) keyedFragmentCount++; - ret = ret.concat( - getTransitionRawChildren(child.children, keepComment, key) - ); - } else if (keepComment || child.type !== Comment) { - ret.push(key != null ? cloneVNode(child, { key }) : child); - } - } - if (keyedFragmentCount > 1) { - for (let i = 0; i < ret.length; i++) { - ret[i].patchFlag = -2; - } - } - return ret; - } - function getTransitionRoot(vnode) { - if (vnode.component) { - return getTransitionRoot(vnode.component.subTree); - } - if (vnode.type === Fragment) { - const child = shared.isArray(vnode.children) && filterSingleRoot(vnode.children, false); - return child ? getTransitionRoot(child) : void 0; - } - if (vnode.type !== Comment) { - return vnode; - } - } - // @__NO_SIDE_EFFECTS__ - function defineComponent(options, extraOptions) { - return shared.isFunction(options) ? ( - // #8236: extend call and options.name access are considered side-effects - // by Rollup, so we have to wrap it in a pure-annotated IIFE. - /* @__PURE__ */ (() => shared.extend({ name: options.name }, extraOptions, { setup: options }))() - ) : options; - } - function useId() { - const i = getCurrentInstance(); - if (i) { - return (i.appContext.config.idPrefix || "v") + "-" + i.ids[0] + i.ids[1]++; - } - return ""; - } - function markAsyncBoundary(instance) { - instance.ids = [instance.ids[0] + instance.ids[2]++ + "-", 0, 0]; - } - function useTemplateRef(key) { - const i = getCurrentInstance(); - const r = reactivity.shallowRef(null); - if (i) { - const refs = i.refs === shared.EMPTY_OBJ ? i.refs = {} : i.refs; - { - Object.defineProperty(refs, key, { - enumerable: true, - get: () => r.value, - set: (val) => r.value = val - }); - } - } - const ret = r; - return ret; - } - function isTemplateRefKey(refs, key) { - let desc; - return !!((desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable); - } - var pendingSetRefMap = /* @__PURE__ */ new WeakMap(); - function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { - if (shared.isArray(rawRef)) { - rawRef.forEach( - (r, i) => setRef( - r, - oldRawRef && (shared.isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), - parentSuspense, - vnode, - isUnmount - ) - ); - return; - } - if (isAsyncWrapper(vnode) && !isUnmount) { - if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) { - setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree); - } - return; - } - const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el; - const value = isUnmount ? null : refValue; - const { i: owner, r: ref2 } = rawRef; - const oldRef = oldRawRef && oldRawRef.r; - const refs = owner.refs === shared.EMPTY_OBJ ? owner.refs = {} : owner.refs; - const setupState = owner.setupState; - const rawSetupState = reactivity.toRaw(setupState); - const canSetSetupRef = setupState === shared.EMPTY_OBJ ? shared.NO : (key) => { - if (isTemplateRefKey(refs, key)) { - return false; - } - return shared.hasOwn(rawSetupState, key); - }; - const canSetRef = (ref22, key) => { - if (key && isTemplateRefKey(refs, key)) { - return false; - } - return true; - }; - if (oldRef != null && oldRef !== ref2) { - invalidatePendingSetRef(oldRawRef); - if (shared.isString(oldRef)) { - refs[oldRef] = null; - if (canSetSetupRef(oldRef)) { - setupState[oldRef] = null; - } - } else if (reactivity.isRef(oldRef)) { - const oldRawRefAtom = oldRawRef; - if (canSetRef(oldRef, oldRawRefAtom.k)) { - oldRef.value = null; - } - if (oldRawRefAtom.k) refs[oldRawRefAtom.k] = null; - } - } - if (shared.isFunction(ref2)) { - callWithErrorHandling(ref2, owner, 12, [value, refs]); - } else { - const _isString = shared.isString(ref2); - const _isRef = reactivity.isRef(ref2); - if (_isString || _isRef) { - const doSet = () => { - if (rawRef.f) { - const existing = _isString ? canSetSetupRef(ref2) ? setupState[ref2] : refs[ref2] : canSetRef() || !rawRef.k ? ref2.value : refs[rawRef.k]; - if (isUnmount) { - shared.isArray(existing) && shared.remove(existing, refValue); - } else { - if (!shared.isArray(existing)) { - if (_isString) { - refs[ref2] = [refValue]; - if (canSetSetupRef(ref2)) { - setupState[ref2] = refs[ref2]; - } - } else { - const newVal = [refValue]; - if (canSetRef(ref2, rawRef.k)) { - ref2.value = newVal; - } - if (rawRef.k) refs[rawRef.k] = newVal; - } - } else if (!existing.includes(refValue)) { - existing.push(refValue); - } - } - } else if (_isString) { - refs[ref2] = value; - if (canSetSetupRef(ref2)) { - setupState[ref2] = value; - } - } else if (_isRef) { - if (canSetRef(ref2, rawRef.k)) { - ref2.value = value; - } - if (rawRef.k) refs[rawRef.k] = value; - } else ; - }; - if (value) { - const job = () => { - doSet(); - pendingSetRefMap.delete(rawRef); - }; - job.id = -1; - pendingSetRefMap.set(rawRef, job); - queuePostRenderEffect(job, parentSuspense); - } else { - invalidatePendingSetRef(rawRef); - doSet(); - } - } - } - } - function invalidatePendingSetRef(rawRef) { - const pendingSetRef = pendingSetRefMap.get(rawRef); - if (pendingSetRef) { - pendingSetRef.flags |= 8; - pendingSetRefMap.delete(rawRef); - } - } - var hasLoggedMismatchError = false; - var logMismatchError = () => { - if (hasLoggedMismatchError) { - return; - } - console.error("Hydration completed but contains mismatches."); - hasLoggedMismatchError = true; - }; - var isSVGContainer = (container) => container.namespaceURI.includes("svg") && container.tagName !== "foreignObject"; - var isMathMLContainer = (container) => container.namespaceURI.includes("MathML"); - var getContainerType = (container) => { - if (container.nodeType !== 1) return void 0; - if (isSVGContainer(container)) return "svg"; - if (isMathMLContainer(container)) return "mathml"; - return void 0; - }; - var isComment = (node) => node.nodeType === 8; - function createHydrationFunctions(rendererInternals) { - const { - mt: mountComponent, - p: patch, - o: { - patchProp, - createText, - nextSibling, - parentNode, - remove: remove2, - insert, - createComment - } - } = rendererInternals; - const hydrate = (vnode, container) => { - if (!container.hasChildNodes()) { - patch(null, vnode, container); - flushPostFlushCbs(); - container._vnode = vnode; - return; - } - hydrateNode(container.firstChild, vnode, null, null, null); - flushPostFlushCbs(); - container._vnode = vnode; - }; - const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => { - optimized = optimized || !!vnode.dynamicChildren; - const isFragmentStart = isComment(node) && node.data === "["; - const onMismatch = () => handleMismatch( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - isFragmentStart - ); - const { type, ref: ref2, shapeFlag, patchFlag } = vnode; - let domType = node.nodeType; - vnode.el = node; - if (patchFlag === -2) { - optimized = false; - vnode.dynamicChildren = null; - } - let nextNode = null; - switch (type) { - case Text: - if (domType !== 3) { - if (vnode.children === "") { - insert(vnode.el = createText(""), parentNode(node), node); - nextNode = node; - } else { - nextNode = onMismatch(); - } - } else { - if (node.data !== vnode.children) { - logMismatchError(); - node.data = vnode.children; - } - nextNode = nextSibling(node); - } - break; - case Comment: - if (isTemplateNode(node)) { - nextNode = nextSibling(node); - replaceNode( - vnode.el = node.content.firstChild, - node, - parentComponent - ); - } else if (domType !== 8 || isFragmentStart) { - nextNode = onMismatch(); - } else { - nextNode = nextSibling(node); - } - break; - case Static: - if (isFragmentStart) { - node = nextSibling(node); - domType = node.nodeType; - } - if (domType === 1 || domType === 3) { - nextNode = node; - const needToAdoptContent = !vnode.children.length; - for (let i = 0; i < vnode.staticCount; i++) { - if (needToAdoptContent) - vnode.children += nextNode.nodeType === 1 ? nextNode.outerHTML : nextNode.data; - if (i === vnode.staticCount - 1) { - vnode.anchor = nextNode; - } - nextNode = nextSibling(nextNode); - } - return isFragmentStart ? nextSibling(nextNode) : nextNode; - } else { - onMismatch(); - } - break; - case Fragment: - if (!isFragmentStart) { - nextNode = onMismatch(); - } else { - nextNode = hydrateFragment( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - break; - default: - if (shapeFlag & 1) { - if ((domType !== 1 || vnode.type.toLowerCase() !== node.tagName.toLowerCase()) && !isTemplateNode(node)) { - nextNode = onMismatch(); - } else { - nextNode = hydrateElement( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - } else if (shapeFlag & 6) { - vnode.slotScopeIds = slotScopeIds; - const container = parentNode(node); - if (isFragmentStart) { - nextNode = locateClosingAnchor(node); - } else if (isComment(node) && node.data === "teleport start") { - nextNode = locateClosingAnchor(node, node.data, "teleport end"); - } else { - nextNode = nextSibling(node); - } - mountComponent( - vnode, - container, - null, - parentComponent, - parentSuspense, - getContainerType(container), - optimized - ); - if ((isAsyncWrapper(vnode) || vnode.component.asyncDep) && !vnode.component.subTree) { - let subTree; - if (isFragmentStart) { - subTree = createVNode(Static); - subTree.anchor = nextNode ? nextNode.previousSibling : container.lastChild; - } else { - subTree = node.nodeType === 3 ? createTextVNode("") : createVNode( - node.nodeType === 8 ? Comment : "div" - ); - } - subTree.el = node; - vnode.component.subTree = subTree; - } - } else if (shapeFlag & 64) { - if (domType !== 8) { - nextNode = onMismatch(); - } else { - nextNode = vnode.type.hydrate( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized, - rendererInternals, - hydrateChildren - ); - } - } else if (shapeFlag & 128) { - nextNode = vnode.type.hydrate( - node, - vnode, - parentComponent, - parentSuspense, - getContainerType(parentNode(node)), - slotScopeIds, - optimized, - rendererInternals, - hydrateNode - ); - } else ; - } - if (ref2 != null) { - setRef(ref2, null, parentSuspense, vnode); - } - return nextNode; - }; - const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => { - optimized = optimized || !!vnode.dynamicChildren; - const { - type, - dynamicProps, - props, - patchFlag, - shapeFlag, - dirs, - transition - } = vnode; - const forcePatch = type === "input" || type === "option"; - const hasDynamicProps = !!dynamicProps; - if (forcePatch || hasDynamicProps || patchFlag !== -1) { - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "created"); - } - let needCallTransitionHooks = false; - if (isTemplateNode(el)) { - needCallTransitionHooks = needTransition( - null, - // no need check parentSuspense in hydration - transition - ) && parentComponent && parentComponent.vnode.props && parentComponent.vnode.props.appear; - const content = el.content.firstChild; - if (needCallTransitionHooks) { - const cls = content.getAttribute("class"); - if (cls) content.$cls = cls; - transition.beforeEnter(content); - } - replaceNode(content, el, parentComponent); - vnode.el = el = content; - } - if (shapeFlag & 16 && // skip if element has innerHTML / textContent - !(props && (props.innerHTML || props.textContent))) { - let next = hydrateChildren( - el.firstChild, - vnode, - el, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - if (next && !isMismatchAllowed( - el, - 1 - /* CHILDREN */ - )) { - logMismatchError(); - } - while (next) { - const cur = next; - next = next.nextSibling; - remove2(cur); - } - } else if (shapeFlag & 8) { - let clientText = vnode.children; - if (clientText[0] === "\n" && (el.tagName === "PRE" || el.tagName === "TEXTAREA")) { - clientText = clientText.slice(1); - } - const { textContent } = el; - if (textContent !== clientText && // innerHTML normalize \r\n or \r into a single \n in the DOM - textContent !== clientText.replace(/\r\n|\r/g, "\n")) { - if (!isMismatchAllowed( - el, - 0 - /* TEXT */ - )) { - logMismatchError(); - } - el.textContent = vnode.children; - } - } - if (props) { - if (forcePatch || hasDynamicProps || !optimized || patchFlag & (16 | 32)) { - const isCustomElement = el.tagName.includes("-"); - const namespace = el.namespaceURI.includes("svg") ? "svg" : el.namespaceURI.includes("MathML") ? "mathml" : void 0; - for (const key in props) { - if (forcePatch && (key.endsWith("value") || key === "indeterminate") || shared.isOn(key) && !shared.isReservedProp(key) || // force hydrate v-bind with .prop modifiers - key[0] === "." || isCustomElement && !shared.isReservedProp(key) || dynamicProps && dynamicProps.includes(key)) { - if (isUnchangedResourceProp(el, key, props[key])) { - continue; - } - patchProp(el, key, null, props[key], namespace, parentComponent); - } - } - } else if (props.onClick) { - patchProp( - el, - "onClick", - null, - props.onClick, - void 0, - parentComponent - ); - } else if (patchFlag & 4 && reactivity.isReactive(props.style)) { - for (const key in props.style) props.style[key]; - } - } - let vnodeHooks; - if (vnodeHooks = props && props.onVnodeBeforeMount) { - invokeVNodeHook(vnodeHooks, parentComponent, vnode); - } - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "beforeMount"); - } - if ((vnodeHooks = props && props.onVnodeMounted) || dirs || needCallTransitionHooks) { - queueEffectWithSuspense(() => { - vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode); - needCallTransitionHooks && transition.enter(el); - dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted"); - }, parentSuspense); - } - } - return el.nextSibling; - }; - const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => { - optimized = optimized || !!parentVNode.dynamicChildren; - const children = parentVNode.children; - const l = children.length; - let hasCheckedMismatch = false; - for (let i = 0; i < l; i++) { - const vnode = optimized ? children[i] : children[i] = normalizeVNode(children[i]); - const isText = vnode.type === Text; - if (node) { - if (isText && !optimized) { - if (i + 1 < l && normalizeVNode(children[i + 1]).type === Text) { - insert( - createText( - node.data.slice(vnode.children.length) - ), - container, - nextSibling(node) - ); - node.data = vnode.children; - } - } - node = hydrateNode( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } else if (isText && !vnode.children) { - insert(vnode.el = createText(""), container); - } else { - if (!hasCheckedMismatch) { - hasCheckedMismatch = true; - if (!isMismatchAllowed( - container, - 1 - /* CHILDREN */ - )) { - logMismatchError(); - } - } - patch( - null, - vnode, - container, - null, - parentComponent, - parentSuspense, - getContainerType(container), - slotScopeIds - ); - } - } - return node; - }; - const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => { - const { slotScopeIds: fragmentSlotScopeIds } = vnode; - if (fragmentSlotScopeIds) { - slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds; - } - const container = parentNode(node); - const next = hydrateChildren( - nextSibling(node), - vnode, - container, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - if (next && isComment(next) && next.data === "]") { - return nextSibling(vnode.anchor = next); - } else { - logMismatchError(); - insert(vnode.anchor = createComment(`]`), container, next); - return next; - } - }; - const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => { - if (!isNodeMismatchAllowed(node, vnode)) { - logMismatchError(); - } - vnode.el = null; - if (isFragment) { - const end = locateClosingAnchor(node); - while (true) { - const next2 = nextSibling(node); - if (next2 && next2 !== end) { - remove2(next2); - } else { - break; - } - } - } - const next = nextSibling(node); - const container = parentNode(node); - remove2(node); - patch( - null, - vnode, - container, - next, - parentComponent, - parentSuspense, - getContainerType(container), - slotScopeIds - ); - if (parentComponent) { - parentComponent.vnode.el = vnode.el; - updateHOCHostEl(parentComponent, vnode.el); - } - return next; - }; - const locateClosingAnchor = (node, open = "[", close = "]") => { - let match = 0; - while (node) { - node = nextSibling(node); - if (node && isComment(node)) { - if (node.data === open) match++; - if (node.data === close) { - if (match === 0) { - return nextSibling(node); - } else { - match--; - } - } - } - } - return node; - }; - const replaceNode = (newNode, oldNode, parentComponent) => { - const parentNode2 = oldNode.parentNode; - if (parentNode2) { - parentNode2.replaceChild(newNode, oldNode); - } - let parent = parentComponent; - while (parent) { - if (parent.vnode.el === oldNode) { - parent.vnode.el = parent.subTree.el = newNode; - } - parent = parent.parent; - } - }; - const isTemplateNode = (node) => { - return node.nodeType === 1 && node.tagName === "TEMPLATE"; - }; - return [hydrate, hydrateNode]; - } - var resourceProps = /* @__PURE__ */ new Set(["src", "srcset", "href", "poster"]); - function isUnchangedResourceProp(el, key, clientValue) { - if (!resourceProps.has(key)) { - return false; - } - return el.getAttribute(key) === (clientValue == null ? null : `${clientValue}`); - } - var allowMismatchAttr = "data-allow-mismatch"; - var MismatchTypeString = { - [ - 0 - /* TEXT */ - ]: "text", - [ - 1 - /* CHILDREN */ - ]: "children", - [ - 2 - /* CLASS */ - ]: "class", - [ - 3 - /* STYLE */ - ]: "style", - [ - 4 - /* ATTRIBUTE */ - ]: "attribute" - }; - function isMismatchAllowed(el, allowedType) { - if (allowedType === 0 || allowedType === 1) { - while (el && !el.hasAttribute(allowMismatchAttr)) { - el = el.parentElement; - } - } - return isMismatchAllowedByAttr( - el && el.getAttribute(allowMismatchAttr), - allowedType - ); - } - function isMismatchAllowedByAttr(allowedAttr, allowedType) { - if (allowedAttr == null) { - return false; - } else if (allowedAttr === "") { - return true; - } else { - const list = allowedAttr.split(","); - if (allowedType === 0 && list.includes("children")) { - return true; - } - return list.includes(MismatchTypeString[allowedType]); - } - } - function isNodeMismatchAllowed(node, vnode) { - return isMismatchAllowed( - node.parentElement, - 1 - /* CHILDREN */ - ) || isMismatchAllowedByNode(node) || isMismatchAllowedByVNode(vnode); - } - function isMismatchAllowedByNode(node) { - return node.nodeType === 1 && isMismatchAllowedByAttr( - node.getAttribute(allowMismatchAttr), - 1 - /* CHILDREN */ - ); - } - function isMismatchAllowedByVNode({ props }) { - const allowedAttr = props && props[allowMismatchAttr]; - return typeof allowedAttr === "string" && isMismatchAllowedByAttr( - allowedAttr, - 1 - /* CHILDREN */ - ); - } - var requestIdleCallback = shared.getGlobalThis().requestIdleCallback || ((cb) => setTimeout(cb, 1)); - var cancelIdleCallback = shared.getGlobalThis().cancelIdleCallback || ((id) => clearTimeout(id)); - var hydrateOnIdle = (timeout = 1e4) => (hydrate) => { - const id = requestIdleCallback(hydrate, { timeout }); - return () => cancelIdleCallback(id); - }; - function elementIsVisibleInViewport(el) { - const { top, left, bottom, right } = el.getBoundingClientRect(); - const { innerHeight, innerWidth } = window; - return (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth); - } - var hydrateOnVisible = (opts) => (hydrate, forEach) => { - const ob = new IntersectionObserver((entries) => { - for (const e of entries) { - if (!e.isIntersecting) continue; - ob.disconnect(); - hydrate(); - break; - } - }, opts); - const observe = (el) => { - if (elementIsVisibleInViewport(el)) { - hydrate(); - ob.disconnect(); - return false; - } - if (getComputedStyle(el).display === "contents") { - for (let i = 0; i < el.children.length; i++) { - if (observe(el.children[i]) === false) return false; - } - } - ob.observe(el); - }; - forEach((el) => { - if (!(el instanceof Element)) return; - return observe(el); - }); - return () => ob.disconnect(); - }; - var hydrateOnMediaQuery = (query) => (hydrate) => { - if (query) { - const mql = matchMedia(query); - if (mql.matches) { - hydrate(); - } else { - mql.addEventListener("change", hydrate, { once: true }); - return () => mql.removeEventListener("change", hydrate); - } - } - }; - var hydrateOnInteraction = (interactions = []) => (hydrate, forEach) => { - if (shared.isString(interactions)) interactions = [interactions]; - let hasHydrated = false; - const doHydrate = (e) => { - if (!hasHydrated) { - hasHydrated = true; - teardown(); - hydrate(); - e.target.dispatchEvent(new e.constructor(e.type, e)); - } - }; - const teardown = () => { - forEach((el) => { - for (const i of interactions) { - el.removeEventListener(i, doHydrate); - } - }); - }; - forEach((el) => { - for (const i of interactions) { - el.addEventListener(i, doHydrate, { once: true }); - } - }); - return teardown; - }; - function forEachElement(node, cb) { - if (isComment(node) && node.data === "[") { - let depth = 1; - let next = node.nextSibling; - while (next) { - if (next.nodeType === 1) { - const result = cb(next); - if (result === false) { - break; - } - } else if (isComment(next)) { - if (next.data === "]") { - if (--depth === 0) break; - } else if (next.data === "[") { - depth++; - } - } - next = next.nextSibling; - } - } else { - cb(node); - } - } - var isAsyncWrapper = (i) => !!i.type.__asyncLoader; - // @__NO_SIDE_EFFECTS__ - function defineAsyncComponent(source) { - if (shared.isFunction(source)) { - source = { loader: source }; - } - const { - loader, - loadingComponent, - errorComponent, - delay = 200, - hydrate: hydrateStrategy, - timeout, - // undefined = never times out - suspensible = true, - onError: userOnError - } = source; - let pendingRequest = null; - let resolvedComp; - let retries = 0; - const retry = () => { - retries++; - pendingRequest = null; - return load(); - }; - const load = () => { - let thisRequest; - return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { - err = err instanceof Error ? err : new Error(String(err)); - if (userOnError) { - return new Promise((resolve2, reject) => { - const userRetry = () => resolve2(retry()); - const userFail = () => reject(err); - userOnError(err, userRetry, userFail, retries + 1); - }); - } else { - throw err; - } - }).then((comp) => { - if (thisRequest !== pendingRequest && pendingRequest) { - return pendingRequest; - } - if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { - comp = comp.default; - } - resolvedComp = comp; - return comp; - })); - }; - return /* @__PURE__ */ defineComponent({ - name: "AsyncComponentWrapper", - __asyncLoader: load, - __asyncHydrate(el, instance, hydrate) { - const wasConnected = el.isConnected; - let patched = false; - (instance.bu || (instance.bu = [])).push(() => patched = true); - const performHydrate = () => { - if (patched) { - return; - } - if (!el.parentNode || wasConnected && !el.isConnected) return; - hydrate(); - }; - const doHydrate = hydrateStrategy ? () => { - const teardown = hydrateStrategy( - performHydrate, - (cb) => forEachElement(el, cb) - ); - if (teardown) { - (instance.bum || (instance.bum = [])).push(teardown); - } - } : performHydrate; - if (resolvedComp) { - doHydrate(); - } else { - load().then(() => !instance.isUnmounted && doHydrate()); - } - }, - get __asyncResolved() { - return resolvedComp; - }, - setup() { - const instance = currentInstance; - markAsyncBoundary(instance); - if (resolvedComp) { - return () => createInnerComp(resolvedComp, instance); - } - const onError = (err) => { - pendingRequest = null; - handleError( - err, - instance, - 13, - !errorComponent - ); - }; - if (suspensible && instance.suspense || isInSSRComponentSetup) { - return load().then((comp) => { - return () => createInnerComp(comp, instance); - }).catch((err) => { - onError(err); - return () => errorComponent ? createVNode(errorComponent, { - error: err - }) : null; - }); - } - const loaded = reactivity.ref(false); - const error = reactivity.ref(); - const delayed = reactivity.ref(!!delay); - let timeoutTimer; - let delayTimer; - onUnmounted(() => { - if (timeoutTimer != null) clearTimeout(timeoutTimer); - if (delayTimer != null) clearTimeout(delayTimer); - }); - if (delay) { - delayTimer = setTimeout(() => { - if (instance.isUnmounted) return; - delayed.value = false; - }, delay); - } - if (timeout != null) { - timeoutTimer = setTimeout(() => { - if (instance.isUnmounted) return; - if (!loaded.value && !error.value) { - const err = new Error( - `Async component timed out after ${timeout}ms.` - ); - onError(err); - error.value = err; - } - }, timeout); - } - load().then(() => { - if (instance.isUnmounted) return; - loaded.value = true; - if (instance.parent && isKeepAlive(instance.parent.vnode)) { - instance.parent.update(); - } - }).catch((err) => { - if (instance.isUnmounted) { - pendingRequest = null; - return; - } - onError(err); - error.value = err; - }); - return () => { - if (loaded.value && resolvedComp) { - return createInnerComp(resolvedComp, instance); - } else if (error.value && errorComponent) { - return createVNode(errorComponent, { - error: error.value - }); - } else if (loadingComponent && !delayed.value) { - return createInnerComp( - loadingComponent, - instance - ); - } - }; - } - }); - } - function createInnerComp(comp, parent) { - const { ref: ref2, props, children, ce } = parent.vnode; - const vnode = createVNode(comp, props, children); - vnode.ref = ref2; - vnode.ce = ce; - delete parent.vnode.ce; - return vnode; - } - var isKeepAlive = (vnode) => vnode.type.__isKeepAlive; - var KeepAliveImpl = { - name: `KeepAlive`, - // Marker for special handling inside the renderer. We are not using a === - // check directly on KeepAlive in the renderer, because importing it directly - // would prevent it from being tree-shaken. - __isKeepAlive: true, - props: { - include: [String, RegExp, Array], - exclude: [String, RegExp, Array], - max: [String, Number] - }, - setup(props, { slots }) { - const instance = getCurrentInstance(); - const sharedContext = instance.ctx; - if (!sharedContext.renderer) { - return () => { - const children = slots.default && slots.default(); - return children && children.length === 1 ? children[0] : children; - }; - } - const cache = /* @__PURE__ */ new Map(); - const keys = /* @__PURE__ */ new Set(); - let current = null; - const parentSuspense = instance.suspense; - const { - renderer: { - p: patch, - m: move, - um: _unmount, - o: { createElement } - } - } = sharedContext; - const storageContainer = createElement("div"); - sharedContext.activate = (vnode, container, anchor, namespace, optimized) => { - const instance2 = vnode.component; - move(vnode, container, anchor, 0, parentSuspense); - patch( - instance2.vnode, - vnode, - container, - anchor, - instance2, - parentSuspense, - namespace, - vnode.slotScopeIds, - optimized - ); - queuePostRenderEffect(() => { - instance2.isDeactivated = false; - if (instance2.a) { - shared.invokeArrayFns(instance2.a); - } - const vnodeHook = vnode.props && vnode.props.onVnodeMounted; - if (vnodeHook) { - invokeVNodeHook(vnodeHook, instance2.parent, vnode); - } - }, parentSuspense); - }; - sharedContext.deactivate = (vnode) => { - const instance2 = vnode.component; - invalidateMount(instance2.m); - invalidateMount(instance2.a); - move(vnode, storageContainer, null, 1, parentSuspense); - queuePostRenderEffect(() => { - if (instance2.da) { - shared.invokeArrayFns(instance2.da); - } - const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted; - if (vnodeHook) { - invokeVNodeHook(vnodeHook, instance2.parent, vnode); - } - instance2.isDeactivated = true; - }, parentSuspense); - }; - function unmount(vnode) { - resetShapeFlag(vnode); - _unmount(vnode, instance, parentSuspense, true); - } - function pruneCache(filter) { - cache.forEach((vnode, key) => { - const name = getComponentName( - isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : vnode.type - ); - if (name && !filter(name)) { - pruneCacheEntry(key); - } - }); - } - function pruneCacheEntry(key) { - const cached = cache.get(key); - if (cached && (!current || !isSameVNodeType(cached, current))) { - unmount(cached); - } else if (current) { - resetShapeFlag(current); - if (cached) resetShapeFlag(cached); - } - cache.delete(key); - keys.delete(key); - } - watch( - () => [props.include, props.exclude], - ([include, exclude]) => { - include && pruneCache((name) => matches(include, name)); - exclude && pruneCache((name) => !matches(exclude, name)); - }, - // prune post-render after `current` has been updated - { flush: "post", deep: true } - ); - let pendingCacheKey = null; - const cacheSubtree = () => { - if (pendingCacheKey != null) { - if (isSuspense(instance.subTree.type)) { - queuePostRenderEffect(() => { - const vnode = getInnerChild(instance.subTree); - if (vnode.component) { - cache.set(pendingCacheKey, vnode); - } - }, instance.subTree.suspense); - } else { - cache.set(pendingCacheKey, getInnerChild(instance.subTree)); - } - } - }; - onMounted(cacheSubtree); - onUpdated(cacheSubtree); - onBeforeUnmount(() => { - cache.forEach((cached) => { - const { subTree, suspense } = instance; - const vnode = getInnerChild(subTree); - if (cached.type === vnode.type && cached.key === vnode.key) { - resetShapeFlag(vnode); - const da = vnode.component.da; - da && queuePostRenderEffect(da, suspense); - return; - } - unmount(cached); - }); - }); - return () => { - pendingCacheKey = null; - if (!slots.default) { - return current = null; - } - const children = slots.default(); - const rawVNode = children[0]; - if (children.length > 1) { - current = null; - return children; - } else if (!isVNode(rawVNode) || !(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) { - current = null; - return rawVNode; - } - let vnode = getInnerChild(rawVNode); - if (vnode.type === Comment) { - current = null; - return vnode; - } - const comp = vnode.type; - const name = getComponentName( - isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp - ); - const { include, exclude, max } = props; - if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) { - vnode.shapeFlag &= -257; - current = vnode; - return rawVNode; - } - const key = vnode.key == null ? comp : vnode.key; - const cachedVNode = cache.get(key); - if (vnode.el) { - vnode = cloneVNode(vnode); - if (rawVNode.shapeFlag & 128) { - rawVNode.ssContent = vnode; - } - } - pendingCacheKey = key; - if (cachedVNode) { - vnode.el = cachedVNode.el; - vnode.component = cachedVNode.component; - if (vnode.transition) { - setTransitionHooks(vnode, vnode.transition); - } - vnode.shapeFlag |= 512; - keys.delete(key); - keys.add(key); - } else { - keys.add(key); - if (max && keys.size > parseInt(max, 10)) { - pruneCacheEntry(keys.values().next().value); - } - } - vnode.shapeFlag |= 256; - current = vnode; - return isSuspense(rawVNode.type) ? rawVNode : vnode; - }; - } - }; - var KeepAlive = KeepAliveImpl; - function matches(pattern, name) { - if (shared.isArray(pattern)) { - return pattern.some((p) => matches(p, name)); - } else if (shared.isString(pattern)) { - return pattern.split(",").includes(name); - } else if (shared.isRegExp(pattern)) { - pattern.lastIndex = 0; - return pattern.test(name); - } - return false; - } - function onActivated(hook, target) { - registerKeepAliveHook(hook, "a", target); - } - function onDeactivated(hook, target) { - registerKeepAliveHook(hook, "da", target); - } - function registerKeepAliveHook(hook, type, target = currentInstance) { - const wrappedHook = hook.__wdc || (hook.__wdc = () => { - let current = target; - while (current) { - if (current.isDeactivated) { - return; - } - current = current.parent; - } - return hook(); - }); - injectHook(type, wrappedHook, target); - if (target) { - let current = target.parent; - while (current && current.parent) { - if (isKeepAlive(current.parent.vnode)) { - injectToKeepAliveRoot(wrappedHook, type, target, current); - } - current = current.parent; - } - } - } - function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { - const injected = injectHook( - type, - hook, - keepAliveRoot, - true - /* prepend */ - ); - onUnmounted(() => { - shared.remove(keepAliveRoot[type], injected); - }, target); - } - function resetShapeFlag(vnode) { - vnode.shapeFlag &= -257; - vnode.shapeFlag &= -513; - } - function getInnerChild(vnode) { - return vnode.shapeFlag & 128 ? vnode.ssContent : vnode; - } - function injectHook(type, hook, target = currentInstance, prepend = false) { - if (target) { - const hooks = target[type] || (target[type] = []); - const wrappedHook = hook.__weh || (hook.__weh = (...args) => { - reactivity.pauseTracking(); - const reset = setCurrentInstance(target); - const res = callWithAsyncErrorHandling(hook, target, type, args); - reset(); - reactivity.resetTracking(); - return res; - }); - if (prepend) { - hooks.unshift(wrappedHook); - } else { - hooks.push(wrappedHook); - } - return wrappedHook; - } - } - var createHook = (lifecycle) => (hook, target = currentInstance) => { - if (!isInSSRComponentSetup || lifecycle === "sp") { - injectHook(lifecycle, (...args) => hook(...args), target); - } - }; - var onBeforeMount = createHook("bm"); - var onMounted = createHook("m"); - var onBeforeUpdate = createHook( - "bu" - ); - var onUpdated = createHook("u"); - var onBeforeUnmount = createHook( - "bum" - ); - var onUnmounted = createHook("um"); - var onServerPrefetch = createHook( - "sp" - ); - var onRenderTriggered = createHook("rtg"); - var onRenderTracked = createHook("rtc"); - function onErrorCaptured(hook, target = currentInstance) { - injectHook("ec", hook, target); - } - var COMPONENTS = "components"; - var DIRECTIVES = "directives"; - function resolveComponent(name, maybeSelfReference) { - return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; - } - var NULL_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol.for("v-ndc"); - function resolveDynamicComponent(component) { - if (shared.isString(component)) { - return resolveAsset(COMPONENTS, component, false) || component; - } else { - return component || NULL_DYNAMIC_COMPONENT; - } - } - function resolveDirective(name) { - return resolveAsset(DIRECTIVES, name); - } - function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { - const instance = currentRenderingInstance || currentInstance; - if (instance) { - const Component = instance.type; - if (type === COMPONENTS) { - const selfName = getComponentName( - Component, - false - ); - if (selfName && (selfName === name || selfName === shared.camelize(name) || selfName === shared.capitalize(shared.camelize(name)))) { - return Component; - } - } - const res = ( - // local registration - // check instance[type] first which is resolved for options API - resolve(instance[type] || Component[type], name) || // global registration - resolve(instance.appContext[type], name) - ); - if (!res && maybeSelfReference) { - return Component; - } - return res; - } - } - function resolve(registry2, name) { - return registry2 && (registry2[name] || registry2[shared.camelize(name)] || registry2[shared.capitalize(shared.camelize(name))]); - } - function renderList(source, renderItem, cache, index) { - let ret; - const cached = cache && cache[index]; - const sourceIsArray = shared.isArray(source); - if (sourceIsArray || shared.isString(source)) { - const sourceIsReactiveArray = sourceIsArray && reactivity.isReactive(source); - let needsWrap = false; - let isReadonlySource = false; - if (sourceIsReactiveArray) { - needsWrap = !reactivity.isShallow(source); - isReadonlySource = reactivity.isReadonly(source); - source = reactivity.shallowReadArray(source); - } - ret = new Array(source.length); - for (let i = 0, l = source.length; i < l; i++) { - ret[i] = renderItem( - needsWrap ? isReadonlySource ? reactivity.toReadonly(reactivity.toReactive(source[i])) : reactivity.toReactive(source[i]) : source[i], - i, - void 0, - cached && cached[i] - ); - } - } else if (typeof source === "number") { - if (!Number.isInteger(source) || source < 0) { - ret = []; - } else { - ret = new Array(source); - for (let i = 0; i < source; i++) { - ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]); - } - } - } else if (shared.isObject(source)) { - if (source[Symbol.iterator]) { - ret = Array.from( - source, - (item, i) => renderItem(item, i, void 0, cached && cached[i]) - ); - } else { - const keys = Object.keys(source); - ret = new Array(keys.length); - for (let i = 0, l = keys.length; i < l; i++) { - const key = keys[i]; - ret[i] = renderItem(source[key], key, i, cached && cached[i]); - } - } - } else { - ret = []; - } - if (cache) { - cache[index] = ret; - } - return ret; - } - function createSlots(slots, dynamicSlots) { - for (let i = 0; i < dynamicSlots.length; i++) { - const slot = dynamicSlots[i]; - if (shared.isArray(slot)) { - for (let j = 0; j < slot.length; j++) { - slots[slot[j].name] = slot[j].fn; - } - } else if (slot) { - slots[slot.name] = slot.key ? (...args) => { - const res = slot.fn(...args); - if (res) res.key = slot.key; - return res; - } : slot.fn; - } - } - return slots; - } - function renderSlot(slots, name, props, fallback, noSlotted, branchKey) { - if (props == null) props = {}; - if (currentRenderingInstance.ce || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.ce) { - const slotProps = branchKey != null && props.key == null ? shared.extend({}, props, { key: branchKey }) : props; - const hasProps = Object.keys(slotProps).length > 0; - if (name !== "default") slotProps.name = name; - return openBlock(), createBlock( - Fragment, - null, - [createVNode("slot", slotProps, fallback && fallback())], - hasProps ? -2 : 64 - ); - } - let slot = slots[name]; - if (slot && slot._c) { - slot._d = false; - } - const prevStackSize = blockStack.length; - openBlock(); - let rendered; - try { - const validSlotContent = slot && ensureValidVNode(slot(props)); - const slotKey = props.key || branchKey || // slot content array of a dynamic conditional slot may have a branch - // key attached in the `createSlots` helper, respect that - validSlotContent && validSlotContent.key; - rendered = createBlock( - Fragment, - { - key: (slotKey && !shared.isSymbol(slotKey) ? slotKey : `_${name}`) + // #7256 force differentiate fallback content from actual content - (!validSlotContent && fallback ? "_fb" : "") - }, - validSlotContent || (fallback ? fallback() : []), - validSlotContent && slots._ === 1 ? 64 : -2 - ); - } catch (err) { - for (let i = blockStack.length; i > prevStackSize; i--) closeBlock(); - throw err; - } finally { - if (slot && slot._c) { - slot._d = true; - } - } - if (!noSlotted && rendered.scopeId) { - rendered.slotScopeIds = [rendered.scopeId + "-s"]; - } - return rendered; - } - function ensureValidVNode(vnodes) { - return vnodes.some((child) => { - if (!isVNode(child)) return true; - if (child.type === Comment) return false; - if (child.type === Fragment && !ensureValidVNode(child.children)) - return false; - return true; - }) ? vnodes : null; - } - function toHandlers(obj, preserveCaseIfNecessary) { - const ret = {}; - for (const key in obj) { - ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : shared.toHandlerKey(key)] = obj[key]; - } - return ret; - } - var getPublicInstance = (i) => { - if (!i) return null; - if (isStatefulComponent(i)) return getComponentPublicInstance(i); - return getPublicInstance(i.parent); - }; - var publicPropertiesMap = ( - // Move PURE marker to new line to workaround compiler discarding it - // due to type annotation - /* @__PURE__ */ shared.extend(/* @__PURE__ */ Object.create(null), { - $: (i) => i, - $el: (i) => i.vnode.el, - $data: (i) => i.data, - $props: (i) => i.props, - $attrs: (i) => i.attrs, - $slots: (i) => i.slots, - $refs: (i) => i.refs, - $parent: (i) => getPublicInstance(i.parent), - $root: (i) => getPublicInstance(i.root), - $host: (i) => i.ce, - $emit: (i) => i.emit, - $options: (i) => resolveMergedOptions(i), - $forceUpdate: (i) => i.f || (i.f = () => { - queueJob(i.update); - }), - $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)), - $watch: (i) => instanceWatch.bind(i) - }) - ); - var hasSetupBinding = (state, key) => state !== shared.EMPTY_OBJ && !state.__isScriptSetup && shared.hasOwn(state, key); - var PublicInstanceProxyHandlers = { - get({ _: instance }, key) { - if (key === "__v_skip") { - return true; - } - const { ctx, setupState, data, props, accessCache, type, appContext } = instance; - if (key[0] !== "$") { - const n = accessCache[key]; - if (n !== void 0) { - switch (n) { - case 1: - return setupState[key]; - case 2: - return data[key]; - case 4: - return ctx[key]; - case 3: - return props[key]; - } - } else if (hasSetupBinding(setupState, key)) { - accessCache[key] = 1; - return setupState[key]; - } else if (data !== shared.EMPTY_OBJ && shared.hasOwn(data, key)) { - accessCache[key] = 2; - return data[key]; - } else if (shared.hasOwn(props, key)) { - accessCache[key] = 3; - return props[key]; - } else if (ctx !== shared.EMPTY_OBJ && shared.hasOwn(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if (shouldCacheAccess) { - accessCache[key] = 0; - } - } - const publicGetter = publicPropertiesMap[key]; - let cssModule, globalProperties; - if (publicGetter) { - if (key === "$attrs") { - reactivity.track(instance.attrs, "get", ""); - } - return publicGetter(instance); - } else if ( - // css module (injected by vue-loader) - (cssModule = type.__cssModules) && (cssModule = cssModule[key]) - ) { - return cssModule; - } else if (ctx !== shared.EMPTY_OBJ && shared.hasOwn(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if ( - // global properties - globalProperties = appContext.config.globalProperties, shared.hasOwn(globalProperties, key) - ) { - { - return globalProperties[key]; - } - } else ; - }, - set({ _: instance }, key, value) { - const { data, setupState, ctx } = instance; - if (hasSetupBinding(setupState, key)) { - setupState[key] = value; - return true; - } else if (data !== shared.EMPTY_OBJ && shared.hasOwn(data, key)) { - data[key] = value; - return true; - } else if (shared.hasOwn(instance.props, key)) { - return false; - } - if (key[0] === "$" && key.slice(1) in instance) { - return false; - } else { - { - ctx[key] = value; - } - } - return true; - }, - has({ - _: { data, setupState, accessCache, ctx, appContext, props, type } - }, key) { - let cssModules; - return !!(accessCache[key] || data !== shared.EMPTY_OBJ && key[0] !== "$" && shared.hasOwn(data, key) || hasSetupBinding(setupState, key) || shared.hasOwn(props, key) || shared.hasOwn(ctx, key) || shared.hasOwn(publicPropertiesMap, key) || shared.hasOwn(appContext.config.globalProperties, key) || (cssModules = type.__cssModules) && cssModules[key]); - }, - defineProperty(target, key, descriptor) { - if (descriptor.get != null) { - target._.accessCache[key] = 0; - } else if (shared.hasOwn(descriptor, "value")) { - this.set(target, key, descriptor.value, null); - } - return Reflect.defineProperty(target, key, descriptor); - } - }; - var RuntimeCompiledPublicInstanceProxyHandlers = /* @__PURE__ */ shared.extend({}, PublicInstanceProxyHandlers, { - get(target, key) { - if (key === Symbol.unscopables) { - return; - } - return PublicInstanceProxyHandlers.get(target, key, target); - }, - has(_, key) { - const has = key[0] !== "_" && !shared.isGloballyAllowed(key); - return has; - } - }); - function defineProps() { - return null; - } - function defineEmits() { - return null; - } - function defineExpose(exposed) { - } - function defineOptions(options) { - } - function defineSlots() { - return null; - } - function defineModel() { - } - function withDefaults(props, defaults) { - return null; - } - function useSlots() { - return getContext().slots; - } - function useAttrs() { - return getContext().attrs; - } - function getContext(calledFunctionName) { - const i = getCurrentInstance(); - return i.setupContext || (i.setupContext = createSetupContext(i)); - } - function normalizePropsOrEmits(props) { - return shared.isArray(props) ? props.reduce( - (normalized, p) => (normalized[p] = null, normalized), - {} - ) : props; - } - function mergeDefaults(raw, defaults) { - const props = normalizePropsOrEmits(raw); - for (const key in defaults) { - if (key.startsWith("__skip")) continue; - let opt = props[key]; - if (opt) { - if (shared.isArray(opt) || shared.isFunction(opt)) { - opt = props[key] = { type: opt, default: defaults[key] }; - } else { - opt.default = defaults[key]; - } - } else if (opt === null) { - opt = props[key] = { default: defaults[key] }; - } else ; - if (opt && defaults[`__skip_${key}`]) { - opt.skipFactory = true; - } - } - return props; - } - function mergeModels(a, b) { - if (!a || !b) return a || b; - if (shared.isArray(a) && shared.isArray(b)) return a.concat(b); - return shared.extend({}, normalizePropsOrEmits(a), normalizePropsOrEmits(b)); - } - function createPropsRestProxy(props, excludedKeys) { - const ret = {}; - for (const key in props) { - if (!excludedKeys.includes(key)) { - Object.defineProperty(ret, key, { - enumerable: true, - get: () => props[key] - }); - } - } - return ret; - } - function withAsyncContext(getAwaitable) { - const ctx = getCurrentInstance(); - const inSSRSetup = isInSSRComponentSetup; - let awaitable = getAwaitable(); - unsetCurrentInstance(); - if (inSSRSetup) { - setInSSRSetupState(false); - } - const restore = () => { - setCurrentInstance(ctx); - if (inSSRSetup) { - setInSSRSetupState(true); - } - }; - const cleanup = () => { - if (getCurrentInstance() !== ctx) ctx.scope.off(); - unsetCurrentInstance(); - if (inSSRSetup) { - setInSSRSetupState(false); - } - }; - if (shared.isPromise(awaitable)) { - awaitable = awaitable.catch((e) => { - restore(); - Promise.resolve().then(() => Promise.resolve().then(cleanup)); - throw e; - }); - } - return [ - awaitable, - () => { - restore(); - Promise.resolve().then(cleanup); - } - ]; - } - var shouldCacheAccess = true; - function applyOptions(instance) { - const options = resolveMergedOptions(instance); - const publicThis = instance.proxy; - const ctx = instance.ctx; - shouldCacheAccess = false; - if (options.beforeCreate) { - callHook(options.beforeCreate, instance, "bc"); - } - const { - // state - data: dataOptions, - computed: computedOptions, - methods, - watch: watchOptions, - provide: provideOptions, - inject: injectOptions, - // lifecycle - created, - beforeMount, - mounted, - beforeUpdate, - updated, - activated, - deactivated, - beforeDestroy, - beforeUnmount, - destroyed, - unmounted, - render, - renderTracked, - renderTriggered, - errorCaptured, - serverPrefetch, - // public API - expose, - inheritAttrs, - // assets - components, - directives, - filters - } = options; - const checkDuplicateProperties = null; - if (injectOptions) { - resolveInjections(injectOptions, ctx, checkDuplicateProperties); - } - if (methods) { - for (const key in methods) { - const methodHandler = methods[key]; - if (shared.isFunction(methodHandler)) { - { - ctx[key] = methodHandler.bind(publicThis); - } - } - } - } - if (dataOptions) { - const data = dataOptions.call(publicThis, publicThis); - if (!shared.isObject(data)) ; - else { - instance.data = reactivity.reactive(data); - } - } - shouldCacheAccess = true; - if (computedOptions) { - for (const key in computedOptions) { - const opt = computedOptions[key]; - const get = shared.isFunction(opt) ? opt.bind(publicThis, publicThis) : shared.isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : shared.NOOP; - const set = !shared.isFunction(opt) && shared.isFunction(opt.set) ? opt.set.bind(publicThis) : shared.NOOP; - const c = computed({ - get, - set - }); - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => c.value, - set: (v) => c.value = v - }); - } - } - if (watchOptions) { - for (const key in watchOptions) { - createWatcher(watchOptions[key], ctx, publicThis, key); - } - } - if (provideOptions) { - const provides = shared.isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions; - Reflect.ownKeys(provides).forEach((key) => { - provide(key, provides[key]); - }); - } - if (created) { - callHook(created, instance, "c"); - } - function registerLifecycleHook(register, hook) { - if (shared.isArray(hook)) { - hook.forEach((_hook) => register(_hook.bind(publicThis))); - } else if (hook) { - register(hook.bind(publicThis)); - } - } - registerLifecycleHook(onBeforeMount, beforeMount); - registerLifecycleHook(onMounted, mounted); - registerLifecycleHook(onBeforeUpdate, beforeUpdate); - registerLifecycleHook(onUpdated, updated); - registerLifecycleHook(onActivated, activated); - registerLifecycleHook(onDeactivated, deactivated); - registerLifecycleHook(onErrorCaptured, errorCaptured); - registerLifecycleHook(onRenderTracked, renderTracked); - registerLifecycleHook(onRenderTriggered, renderTriggered); - registerLifecycleHook(onBeforeUnmount, beforeUnmount); - registerLifecycleHook(onUnmounted, unmounted); - registerLifecycleHook(onServerPrefetch, serverPrefetch); - if (shared.isArray(expose)) { - if (expose.length) { - const exposed = instance.exposed || (instance.exposed = {}); - expose.forEach((key) => { - Object.defineProperty(exposed, key, { - get: () => publicThis[key], - set: (val) => publicThis[key] = val, - enumerable: true - }); - }); - } else if (!instance.exposed) { - instance.exposed = {}; - } - } - if (render && instance.render === shared.NOOP) { - instance.render = render; - } - if (inheritAttrs != null) { - instance.inheritAttrs = inheritAttrs; - } - if (components) instance.components = components; - if (directives) instance.directives = directives; - if (serverPrefetch) { - markAsyncBoundary(instance); - } - } - function resolveInjections(injectOptions, ctx, checkDuplicateProperties = shared.NOOP) { - if (shared.isArray(injectOptions)) { - injectOptions = normalizeInject(injectOptions); - } - for (const key in injectOptions) { - const opt = injectOptions[key]; - let injected; - if (shared.isObject(opt)) { - if ("default" in opt) { - injected = inject( - opt.from || key, - opt.default, - true - ); - } else { - injected = inject(opt.from || key); - } - } else { - injected = inject(opt); - } - if (reactivity.isRef(injected)) { - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => injected.value, - set: (v) => injected.value = v - }); - } else { - ctx[key] = injected; - } - } - } - function callHook(hook, instance, type) { - callWithAsyncErrorHandling( - shared.isArray(hook) ? hook.map((h2) => h2.bind(instance.proxy)) : hook.bind(instance.proxy), - instance, - type - ); - } - function createWatcher(raw, ctx, publicThis, key) { - let getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key]; - if (shared.isString(raw)) { - const handler = ctx[raw]; - if (shared.isFunction(handler)) { - { - watch(getter, handler); - } - } - } else if (shared.isFunction(raw)) { - { - watch(getter, raw.bind(publicThis)); - } - } else if (shared.isObject(raw)) { - if (shared.isArray(raw)) { - raw.forEach((r) => createWatcher(r, ctx, publicThis, key)); - } else { - const handler = shared.isFunction(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler]; - if (shared.isFunction(handler)) { - watch(getter, handler, raw); - } - } - } else ; - } - function resolveMergedOptions(instance) { - const base = instance.type; - const { mixins, extends: extendsOptions } = base; - const { - mixins: globalMixins, - optionsCache: cache, - config: { optionMergeStrategies } - } = instance.appContext; - const cached = cache.get(base); - let resolved; - if (cached) { - resolved = cached; - } else if (!globalMixins.length && !mixins && !extendsOptions) { - { - resolved = base; - } - } else { - resolved = {}; - if (globalMixins.length) { - globalMixins.forEach( - (m) => mergeOptions(resolved, m, optionMergeStrategies, true) - ); - } - mergeOptions(resolved, base, optionMergeStrategies); - } - if (shared.isObject(base)) { - cache.set(base, resolved); - } - return resolved; - } - function mergeOptions(to, from, strats, asMixin = false) { - const { mixins, extends: extendsOptions } = from; - if (extendsOptions) { - mergeOptions(to, extendsOptions, strats, true); - } - if (mixins) { - mixins.forEach( - (m) => mergeOptions(to, m, strats, true) - ); - } - for (const key in from) { - if (asMixin && key === "expose") ; - else { - const strat = internalOptionMergeStrats[key] || strats && strats[key]; - to[key] = strat ? strat(to[key], from[key]) : from[key]; - } - } - return to; - } - var internalOptionMergeStrats = { - data: mergeDataFn, - props: mergeEmitsOrPropsOptions, - emits: mergeEmitsOrPropsOptions, - // objects - methods: mergeObjectOptions, - computed: mergeObjectOptions, - // lifecycle - beforeCreate: mergeAsArray, - created: mergeAsArray, - beforeMount: mergeAsArray, - mounted: mergeAsArray, - beforeUpdate: mergeAsArray, - updated: mergeAsArray, - beforeDestroy: mergeAsArray, - beforeUnmount: mergeAsArray, - destroyed: mergeAsArray, - unmounted: mergeAsArray, - activated: mergeAsArray, - deactivated: mergeAsArray, - errorCaptured: mergeAsArray, - serverPrefetch: mergeAsArray, - // assets - components: mergeObjectOptions, - directives: mergeObjectOptions, - // watch - watch: mergeWatchOptions, - // provide / inject - provide: mergeDataFn, - inject: mergeInject - }; - function mergeDataFn(to, from) { - if (!from) { - return to; - } - if (!to) { - return from; - } - return function mergedDataFn() { - return shared.extend( - shared.isFunction(to) ? to.call(this, this) : to, - shared.isFunction(from) ? from.call(this, this) : from - ); - }; - } - function mergeInject(to, from) { - return mergeObjectOptions(normalizeInject(to), normalizeInject(from)); - } - function normalizeInject(raw) { - if (shared.isArray(raw)) { - const res = {}; - for (let i = 0; i < raw.length; i++) { - res[raw[i]] = raw[i]; - } - return res; - } - return raw; - } - function mergeAsArray(to, from) { - return to ? [...new Set([].concat(to, from))] : from; - } - function mergeObjectOptions(to, from) { - return to ? shared.extend(/* @__PURE__ */ Object.create(null), to, from) : from; - } - function mergeEmitsOrPropsOptions(to, from) { - if (to) { - if (shared.isArray(to) && shared.isArray(from)) { - return [.../* @__PURE__ */ new Set([...to, ...from])]; - } - return shared.extend( - /* @__PURE__ */ Object.create(null), - normalizePropsOrEmits(to), - normalizePropsOrEmits(from != null ? from : {}) - ); - } else { - return from; - } - } - function mergeWatchOptions(to, from) { - if (!to) return from; - if (!from) return to; - const merged = shared.extend(/* @__PURE__ */ Object.create(null), to); - for (const key in from) { - merged[key] = mergeAsArray(to[key], from[key]); - } - return merged; - } - function createAppContext() { - return { - app: null, - config: { - isNativeTag: shared.NO, - performance: false, - globalProperties: {}, - optionMergeStrategies: {}, - errorHandler: void 0, - warnHandler: void 0, - compilerOptions: {} - }, - mixins: [], - components: {}, - directives: {}, - provides: /* @__PURE__ */ Object.create(null), - optionsCache: /* @__PURE__ */ new WeakMap(), - propsCache: /* @__PURE__ */ new WeakMap(), - emitsCache: /* @__PURE__ */ new WeakMap() - }; - } - var uid$1 = 0; - function createAppAPI(render, hydrate) { - return function createApp(rootComponent, rootProps = null) { - if (!shared.isFunction(rootComponent)) { - rootComponent = shared.extend({}, rootComponent); - } - if (rootProps != null && !shared.isObject(rootProps)) { - rootProps = null; - } - const context = createAppContext(); - const installedPlugins = /* @__PURE__ */ new WeakSet(); - const pluginCleanupFns = []; - let isMounted = false; - const app = context.app = { - _uid: uid$1++, - _component: rootComponent, - _props: rootProps, - _container: null, - _context: context, - _instance: null, - version, - get config() { - return context.config; - }, - set config(v) { - }, - use(plugin, ...options) { - if (installedPlugins.has(plugin)) ; - else if (plugin && shared.isFunction(plugin.install)) { - installedPlugins.add(plugin); - plugin.install(app, ...options); - } else if (shared.isFunction(plugin)) { - installedPlugins.add(plugin); - plugin(app, ...options); - } else ; - return app; - }, - mixin(mixin) { - { - if (!context.mixins.includes(mixin)) { - context.mixins.push(mixin); - } - } - return app; - }, - component(name, component) { - if (!component) { - return context.components[name]; - } - context.components[name] = component; - return app; - }, - directive(name, directive) { - if (!directive) { - return context.directives[name]; - } - context.directives[name] = directive; - return app; - }, - mount(rootContainer, isHydrate, namespace) { - if (!isMounted) { - const vnode = app._ceVNode || createVNode(rootComponent, rootProps); - vnode.appContext = context; - if (namespace === true) { - namespace = "svg"; - } else if (namespace === false) { - namespace = void 0; - } - if (isHydrate && hydrate) { - hydrate(vnode, rootContainer); - } else { - render(vnode, rootContainer, namespace); - } - isMounted = true; - app._container = rootContainer; - rootContainer.__vue_app__ = app; - return getComponentPublicInstance(vnode.component); - } - }, - onUnmount(cleanupFn) { - pluginCleanupFns.push(cleanupFn); - }, - unmount() { - if (isMounted) { - callWithAsyncErrorHandling( - pluginCleanupFns, - app._instance, - 16 - ); - render(null, app._container); - delete app._container.__vue_app__; - } - }, - provide(key, value) { - context.provides[key] = value; - return app; - }, - runWithContext(fn) { - const lastApp = currentApp; - currentApp = app; - try { - return fn(); - } finally { - currentApp = lastApp; - } - } - }; - return app; - }; - } - var currentApp = null; - function useModel(props, name, options = shared.EMPTY_OBJ) { - const i = getCurrentInstance(); - const camelizedName = shared.camelize(name); - const hyphenatedName = shared.hyphenate(name); - const modifiers = getModelModifiers(props, camelizedName); - const res = reactivity.customRef((track, trigger) => { - let localValue; - let prevSetValue = shared.EMPTY_OBJ; - let prevEmittedValue; - watchSyncEffect(() => { - const propValue = props[camelizedName]; - if (shared.hasChanged(localValue, propValue)) { - localValue = propValue; - trigger(); - } - }); - return { - get() { - track(); - return options.get ? options.get(localValue) : localValue; - }, - set(value) { - const emittedValue = options.set ? options.set(value) : value; - if (!shared.hasChanged(emittedValue, localValue) && !(prevSetValue !== shared.EMPTY_OBJ && shared.hasChanged(value, prevSetValue))) { - return; - } - const rawProps = i.vnode.props; - const hasVModel = !!(rawProps && // check if parent has passed v-model - (name in rawProps || camelizedName in rawProps || hyphenatedName in rawProps) && (`onUpdate:${name}` in rawProps || `onUpdate:${camelizedName}` in rawProps || `onUpdate:${hyphenatedName}` in rawProps)); - if (!hasVModel) { - localValue = value; - trigger(); - } - i.emit(`update:${name}`, emittedValue); - if (shared.hasChanged(value, prevSetValue) && (shared.hasChanged(value, emittedValue) && !shared.hasChanged(emittedValue, prevEmittedValue) || // #13524: browsers differ in when they flush microtasks between - // event listeners. If a v-model listener emits an intermediate value - // and a following listener restores the model to its previous prop - // value before parent updates are flushed, the parent render can be - // deduped as having no prop change. Force a local update so DOM state - // such as an input's value is synchronized back to the current model. - hasVModel && prevSetValue !== shared.EMPTY_OBJ && !shared.hasChanged(emittedValue, localValue))) { - trigger(); - } - prevSetValue = value; - prevEmittedValue = emittedValue; - } - }; - }); - res[Symbol.iterator] = () => { - let i2 = 0; - return { - next() { - if (i2 < 2) { - return { value: i2++ ? modifiers || shared.EMPTY_OBJ : res, done: false }; - } else { - return { done: true }; - } - } - }; - }; - return res; - } - var getModelModifiers = (props, modelName) => { - return modelName === "modelValue" || modelName === "model-value" ? props.modelModifiers : props[`${modelName}Modifiers`] || props[`${shared.camelize(modelName)}Modifiers`] || props[`${shared.hyphenate(modelName)}Modifiers`]; - }; - function emit(instance, event, ...rawArgs) { - if (instance.isUnmounted) return; - const props = instance.vnode.props || shared.EMPTY_OBJ; - let args = rawArgs; - const isModelListener = event.startsWith("update:"); - const modifiers = isModelListener && getModelModifiers(props, event.slice(7)); - if (modifiers) { - if (modifiers.trim) { - args = rawArgs.map((a) => shared.isString(a) ? a.trim() : a); - } - if (modifiers.number) { - args = args.map(shared.looseToNumber); - } - } - let handlerName; - let handler = props[handlerName = shared.toHandlerKey(event)] || // also try camelCase event handler (#2249) - props[handlerName = shared.toHandlerKey(shared.camelize(event))]; - if (!handler && isModelListener) { - handler = props[handlerName = shared.toHandlerKey(shared.hyphenate(event))]; - } - if (handler) { - callWithAsyncErrorHandling( - handler, - instance, - 6, - args - ); - } - const onceHandler = props[handlerName + `Once`]; - if (onceHandler) { - if (!instance.emitted) { - instance.emitted = {}; - } else if (instance.emitted[handlerName]) { - return; - } - instance.emitted[handlerName] = true; - callWithAsyncErrorHandling( - onceHandler, - instance, - 6, - args - ); - } - } - var mixinEmitsCache = /* @__PURE__ */ new WeakMap(); - function normalizeEmitsOptions(comp, appContext, asMixin = false) { - const cache = asMixin ? mixinEmitsCache : appContext.emitsCache; - const cached = cache.get(comp); - if (cached !== void 0) { - return cached; - } - const raw = comp.emits; - let normalized = {}; - let hasExtends = false; - if (!shared.isFunction(comp)) { - const extendEmits = (raw2) => { - const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); - if (normalizedFromExtend) { - hasExtends = true; - shared.extend(normalized, normalizedFromExtend); - } - }; - if (!asMixin && appContext.mixins.length) { - appContext.mixins.forEach(extendEmits); - } - if (comp.extends) { - extendEmits(comp.extends); - } - if (comp.mixins) { - comp.mixins.forEach(extendEmits); - } - } - if (!raw && !hasExtends) { - if (shared.isObject(comp)) { - cache.set(comp, null); - } - return null; - } - if (shared.isArray(raw)) { - raw.forEach((key) => normalized[key] = null); - } else { - shared.extend(normalized, raw); - } - if (shared.isObject(comp)) { - cache.set(comp, normalized); - } - return normalized; - } - function isEmitListener(options, key) { - if (!options || !shared.isOn(key)) { - return false; - } - key = key.slice(2); - key = key === "Once" ? key : key.replace(/Once$/, ""); - return shared.hasOwn(options, key[0].toLowerCase() + key.slice(1)) || shared.hasOwn(options, shared.hyphenate(key)) || shared.hasOwn(options, key); - } - function renderComponentRoot(instance) { - const { - type: Component, - vnode, - proxy, - withProxy, - propsOptions: [propsOptions], - slots, - attrs, - emit: emit2, - render, - renderCache, - props, - data, - setupState, - ctx, - inheritAttrs - } = instance; - const prev = setCurrentRenderingInstance(instance); - let result; - let fallthroughAttrs; - try { - if (vnode.shapeFlag & 4) { - const proxyToUse = withProxy || proxy; - const thisProxy = false ? new Proxy(proxyToUse, { - get(target, key, receiver) { - warn( - `Property '${String( - key - )}' was accessed via 'this'. Avoid using 'this' in templates.` - ); - return Reflect.get(target, key, receiver); - } - }) : proxyToUse; - result = normalizeVNode( - render.call( - thisProxy, - proxyToUse, - renderCache, - false ? shallowReadonly(props) : props, - setupState, - data, - ctx - ) - ); - fallthroughAttrs = attrs; - } else { - const render2 = Component; - if (false) ; - result = normalizeVNode( - render2.length > 1 ? render2( - false ? shallowReadonly(props) : props, - false ? { - get attrs() { - markAttrsAccessed(); - return shallowReadonly(attrs); - }, - slots, - emit: emit2 - } : { attrs, slots, emit: emit2 } - ) : render2( - false ? shallowReadonly(props) : props, - null - ) - ); - fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs); - } - } catch (err) { - blockStack.length = 0; - handleError(err, instance, 1); - result = createVNode(Comment); - } - let root = result; - if (fallthroughAttrs && inheritAttrs !== false) { - const keys = Object.keys(fallthroughAttrs); - const { shapeFlag } = root; - if (keys.length) { - if (shapeFlag & (1 | 6)) { - if (propsOptions && keys.some(shared.isModelListener)) { - fallthroughAttrs = filterModelListeners( - fallthroughAttrs, - propsOptions - ); - } - root = cloneVNode(root, fallthroughAttrs, false, true); - } - } - } - if (vnode.dirs) { - root = cloneVNode(root, null, false, true); - root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs; - } - if (vnode.transition) { - const child = isTeleport(root.type) ? getInnerChild$1(root) || root : root; - setTransitionHooks(child, vnode.transition); - } - { - result = root; - } - setCurrentRenderingInstance(prev); - return result; - } - function filterSingleRoot(children, recurse = true) { - let singleRoot; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (isVNode(child)) { - if (child.type !== Comment || child.children === "v-if") { - if (singleRoot) { - return; - } else { - singleRoot = child; - } - } - } else { - return; - } - } - return singleRoot; - } - var getFunctionalFallthrough = (attrs) => { - let res; - for (const key in attrs) { - if (key === "class" || key === "style" || shared.isOn(key)) { - (res || (res = {}))[key] = attrs[key]; - } - } - return res; - }; - var filterModelListeners = (attrs, props) => { - const res = {}; - for (const key in attrs) { - if (!shared.isModelListener(key) || !(key.slice(9) in props)) { - res[key] = attrs[key]; - } - } - return res; - }; - function shouldUpdateComponent(prevVNode, nextVNode, optimized) { - const { props: prevProps, children: prevChildren, component } = prevVNode; - const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; - const emits = component.emitsOptions; - if (nextVNode.dirs || nextVNode.transition) { - return true; - } - if (optimized && patchFlag >= 0) { - if (patchFlag & 1024) { - return true; - } - if (patchFlag & 16) { - if (!prevProps) { - return !!nextProps; - } - return hasPropsChanged(prevProps, nextProps, emits); - } else if (patchFlag & 8) { - const dynamicProps = nextVNode.dynamicProps; - for (let i = 0; i < dynamicProps.length; i++) { - const key = dynamicProps[i]; - if (hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emits, key)) { - return true; - } - } - } - } else { - if (prevChildren || nextChildren) { - if (!nextChildren || !nextChildren.$stable) { - return true; - } - } - if (prevProps === nextProps) { - return false; - } - if (!prevProps) { - return !!nextProps; - } - if (!nextProps) { - return true; - } - return hasPropsChanged(prevProps, nextProps, emits); - } - return false; - } - function hasPropsChanged(prevProps, nextProps, emitsOptions) { - const nextKeys = Object.keys(nextProps); - if (nextKeys.length !== Object.keys(prevProps).length) { - return true; - } - for (let i = 0; i < nextKeys.length; i++) { - const key = nextKeys[i]; - if (!shared.hasOwn(prevProps, key) || hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emitsOptions, key)) { - return true; - } - } - return false; - } - function hasPropValueChanged(nextProps, prevProps, key) { - const nextProp = nextProps[key]; - const prevProp = prevProps[key]; - if (key === "style" && shared.isObject(nextProp) && shared.isObject(prevProp)) { - return !shared.looseEqual(nextProp, prevProp); - } - return nextProp !== prevProp; - } - function updateHOCHostEl({ vnode, parent, suspense }, el) { - while (parent) { - const root = parent.subTree; - if (root.suspense && root.suspense.activeBranch === vnode) { - root.suspense.vnode.el = root.el = el; - vnode = root; - } - if (root === vnode) { - (vnode = parent.vnode).el = el; - parent = parent.parent; - } else { - break; - } - } - if (suspense && suspense.activeBranch === vnode) { - suspense.vnode.el = el; - } - } - var internalObjectProto = {}; - var createInternalObject = () => Object.create(internalObjectProto); - var isInternalObject = (obj) => Object.getPrototypeOf(obj) === internalObjectProto; - function initProps(instance, rawProps, isStateful, isSSR = false) { - const props = {}; - const attrs = createInternalObject(); - instance.propsDefaults = /* @__PURE__ */ Object.create(null); - setFullProps(instance, rawProps, props, attrs); - for (const key in instance.propsOptions[0]) { - if (!(key in props)) { - props[key] = void 0; - } - } - if (isStateful) { - instance.props = isSSR ? props : reactivity.shallowReactive(props); - } else { - if (!instance.type.props) { - instance.props = attrs; - } else { - instance.props = props; - } - } - instance.attrs = attrs; - } - function updateProps(instance, rawProps, rawPrevProps, optimized) { - const { - props, - attrs, - vnode: { patchFlag } - } = instance; - const rawCurrentProps = reactivity.toRaw(props); - const [options] = instance.propsOptions; - let hasAttrsChanged = false; - if ( - // always force full diff in dev - // - #1942 if hmr is enabled with sfc component - // - vite#872 non-sfc component used by sfc component - (optimized || patchFlag > 0) && !(patchFlag & 16) - ) { - if (patchFlag & 8) { - const propsToUpdate = instance.vnode.dynamicProps; - for (let i = 0; i < propsToUpdate.length; i++) { - let key = propsToUpdate[i]; - if (isEmitListener(instance.emitsOptions, key)) { - continue; - } - const value = rawProps[key]; - if (options) { - if (shared.hasOwn(attrs, key)) { - if (value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } else { - const camelizedKey = shared.camelize(key); - props[camelizedKey] = resolvePropValue( - options, - rawCurrentProps, - camelizedKey, - value, - instance, - false - ); - } - } else { - if (value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } - } - } - } else { - if (setFullProps(instance, rawProps, props, attrs)) { - hasAttrsChanged = true; - } - let kebabKey; - for (const key in rawCurrentProps) { - if (!rawProps || // for camelCase - !shared.hasOwn(rawProps, key) && // it's possible the original props was passed in as kebab-case - // and converted to camelCase (#955) - ((kebabKey = shared.hyphenate(key)) === key || !shared.hasOwn(rawProps, kebabKey))) { - if (options) { - if (rawPrevProps && // for camelCase - (rawPrevProps[key] !== void 0 || // for kebab-case - rawPrevProps[kebabKey] !== void 0)) { - props[key] = resolvePropValue( - options, - rawCurrentProps, - key, - void 0, - instance, - true - ); - } - } else { - delete props[key]; - } - } - } - if (attrs !== rawCurrentProps) { - for (const key in attrs) { - if (!rawProps || !shared.hasOwn(rawProps, key) && true) { - delete attrs[key]; - hasAttrsChanged = true; - } - } - } - } - if (hasAttrsChanged) { - reactivity.trigger(instance.attrs, "set", ""); - } - } - function setFullProps(instance, rawProps, props, attrs) { - const [options, needCastKeys] = instance.propsOptions; - let hasAttrsChanged = false; - let rawCastValues; - if (rawProps) { - for (let key in rawProps) { - if (shared.isReservedProp(key)) { - continue; - } - const value = rawProps[key]; - let camelKey; - if (options && shared.hasOwn(options, camelKey = shared.camelize(key))) { - if (!needCastKeys || !needCastKeys.includes(camelKey)) { - props[camelKey] = value; - } else { - (rawCastValues || (rawCastValues = {}))[camelKey] = value; - } - } else if (!isEmitListener(instance.emitsOptions, key)) { - if (!(key in attrs) || value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } - } - } - if (needCastKeys) { - const rawCurrentProps = reactivity.toRaw(props); - const castValues = rawCastValues || shared.EMPTY_OBJ; - for (let i = 0; i < needCastKeys.length; i++) { - const key = needCastKeys[i]; - props[key] = resolvePropValue( - options, - rawCurrentProps, - key, - castValues[key], - instance, - !shared.hasOwn(castValues, key) - ); - } - } - return hasAttrsChanged; - } - function resolvePropValue(options, props, key, value, instance, isAbsent) { - const opt = options[key]; - if (opt != null) { - const hasDefault = shared.hasOwn(opt, "default"); - if (hasDefault && value === void 0) { - const defaultValue = opt.default; - if (opt.type !== Function && !opt.skipFactory && shared.isFunction(defaultValue)) { - const { propsDefaults } = instance; - if (key in propsDefaults) { - value = propsDefaults[key]; - } else { - const reset = setCurrentInstance(instance); - value = propsDefaults[key] = defaultValue.call( - null, - props - ); - reset(); - } - } else { - value = defaultValue; - } - if (instance.ce) { - instance.ce._setProp(key, value); - } - } - if (opt[ - 0 - /* shouldCast */ - ]) { - if (isAbsent && !hasDefault) { - value = false; - } else if (opt[ - 1 - /* shouldCastTrue */ - ] && (value === "" || value === shared.hyphenate(key))) { - value = true; - } - } - } - return value; - } - var mixinPropsCache = /* @__PURE__ */ new WeakMap(); - function normalizePropsOptions(comp, appContext, asMixin = false) { - const cache = asMixin ? mixinPropsCache : appContext.propsCache; - const cached = cache.get(comp); - if (cached) { - return cached; - } - const raw = comp.props; - const normalized = {}; - const needCastKeys = []; - let hasExtends = false; - if (!shared.isFunction(comp)) { - const extendProps = (raw2) => { - hasExtends = true; - const [props, keys] = normalizePropsOptions(raw2, appContext, true); - shared.extend(normalized, props); - if (keys) needCastKeys.push(...keys); - }; - if (!asMixin && appContext.mixins.length) { - appContext.mixins.forEach(extendProps); - } - if (comp.extends) { - extendProps(comp.extends); - } - if (comp.mixins) { - comp.mixins.forEach(extendProps); - } - } - if (!raw && !hasExtends) { - if (shared.isObject(comp)) { - cache.set(comp, shared.EMPTY_ARR); - } - return shared.EMPTY_ARR; - } - if (shared.isArray(raw)) { - for (let i = 0; i < raw.length; i++) { - const normalizedKey = shared.camelize(raw[i]); - if (validatePropName(normalizedKey)) { - normalized[normalizedKey] = shared.EMPTY_OBJ; - } - } - } else if (raw) { - for (const key in raw) { - const normalizedKey = shared.camelize(key); - if (validatePropName(normalizedKey)) { - const opt = raw[key]; - const prop = normalized[normalizedKey] = shared.isArray(opt) || shared.isFunction(opt) ? { type: opt } : shared.extend({}, opt); - const propType = prop.type; - let shouldCast = false; - let shouldCastTrue = true; - if (shared.isArray(propType)) { - for (let index = 0; index < propType.length; ++index) { - const type = propType[index]; - const typeName = shared.isFunction(type) && type.name; - if (typeName === "Boolean") { - shouldCast = true; - break; - } else if (typeName === "String") { - shouldCastTrue = false; - } - } - } else { - shouldCast = shared.isFunction(propType) && propType.name === "Boolean"; - } - prop[ - 0 - /* shouldCast */ - ] = shouldCast; - prop[ - 1 - /* shouldCastTrue */ - ] = shouldCastTrue; - if (shouldCast || shared.hasOwn(prop, "default")) { - needCastKeys.push(normalizedKey); - } - } - } - } - const res = [normalized, needCastKeys]; - if (shared.isObject(comp)) { - cache.set(comp, res); - } - return res; - } - function validatePropName(key) { - if (key[0] !== "$" && !shared.isReservedProp(key)) { - return true; - } - return false; - } - var isInternalKey = (key) => key === "_" || key === "_ctx" || key === "$stable"; - var normalizeSlotValue = (value) => shared.isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)]; - var normalizeSlot = (key, rawSlot, ctx) => { - if (rawSlot._n) { - return rawSlot; - } - const normalized = withCtx((...args) => { - if (false) ; - return normalizeSlotValue(rawSlot(...args)); - }, ctx); - normalized._c = false; - return normalized; - }; - var normalizeObjectSlots = (rawSlots, slots, instance) => { - const ctx = rawSlots._ctx; - for (const key in rawSlots) { - if (isInternalKey(key)) continue; - const value = rawSlots[key]; - if (shared.isFunction(value)) { - slots[key] = normalizeSlot(key, value, ctx); - } else if (value != null) { - const normalized = normalizeSlotValue(value); - slots[key] = () => normalized; - } - } - }; - var normalizeVNodeSlots = (instance, children) => { - const normalized = normalizeSlotValue(children); - instance.slots.default = () => normalized; - }; - var assignSlots = (slots, children, optimized) => { - for (const key in children) { - if (optimized || !isInternalKey(key)) { - slots[key] = children[key]; - } - } - }; - var initSlots = (instance, children, optimized) => { - const slots = instance.slots = createInternalObject(); - if (instance.vnode.shapeFlag & 32) { - const type = children._; - if (type) { - assignSlots(slots, children, optimized); - if (optimized) { - shared.def(slots, "_", type, true); - } - } else { - normalizeObjectSlots(children, slots); - } - } else if (children) { - normalizeVNodeSlots(instance, children); - } - }; - var updateSlots = (instance, children, optimized) => { - const { vnode, slots } = instance; - let needDeletionCheck = true; - let deletionComparisonTarget = shared.EMPTY_OBJ; - if (vnode.shapeFlag & 32) { - const type = children._; - if (type) { - if (optimized && type === 1) { - needDeletionCheck = false; - } else { - assignSlots(slots, children, optimized); - } - } else { - needDeletionCheck = !children.$stable; - normalizeObjectSlots(children, slots); - } - deletionComparisonTarget = children; - } else if (children) { - normalizeVNodeSlots(instance, children); - deletionComparisonTarget = { default: 1 }; - } - if (needDeletionCheck) { - for (const key in slots) { - if (!isInternalKey(key) && deletionComparisonTarget[key] == null) { - delete slots[key]; - } - } - } - }; - var queuePostRenderEffect = queueEffectWithSuspense; - function createRenderer(options) { - return baseCreateRenderer(options); - } - function createHydrationRenderer(options) { - return baseCreateRenderer(options, createHydrationFunctions); - } - function baseCreateRenderer(options, createHydrationFns) { - const target = shared.getGlobalThis(); - target.__VUE__ = true; - const { - insert: hostInsert, - remove: hostRemove, - patchProp: hostPatchProp, - createElement: hostCreateElement, - createText: hostCreateText, - createComment: hostCreateComment, - setText: hostSetText, - setElementText: hostSetElementText, - parentNode: hostParentNode, - nextSibling: hostNextSibling, - setScopeId: hostSetScopeId = shared.NOOP, - insertStaticContent: hostInsertStaticContent - } = options; - const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = void 0, slotScopeIds = null, optimized = !!n2.dynamicChildren) => { - if (n1 === n2) { - return; - } - if (n1 && !isSameVNodeType(n1, n2)) { - anchor = getNextHostNode(n1); - unmount(n1, parentComponent, parentSuspense, true); - n1 = null; - } - if (n2.patchFlag === -2) { - optimized = false; - n2.dynamicChildren = null; - } - if (n2.dynamicChildren && n1 && n1.dynamicChildren && n1.dynamicChildren.hasOnce) { - if (n2.dynamicChildren === shared.EMPTY_ARR) { - n2.dynamicChildren = []; - } - n2.dynamicChildren.hasOnce = true; - } - const { type, ref: ref2, shapeFlag } = n2; - switch (type) { - case Text: - processText(n1, n2, container, anchor); - break; - case Comment: - processCommentNode(n1, n2, container, anchor); - break; - case Static: - if (n1 == null) { - mountStaticNode(n2, container, anchor, namespace); - } - break; - case Fragment: - processFragment( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - break; - default: - if (shapeFlag & 1) { - processElement( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else if (shapeFlag & 6) { - processComponent( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else if (shapeFlag & 64) { - type.process( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - internals - ); - } else if (shapeFlag & 128) { - type.process( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - internals - ); - } else ; - } - if (ref2 != null && parentComponent) { - setRef(ref2, n1 && n1.ref, parentSuspense, n2 || n1, !n2); - } else if (ref2 == null && n1 && n1.ref != null) { - setRef(n1.ref, null, parentSuspense, n1, true); - } - }; - const processText = (n1, n2, container, anchor) => { - if (n1 == null) { - hostInsert( - n2.el = hostCreateText(n2.children), - container, - anchor - ); - } else { - const el = n2.el = n1.el; - if (n2.children !== n1.children) { - hostSetText(el, n2.children); - } - } - }; - const processCommentNode = (n1, n2, container, anchor) => { - if (n1 == null) { - hostInsert( - n2.el = hostCreateComment(n2.children || ""), - container, - anchor - ); - } else { - n2.el = n1.el; - } - }; - const mountStaticNode = (n2, container, anchor, namespace) => { - [n2.el, n2.anchor] = hostInsertStaticContent( - n2.children, - container, - anchor, - namespace, - n2.el, - n2.anchor - ); - }; - const moveStaticNode = ({ el, anchor }, container, nextSibling) => { - let next; - while (el && el !== anchor) { - next = hostNextSibling(el); - hostInsert(el, container, nextSibling); - el = next; - } - hostInsert(anchor, container, nextSibling); - }; - const removeStaticNode = ({ el, anchor }) => { - let next; - while (el && el !== anchor) { - next = hostNextSibling(el); - hostRemove(el); - el = next; - } - hostRemove(anchor); - }; - const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - if (n2.type === "svg") { - namespace = "svg"; - } else if (n2.type === "math") { - namespace = "mathml"; - } - if (n1 == null) { - mountElement( - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - const customElement = n1.el && n1.el._isVueCE ? n1.el : null; - try { - if (customElement) { - customElement._beginPatch(); - } - patchElement( - n1, - n2, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } finally { - if (customElement) { - customElement._endPatch(); - } - } - } - }; - const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - let el; - let vnodeHook; - const { props, shapeFlag, transition, dirs } = vnode; - el = vnode.el = hostCreateElement( - vnode.type, - namespace, - props && props.is, - props - ); - if (shapeFlag & 8) { - hostSetElementText(el, vnode.children); - } else if (shapeFlag & 16) { - mountChildren( - vnode.children, - el, - null, - parentComponent, - parentSuspense, - resolveChildrenNamespace(vnode, namespace), - slotScopeIds, - optimized - ); - } - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "created"); - } - setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent); - if (props) { - for (const key in props) { - if (key !== "value" && !shared.isReservedProp(key)) { - hostPatchProp(el, key, null, props[key], namespace, parentComponent); - } - } - if ("value" in props) { - hostPatchProp(el, "value", null, props.value, namespace); - } - if (vnodeHook = props.onVnodeBeforeMount) { - invokeVNodeHook(vnodeHook, parentComponent, vnode); - } - } - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "beforeMount"); - } - const needCallTransitionHooks = needTransition(parentSuspense, transition); - if (needCallTransitionHooks) { - transition.beforeEnter(el); - } - hostInsert(el, container, anchor); - if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) { - queuePostRenderEffect(() => { - try { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); - needCallTransitionHooks && transition.enter(el); - dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted"); - } finally { - } - }, parentSuspense); - } - }; - const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => { - if (scopeId) { - hostSetScopeId(el, scopeId); - } - if (slotScopeIds) { - for (let i = 0; i < slotScopeIds.length; i++) { - hostSetScopeId(el, slotScopeIds[i]); - } - } - if (parentComponent) { - let subTree = parentComponent.subTree; - if (vnode === subTree || isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) { - const parentVNode = parentComponent.vnode; - setScopeId( - el, - parentVNode, - parentVNode.scopeId, - parentVNode.slotScopeIds, - parentComponent.parent - ); - } - } - }; - const mountChildren = (children, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, start = 0) => { - for (let i = start; i < children.length; i++) { - const child = children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]); - patch( - null, - child, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - }; - const patchElement = (n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - const el = n2.el = n1.el; - let { patchFlag, dynamicChildren, dirs } = n2; - patchFlag |= n1.patchFlag & 16; - const oldProps = n1.props || shared.EMPTY_OBJ; - const newProps = n2.props || shared.EMPTY_OBJ; - let vnodeHook; - parentComponent && toggleRecurse(parentComponent, false); - if (vnodeHook = newProps.onVnodeBeforeUpdate) { - invokeVNodeHook(vnodeHook, parentComponent, n2, n1); - } - if (dirs) { - invokeDirectiveHook(n2, n1, parentComponent, "beforeUpdate"); - } - parentComponent && toggleRecurse(parentComponent, true); - if ( - // #6385 the old vnode may be a user-wrapped non-isomorphic block - // Force full diff when block metadata is unstable. - dynamicChildren && (!n1.dynamicChildren || n1.dynamicChildren.length !== dynamicChildren.length) - ) { - patchFlag = 0; - optimized = false; - dynamicChildren = null; - } - if (oldProps.innerHTML && newProps.innerHTML == null || oldProps.textContent && newProps.textContent == null) { - hostSetElementText(el, ""); - } - if (dynamicChildren) { - patchBlockChildren( - n1.dynamicChildren, - dynamicChildren, - el, - parentComponent, - parentSuspense, - resolveChildrenNamespace(n2, namespace), - slotScopeIds - ); - } else if (!optimized) { - patchChildren( - n1, - n2, - el, - null, - parentComponent, - parentSuspense, - resolveChildrenNamespace(n2, namespace), - slotScopeIds, - false - ); - } - if (patchFlag > 0) { - if (patchFlag & 16) { - patchProps(el, oldProps, newProps, parentComponent, namespace); - } else { - if (patchFlag & 2) { - if (oldProps.class !== newProps.class) { - hostPatchProp(el, "class", null, newProps.class, namespace); - } - } - if (patchFlag & 4) { - hostPatchProp(el, "style", oldProps.style, newProps.style, namespace); - } - if (patchFlag & 8) { - const propsToUpdate = n2.dynamicProps; - for (let i = 0; i < propsToUpdate.length; i++) { - const key = propsToUpdate[i]; - const prev = oldProps[key]; - const next = newProps[key]; - if (next !== prev || key === "value") { - hostPatchProp(el, key, prev, next, namespace, parentComponent); - } - } - } - } - if (patchFlag & 1) { - if (n1.children !== n2.children) { - hostSetElementText(el, n2.children); - } - } - } else if (!optimized && dynamicChildren == null) { - patchProps(el, oldProps, newProps, parentComponent, namespace); - } - if ((vnodeHook = newProps.onVnodeUpdated) || dirs) { - queuePostRenderEffect(() => { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1); - dirs && invokeDirectiveHook(n2, n1, parentComponent, "updated"); - }, parentSuspense); - } - }; - const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace, slotScopeIds) => { - for (let i = 0; i < newChildren.length; i++) { - const oldVNode = oldChildren[i]; - const newVNode = newChildren[i]; - const oldEl = oldVNode.el || resolveAsyncComponentPlaceholder(oldVNode); - const container = ( - // oldVNode may be an errored async setup() component inside Suspense - // which will not have a mounted element - oldEl && // - In the case of a Fragment, we need to provide the actual parent - // of the Fragment itself so it can move its children. - (oldVNode.type === Fragment || // - In the case of different nodes, there is going to be a replacement - // which also requires the correct parent container - !isSameVNodeType(oldVNode, newVNode) || // - In the case of a component, it could contain anything. - oldVNode.shapeFlag & (6 | 64 | 128)) ? hostParentNode(oldEl) : ( - // In other cases, the parent container is not actually used so we - // just pass the block element here to avoid a DOM parentNode call. - fallbackContainer - ) - ); - patch( - oldVNode, - newVNode, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - true - ); - } - }; - const patchProps = (el, oldProps, newProps, parentComponent, namespace) => { - if (oldProps !== newProps) { - if (oldProps !== shared.EMPTY_OBJ) { - for (const key in oldProps) { - if (!shared.isReservedProp(key) && !(key in newProps)) { - hostPatchProp( - el, - key, - oldProps[key], - null, - namespace, - parentComponent - ); - } - } - } - for (const key in newProps) { - if (shared.isReservedProp(key)) continue; - const next = newProps[key]; - const prev = oldProps[key]; - if (next !== prev && key !== "value") { - hostPatchProp(el, key, prev, next, namespace, parentComponent); - } - } - if ("value" in newProps) { - hostPatchProp(el, "value", oldProps.value, newProps.value, namespace); - } - } - }; - const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText(""); - const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText(""); - let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2; - if (fragmentSlotScopeIds) { - slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds; - } - if (n1 == null) { - hostInsert(fragmentStartAnchor, container, anchor); - hostInsert(fragmentEndAnchor, container, anchor); - mountChildren( - // #10007 - // such fragment like `<></>` will be compiled into - // a fragment which doesn't have a children. - // In this case fallback to an empty array - n2.children || [], - container, - fragmentEndAnchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && // #2715 the previous fragment could've been a BAILed one as a result - // of renderSlot() with no valid children - n1.dynamicChildren && n1.dynamicChildren.length === dynamicChildren.length) { - patchBlockChildren( - n1.dynamicChildren, - dynamicChildren, - container, - parentComponent, - parentSuspense, - namespace, - slotScopeIds - ); - if ( - // #2080 if the stable fragment has a key, it's a <template v-for> that may - // get moved around. Make sure all root level vnodes inherit el. - // #2134 or if it's a component root, it may also get moved around - // as the component is being moved. - n2.key != null || parentComponent && n2 === parentComponent.subTree - ) { - traverseStaticChildren( - n1, - n2, - true - /* shallow */ - ); - } - } else { - patchChildren( - n1, - n2, - container, - fragmentEndAnchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - } - }; - const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - n2.slotScopeIds = slotScopeIds; - if (n1 == null) { - if (n2.shapeFlag & 512) { - parentComponent.ctx.activate( - n2, - container, - anchor, - namespace, - optimized - ); - } else { - mountComponent( - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - optimized - ); - } - } else { - updateComponent(n1, n2, optimized); - } - }; - const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, namespace, optimized) => { - const instance = initialVNode.component = createComponentInstance( - initialVNode, - parentComponent, - parentSuspense - ); - if (isKeepAlive(initialVNode)) { - instance.ctx.renderer = internals; - } - { - setupComponent(instance, false, optimized); - } - if (instance.asyncDep) { - parentSuspense && parentSuspense.registerDep( - instance, - setupRenderEffect, - optimized, - namespace - ); - if (!initialVNode.el) { - const placeholder = instance.subTree = createVNode(Comment); - processCommentNode(null, placeholder, container, anchor); - initialVNode.placeholder = placeholder.el; - } - } else { - setupRenderEffect( - instance, - initialVNode, - container, - anchor, - parentSuspense, - namespace, - optimized - ); - } - }; - const updateComponent = (n1, n2, optimized) => { - const instance = n2.component = n1.component; - if (shouldUpdateComponent(n1, n2, optimized)) { - if (instance.asyncDep && !instance.asyncResolved) { - n2.el = n1.el; - n2.placeholder = n1.placeholder; - updateComponentPreRender(instance, n2, optimized); - return; - } else { - instance.next = n2; - instance.update(); - } - } else { - n2.el = n1.el; - n2.placeholder = n1.placeholder; - instance.vnode = n2; - } - }; - const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, namespace, optimized) => { - const componentUpdateFn = () => { - if (!instance.isMounted) { - let vnodeHook; - const { el, props } = initialVNode; - const { bm, m, parent, root, type } = instance; - const isAsyncWrapperVNode = isAsyncWrapper(initialVNode); - toggleRecurse(instance, false); - if (bm) { - shared.invokeArrayFns(bm); - } - if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) { - invokeVNodeHook(vnodeHook, parent, initialVNode); - } - toggleRecurse(instance, true); - if (el && hydrateNode) { - const hydrateSubTree = () => { - instance.subTree = renderComponentRoot(instance); - hydrateNode( - el, - instance.subTree, - instance, - parentSuspense, - null - ); - }; - if (isAsyncWrapperVNode && type.__asyncHydrate) { - type.__asyncHydrate( - el, - instance, - hydrateSubTree - ); - } else { - hydrateSubTree(); - } - } else { - if (root.ce && root.ce._hasShadowRoot()) { - root.ce._injectChildStyle( - type, - instance.parent ? instance.parent.type : void 0 - ); - } - const subTree = instance.subTree = renderComponentRoot(instance); - patch( - null, - subTree, - container, - anchor, - instance, - parentSuspense, - namespace - ); - initialVNode.el = subTree.el; - } - if (m) { - queuePostRenderEffect(m, parentSuspense); - } - if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) { - const scopedInitialVNode = initialVNode; - queuePostRenderEffect( - () => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), - parentSuspense - ); - } - if (initialVNode.shapeFlag & 256 || parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & 256) { - instance.a && queuePostRenderEffect(instance.a, parentSuspense); - } - instance.isMounted = true; - initialVNode = container = anchor = null; - } else { - let { next, bu, u, parent, vnode } = instance; - { - const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance); - if (nonHydratedAsyncRoot) { - if (next) { - next.el = vnode.el; - updateComponentPreRender(instance, next, optimized); - } - nonHydratedAsyncRoot.asyncDep.then(() => { - queuePostRenderEffect(() => { - if (!instance.isUnmounted) update(); - }, parentSuspense); - }); - return; - } - } - let originNext = next; - let vnodeHook; - toggleRecurse(instance, false); - if (next) { - next.el = vnode.el; - updateComponentPreRender(instance, next, optimized); - } else { - next = vnode; - } - if (bu) { - shared.invokeArrayFns(bu); - } - if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) { - invokeVNodeHook(vnodeHook, parent, next, vnode); - } - toggleRecurse(instance, true); - const nextTree = renderComponentRoot(instance); - const prevTree = instance.subTree; - instance.subTree = nextTree; - patch( - prevTree, - nextTree, - // parent may have changed if it's in a teleport - hostParentNode(prevTree.el), - // anchor may have changed if it's in a fragment - getNextHostNode(prevTree), - instance, - parentSuspense, - namespace - ); - next.el = nextTree.el; - if (originNext === null) { - updateHOCHostEl(instance, nextTree.el); - } - if (u) { - queuePostRenderEffect(u, parentSuspense); - } - if (vnodeHook = next.props && next.props.onVnodeUpdated) { - queuePostRenderEffect( - () => invokeVNodeHook(vnodeHook, parent, next, vnode), - parentSuspense - ); - } - } - }; - instance.scope.on(); - const effect = instance.effect = new reactivity.ReactiveEffect(componentUpdateFn); - instance.scope.off(); - const update = instance.update = effect.run.bind(effect); - const job = instance.job = effect.runIfDirty.bind(effect); - job.i = instance; - job.id = instance.uid; - effect.scheduler = () => queueJob(job); - toggleRecurse(instance, true); - update(); - }; - const updateComponentPreRender = (instance, nextVNode, optimized) => { - nextVNode.component = instance; - const prevProps = instance.vnode.props; - instance.vnode = nextVNode; - instance.next = null; - updateProps(instance, nextVNode.props, prevProps, optimized); - updateSlots(instance, nextVNode.children, optimized); - reactivity.pauseTracking(); - flushPreFlushCbs(instance); - reactivity.resetTracking(); - }; - const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized = false) => { - const c1 = n1 && n1.children; - const prevShapeFlag = n1 ? n1.shapeFlag : 0; - const c2 = n2.children; - const { patchFlag, shapeFlag } = n2; - if (patchFlag > 0) { - if (patchFlag & 128) { - patchKeyedChildren( - c1, - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - return; - } else if (patchFlag & 256) { - patchUnkeyedChildren( - c1, - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - return; - } - } - if (shapeFlag & 8) { - if (prevShapeFlag & 16) { - unmountChildren(c1, parentComponent, parentSuspense); - } - if (c2 !== c1) { - hostSetElementText(container, c2); - } - } else { - if (prevShapeFlag & 16) { - if (shapeFlag & 16) { - patchKeyedChildren( - c1, - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - unmountChildren(c1, parentComponent, parentSuspense, true); - } - } else { - if (prevShapeFlag & 8) { - hostSetElementText(container, ""); - } - if (shapeFlag & 16) { - mountChildren( - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - } - } - }; - const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - c1 = c1 || shared.EMPTY_ARR; - c2 = c2 || shared.EMPTY_ARR; - const oldLength = c1.length; - const newLength = c2.length; - const commonLength = Math.min(oldLength, newLength); - let i; - for (i = 0; i < commonLength; i++) { - const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - patch( - c1[i], - nextChild, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - if (oldLength > newLength) { - unmountChildren( - c1, - parentComponent, - parentSuspense, - true, - false, - commonLength - ); - } else { - mountChildren( - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - commonLength - ); - } - }; - const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - let i = 0; - const l2 = c2.length; - let e1 = c1.length - 1; - let e2 = l2 - 1; - while (i <= e1 && i <= e2) { - const n1 = c1[i]; - const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - if (isSameVNodeType(n1, n2)) { - patch( - n1, - n2, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - break; - } - i++; - } - while (i <= e1 && i <= e2) { - const n1 = c1[e1]; - const n2 = c2[e2] = optimized ? cloneIfMounted(c2[e2]) : normalizeVNode(c2[e2]); - if (isSameVNodeType(n1, n2)) { - patch( - n1, - n2, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - break; - } - e1--; - e2--; - } - if (i > e1) { - if (i <= e2) { - const nextPos = e2 + 1; - const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor; - while (i <= e2) { - patch( - null, - c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]), - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - i++; - } - } - } else if (i > e2) { - while (i <= e1) { - unmount(c1[i], parentComponent, parentSuspense, true); - i++; - } - } else { - const s1 = i; - const s2 = i; - const keyToNewIndexMap = /* @__PURE__ */ new Map(); - for (i = s2; i <= e2; i++) { - const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - if (nextChild.key != null) { - keyToNewIndexMap.set(nextChild.key, i); - } - } - let j; - let patched = 0; - const toBePatched = e2 - s2 + 1; - let moved = false; - let maxNewIndexSoFar = 0; - const newIndexToOldIndexMap = new Array(toBePatched); - for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0; - for (i = s1; i <= e1; i++) { - const prevChild = c1[i]; - if (patched >= toBePatched) { - unmount(prevChild, parentComponent, parentSuspense, true); - continue; - } - let newIndex; - if (prevChild.key != null) { - newIndex = keyToNewIndexMap.get(prevChild.key); - } else { - for (j = s2; j <= e2; j++) { - if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j])) { - newIndex = j; - break; - } - } - } - if (newIndex === void 0) { - unmount(prevChild, parentComponent, parentSuspense, true); - } else { - newIndexToOldIndexMap[newIndex - s2] = i + 1; - if (newIndex >= maxNewIndexSoFar) { - maxNewIndexSoFar = newIndex; - } else { - moved = true; - } - patch( - prevChild, - c2[newIndex], - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - patched++; - } - } - const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : shared.EMPTY_ARR; - j = increasingNewIndexSequence.length - 1; - for (i = toBePatched - 1; i >= 0; i--) { - const nextIndex = s2 + i; - const nextChild = c2[nextIndex]; - const anchorVNode = c2[nextIndex + 1]; - const anchor = nextIndex + 1 < l2 ? ( - // #13559, #14173 fallback to el placeholder for unresolved async component - anchorVNode.el || resolveAsyncComponentPlaceholder(anchorVNode) - ) : parentAnchor; - if (newIndexToOldIndexMap[i] === 0) { - patch( - null, - nextChild, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else if (moved) { - if (j < 0 || i !== increasingNewIndexSequence[j]) { - move(nextChild, container, anchor, 2); - } else { - j--; - } - } - } - } - }; - const move = (vnode, container, anchor, moveType, parentSuspense = null) => { - const { el, type, transition, children, shapeFlag } = vnode; - if (shapeFlag & 6) { - move(vnode.component.subTree, container, anchor, moveType); - return; - } - if (shapeFlag & 128) { - vnode.suspense.move(container, anchor, moveType); - return; - } - if (shapeFlag & 64) { - type.move(vnode, container, anchor, internals); - return; - } - if (type === Fragment) { - hostInsert(el, container, anchor); - for (let i = 0; i < children.length; i++) { - move(children[i], container, anchor, moveType); - } - hostInsert(vnode.anchor, container, anchor); - return; - } - if (type === Static) { - moveStaticNode(vnode, container, anchor); - return; - } - const needTransition2 = moveType !== 2 && shapeFlag & 1 && transition; - if (needTransition2) { - if (moveType === 0) { - if (transition.persisted && !el[leaveCbKey]) { - hostInsert(el, container, anchor); - } else { - transition.beforeEnter(el); - hostInsert(el, container, anchor); - queuePostRenderEffect(() => transition.enter(el), parentSuspense); - } - } else { - const { leave, delayLeave, afterLeave } = transition; - const remove22 = () => { - if (vnode.ctx.isUnmounted) { - hostRemove(el); - } else { - hostInsert(el, container, anchor); - } - }; - const performLeave = () => { - const wasLeaving = el._isLeaving || !!el[leaveCbKey]; - if (el._isLeaving) { - el[leaveCbKey]( - true - /* cancelled */ - ); - } - if (transition.persisted && !wasLeaving) { - remove22(); - } else { - leave(el, () => { - remove22(); - afterLeave && afterLeave(); - }); - } - }; - if (delayLeave) { - delayLeave(el, remove22, performLeave); - } else { - performLeave(); - } - } - } else { - hostInsert(el, container, anchor); - } - }; - const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => { - const { - type, - props, - ref: ref2, - children, - dynamicChildren, - shapeFlag, - patchFlag, - dirs, - cacheIndex, - memo - } = vnode; - if (patchFlag === -2 || dynamicChildren && dynamicChildren.hasOnce) { - optimized = false; - } - if (ref2 != null) { - reactivity.pauseTracking(); - setRef(ref2, null, parentSuspense, vnode, true); - reactivity.resetTracking(); - } - if (cacheIndex != null && (!vnode.ctx || vnode.ctx === parentComponent)) { - parentComponent.renderCache[cacheIndex] = void 0; - } - if (shapeFlag & 256) { - parentComponent.ctx.deactivate(vnode); - return; - } - const shouldInvokeDirs = shapeFlag & 1 && dirs; - const shouldInvokeVnodeHook = !isAsyncWrapper(vnode); - let vnodeHook; - if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) { - invokeVNodeHook(vnodeHook, parentComponent, vnode); - } - if (shapeFlag & 6) { - unmountComponent(vnode.component, parentSuspense, doRemove); - } else { - if (shapeFlag & 128) { - vnode.suspense.unmount(parentSuspense, doRemove); - return; - } - if (shouldInvokeDirs) { - invokeDirectiveHook(vnode, null, parentComponent, "beforeUnmount"); - } - if (shapeFlag & 64) { - vnode.type.remove( - vnode, - parentComponent, - parentSuspense, - internals, - doRemove - ); - } else if (dynamicChildren && // #5154 - // when v-once is used inside a block, setBlockTracking(-1) marks the - // parent block with hasOnce: true - // so that it doesn't take the fast path during unmount - otherwise - // components nested in v-once are never unmounted. - !dynamicChildren.hasOnce && // #1153: fast path should not be taken for non-stable (v-for) fragments - (type !== Fragment || patchFlag > 0 && patchFlag & 64)) { - unmountChildren( - dynamicChildren, - parentComponent, - parentSuspense, - false, - true - ); - } else if (type === Fragment && patchFlag & (128 | 256) || !optimized && shapeFlag & 16) { - unmountChildren(children, parentComponent, parentSuspense); - } - if (doRemove) { - remove2(vnode); - } - } - const shouldInvalidateMemo = memo != null && cacheIndex == null; - if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs || shouldInvalidateMemo) { - queuePostRenderEffect(() => { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); - shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, "unmounted"); - if (shouldInvalidateMemo) { - vnode.el = null; - } - }, parentSuspense); - } - }; - const remove2 = (vnode) => { - const { type, el, anchor, transition } = vnode; - const isFragment = type === Fragment; - if (isFragment && !transition) { - removeFragment(el, anchor); - return; - } - if (type === Static) { - removeStaticNode(vnode); - if (transition && !transition.persisted && transition.afterLeave) { - transition.afterLeave(); - } - return; - } - const leavingNode = isFragment ? getTransitionRoot(vnode) : vnode; - const performRemove = () => { - if (isFragment) { - if (hostParentNode(el)) { - removeFragment(el, anchor); - } - } else { - hostRemove(el); - } - if (transition && !transition.persisted && transition.afterLeave) { - transition.afterLeave(); - } - }; - if (leavingNode && leavingNode.shapeFlag & 1 && transition && !transition.persisted) { - const { leave, delayLeave } = transition; - const leavingEl = leavingNode.el; - const performLeave = () => leave(leavingEl, performRemove); - if (delayLeave) { - delayLeave(leavingEl, performRemove, performLeave); - } else { - performLeave(); - } - } else { - performRemove(); - } - }; - const removeFragment = (cur, end) => { - let next; - while (cur !== end) { - next = hostNextSibling(cur); - hostRemove(cur); - cur = next; - } - hostRemove(end); - }; - const unmountComponent = (instance, parentSuspense, doRemove) => { - const { bum, scope, job, subTree, um, m, a } = instance; - invalidateMount(m); - invalidateMount(a); - if (bum) { - shared.invokeArrayFns(bum); - } - scope.stop(); - if (job) { - job.flags |= 8; - unmount(subTree, instance, parentSuspense, doRemove); - } else if (instance.vnode.el && subTree) { - subTree.transition = instance.vnode.transition; - unmount(subTree, instance, parentSuspense, doRemove); - } - if (um) { - queuePostRenderEffect(um, parentSuspense); - } - queuePostRenderEffect(() => { - instance.isUnmounted = true; - }, parentSuspense); - }; - const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => { - for (let i = start; i < children.length; i++) { - unmount(children[i], parentComponent, parentSuspense, doRemove, optimized); - } - }; - const getNextHostNode = (vnode) => { - if (vnode.shapeFlag & 6) { - return getNextHostNode(vnode.component.subTree); - } - if (vnode.shapeFlag & 128) { - return vnode.suspense.next(); - } - const el = hostNextSibling(vnode.anchor || vnode.el); - const teleportEnd = el && el[TeleportEndKey]; - return teleportEnd ? hostNextSibling(teleportEnd) : el; - }; - const render = (vnode, container, namespace) => { - const minUid = vnode && container._vnode ? void 0 : vnode && vnode.component ? vnode.component.uid : getNextUid(); - flushOnAppMount(() => { - if (vnode == null) { - if (container._vnode) { - unmount(container._vnode, null, null, true); - } - } else { - patch( - container._vnode || null, - vnode, - container, - null, - null, - null, - namespace - ); - } - container._vnode = vnode; - }, minUid); - }; - const internals = { - p: patch, - um: unmount, - m: move, - r: remove2, - mt: mountComponent, - mc: mountChildren, - pc: patchChildren, - pbc: patchBlockChildren, - n: getNextHostNode, - o: options - }; - let hydrate; - let hydrateNode; - if (createHydrationFns) { - [hydrate, hydrateNode] = createHydrationFns( - internals - ); - } - return { - render, - hydrate, - createApp: createAppAPI(render, hydrate) - }; - } - function resolveChildrenNamespace({ type, props }, currentNamespace) { - return currentNamespace === "svg" && type === "foreignObject" || currentNamespace === "mathml" && type === "annotation-xml" && props && props.encoding && props.encoding.includes("html") ? void 0 : currentNamespace; - } - function toggleRecurse({ effect, job }, allowed) { - if (allowed) { - effect.flags |= 32; - job.flags |= 4; - } else { - effect.flags &= -33; - job.flags &= -5; - } - } - function needTransition(parentSuspense, transition) { - return (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted; - } - function traverseStaticChildren(n1, n2, shallow = false) { - const ch1 = n1.children; - const ch2 = n2.children; - if (shared.isArray(ch1) && shared.isArray(ch2)) { - for (let i = 0; i < ch1.length; i++) { - const c1 = ch1[i]; - let c2 = ch2[i]; - if (c2.shapeFlag & 1 && !c2.dynamicChildren) { - if (c2.patchFlag <= 0 || c2.patchFlag === 32) { - c2 = ch2[i] = cloneIfMounted(ch2[i]); - c2.el = c1.el; - } - if (!shallow && c2.patchFlag !== -2) - traverseStaticChildren(c1, c2); - } - if (c2.type === Text) { - if (c2.patchFlag === -1) { - c2 = ch2[i] = cloneIfMounted(c2); - } - c2.el = c1.el; - } - if (c2.type === Comment && !c2.el) { - c2.el = c1.el; - } - } - } - } - function getSequence(arr) { - const p = arr.slice(); - const result = [0]; - let i, j, u, v, c; - const len = arr.length; - for (i = 0; i < len; i++) { - const arrI = arr[i]; - if (arrI !== 0) { - j = result[result.length - 1]; - if (arr[j] < arrI) { - p[i] = j; - result.push(i); - continue; - } - u = 0; - v = result.length - 1; - while (u < v) { - c = u + v >> 1; - if (arr[result[c]] < arrI) { - u = c + 1; - } else { - v = c; - } - } - if (arrI < arr[result[u]]) { - if (u > 0) { - p[i] = result[u - 1]; - } - result[u] = i; - } - } - } - u = result.length; - v = result[u - 1]; - while (u-- > 0) { - result[u] = v; - v = p[v]; - } - return result; - } - function locateNonHydratedAsyncRoot(instance) { - const subComponent = instance.subTree.component; - if (subComponent) { - if (subComponent.asyncDep && !subComponent.asyncResolved) { - return subComponent; - } else { - return locateNonHydratedAsyncRoot(subComponent); - } - } - } - function invalidateMount(hooks) { - if (hooks) { - for (let i = 0; i < hooks.length; i++) - hooks[i].flags |= 8; - } - } - function resolveAsyncComponentPlaceholder(anchorVnode) { - if (anchorVnode.placeholder) { - return anchorVnode.placeholder; - } - const instance = anchorVnode.component; - if (instance) { - return resolveAsyncComponentPlaceholder(instance.subTree); - } - return null; - } - var isSuspense = (type) => type.__isSuspense; - var suspenseId = 0; - var SuspenseImpl = { - name: "Suspense", - // In order to make Suspense tree-shakable, we need to avoid importing it - // directly in the renderer. The renderer checks for the __isSuspense flag - // on a vnode's type and calls the `process` method, passing in renderer - // internals. - __isSuspense: true, - process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { - if (n1 == null) { - mountSuspense( - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - } else { - if (parentSuspense && parentSuspense.deps > 0 && !n1.suspense.isInFallback && !parentSuspense.isHydrating) { - n2.suspense = n1.suspense; - n2.suspense.vnode = n2; - n2.el = n1.el; - return; - } - patchSuspense( - n1, - n2, - container, - anchor, - parentComponent, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - } - }, - hydrate: hydrateSuspense, - normalize: normalizeSuspenseChildren - }; - var Suspense = SuspenseImpl; - function triggerEvent(vnode, name) { - const eventListener = vnode.props && vnode.props[name]; - if (shared.isFunction(eventListener)) { - eventListener(); - } - } - function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { - const { - p: patch, - o: { createElement } - } = rendererInternals; - const hiddenContainer = createElement("div"); - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - container, - hiddenContainer, - anchor, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - patch( - null, - suspense.pendingBranch = vnode.ssContent, - hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds - ); - if (suspense.deps > 0) { - triggerEvent(vnode, "onPending"); - triggerEvent(vnode, "onFallback"); - patch( - null, - vnode.ssFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds - ); - setActiveBranch(suspense, vnode.ssFallback); - } else { - suspense.resolve(false, true); - } - } - function patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) { - const suspense = n2.suspense = n1.suspense; - suspense.vnode = n2; - n2.el = n1.el; - const newBranch = n2.ssContent; - const newFallback = n2.ssFallback; - const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense; - if (pendingBranch) { - suspense.pendingBranch = newBranch; - if (isSameVNodeType(pendingBranch, newBranch)) { - suspense.deps++; - patch( - pendingBranch, - newBranch, - // a hydrating pending branch is adopted SSR DOM, already in place - isHydrating ? container : suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - suspense.deps--; - if (suspense.deps <= 0) { - suspense.resolve(); - } else if (isInFallback) { - if (!isHydrating && !suspense.isFallbackMountPending) { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } - } else { - suspense.pendingId = suspenseId++; - if (isHydrating) { - suspense.isHydrating = false; - suspense.activeBranch = pendingBranch; - } else { - unmount(pendingBranch, parentComponent, suspense); - } - suspense.deps = 0; - suspense.effects.length = 0; - suspense.hiddenContainer = createElement("div"); - if (isInFallback) { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else if (!suspense.isFallbackMountPending) { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } else if (activeBranch && isSameVNodeType(activeBranch, newBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - suspense.resolve(true); - } else { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } - } - } - } else { - if (activeBranch && isSameVNodeType(activeBranch, newBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newBranch); - } else { - triggerEvent(n2, "onPending"); - suspense.pendingBranch = newBranch; - if (newBranch.shapeFlag & 512) { - suspense.pendingId = newBranch.component.suspenseId; - } else { - suspense.pendingId = suspenseId++; - } - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else { - const { timeout, pendingId } = suspense; - if (timeout > 0) { - setTimeout(() => { - if (suspense.pendingId === pendingId) { - suspense.fallback(newFallback); - } - }, timeout); - } else if (timeout === 0) { - suspense.fallback(newFallback); - } - } - } - } - } - function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) { - const { - p: patch, - m: move, - um: unmount, - n: next, - o: { parentNode, remove: remove2 } - } = rendererInternals; - let parentSuspenseId; - const isSuspensible = isVNodeSuspensible(vnode); - if (isSuspensible) { - if (parentSuspense && parentSuspense.pendingBranch) { - parentSuspenseId = parentSuspense.pendingId; - parentSuspense.deps++; - } - } - const timeout = vnode.props ? shared.toNumber(vnode.props.timeout) : void 0; - const initialAnchor = anchor; - const suspense = { - vnode, - parent: parentSuspense, - parentComponent, - namespace, - container, - hiddenContainer, - deps: 0, - pendingId: suspenseId++, - timeout: typeof timeout === "number" ? timeout : -1, - activeBranch: null, - isFallbackMountPending: false, - pendingBranch: null, - isInFallback: !isHydrating, - isHydrating, - isUnmounted: false, - effects: [], - resolve(resume = false, sync = false) { - const { - vnode: vnode2, - activeBranch, - pendingBranch, - pendingId, - effects, - parentComponent: parentComponent2, - container: container2, - isInFallback - } = suspense; - let delayEnter = false; - if (suspense.isHydrating) { - suspense.isHydrating = false; - } else if (!resume) { - delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in"; - let hasUpdatedAnchor = false; - if (delayEnter) { - activeBranch.transition.afterLeave = () => { - if (pendingId === suspense.pendingId) { - move( - pendingBranch, - container2, - anchor === initialAnchor && !hasUpdatedAnchor ? next(activeBranch) : anchor, - 0 - ); - queuePostFlushCb(effects); - if (isInFallback && vnode2.ssFallback) { - vnode2.ssFallback.el = null; - } - } - }; - } - if (activeBranch && !suspense.isFallbackMountPending) { - if (parentNode(activeBranch.el) === container2) { - anchor = next(activeBranch); - hasUpdatedAnchor = true; - } - unmount(activeBranch, parentComponent2, suspense, true); - if (!delayEnter && isInFallback && vnode2.ssFallback) { - queuePostRenderEffect(() => vnode2.ssFallback.el = null, suspense); - } - } - if (!delayEnter) { - move(pendingBranch, container2, anchor, 0); - } - } - suspense.isFallbackMountPending = false; - setActiveBranch(suspense, pendingBranch); - suspense.pendingBranch = null; - suspense.isInFallback = false; - let parent = suspense.parent; - let hasUnresolvedAncestor = false; - while (parent) { - if (parent.pendingBranch) { - for (let i = 0; i < effects.length; i++) { - parent.effects.push(effects[i]); - } - hasUnresolvedAncestor = true; - break; - } - parent = parent.parent; - } - if (!hasUnresolvedAncestor && !delayEnter) { - queuePostFlushCb(effects); - } - suspense.effects = []; - if (isSuspensible) { - if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) { - parentSuspenseId = void 0; - parentSuspense.deps--; - if (parentSuspense.deps === 0 && !sync) { - parentSuspense.resolve(); - } - } - } - triggerEvent(vnode2, "onResolve"); - }, - fallback(fallbackVNode) { - if (!suspense.pendingBranch) { - return; - } - const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense; - triggerEvent(vnode2, "onFallback"); - const anchor2 = next(activeBranch); - const mountFallback = () => { - suspense.isFallbackMountPending = false; - if (!suspense.isInFallback) { - return; - } - const latestFallback = suspense.vnode.ssFallback; - patch( - null, - latestFallback, - container2, - anchor2, - parentComponent2, - null, - // fallback tree will not have suspense context - namespace2, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, latestFallback); - }; - const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in"; - if (delayEnter) { - suspense.isFallbackMountPending = true; - activeBranch.transition.afterLeave = mountFallback; - } - suspense.isInFallback = true; - unmount( - activeBranch, - parentComponent2, - null, - // no suspense so unmount hooks fire now - true - // shouldRemove - ); - if (!delayEnter) { - mountFallback(); - } - }, - move(container2, anchor2, type) { - suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type); - suspense.container = container2; - }, - next() { - return suspense.activeBranch && next(suspense.activeBranch); - }, - // `namespace` intentionally shadows the boundary's own: the dep must be - // mounted with the namespace of the position it was rendered at, which can - // differ from the boundary's (e.g. a component nested inside an <svg>). - registerDep(instance, setupRenderEffect, optimized2, namespace2) { - const isInPendingSuspense = !!suspense.pendingBranch; - if (isInPendingSuspense) { - suspense.deps++; - } - const hydratedEl = instance.vnode.el; - instance.asyncDep.catch((err) => { - handleError(err, instance, 0); - }).then((asyncSetupResult) => { - if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { - return; - } - unsetCurrentInstance(); - if (!instance.scope.active) { - if (isInPendingSuspense && --suspense.deps === 0) { - suspense.resolve(); - } - return; - } - instance.asyncResolved = true; - const { vnode: vnode2 } = instance; - handleSetupResult(instance, asyncSetupResult, false); - if (hydratedEl) { - vnode2.el = hydratedEl; - } - const placeholder = !hydratedEl && instance.subTree.el; - setupRenderEffect( - instance, - vnode2, - // component may have been moved before resolve. - // if this is not a hydration, instance.subTree will be the comment - // placeholder. - parentNode(hydratedEl || instance.subTree.el), - // anchor will not be used if this is hydration, so only need to - // consider the comment placeholder case. - hydratedEl ? null : next(instance.subTree), - suspense, - namespace2, - optimized2 - ); - if (placeholder) { - vnode2.placeholder = null; - remove2(placeholder); - } - updateHOCHostEl(instance, vnode2.el); - if (isInPendingSuspense && --suspense.deps === 0) { - suspense.resolve(); - } - }); - }, - unmount(parentSuspense2, doRemove) { - suspense.isUnmounted = true; - if (suspense.activeBranch) { - unmount( - suspense.activeBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - if (suspense.pendingBranch) { - unmount( - suspense.pendingBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - } - }; - return suspense; - } - function hydrateSuspense(node, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) { - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - node.parentNode, - // eslint-disable-next-line no-restricted-globals - document.createElement("div"), - null, - namespace, - slotScopeIds, - optimized, - rendererInternals, - true - ); - const result = hydrateNode( - node, - suspense.pendingBranch = vnode.ssContent, - parentComponent, - suspense, - slotScopeIds, - optimized - ); - if (suspense.deps === 0) { - suspense.resolve(false, true); - } - return result; - } - function normalizeSuspenseChildren(vnode) { - const { shapeFlag, children } = vnode; - const isSlotChildren = shapeFlag & 32; - vnode.ssContent = normalizeSuspenseSlot( - isSlotChildren ? children.default : children - ); - vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment); - } - function normalizeSuspenseSlot(s) { - let block; - if (shared.isFunction(s)) { - const trackBlock = isBlockTreeEnabled && s._c; - if (trackBlock) { - s._d = false; - openBlock(); - } - s = s(); - if (trackBlock) { - s._d = true; - block = currentBlock; - closeBlock(); - } - } - if (shared.isArray(s)) { - const singleChild = filterSingleRoot(s); - s = singleChild; - } - s = normalizeVNode(s); - if (block && !s.dynamicChildren) { - s.dynamicChildren = block.filter((c) => c !== s); - } - return s; - } - function queueEffectWithSuspense(fn, suspense) { - if (suspense && suspense.pendingBranch) { - if (shared.isArray(fn)) { - suspense.effects.push(...fn); - } else { - suspense.effects.push(fn); - } - } else { - queuePostFlushCb(fn); - } - } - function setActiveBranch(suspense, branch) { - suspense.activeBranch = branch; - const { vnode, parentComponent } = suspense; - let el = branch.el; - while (!el && branch.component) { - branch = branch.component.subTree; - el = branch.el; - } - vnode.el = el; - if (parentComponent && parentComponent.subTree === vnode) { - parentComponent.vnode.el = el; - updateHOCHostEl(parentComponent, el); - } - } - function isVNodeSuspensible(vnode) { - const suspensible = vnode.props && vnode.props.suspensible; - return suspensible != null && suspensible !== false; - } - var Fragment = /* @__PURE__ */ Symbol.for("v-fgt"); - var Text = /* @__PURE__ */ Symbol.for("v-txt"); - var Comment = /* @__PURE__ */ Symbol.for("v-cmt"); - var Static = /* @__PURE__ */ Symbol.for("v-stc"); - var blockStack = []; - var currentBlock = null; - function openBlock(disableTracking = false) { - blockStack.push(currentBlock = disableTracking ? null : []); - } - function closeBlock() { - blockStack.pop(); - currentBlock = blockStack[blockStack.length - 1] || null; - } - var isBlockTreeEnabled = 1; - function setBlockTracking(value, inVOnce = false) { - isBlockTreeEnabled += value; - if (value < 0 && currentBlock && inVOnce) { - currentBlock.hasOnce = true; - } - } - function setupBlock(vnode) { - vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || shared.EMPTY_ARR : null; - closeBlock(); - if (isBlockTreeEnabled > 0 && currentBlock) { - currentBlock.push(vnode); - } - return vnode; - } - function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) { - return setupBlock( - createBaseVNode( - type, - props, - children, - patchFlag, - dynamicProps, - shapeFlag, - true - ) - ); - } - function createBlock(type, props, children, patchFlag, dynamicProps) { - return setupBlock( - createVNode( - type, - props, - children, - patchFlag, - dynamicProps, - true - ) - ); - } - function isVNode(value) { - return value ? value.__v_isVNode === true : false; - } - function isSameVNodeType(n1, n2) { - return n1.type === n2.type && n1.key === n2.key; - } - function transformVNodeArgs(transformer) { - } - var normalizeKey = ({ key }) => key != null ? key : null; - var normalizeRef = ({ - ref: ref2, - ref_key, - ref_for - }) => { - if (typeof ref2 === "number") { - ref2 = "" + ref2; - } - return ref2 != null ? shared.isString(ref2) || reactivity.isRef(ref2) || shared.isFunction(ref2) ? { i: currentRenderingInstance, r: ref2, k: ref_key, f: !!ref_for } : ref2 : null; - }; - function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1, isBlockNode = false, needFullChildrenNormalization = false) { - const vnode = { - __v_isVNode: true, - __v_skip: true, - type, - props, - key: props && normalizeKey(props), - ref: props && normalizeRef(props), - scopeId: currentScopeId, - slotScopeIds: null, - children, - component: null, - suspense: null, - ssContent: null, - ssFallback: null, - dirs: null, - transition: null, - el: null, - anchor: null, - target: null, - targetStart: null, - targetAnchor: null, - staticCount: 0, - shapeFlag, - patchFlag, - dynamicProps, - dynamicChildren: null, - appContext: null, - ctx: currentRenderingInstance - }; - if (needFullChildrenNormalization) { - normalizeChildren(vnode, children); - if (shapeFlag & 128) { - type.normalize(vnode); - } - } else if (children) { - vnode.shapeFlag |= shared.isString(children) ? 8 : 16; - } - if (isBlockTreeEnabled > 0 && // avoid a block node from tracking itself - !isBlockNode && // has current parent block - currentBlock && // presence of a patch flag indicates this node needs patching on updates. - // component nodes also should always be patched, because even if the - // component doesn't need to update, it needs to persist the instance on to - // the next vnode so that it can be properly unmounted later. - (vnode.patchFlag > 0 || shapeFlag & 6) && // the EVENTS flag is only for hydration and if it is the only flag, the - // vnode should not be considered dynamic due to handler caching. - vnode.patchFlag !== 32) { - currentBlock.push(vnode); - } - return vnode; - } - var createVNode = _createVNode; - function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) { - if (!type || type === NULL_DYNAMIC_COMPONENT) { - type = Comment; - } - if (isVNode(type)) { - const cloned = cloneVNode( - type, - props, - true - /* mergeRef: true */ - ); - if (children) { - normalizeChildren(cloned, children); - } - if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) { - if (cloned.shapeFlag & 6) { - currentBlock[currentBlock.indexOf(type)] = cloned; - } else { - currentBlock.push(cloned); - } - } - cloned.patchFlag = -2; - return cloned; - } - if (isClassComponent(type)) { - type = type.__vccOpts; - } - if (props) { - props = guardReactiveProps(props); - let { class: klass, style } = props; - if (klass && !shared.isString(klass)) { - props.class = shared.normalizeClass(klass); - } - if (shared.isObject(style)) { - if (reactivity.isProxy(style) && !shared.isArray(style)) { - style = shared.extend({}, style); - } - props.style = shared.normalizeStyle(style); - } - } - const shapeFlag = shared.isString(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : shared.isObject(type) ? 4 : shared.isFunction(type) ? 2 : 0; - return createBaseVNode( - type, - props, - children, - patchFlag, - dynamicProps, - shapeFlag, - isBlockNode, - true - ); - } - function guardReactiveProps(props) { - if (!props) return null; - return reactivity.isProxy(props) || isInternalObject(props) ? shared.extend({}, props) : props; - } - function cloneVNode(vnode, extraProps, mergeRef = false, cloneTransition = false) { - const { props, ref: ref2, patchFlag, children, transition } = vnode; - const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props; - const cloned = { - __v_isVNode: true, - __v_skip: true, - type: vnode.type, - props: mergedProps, - key: mergedProps && normalizeKey(mergedProps), - ref: extraProps && extraProps.ref ? ( - // #2078 in the case of <component :is="vnode" ref="extra"/> - // if the vnode itself already has a ref, cloneVNode will need to merge - // the refs so the single vnode can be set on multiple refs - mergeRef && ref2 ? shared.isArray(ref2) ? ref2.concat(normalizeRef(extraProps)) : [ref2, normalizeRef(extraProps)] : normalizeRef(extraProps) - ) : ref2, - scopeId: vnode.scopeId, - slotScopeIds: vnode.slotScopeIds, - children, - target: vnode.target, - targetStart: vnode.targetStart, - targetAnchor: vnode.targetAnchor, - staticCount: vnode.staticCount, - shapeFlag: vnode.shapeFlag, - // if the vnode is cloned with extra props, we can no longer assume its - // existing patch flag to be reliable and need to add the FULL_PROPS flag. - // note: preserve flag for fragments since they use the flag for children - // fast paths only. - patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag, - dynamicProps: vnode.dynamicProps, - dynamicChildren: vnode.dynamicChildren, - appContext: vnode.appContext, - dirs: vnode.dirs, - transition, - // These should technically only be non-null on mounted VNodes. However, - // they *should* be copied for kept-alive vnodes. So we just always copy - // them since them being non-null during a mount doesn't affect the logic as - // they will simply be overwritten. - component: vnode.component, - suspense: vnode.suspense, - ssContent: vnode.ssContent && cloneVNode(vnode.ssContent), - ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback), - placeholder: vnode.placeholder, - el: vnode.el, - anchor: vnode.anchor, - ctx: vnode.ctx, - ce: vnode.ce, - cacheIndex: vnode.cacheIndex - }; - if (transition && cloneTransition) { - setTransitionHooks( - cloned, - transition.clone(cloned) - ); - } - return cloned; - } - function createTextVNode(text = " ", flag = 0) { - return createVNode(Text, null, text, flag); - } - function createStaticVNode(content, numberOfNodes) { - const vnode = createVNode(Static, null, content); - vnode.staticCount = numberOfNodes; - return vnode; - } - function createCommentVNode(text = "", asBlock = false) { - return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text); - } - function normalizeVNode(child) { - if (child == null || typeof child === "boolean") { - return createVNode(Comment); - } else if (shared.isArray(child)) { - return createVNode( - Fragment, - null, - // #3666, avoid reference pollution when reusing vnode - child.slice() - ); - } else if (isVNode(child)) { - return cloneIfMounted(child); - } else { - return createVNode(Text, null, String(child)); - } - } - function cloneIfMounted(child) { - return child.el === null && child.patchFlag !== -1 || child.memo ? child : cloneVNode(child); - } - function normalizeChildren(vnode, children) { - let type = 0; - const { shapeFlag } = vnode; - if (children == null) { - children = null; - } else if (shared.isArray(children)) { - type = 16; - } else if (typeof children === "object") { - if (shapeFlag & (1 | 64)) { - const slot = children.default; - if (slot) { - slot._c && (slot._d = false); - normalizeChildren(vnode, slot()); - slot._c && (slot._d = true); - } - return; - } else { - type = 32; - const slotFlag = children._; - if (!slotFlag && !isInternalObject(children)) { - children._ctx = currentRenderingInstance; - } else if (slotFlag === 3 && currentRenderingInstance) { - if (currentRenderingInstance.slots._ === 1) { - children._ = 1; - } else { - children._ = 2; - vnode.patchFlag |= 1024; - } - } - } - } else if (shared.isFunction(children)) { - if (shapeFlag & (1 | 64)) { - normalizeChildren(vnode, { default: children }); - return; - } - children = { default: children, _ctx: currentRenderingInstance }; - type = 32; - } else { - children = String(children); - if (shapeFlag & 64) { - type = 16; - children = [createTextVNode(children)]; - } else { - type = 8; - } - } - vnode.children = children; - vnode.shapeFlag |= type; - } - function mergeProps(...args) { - const ret = {}; - for (let i = 0; i < args.length; i++) { - const toMerge = args[i]; - for (const key in toMerge) { - if (key === "class") { - if (ret.class !== toMerge.class) { - ret.class = shared.normalizeClass([ret.class, toMerge.class]); - } - } else if (key === "style") { - ret.style = shared.normalizeStyle([ret.style, toMerge.style]); - } else if (shared.isOn(key)) { - const existing = ret[key]; - const incoming = toMerge[key]; - if (incoming && existing !== incoming && !(shared.isArray(existing) && existing.includes(incoming))) { - ret[key] = existing ? [].concat(existing, incoming) : incoming; - } else if (incoming == null && existing == null && // mergeProps({ 'onUpdate:modelValue': undefined }) should not retain - // the model listener. - !shared.isModelListener(key)) { - ret[key] = incoming; - } - } else if (key !== "") { - ret[key] = toMerge[key]; - } - } - } - return ret; - } - function invokeVNodeHook(hook, instance, vnode, prevVNode = null) { - callWithAsyncErrorHandling(hook, instance, 7, [ - vnode, - prevVNode - ]); - } - var emptyAppContext = createAppContext(); - var uid = 0; - function getNextUid() { - return uid; - } - function createComponentInstance(vnode, parent, suspense) { - const type = vnode.type; - const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext; - const instance = { - uid: uid++, - vnode, - type, - parent, - appContext, - root: null, - // to be immediately set - next: null, - subTree: null, - // will be set synchronously right after creation - effect: null, - update: null, - // will be set synchronously right after creation - job: null, - scope: new reactivity.EffectScope( - true - /* detached */ - ), - render: null, - proxy: null, - exposed: null, - exposeProxy: null, - withProxy: null, - provides: parent ? parent.provides : Object.create(appContext.provides), - ids: parent ? parent.ids : ["", 0, 0], - accessCache: null, - renderCache: [], - // local resolved assets - components: null, - directives: null, - // resolved props and emits options - propsOptions: normalizePropsOptions(type, appContext), - emitsOptions: normalizeEmitsOptions(type, appContext), - // emit - emit: null, - // to be set immediately - emitted: null, - // props default value - propsDefaults: shared.EMPTY_OBJ, - // inheritAttrs - inheritAttrs: type.inheritAttrs, - // state - ctx: shared.EMPTY_OBJ, - data: shared.EMPTY_OBJ, - props: shared.EMPTY_OBJ, - attrs: shared.EMPTY_OBJ, - slots: shared.EMPTY_OBJ, - refs: shared.EMPTY_OBJ, - setupState: shared.EMPTY_OBJ, - setupContext: null, - // suspense related - suspense, - suspenseId: suspense ? suspense.pendingId : 0, - asyncDep: null, - asyncResolved: false, - // lifecycle hooks - // not using enums here because it results in computed properties - isMounted: false, - isUnmounted: false, - isDeactivated: false, - bc: null, - c: null, - bm: null, - m: null, - bu: null, - u: null, - um: null, - bum: null, - da: null, - a: null, - rtg: null, - rtc: null, - ec: null, - sp: null - }; - { - instance.ctx = { _: instance }; - } - instance.root = parent ? parent.root : instance; - instance.emit = emit.bind(null, instance); - if (vnode.ce) { - vnode.ce(instance); - } - return instance; - } - var currentInstance = null; - var getCurrentInstance = () => currentInstance || currentRenderingInstance; - var internalSetCurrentInstance; - var setInSSRSetupState; - { - const g = shared.getGlobalThis(); - const registerGlobalSetter = (key, setter) => { - let setters; - if (!(setters = g[key])) setters = g[key] = []; - setters.push(setter); - return (v) => { - if (setters.length > 1) setters.forEach((set) => set(v)); - else setters[0](v); - }; - }; - internalSetCurrentInstance = registerGlobalSetter( - `__VUE_INSTANCE_SETTERS__`, - (v) => currentInstance = v - ); - setInSSRSetupState = registerGlobalSetter( - `__VUE_SSR_SETTERS__`, - (v) => isInSSRComponentSetup = v - ); - } - var setCurrentInstance = (instance) => { - const prev = currentInstance; - internalSetCurrentInstance(instance); - instance.scope.on(); - return () => { - instance.scope.off(); - internalSetCurrentInstance(prev); - }; - }; - var unsetCurrentInstance = () => { - currentInstance && currentInstance.scope.off(); - internalSetCurrentInstance(null); - }; - function isStatefulComponent(instance) { - return instance.vnode.shapeFlag & 4; - } - var isInSSRComponentSetup = false; - function setupComponent(instance, isSSR = false, optimized = false) { - isSSR && setInSSRSetupState(isSSR); - const { props, children } = instance.vnode; - const isStateful = isStatefulComponent(instance); - initProps(instance, props, isStateful, isSSR); - initSlots(instance, children, optimized || isSSR); - const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0; - isSSR && setInSSRSetupState(false); - return setupResult; - } - function setupStatefulComponent(instance, isSSR) { - const Component = instance.type; - instance.accessCache = /* @__PURE__ */ Object.create(null); - instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers); - const { setup } = Component; - if (setup) { - reactivity.pauseTracking(); - const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null; - const reset = setCurrentInstance(instance); - const setupResult = callWithErrorHandling( - setup, - instance, - 0, - [ - instance.props, - setupContext - ] - ); - const isAsyncSetup = shared.isPromise(setupResult); - reactivity.resetTracking(); - reset(); - if ((isAsyncSetup || instance.sp) && !isAsyncWrapper(instance)) { - markAsyncBoundary(instance); - } - if (isAsyncSetup) { - setupResult.then(unsetCurrentInstance, unsetCurrentInstance); - if (isSSR) { - return setupResult.then((resolvedResult) => { - setInSSRSetupState(true); - try { - handleSetupResult(instance, resolvedResult, isSSR); - } finally { - setInSSRSetupState(false); - } - }).catch((e) => { - handleError(e, instance, 0); - }); - } else { - instance.asyncDep = setupResult; - } - } else { - handleSetupResult(instance, setupResult, isSSR); - } - } else { - finishComponentSetup(instance, isSSR); - } - } - function handleSetupResult(instance, setupResult, isSSR) { - if (shared.isFunction(setupResult)) { - if (instance.type.__ssrInlineRender) { - instance.ssrRender = setupResult; - } else { - instance.render = setupResult; - } - } else if (shared.isObject(setupResult)) { - instance.setupState = reactivity.proxyRefs(setupResult); - } else ; - finishComponentSetup(instance, isSSR); - } - var compile; - var installWithProxy; - function registerRuntimeCompiler(_compile) { - compile = _compile; - installWithProxy = (i) => { - if (i.render._rc) { - i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers); - } - }; - } - var isRuntimeOnly = () => !compile; - function finishComponentSetup(instance, isSSR, skipOptions) { - const Component = instance.type; - if (!instance.render) { - if (!isSSR && compile && !Component.render) { - const template = Component.template || resolveMergedOptions(instance).template; - if (template) { - const { isCustomElement, compilerOptions } = instance.appContext.config; - const { delimiters, compilerOptions: componentCompilerOptions } = Component; - const finalCompilerOptions = shared.extend( - shared.extend( - { - isCustomElement, - delimiters - }, - compilerOptions - ), - componentCompilerOptions - ); - Component.render = compile(template, finalCompilerOptions); - } - } - instance.render = Component.render || shared.NOOP; - if (installWithProxy) { - installWithProxy(instance); - } - } - { - const reset = setCurrentInstance(instance); - reactivity.pauseTracking(); - try { - applyOptions(instance); - } finally { - reactivity.resetTracking(); - reset(); - } - } - } - var attrsProxyHandlers = { - get(target, key) { - reactivity.track(target, "get", ""); - return target[key]; - } - }; - function createSetupContext(instance) { - const expose = (exposed) => { - instance.exposed = exposed || {}; - }; - { - return { - attrs: new Proxy(instance.attrs, attrsProxyHandlers), - slots: instance.slots, - emit: instance.emit, - expose - }; - } - } - function getComponentPublicInstance(instance) { - if (instance.exposed) { - return instance.exposeProxy || (instance.exposeProxy = new Proxy(reactivity.proxyRefs(reactivity.markRaw(instance.exposed)), { - get(target, key) { - if (key in target) { - return target[key]; - } else if (key in publicPropertiesMap) { - return publicPropertiesMap[key](instance); - } - }, - has(target, key) { - return key in target || key in publicPropertiesMap; - } - })); - } else { - return instance.proxy; - } - } - function getComponentName(Component, includeInferred = true) { - return shared.isFunction(Component) ? Component.displayName || Component.name : Component.name || includeInferred && Component.__name; - } - function isClassComponent(value) { - return shared.isFunction(value) && "__vccOpts" in value; - } - var computed = (getterOrOptions, debugOptions) => { - const c = reactivity.computed(getterOrOptions, debugOptions, isInSSRComponentSetup); - return c; - }; - function h(type, propsOrChildren, children) { - try { - setBlockTracking(-1); - const l = arguments.length; - if (l === 2) { - if (shared.isObject(propsOrChildren) && !shared.isArray(propsOrChildren)) { - if (isVNode(propsOrChildren)) { - return createVNode(type, null, [propsOrChildren]); - } - return createVNode(type, propsOrChildren); - } else { - return createVNode(type, null, propsOrChildren); - } - } else { - if (l > 3) { - children = Array.prototype.slice.call(arguments, 2); - } else if (l === 3 && isVNode(children)) { - children = [children]; - } - return createVNode(type, propsOrChildren, children); - } - } finally { - setBlockTracking(1); - } - } - function initCustomFormatter() { - { - return; - } - } - function withMemo(memo, render, cache, index) { - const cached = cache[index]; - if (cached && isMemoSame(cached, memo)) { - return cached; - } - const ret = render(); - ret.memo = memo.slice(); - ret.cacheIndex = index; - return cache[index] = ret; - } - function isMemoSame(cached, memo) { - const prev = cached.memo; - if (prev.length != memo.length) { - return false; - } - for (let i = 0; i < prev.length; i++) { - if (shared.hasChanged(prev[i], memo[i])) { - return false; - } - } - if (isBlockTreeEnabled > 0 && currentBlock) { - currentBlock.push(cached); - } - return true; - } - var version = "3.5.44"; - var warn$1 = shared.NOOP; - var ErrorTypeStrings = ErrorTypeStrings$1; - var devtools = void 0; - var setDevtoolsHook = shared.NOOP; - var _ssrUtils = { - createComponentInstance, - setupComponent, - renderComponentRoot, - setCurrentRenderingInstance, - isVNode, - normalizeVNode, - getComponentPublicInstance, - ensureValidVNode, - pushWarningContext, - popWarningContext - }; - var ssrUtils = _ssrUtils; - var resolveFilter = null; - var compatUtils = null; - var DeprecationTypes = null; - exports2.EffectScope = reactivity.EffectScope; - exports2.ReactiveEffect = reactivity.ReactiveEffect; - exports2.TrackOpTypes = reactivity.TrackOpTypes; - exports2.TriggerOpTypes = reactivity.TriggerOpTypes; - exports2.customRef = reactivity.customRef; - exports2.effect = reactivity.effect; - exports2.effectScope = reactivity.effectScope; - exports2.getCurrentScope = reactivity.getCurrentScope; - exports2.getCurrentWatcher = reactivity.getCurrentWatcher; - exports2.isProxy = reactivity.isProxy; - exports2.isReactive = reactivity.isReactive; - exports2.isReadonly = reactivity.isReadonly; - exports2.isRef = reactivity.isRef; - exports2.isShallow = reactivity.isShallow; - exports2.markRaw = reactivity.markRaw; - exports2.onScopeDispose = reactivity.onScopeDispose; - exports2.onWatcherCleanup = reactivity.onWatcherCleanup; - exports2.proxyRefs = reactivity.proxyRefs; - exports2.reactive = reactivity.reactive; - exports2.readonly = reactivity.readonly; - exports2.ref = reactivity.ref; - exports2.shallowReactive = reactivity.shallowReactive; - exports2.shallowReadonly = reactivity.shallowReadonly; - exports2.shallowRef = reactivity.shallowRef; - exports2.stop = reactivity.stop; - exports2.toRaw = reactivity.toRaw; - exports2.toRef = reactivity.toRef; - exports2.toRefs = reactivity.toRefs; - exports2.toValue = reactivity.toValue; - exports2.triggerRef = reactivity.triggerRef; - exports2.unref = reactivity.unref; - exports2.camelize = shared.camelize; - exports2.capitalize = shared.capitalize; - exports2.normalizeClass = shared.normalizeClass; - exports2.normalizeProps = shared.normalizeProps; - exports2.normalizeStyle = shared.normalizeStyle; - exports2.toDisplayString = shared.toDisplayString; - exports2.toHandlerKey = shared.toHandlerKey; - exports2.BaseTransition = BaseTransition; - exports2.BaseTransitionPropsValidators = BaseTransitionPropsValidators; - exports2.Comment = Comment; - exports2.DeprecationTypes = DeprecationTypes; - exports2.ErrorCodes = ErrorCodes; - exports2.ErrorTypeStrings = ErrorTypeStrings; - exports2.Fragment = Fragment; - exports2.KeepAlive = KeepAlive; - exports2.Static = Static; - exports2.Suspense = Suspense; - exports2.Teleport = Teleport; - exports2.Text = Text; - exports2.assertNumber = assertNumber; - exports2.callWithAsyncErrorHandling = callWithAsyncErrorHandling; - exports2.callWithErrorHandling = callWithErrorHandling; - exports2.cloneVNode = cloneVNode; - exports2.compatUtils = compatUtils; - exports2.computed = computed; - exports2.createBlock = createBlock; - exports2.createCommentVNode = createCommentVNode; - exports2.createElementBlock = createElementBlock; - exports2.createElementVNode = createBaseVNode; - exports2.createHydrationRenderer = createHydrationRenderer; - exports2.createPropsRestProxy = createPropsRestProxy; - exports2.createRenderer = createRenderer; - exports2.createSlots = createSlots; - exports2.createStaticVNode = createStaticVNode; - exports2.createTextVNode = createTextVNode; - exports2.createVNode = createVNode; - exports2.defineAsyncComponent = defineAsyncComponent; - exports2.defineComponent = defineComponent; - exports2.defineEmits = defineEmits; - exports2.defineExpose = defineExpose; - exports2.defineModel = defineModel; - exports2.defineOptions = defineOptions; - exports2.defineProps = defineProps; - exports2.defineSlots = defineSlots; - exports2.devtools = devtools; - exports2.getCurrentInstance = getCurrentInstance; - exports2.getTransitionRawChildren = getTransitionRawChildren; - exports2.guardReactiveProps = guardReactiveProps; - exports2.h = h; - exports2.handleError = handleError; - exports2.hasInjectionContext = hasInjectionContext; - exports2.hydrateOnIdle = hydrateOnIdle; - exports2.hydrateOnInteraction = hydrateOnInteraction; - exports2.hydrateOnMediaQuery = hydrateOnMediaQuery; - exports2.hydrateOnVisible = hydrateOnVisible; - exports2.initCustomFormatter = initCustomFormatter; - exports2.inject = inject; - exports2.isMemoSame = isMemoSame; - exports2.isRuntimeOnly = isRuntimeOnly; - exports2.isVNode = isVNode; - exports2.mergeDefaults = mergeDefaults; - exports2.mergeModels = mergeModels; - exports2.mergeProps = mergeProps; - exports2.nextTick = nextTick; - exports2.onActivated = onActivated; - exports2.onBeforeMount = onBeforeMount; - exports2.onBeforeUnmount = onBeforeUnmount; - exports2.onBeforeUpdate = onBeforeUpdate; - exports2.onDeactivated = onDeactivated; - exports2.onErrorCaptured = onErrorCaptured; - exports2.onMounted = onMounted; - exports2.onRenderTracked = onRenderTracked; - exports2.onRenderTriggered = onRenderTriggered; - exports2.onServerPrefetch = onServerPrefetch; - exports2.onUnmounted = onUnmounted; - exports2.onUpdated = onUpdated; - exports2.openBlock = openBlock; - exports2.popScopeId = popScopeId; - exports2.provide = provide; - exports2.pushScopeId = pushScopeId; - exports2.queuePostFlushCb = queuePostFlushCb; - exports2.registerRuntimeCompiler = registerRuntimeCompiler; - exports2.renderList = renderList; - exports2.renderSlot = renderSlot; - exports2.resolveComponent = resolveComponent; - exports2.resolveDirective = resolveDirective; - exports2.resolveDynamicComponent = resolveDynamicComponent; - exports2.resolveFilter = resolveFilter; - exports2.resolveTransitionHooks = resolveTransitionHooks; - exports2.setBlockTracking = setBlockTracking; - exports2.setDevtoolsHook = setDevtoolsHook; - exports2.setTransitionHooks = setTransitionHooks; - exports2.ssrContextKey = ssrContextKey; - exports2.ssrUtils = ssrUtils; - exports2.toHandlers = toHandlers; - exports2.transformVNodeArgs = transformVNodeArgs; - exports2.useAttrs = useAttrs; - exports2.useId = useId; - exports2.useModel = useModel; - exports2.useSSRContext = useSSRContext; - exports2.useSlots = useSlots; - exports2.useTemplateRef = useTemplateRef; - exports2.useTransitionState = useTransitionState; - exports2.version = version; - exports2.warn = warn$1; - exports2.watch = watch; - exports2.watchEffect = watchEffect; - exports2.watchPostEffect = watchPostEffect; - exports2.watchSyncEffect = watchSyncEffect; - exports2.withAsyncContext = withAsyncContext; - exports2.withCtx = withCtx; - exports2.withDefaults = withDefaults; - exports2.withDirectives = withDirectives; - exports2.withMemo = withMemo; - exports2.withScopeId = withScopeId; - } -}); - -// intern-log/node_modules/.pnpm/@vue+runtime-core@3.5.44/node_modules/@vue/runtime-core/dist/runtime-core.cjs.js -var require_runtime_core_cjs = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+runtime-core@3.5.44/node_modules/@vue/runtime-core/dist/runtime-core.cjs.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var reactivity = require_reactivity(); - var shared = require_shared(); - var stack = []; - function pushWarningContext(vnode) { - stack.push(vnode); - } - function popWarningContext() { - stack.pop(); - } - var isWarning = false; - function warn$1(msg, ...args) { - if (isWarning) return; - isWarning = true; - reactivity.pauseTracking(); - const instance = stack.length ? stack[stack.length - 1].component : null; - const appWarnHandler = instance && instance.appContext.config.warnHandler; - const trace = getComponentTrace(); - if (appWarnHandler) { - callWithErrorHandling( - appWarnHandler, - instance, - 11, - [ - // eslint-disable-next-line no-restricted-syntax - msg + args.map((a) => { - var _a, _b; - return (_b = (_a = a.toString) == null ? void 0 : _a.call(a)) != null ? _b : JSON.stringify(a); - }).join(""), - instance && instance.proxy, - trace.map( - ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>` - ).join("\n"), - trace - ] - ); - } else { - const warnArgs = [`[Vue warn]: ${msg}`, ...args]; - if (trace.length && // avoid spamming console during tests - true) { - warnArgs.push(` -`, ...formatTrace(trace)); - } - console.warn(...warnArgs); - } - reactivity.resetTracking(); - isWarning = false; - } - function getComponentTrace() { - let currentVNode = stack[stack.length - 1]; - if (!currentVNode) { - return []; - } - const normalizedStack = []; - while (currentVNode) { - const last = normalizedStack[0]; - if (last && last.vnode === currentVNode) { - last.recurseCount++; - } else { - normalizedStack.push({ - vnode: currentVNode, - recurseCount: 0 - }); - } - const parentInstance = currentVNode.component && currentVNode.component.parent; - currentVNode = parentInstance && parentInstance.vnode; - } - return normalizedStack; - } - function formatTrace(trace) { - const logs = []; - trace.forEach((entry, i) => { - logs.push(...i === 0 ? [] : [` -`], ...formatTraceEntry(entry)); - }); - return logs; - } - function formatTraceEntry({ vnode, recurseCount }) { - const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; - const isRoot = vnode.component ? vnode.component.parent == null : false; - const open = ` at <${formatComponentName( - vnode.component, - vnode.type, - isRoot - )}`; - const close = `>` + postfix; - return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close]; - } - function formatProps(props) { - const res = []; - const keys = Object.keys(props); - keys.slice(0, 3).forEach((key) => { - res.push(...formatProp(key, props[key])); - }); - if (keys.length > 3) { - res.push(` ...`); - } - return res; - } - function formatProp(key, value, raw) { - if (shared.isString(value)) { - value = JSON.stringify(value); - return raw ? value : [`${key}=${value}`]; - } else if (typeof value === "number" || typeof value === "boolean" || value == null) { - return raw ? value : [`${key}=${value}`]; - } else if (reactivity.isRef(value)) { - value = formatProp(key, reactivity.toRaw(value.value), true); - return raw ? value : [`${key}=Ref<`, value, `>`]; - } else if (shared.isFunction(value)) { - return [`${key}=fn${value.name ? `<${value.name}>` : ``}`]; - } else { - value = reactivity.toRaw(value); - return raw ? value : [`${key}=`, value]; - } - } - function assertNumber(val, type) { - if (val === void 0) { - return; - } else if (typeof val !== "number") { - warn$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`); - } else if (isNaN(val)) { - warn$1(`${type} is NaN - the duration expression might be incorrect.`); - } - } - var ErrorCodes = { - "SETUP_FUNCTION": 0, - "0": "SETUP_FUNCTION", - "RENDER_FUNCTION": 1, - "1": "RENDER_FUNCTION", - "NATIVE_EVENT_HANDLER": 5, - "5": "NATIVE_EVENT_HANDLER", - "COMPONENT_EVENT_HANDLER": 6, - "6": "COMPONENT_EVENT_HANDLER", - "VNODE_HOOK": 7, - "7": "VNODE_HOOK", - "DIRECTIVE_HOOK": 8, - "8": "DIRECTIVE_HOOK", - "TRANSITION_HOOK": 9, - "9": "TRANSITION_HOOK", - "APP_ERROR_HANDLER": 10, - "10": "APP_ERROR_HANDLER", - "APP_WARN_HANDLER": 11, - "11": "APP_WARN_HANDLER", - "FUNCTION_REF": 12, - "12": "FUNCTION_REF", - "ASYNC_COMPONENT_LOADER": 13, - "13": "ASYNC_COMPONENT_LOADER", - "SCHEDULER": 14, - "14": "SCHEDULER", - "COMPONENT_UPDATE": 15, - "15": "COMPONENT_UPDATE", - "APP_UNMOUNT_CLEANUP": 16, - "16": "APP_UNMOUNT_CLEANUP" - }; - var ErrorTypeStrings$1 = { - ["sp"]: "serverPrefetch hook", - ["bc"]: "beforeCreate hook", - ["c"]: "created hook", - ["bm"]: "beforeMount hook", - ["m"]: "mounted hook", - ["bu"]: "beforeUpdate hook", - ["u"]: "updated", - ["bum"]: "beforeUnmount hook", - ["um"]: "unmounted hook", - ["a"]: "activated hook", - ["da"]: "deactivated hook", - ["ec"]: "errorCaptured hook", - ["rtc"]: "renderTracked hook", - ["rtg"]: "renderTriggered hook", - [0]: "setup function", - [1]: "render function", - [2]: "watcher getter", - [3]: "watcher callback", - [4]: "watcher cleanup function", - [5]: "native event handler", - [6]: "component event handler", - [7]: "vnode hook", - [8]: "directive hook", - [9]: "transition hook", - [10]: "app errorHandler", - [11]: "app warnHandler", - [12]: "ref function", - [13]: "async component loader", - [14]: "scheduler flush", - [15]: "component update", - [16]: "app unmount cleanup function" - }; - function callWithErrorHandling(fn, instance, type, args) { - try { - return args ? fn(...args) : fn(); - } catch (err) { - handleError(err, instance, type); - } - } - function callWithAsyncErrorHandling(fn, instance, type, args) { - if (shared.isFunction(fn)) { - const res = callWithErrorHandling(fn, instance, type, args); - if (res && shared.isPromise(res)) { - res.catch((err) => { - handleError(err, instance, type); - }); - } - return res; - } - if (shared.isArray(fn)) { - const values = []; - for (let i = 0; i < fn.length; i++) { - values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)); - } - return values; - } else { - warn$1( - `Invalid value type passed to callWithAsyncErrorHandling(): ${typeof fn}` - ); - } - } - function handleError(err, instance, type, throwInDev = true) { - const contextVNode = instance ? instance.vnode : null; - const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || shared.EMPTY_OBJ; - if (instance) { - let cur = instance.parent; - const exposedInstance = instance.proxy; - const errorInfo = ErrorTypeStrings$1[type]; - while (cur) { - const errorCapturedHooks = cur.ec; - if (errorCapturedHooks) { - for (let i = 0; i < errorCapturedHooks.length; i++) { - if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) { - return; - } - } - } - cur = cur.parent; - } - if (errorHandler) { - reactivity.pauseTracking(); - callWithErrorHandling(errorHandler, null, 10, [ - err, - exposedInstance, - errorInfo - ]); - reactivity.resetTracking(); - return; - } - } - logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction); - } - function logError(err, type, contextVNode, throwInDev = true, throwInProd = false) { - { - const info = ErrorTypeStrings$1[type]; - if (contextVNode) { - pushWarningContext(contextVNode); - } - warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`); - if (contextVNode) { - popWarningContext(); - } - if (throwInDev) { - throw err; - } else { - console.error(err); - } - } - } - var queue = []; - var flushIndex = -1; - var pendingPostFlushCbs = []; - var activePostFlushCbs = null; - var postFlushIndex = 0; - var resolvedPromise = /* @__PURE__ */ Promise.resolve(); - var currentFlushPromise = null; - var RECURSION_LIMIT = 100; - function nextTick(fn) { - const p = currentFlushPromise || resolvedPromise; - return fn ? p.then(this ? fn.bind(this) : fn) : p; - } - function findInsertionIndex(id) { - let start = flushIndex + 1; - let end = queue.length; - while (start < end) { - const middle = start + end >>> 1; - const middleJob = queue[middle]; - const middleJobId = getId(middleJob); - if (middleJobId < id || middleJobId === id && middleJob.flags & 2) { - start = middle + 1; - } else { - end = middle; - } - } - return start; - } - function queueJob(job) { - if (!(job.flags & 1)) { - const jobId = getId(job); - const lastJob = queue[queue.length - 1]; - if (!lastJob || // fast path when the job id is larger than the tail - !(job.flags & 2) && jobId >= getId(lastJob)) { - queue.push(job); - } else { - queue.splice(findInsertionIndex(jobId), 0, job); - } - job.flags |= 1; - queueFlush(); - } - } - function queueFlush() { - if (!currentFlushPromise) { - currentFlushPromise = resolvedPromise.then(flushJobs); - } - } - function queuePostFlushCb(cb) { - if (!shared.isArray(cb)) { - if (activePostFlushCbs && cb.id === -1) { - activePostFlushCbs.splice(postFlushIndex + 1, 0, cb); - } else if (!(cb.flags & 1)) { - pendingPostFlushCbs.push(cb); - cb.flags |= 1; - } - } else { - for (let i = 0; i < cb.length; i++) { - pendingPostFlushCbs.push(cb[i]); - } - } - queueFlush(); - } - function flushPreFlushCbs(instance, minUid, seen, i = flushIndex + 1) { - { - seen = seen || /* @__PURE__ */ new Map(); - } - for (; i < queue.length; i++) { - const cb = queue[i]; - if (cb && cb.flags & 2) { - if (instance && cb.id !== instance.uid || minUid !== void 0 && !(cb.id >= minUid)) { - continue; - } - if (checkRecursiveUpdates(seen, cb)) { - continue; - } - queue.splice(i, 1); - i = instance ? i - 1 : flushIndex; - if (cb.flags & 4) { - cb.flags &= -2; - } - cb(); - if (!(cb.flags & 4)) { - cb.flags &= -2; - } - } - } - } - function flushPostFlushCbs(seen, skip, minUid = 0) { - if (pendingPostFlushCbs.length) { - let cbs = pendingPostFlushCbs; - let kept = 0; - if (skip) { - cbs = []; - for (let i = 0; i < pendingPostFlushCbs.length; i++) { - const cb = pendingPostFlushCbs[i]; - if (cb.i !== void 0 ? !cb.i || cb.i.uid < minUid : skip.has(cb)) { - pendingPostFlushCbs[kept++] = cb; - } else { - cbs.push(cb); - } - } - } - const deduped = [...new Set(cbs)].sort((a, b) => getId(a) - getId(b)); - pendingPostFlushCbs.length = kept; - if (activePostFlushCbs) { - for (let i = 0; i < deduped.length; i++) { - activePostFlushCbs.push(deduped[i]); - } - return; - } - activePostFlushCbs = deduped; - { - seen = seen || /* @__PURE__ */ new Map(); - } - for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { - const cb = activePostFlushCbs[postFlushIndex]; - if (checkRecursiveUpdates(seen, cb)) { - continue; - } - if (cb.flags & 4) { - cb.flags &= -2; - } - if (!(cb.flags & 8)) cb(); - cb.flags &= -2; - } - activePostFlushCbs = null; - postFlushIndex = 0; - } - } - var isFlushing = false; - function flushOnAppMount(fn, minUid) { - if (isFlushing) { - fn(); - return; - } - const queued = minUid === void 0 ? void 0 : new Set(pendingPostFlushCbs); - fn(); - isFlushing = true; - try { - flushPreFlushCbs(void 0, minUid); - flushPostFlushCbs(void 0, queued, minUid); - } finally { - isFlushing = false; - } - } - var getId = (job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id; - function flushJobs(seen) { - { - seen = seen || /* @__PURE__ */ new Map(); - } - const check2 = (job) => checkRecursiveUpdates(seen, job); - try { - for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job && !(job.flags & 8)) { - if (check2(job)) { - continue; - } - if (job.flags & 4) { - job.flags &= ~1; - } - callWithErrorHandling( - job, - job.i, - job.i ? 15 : 14 - ); - if (!(job.flags & 4)) { - job.flags &= ~1; - } - } - } - } finally { - for (; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job) { - job.flags &= -2; - } - } - flushIndex = -1; - queue.length = 0; - flushPostFlushCbs(seen); - currentFlushPromise = null; - if (queue.length || pendingPostFlushCbs.length) { - flushJobs(seen); - } - } - } - function checkRecursiveUpdates(seen, fn) { - const count = seen.get(fn) || 0; - if (count > RECURSION_LIMIT) { - const instance = fn.i; - const componentName = instance && getComponentName(instance.type); - handleError( - `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`, - null, - 10 - ); - return true; - } - seen.set(fn, count + 1); - return false; - } - var isHmrUpdating = false; - var setHmrUpdating = (v) => { - try { - return isHmrUpdating; - } finally { - isHmrUpdating = v; - } - }; - var hmrDirtyComponents = /* @__PURE__ */ new Map(); - { - shared.getGlobalThis().__VUE_HMR_RUNTIME__ = { - createRecord: tryWrap(createRecord), - rerender: tryWrap(rerender), - reload: tryWrap(reload) - }; - } - var map = /* @__PURE__ */ new Map(); - function registerHMR(instance) { - const id = instance.type.__hmrId; - let record = map.get(id); - if (!record) { - createRecord(id, instance.type); - record = map.get(id); - } - record.instances.add(instance); - } - function unregisterHMR(instance) { - map.get(instance.type.__hmrId).instances.delete(instance); - } - function createRecord(id, initialDef) { - if (map.has(id)) { - return false; - } - map.set(id, { - initialDef: normalizeClassComponent(initialDef), - instances: /* @__PURE__ */ new Set() - }); - return true; - } - function normalizeClassComponent(component) { - return isClassComponent(component) ? component.__vccOpts : component; - } - function rerender(id, newRender) { - const record = map.get(id); - if (!record) { - return; - } - record.initialDef.render = newRender; - [...record.instances].forEach((instance) => { - if (newRender) { - instance.render = newRender; - normalizeClassComponent(instance.type).render = newRender; - } - instance.renderCache = []; - isHmrUpdating = true; - if (!(instance.job.flags & 8)) { - instance.update(); - } - isHmrUpdating = false; - }); - } - function reload(id, newComp) { - const record = map.get(id); - if (!record) return; - newComp = normalizeClassComponent(newComp); - updateComponentDef(record.initialDef, newComp); - const instances = [...record.instances]; - for (let i = 0; i < instances.length; i++) { - const instance = instances[i]; - const oldComp = normalizeClassComponent(instance.type); - let dirtyInstances = hmrDirtyComponents.get(oldComp); - if (!dirtyInstances) { - if (oldComp !== record.initialDef) { - updateComponentDef(oldComp, newComp); - } - hmrDirtyComponents.set(oldComp, dirtyInstances = /* @__PURE__ */ new Set()); - } - dirtyInstances.add(instance); - instance.appContext.propsCache.delete(instance.type); - instance.appContext.emitsCache.delete(instance.type); - instance.appContext.optionsCache.delete(instance.type); - if (instance.ceReload) { - dirtyInstances.add(instance); - instance.ceReload(newComp.styles); - dirtyInstances.delete(instance); - } else if (instance.parent) { - queueJob(() => { - if (!(instance.job.flags & 8)) { - isHmrUpdating = true; - instance.parent.update(); - isHmrUpdating = false; - dirtyInstances.delete(instance); - } - }); - } else if (instance.appContext.reload) { - instance.appContext.reload(); - } else if (typeof window !== "undefined") { - window.location.reload(); - } else { - console.warn( - "[HMR] Root or manually mounted instance modified. Full reload required." - ); - } - if (instance.root.ce && instance !== instance.root) { - instance.root.ce._removeChildStyle(oldComp); - } - } - queuePostFlushCb(() => { - hmrDirtyComponents.clear(); - }); - } - function updateComponentDef(oldComp, newComp) { - shared.extend(oldComp, newComp); - for (const key in oldComp) { - if (key !== "__file" && !(key in newComp)) { - delete oldComp[key]; - } - } - } - function tryWrap(fn) { - return (id, arg) => { - try { - return fn(id, arg); - } catch (e) { - console.error(e); - console.warn( - `[HMR] Something went wrong during Vue component hot-reload. Full reload required.` - ); - } - }; - } - var devtools$1; - var buffer = []; - var devtoolsNotInstalled = false; - function emit$1(event, ...args) { - if (devtools$1) { - devtools$1.emit(event, ...args); - } else if (!devtoolsNotInstalled) { - buffer.push({ event, args }); - } - } - function setDevtoolsHook$1(hook, target) { - var _a, _b; - devtools$1 = hook; - if (devtools$1) { - devtools$1.enabled = true; - buffer.forEach(({ event, args }) => devtools$1.emit(event, ...args)); - buffer = []; - } else if ( - // handle late devtools injection - only do this if we are in an actual - // browser environment to avoid the timer handle stalling test runner exit - // (#4815) - typeof window !== "undefined" && // some envs mock window but not fully - window.HTMLElement && // also exclude jsdom - // eslint-disable-next-line no-restricted-syntax - !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null ? void 0 : _b.includes("jsdom")) - ) { - const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []; - replay.push((newHook) => { - setDevtoolsHook$1(newHook, target); - }); - setTimeout(() => { - if (!devtools$1) { - target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null; - devtoolsNotInstalled = true; - buffer = []; - } - }, 3e3); - } else { - devtoolsNotInstalled = true; - buffer = []; - } - } - function devtoolsInitApp(app, version2) { - emit$1("app:init", app, version2, { - Fragment, - Text, - Comment, - Static - }); - } - function devtoolsUnmountApp(app) { - emit$1("app:unmount", app); - } - var devtoolsComponentAdded = /* @__PURE__ */ createDevtoolsComponentHook( - "component:added" - /* COMPONENT_ADDED */ - ); - var devtoolsComponentUpdated = /* @__PURE__ */ createDevtoolsComponentHook( - "component:updated" - /* COMPONENT_UPDATED */ - ); - var _devtoolsComponentRemoved = /* @__PURE__ */ createDevtoolsComponentHook( - "component:removed" - /* COMPONENT_REMOVED */ - ); - var devtoolsComponentRemoved = (component) => { - if (devtools$1 && typeof devtools$1.cleanupBuffer === "function" && // remove the component if it wasn't buffered - !devtools$1.cleanupBuffer(component)) { - _devtoolsComponentRemoved(component); - } - }; - // @__NO_SIDE_EFFECTS__ - function createDevtoolsComponentHook(hook) { - return (component) => { - emit$1( - hook, - component.appContext.app, - component.uid, - component.parent ? component.parent.uid : void 0, - component - ); - }; - } - var devtoolsPerfStart = /* @__PURE__ */ createDevtoolsPerformanceHook( - "perf:start" - /* PERFORMANCE_START */ - ); - var devtoolsPerfEnd = /* @__PURE__ */ createDevtoolsPerformanceHook( - "perf:end" - /* PERFORMANCE_END */ - ); - function createDevtoolsPerformanceHook(hook) { - return (component, type, time) => { - emit$1(hook, component.appContext.app, component.uid, component, type, time); - }; - } - function devtoolsComponentEmit(component, event, params) { - emit$1( - "component:emit", - component.appContext.app, - component, - event, - params - ); - } - var currentRenderingInstance = null; - var currentScopeId = null; - function setCurrentRenderingInstance(instance) { - const prev = currentRenderingInstance; - currentRenderingInstance = instance; - currentScopeId = instance && instance.type.__scopeId || null; - return prev; - } - function pushScopeId(id) { - currentScopeId = id; - } - function popScopeId() { - currentScopeId = null; - } - var withScopeId = (_id) => withCtx; - function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { - if (!ctx) return fn; - if (fn._n) { - return fn; - } - const renderFnWithContext = (...args) => { - if (renderFnWithContext._d) { - setBlockTracking(-1); - } - const prevInstance = setCurrentRenderingInstance(ctx); - const prevStackSize = blockStack.length; - let res; - try { - res = fn(...args); - } finally { - for (let i = blockStack.length; i > prevStackSize; i--) closeBlock(); - setCurrentRenderingInstance(prevInstance); - if (renderFnWithContext._d) { - setBlockTracking(1); - } - } - { - devtoolsComponentUpdated(ctx); - } - return res; - }; - renderFnWithContext._n = true; - renderFnWithContext._c = true; - renderFnWithContext._d = true; - return renderFnWithContext; - } - function validateDirectiveName(name) { - if (shared.isBuiltInDirective(name)) { - warn$1("Do not use built-in directive ids as custom directive id: " + name); - } - } - function withDirectives(vnode, directives) { - if (currentRenderingInstance === null) { - warn$1(`withDirectives can only be used inside render functions.`); - return vnode; - } - const instance = getComponentPublicInstance(currentRenderingInstance); - const bindings = vnode.dirs || (vnode.dirs = []); - for (let i = 0; i < directives.length; i++) { - let [dir, value, arg, modifiers = shared.EMPTY_OBJ] = directives[i]; - if (dir) { - if (shared.isFunction(dir)) { - dir = { - mounted: dir, - updated: dir - }; - } - if (dir.deep) { - reactivity.traverse(value); - } - bindings.push({ - dir, - instance, - value, - oldValue: void 0, - arg, - modifiers - }); - } - } - return vnode; - } - function invokeDirectiveHook(vnode, prevVNode, instance, name) { - const bindings = vnode.dirs; - const oldBindings = prevVNode && prevVNode.dirs; - for (let i = 0; i < bindings.length; i++) { - const binding = bindings[i]; - if (oldBindings) { - binding.oldValue = oldBindings[i].value; - } - let hook = binding.dir[name]; - if (hook) { - reactivity.pauseTracking(); - callWithAsyncErrorHandling(hook, instance, 8, [ - vnode.el, - binding, - vnode, - prevVNode - ]); - reactivity.resetTracking(); - } - } - } - function provide(key, value) { - { - if (!currentInstance || currentInstance.isMounted) { - warn$1(`provide() can only be used inside setup().`); - } - } - if (currentInstance) { - let provides = currentInstance.provides; - const parentProvides = currentInstance.parent && currentInstance.parent.provides; - if (parentProvides === provides) { - provides = currentInstance.provides = Object.create(parentProvides); - } - provides[key] = value; - } - } - function inject(key, defaultValue, treatDefaultAsFactory = false) { - const instance = getCurrentInstance(); - if (instance || currentApp) { - let provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null || instance.ce ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0; - if (provides && key in provides) { - return provides[key]; - } else if (arguments.length > 1) { - return treatDefaultAsFactory && shared.isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue; - } else { - warn$1(`injection "${String(key)}" not found.`); - } - } else { - warn$1(`inject() can only be used inside setup() or functional components.`); - } - } - function hasInjectionContext() { - return !!(getCurrentInstance() || currentApp); - } - var ssrContextKey = /* @__PURE__ */ Symbol.for("v-scx"); - var useSSRContext = () => { - { - const ctx = inject(ssrContextKey); - if (!ctx) { - warn$1( - `Server rendering context not provided. Make sure to only call useSSRContext() conditionally in the server build.` - ); - } - return ctx; - } - }; - function watchEffect(effect, options) { - return doWatch(effect, null, options); - } - function watchPostEffect(effect, options) { - return doWatch( - effect, - null, - shared.extend({}, options, { flush: "post" }) - ); - } - function watchSyncEffect(effect, options) { - return doWatch( - effect, - null, - shared.extend({}, options, { flush: "sync" }) - ); - } - function watch(source, cb, options) { - if (!shared.isFunction(cb)) { - warn$1( - `\`watch(fn, options?)\` signature has been moved to a separate API. Use \`watchEffect(fn, options?)\` instead. \`watch\` now only supports \`watch(source, cb, options?) signature.` - ); - } - return doWatch(source, cb, options); - } - function doWatch(source, cb, options = shared.EMPTY_OBJ) { - const { immediate, deep, flush, once } = options; - if (!cb) { - if (immediate !== void 0) { - warn$1( - `watch() "immediate" option is only respected when using the watch(source, callback, options?) signature.` - ); - } - if (deep !== void 0) { - warn$1( - `watch() "deep" option is only respected when using the watch(source, callback, options?) signature.` - ); - } - if (once !== void 0) { - warn$1( - `watch() "once" option is only respected when using the watch(source, callback, options?) signature.` - ); - } - } - const baseWatchOptions = shared.extend({}, options); - baseWatchOptions.onWarn = warn$1; - const runsImmediately = cb && immediate || !cb && flush !== "post"; - let ssrCleanup; - if (isInSSRComponentSetup) { - if (flush === "sync") { - const ctx = useSSRContext(); - ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []); - } else if (!runsImmediately) { - const watchStopHandle = () => { - }; - watchStopHandle.stop = shared.NOOP; - watchStopHandle.resume = shared.NOOP; - watchStopHandle.pause = shared.NOOP; - return watchStopHandle; - } - } - const instance = currentInstance; - baseWatchOptions.call = (fn, type, args) => callWithAsyncErrorHandling(fn, instance, type, args); - let isPre = false; - if (flush === "post") { - baseWatchOptions.scheduler = (job) => { - job.i = instance; - queuePostRenderEffect(job, instance && instance.suspense); - }; - } else if (flush !== "sync") { - isPre = true; - baseWatchOptions.scheduler = (job, isFirstRun) => { - if (isFirstRun) { - job(); - } else { - queueJob(job); - } - }; - } - baseWatchOptions.augmentJob = (job) => { - if (cb) { - job.flags |= 4; - } - if (isPre) { - job.flags |= 2; - if (instance) { - job.id = instance.uid; - job.i = instance; - } - } - }; - const watchHandle = reactivity.watch(source, cb, baseWatchOptions); - if (isInSSRComponentSetup) { - if (ssrCleanup) { - ssrCleanup.push(watchHandle); - } else if (runsImmediately) { - watchHandle(); - } - } - return watchHandle; - } - function instanceWatch(source, value, options) { - const publicThis = this.proxy; - const getter = shared.isString(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); - let cb; - if (shared.isFunction(value)) { - cb = value; - } else { - cb = value.handler; - options = value; - } - const reset = setCurrentInstance(this); - const res = doWatch(getter, cb.bind(publicThis), options); - reset(); - return res; - } - function createPathGetter(ctx, path) { - const segments = path.split("."); - return () => { - let cur = ctx; - for (let i = 0; i < segments.length && cur; i++) { - cur = cur[segments[i]]; - } - return cur; - }; - } - var pendingMounts = /* @__PURE__ */ new WeakMap(); - var TeleportEndKey = /* @__PURE__ */ Symbol("_vte"); - var isTeleport = (type) => type.__isTeleport; - var isTeleportDisabled = (props) => props && (props.disabled || props.disabled === ""); - var isTeleportDeferred = (props) => props && (props.defer || props.defer === ""); - var isTargetSVG = (target) => typeof SVGElement !== "undefined" && target instanceof SVGElement; - var isTargetMathML = (target) => typeof MathMLElement === "function" && target instanceof MathMLElement; - var resolveTarget = (props, select) => { - const targetSelector = props && props.to; - if (shared.isString(targetSelector)) { - if (!select) { - warn$1( - `Current renderer does not support string target for Teleports. (missing querySelector renderer option)` - ); - return null; - } else { - const target = select(targetSelector); - if (!target && !isTeleportDisabled(props)) { - warn$1( - `Failed to locate Teleport target with selector "${targetSelector}". Note the target element must exist before the component is mounted - i.e. the target cannot be rendered by the component itself, and ideally should be outside of the entire Vue component tree.` - ); - } - return target; - } - } else { - if (!targetSelector && !isTeleportDisabled(props)) { - warn$1(`Invalid Teleport target: ${targetSelector}`); - } - return targetSelector; - } - }; - var TeleportImpl = { - name: "Teleport", - __isTeleport: true, - process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals) { - const { - mc: mountChildren, - pc: patchChildren, - pbc: patchBlockChildren, - o: { insert, querySelector, createText, createComment, parentNode } - } = internals; - const disabled = isTeleportDisabled(n2.props); - let { dynamicChildren } = n2; - if (isHmrUpdating) { - optimized = false; - dynamicChildren = null; - } - const mount = (vnode, container2, anchor2) => { - if (vnode.shapeFlag & 16) { - mountChildren( - vnode.children, - container2, - anchor2, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - }; - const mountToTarget = (vnode = n2) => { - const disabled2 = isTeleportDisabled(vnode.props); - const target = vnode.target = resolveTarget(vnode.props, querySelector); - const targetAnchor = prepareAnchor(target, vnode, createText, insert); - if (target) { - if (namespace !== "svg" && isTargetSVG(target)) { - namespace = "svg"; - } else if (namespace !== "mathml" && isTargetMathML(target)) { - namespace = "mathml"; - } - if (parentComponent && parentComponent.isCE) { - (parentComponent.ce._teleportTargets || (parentComponent.ce._teleportTargets = /* @__PURE__ */ new Set())).add(target); - } - if (!disabled2) { - mount(vnode, target, targetAnchor); - updateCssVars(vnode, false); - } - } else if (!disabled2) { - warn$1("Invalid Teleport target on mount:", target, `(${typeof target})`); - } - }; - const queuePendingMount = (vnode) => { - const mountJob = () => { - if (pendingMounts.get(vnode) !== mountJob) return; - pendingMounts.delete(vnode); - if (isTeleportDisabled(vnode.props)) { - const mountContainer = parentNode(vnode.el) || container; - mount(vnode, mountContainer, vnode.anchor); - updateCssVars(vnode, true); - } - mountToTarget(vnode); - }; - pendingMounts.set(vnode, mountJob); - queuePostRenderEffect(mountJob, parentSuspense); - }; - if (n1 == null) { - const placeholder = n2.el = createComment("teleport start"); - const mainAnchor = n2.anchor = createComment("teleport end"); - insert(placeholder, container, anchor); - insert(mainAnchor, container, anchor); - if (isTeleportDeferred(n2.props) || parentSuspense && parentSuspense.pendingBranch) { - queuePendingMount(n2); - return; - } - if (disabled) { - mount(n2, container, mainAnchor); - updateCssVars(n2, true); - } - mountToTarget(); - } else { - n2.el = n1.el; - const mainAnchor = n2.anchor = n1.anchor; - const pendingMount = pendingMounts.get(n1); - if (pendingMount) { - pendingMount.flags |= 8; - pendingMounts.delete(n1); - queuePendingMount(n2); - return; - } - n2.targetStart = n1.targetStart; - const target = n2.target = n1.target; - const targetAnchor = n2.targetAnchor = n1.targetAnchor; - const wasDisabled = isTeleportDisabled(n1.props); - const currentContainer = wasDisabled ? container : target; - const currentAnchor = wasDisabled ? mainAnchor : targetAnchor; - if (namespace === "svg" || isTargetSVG(target)) { - namespace = "svg"; - } else if (namespace === "mathml" || isTargetMathML(target)) { - namespace = "mathml"; - } - if (dynamicChildren) { - patchBlockChildren( - n1.dynamicChildren, - dynamicChildren, - currentContainer, - parentComponent, - parentSuspense, - namespace, - slotScopeIds - ); - traverseStaticChildren(n1, n2, false); - } else if (!optimized) { - patchChildren( - n1, - n2, - currentContainer, - currentAnchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - false - ); - } - if (disabled) { - if (!wasDisabled) { - moveTeleport( - n2, - container, - mainAnchor, - internals, - 1 - ); - } else { - if (n2.props && n1.props && n2.props.to !== n1.props.to) { - n2.props.to = n1.props.to; - } - } - } else { - if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) { - const nextTarget = resolveTarget(n2.props, querySelector); - if (nextTarget) { - n2.target = nextTarget; - moveTeleport( - n2, - nextTarget, - null, - internals, - 0 - ); - } else { - warn$1( - "Invalid Teleport target on update:", - target, - `(${typeof target})` - ); - } - } else if (wasDisabled) { - moveTeleport( - n2, - target, - targetAnchor, - internals, - 1 - ); - } - } - updateCssVars(n2, disabled); - } - }, - remove(vnode, parentComponent, parentSuspense, { um: unmount, o: { remove: hostRemove } }, doRemove) { - const { - shapeFlag, - children, - anchor, - targetStart, - targetAnchor, - target, - props - } = vnode; - const disabled = isTeleportDisabled(props); - const shouldRemove = doRemove || !disabled; - const pendingMount = pendingMounts.get(vnode); - if (pendingMount) { - pendingMount.flags |= 8; - pendingMounts.delete(vnode); - } - if (target) { - hostRemove(targetStart); - hostRemove(targetAnchor); - } - doRemove && hostRemove(anchor); - if (!pendingMount && (disabled || target) && shapeFlag & 16) { - for (let i = 0; i < children.length; i++) { - const child = children[i]; - unmount( - child, - parentComponent, - parentSuspense, - shouldRemove, - !!child.dynamicChildren - ); - } - } - }, - move: moveTeleport, - hydrate: hydrateTeleport - }; - function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2) { - if (moveType === 0) { - if (vnode.targetStart) { - insert(vnode.targetStart, container, parentAnchor); - } - insert(vnode.targetAnchor, container, parentAnchor); - parentAnchor = vnode.targetAnchor; - } - const { el, anchor, shapeFlag, children, props } = vnode; - const isReorder = moveType === 2; - if (isReorder) { - insert(el, container, parentAnchor); - } - if (!pendingMounts.has(vnode) && (!isReorder || isTeleportDisabled(props))) { - if (shapeFlag & 16) { - for (let i = 0; i < children.length; i++) { - move( - children[i], - container, - parentAnchor, - 2 - ); - } - } - } - if (isReorder) { - insert(anchor, container, parentAnchor); - } - } - function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { - o: { nextSibling, parentNode, querySelector, insert, createText } - }, hydrateChildren) { - function hydrateAnchor(target2, targetNode) { - let targetAnchor = targetNode; - while (targetAnchor) { - if (targetAnchor && targetAnchor.nodeType === 8) { - if (targetAnchor.data === "teleport start anchor") { - vnode.targetStart = targetAnchor; - } else if (targetAnchor.data === "teleport anchor") { - vnode.targetAnchor = targetAnchor; - target2._lpa = vnode.targetAnchor && nextSibling(vnode.targetAnchor); - break; - } - } - targetAnchor = nextSibling(targetAnchor); - } - } - function hydrateDisabledTeleport(node2, vnode2) { - vnode2.anchor = hydrateChildren( - nextSibling(node2), - vnode2, - parentNode(node2), - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - const target = vnode.target = resolveTarget( - vnode.props, - querySelector - ); - const disabled = isTeleportDisabled(vnode.props); - if (target) { - const targetNode = target._lpa || target.firstChild; - if (vnode.shapeFlag & 16) { - if (disabled) { - hydrateDisabledTeleport(node, vnode); - hydrateAnchor(target, targetNode); - if (!vnode.targetAnchor) { - prepareAnchor( - target, - vnode, - createText, - insert, - // if target is the same as the main view, insert anchors before current node - // to avoid hydrating mismatch - parentNode(node) === target ? node : null - ); - } - } else { - vnode.anchor = nextSibling(node); - hydrateAnchor(target, targetNode); - if (!vnode.targetAnchor) { - prepareAnchor(target, vnode, createText, insert); - } - hydrateChildren( - targetNode && nextSibling(targetNode), - vnode, - target, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - } - updateCssVars(vnode, disabled); - } else if (disabled) { - if (vnode.shapeFlag & 16) { - hydrateDisabledTeleport(node, vnode); - vnode.targetStart = node; - vnode.targetAnchor = nextSibling(node); - } - } - return vnode.anchor && nextSibling(vnode.anchor); - } - var Teleport = TeleportImpl; - function updateCssVars(vnode, isDisabled) { - const ctx = vnode.ctx; - if (ctx && ctx.ut) { - let node, anchor; - if (isDisabled) { - node = vnode.el; - anchor = vnode.anchor; - } else { - node = vnode.targetStart; - anchor = vnode.targetAnchor; - } - while (node && node !== anchor) { - if (node.nodeType === 1) node.setAttribute("data-v-owner", ctx.uid); - node = node.nextSibling; - } - ctx.ut(); - } - } - function prepareAnchor(target, vnode, createText, insert, anchor = null) { - const targetStart = vnode.targetStart = createText(""); - const targetAnchor = vnode.targetAnchor = createText(""); - targetStart[TeleportEndKey] = targetAnchor; - if (target) { - insert(targetStart, target, anchor); - insert(targetAnchor, target, anchor); - } - return targetAnchor; - } - var leaveCbKey = /* @__PURE__ */ Symbol("_leaveCb"); - var enterCbKey = /* @__PURE__ */ Symbol("_enterCb"); - function useTransitionState() { - const state = { - isMounted: false, - isLeaving: false, - isUnmounting: false, - leavingVNodes: /* @__PURE__ */ new Map() - }; - onMounted(() => { - state.isMounted = true; - }); - onBeforeUnmount(() => { - state.isUnmounting = true; - }); - return state; - } - var TransitionHookValidator = [Function, Array]; - var BaseTransitionPropsValidators = { - mode: String, - appear: Boolean, - persisted: Boolean, - // enter - onBeforeEnter: TransitionHookValidator, - onEnter: TransitionHookValidator, - onAfterEnter: TransitionHookValidator, - onEnterCancelled: TransitionHookValidator, - // leave - onBeforeLeave: TransitionHookValidator, - onLeave: TransitionHookValidator, - onAfterLeave: TransitionHookValidator, - onLeaveCancelled: TransitionHookValidator, - // appear - onBeforeAppear: TransitionHookValidator, - onAppear: TransitionHookValidator, - onAfterAppear: TransitionHookValidator, - onAppearCancelled: TransitionHookValidator - }; - var BaseTransitionImpl = { - name: `BaseTransition`, - props: BaseTransitionPropsValidators, - setup(props, { slots }) { - const instance = getCurrentInstance(); - const state = useTransitionState(); - return () => { - const children = slots.default && getTransitionRawChildren(slots.default(), true); - const child = children && children.length ? findNonCommentChild(children) : ( - // Keep explicit default-slot conditionals on the same transition path - // as regular v-if branches, which render a comment placeholder. - instance.subTree ? createCommentVNode() : void 0 - ); - if (!child) { - return; - } - const rawProps = reactivity.toRaw(props); - const { mode } = rawProps; - if (mode && mode !== "in-out" && mode !== "out-in" && mode !== "default") { - warn$1(`invalid <transition> mode: ${mode}`); - } - if (state.isLeaving) { - return emptyPlaceholder(child); - } - const innerChild = getInnerChild$1(child); - if (!innerChild) { - return emptyPlaceholder(child); - } - let enterHooks = resolveTransitionHooks( - innerChild, - rawProps, - state, - instance, - // #11061, ensure enterHooks is fresh after clone - (hooks) => enterHooks = hooks - ); - if (innerChild.type !== Comment) { - setTransitionHooks(innerChild, enterHooks); - } - let oldInnerChild = instance.subTree && getInnerChild$1(instance.subTree); - if (oldInnerChild && oldInnerChild.type !== Comment && !isSameVNodeType(oldInnerChild, innerChild) && getTransitionRoot(instance.subTree)) { - let leavingHooks = resolveTransitionHooks( - oldInnerChild, - rawProps, - state, - instance - ); - setTransitionHooks(oldInnerChild, leavingHooks); - if (mode === "out-in" && innerChild.type !== Comment) { - state.isLeaving = true; - leavingHooks.afterLeave = () => { - state.isLeaving = false; - if (!(instance.job.flags & 8)) { - instance.update(); - } - delete leavingHooks.afterLeave; - oldInnerChild = void 0; - }; - return emptyPlaceholder(child); - } else if (mode === "in-out" && innerChild.type !== Comment) { - leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => { - const leavingVNodesCache = getLeavingNodesForType( - state, - oldInnerChild - ); - leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild; - el[leaveCbKey] = () => { - earlyRemove(); - el[leaveCbKey] = void 0; - delete enterHooks.delayedLeave; - oldInnerChild = void 0; - }; - enterHooks.delayedLeave = () => { - delayedLeave(); - delete enterHooks.delayedLeave; - oldInnerChild = void 0; - }; - }; - } else { - oldInnerChild = void 0; - } - } else if (oldInnerChild) { - oldInnerChild = void 0; - } - return child; - }; - } - }; - function findNonCommentChild(children) { - let child = children[0]; - if (children.length > 1) { - let hasFound = false; - for (const c of children) { - if (c.type !== Comment) { - if (hasFound) { - warn$1( - "<transition> can only be used on a single element or component. Use <transition-group> for lists." - ); - break; - } - child = c; - hasFound = true; - } - } - } - return child; - } - var BaseTransition = BaseTransitionImpl; - function getLeavingNodesForType(state, vnode) { - const { leavingVNodes } = state; - let leavingVNodesCache = leavingVNodes.get(vnode.type); - if (!leavingVNodesCache) { - leavingVNodesCache = /* @__PURE__ */ Object.create(null); - leavingVNodes.set(vnode.type, leavingVNodesCache); - } - return leavingVNodesCache; - } - function resolveTransitionHooks(vnode, props, state, instance, postClone) { - const { - appear, - mode, - persisted = false, - onBeforeEnter, - onEnter, - onAfterEnter, - onEnterCancelled, - onBeforeLeave, - onLeave, - onAfterLeave, - onLeaveCancelled, - onBeforeAppear, - onAppear, - onAfterAppear, - onAppearCancelled - } = props; - const key = String(vnode.key); - const leavingVNodesCache = getLeavingNodesForType(state, vnode); - const callHook2 = (hook, args) => { - hook && callWithAsyncErrorHandling( - hook, - instance, - 9, - args - ); - }; - const callAsyncHook = (hook, args) => { - const done = args[1]; - callHook2(hook, args); - if (shared.isArray(hook)) { - if (hook.every((hook2) => hook2.length <= 1)) done(); - } else if (hook.length <= 1) { - done(); - } - }; - const hooks = { - mode, - persisted, - beforeEnter(el) { - let hook = onBeforeEnter; - if (!state.isMounted) { - if (appear) { - hook = onBeforeAppear || onBeforeEnter; - } else { - return; - } - } - if (el[leaveCbKey]) { - el[leaveCbKey]( - true - /* cancelled */ - ); - } - const leavingVNode = leavingVNodesCache[key]; - if (leavingVNode && isSameVNodeType(vnode, leavingVNode)) { - let leavingCb = leavingVNode.el[leaveCbKey]; - if (!leavingCb) { - const leavingRoot = getTransitionRoot(leavingVNode); - leavingCb = leavingRoot && leavingRoot.el[leaveCbKey]; - } - if (leavingCb) { - leavingCb(); - } - } - callHook2(hook, [el]); - }, - enter(el) { - if (!isHmrUpdating && leavingVNodesCache[key] === vnode) return; - let hook = onEnter; - let afterHook = onAfterEnter; - let cancelHook = onEnterCancelled; - if (!state.isMounted) { - if (appear) { - hook = onAppear || onEnter; - afterHook = onAfterAppear || onAfterEnter; - cancelHook = onAppearCancelled || onEnterCancelled; - } else { - return; - } - } - let called = false; - el[enterCbKey] = (cancelled) => { - if (called) return; - called = true; - if (cancelled) { - callHook2(cancelHook, [el]); - } else { - callHook2(afterHook, [el]); - } - if (hooks.delayedLeave) { - hooks.delayedLeave(); - } - el[enterCbKey] = void 0; - }; - const done = el[enterCbKey].bind(null, false); - if (hook) { - callAsyncHook(hook, [el, done]); - } else { - done(); - } - }, - leave(el, remove2) { - const key2 = String(vnode.key); - if (el[enterCbKey]) { - el[enterCbKey]( - true - /* cancelled */ - ); - } - if (state.isUnmounting) { - return remove2(); - } - callHook2(onBeforeLeave, [el]); - let called = false; - el[leaveCbKey] = (cancelled) => { - if (called) return; - called = true; - remove2(); - if (cancelled) { - callHook2(onLeaveCancelled, [el]); - } else { - callHook2(onAfterLeave, [el]); - } - el[leaveCbKey] = void 0; - if (leavingVNodesCache[key2] === vnode) { - delete leavingVNodesCache[key2]; - } - }; - const done = el[leaveCbKey].bind(null, false); - leavingVNodesCache[key2] = vnode; - if (onLeave) { - callAsyncHook(onLeave, [el, done]); - } else { - done(); - } - }, - clone(vnode2) { - const hooks2 = resolveTransitionHooks( - vnode2, - props, - state, - instance, - postClone - ); - if (postClone) postClone(hooks2); - return hooks2; - } - }; - return hooks; - } - function emptyPlaceholder(vnode) { - if (isKeepAlive(vnode)) { - vnode = cloneVNode(vnode); - vnode.children = null; - return vnode; - } - } - function getInnerChild$1(vnode) { - if (!isKeepAlive(vnode)) { - if (isTeleport(vnode.type) && vnode.children) { - return findNonCommentChild(vnode.children); - } - return vnode; - } - if (vnode.component) { - return vnode.component.subTree; - } - const { shapeFlag, children } = vnode; - if (children) { - if (shapeFlag & 16) { - return children[0]; - } - if (shapeFlag & 32 && shared.isFunction(children.default)) { - return children.default(); - } - } - } - function setTransitionHooks(vnode, hooks) { - if (vnode.shapeFlag & 6 && vnode.component) { - vnode.transition = hooks; - const subTree = vnode.component.subTree; - setTransitionHooks( - isTeleport(subTree.type) ? getInnerChild$1(subTree) || subTree : subTree, - hooks - ); - } else if (vnode.shapeFlag & 128) { - vnode.ssContent.transition = hooks.clone(vnode.ssContent); - vnode.ssFallback.transition = hooks.clone(vnode.ssFallback); - } else { - vnode.transition = hooks; - if (vnode.type === Fragment && shared.isArray(vnode.children)) { - const child = filterSingleRoot(vnode.children, false); - if (child) { - setTransitionHooks(child, hooks); - } - } - } - } - function getTransitionRawChildren(children, keepComment = false, parentKey) { - let ret = []; - let keyedFragmentCount = 0; - for (let i = 0; i < children.length; i++) { - let child = children[i]; - const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i); - if (child.type === Fragment) { - if (child.patchFlag & 128) keyedFragmentCount++; - ret = ret.concat( - getTransitionRawChildren(child.children, keepComment, key) - ); - } else if (keepComment || child.type !== Comment) { - ret.push(key != null ? cloneVNode(child, { key }) : child); - } - } - if (keyedFragmentCount > 1) { - for (let i = 0; i < ret.length; i++) { - ret[i].patchFlag = -2; - } - } - return ret; - } - function getTransitionRoot(vnode) { - if (vnode.component) { - return getTransitionRoot(vnode.component.subTree); - } - if (vnode.type === Fragment) { - const child = shared.isArray(vnode.children) && filterSingleRoot(vnode.children, false); - return child ? getTransitionRoot(child) : void 0; - } - if (vnode.type !== Comment) { - return vnode; - } - } - // @__NO_SIDE_EFFECTS__ - function defineComponent(options, extraOptions) { - return shared.isFunction(options) ? ( - // #8236: extend call and options.name access are considered side-effects - // by Rollup, so we have to wrap it in a pure-annotated IIFE. - /* @__PURE__ */ (() => shared.extend({ name: options.name }, extraOptions, { setup: options }))() - ) : options; - } - function useId() { - const i = getCurrentInstance(); - if (i) { - return (i.appContext.config.idPrefix || "v") + "-" + i.ids[0] + i.ids[1]++; - } else { - warn$1( - `useId() is called when there is no active component instance to be associated with.` - ); - } - return ""; - } - function markAsyncBoundary(instance) { - instance.ids = [instance.ids[0] + instance.ids[2]++ + "-", 0, 0]; - } - var knownTemplateRefs = /* @__PURE__ */ new WeakSet(); - function useTemplateRef(key) { - const i = getCurrentInstance(); - const r = reactivity.shallowRef(null); - if (i) { - const refs = i.refs === shared.EMPTY_OBJ ? i.refs = {} : i.refs; - if (isTemplateRefKey(refs, key)) { - warn$1(`useTemplateRef('${key}') already exists.`); - } else { - Object.defineProperty(refs, key, { - enumerable: true, - get: () => r.value, - set: (val) => r.value = val - }); - } - } else { - warn$1( - `useTemplateRef() is called when there is no active component instance to be associated with.` - ); - } - const ret = reactivity.readonly(r); - { - knownTemplateRefs.add(ret); - } - return ret; - } - function isTemplateRefKey(refs, key) { - let desc; - return !!((desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable); - } - var pendingSetRefMap = /* @__PURE__ */ new WeakMap(); - function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { - if (shared.isArray(rawRef)) { - rawRef.forEach( - (r, i) => setRef( - r, - oldRawRef && (shared.isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), - parentSuspense, - vnode, - isUnmount - ) - ); - return; - } - if (isAsyncWrapper(vnode) && !isUnmount) { - if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) { - setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree); - } - return; - } - const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el; - const value = isUnmount ? null : refValue; - const { i: owner, r: ref2 } = rawRef; - if (!owner) { - warn$1( - `Missing ref owner context. ref cannot be used on hoisted vnodes. A vnode with ref must be created inside the render function.` - ); - return; - } - const oldRef = oldRawRef && oldRawRef.r; - const refs = owner.refs === shared.EMPTY_OBJ ? owner.refs = {} : owner.refs; - const setupState = owner.setupState; - const rawSetupState = reactivity.toRaw(setupState); - const canSetSetupRef = setupState === shared.EMPTY_OBJ ? shared.NO : (key) => { - { - if (shared.hasOwn(rawSetupState, key) && !reactivity.isRef(rawSetupState[key])) { - warn$1( - `Template ref "${key}" used on a non-ref value. It will not work in the production build.` - ); - } - if (knownTemplateRefs.has(rawSetupState[key])) { - return false; - } - } - if (isTemplateRefKey(refs, key)) { - return false; - } - return shared.hasOwn(rawSetupState, key); - }; - const canSetRef = (ref22, key) => { - if (knownTemplateRefs.has(ref22)) { - return false; - } - if (key && isTemplateRefKey(refs, key)) { - return false; - } - return true; - }; - if (oldRef != null && oldRef !== ref2) { - invalidatePendingSetRef(oldRawRef); - if (shared.isString(oldRef)) { - refs[oldRef] = null; - if (canSetSetupRef(oldRef)) { - setupState[oldRef] = null; - } - } else if (reactivity.isRef(oldRef)) { - const oldRawRefAtom = oldRawRef; - if (canSetRef(oldRef, oldRawRefAtom.k)) { - oldRef.value = null; - } - if (oldRawRefAtom.k) refs[oldRawRefAtom.k] = null; - } - } - if (shared.isFunction(ref2)) { - callWithErrorHandling(ref2, owner, 12, [value, refs]); - } else { - const _isString = shared.isString(ref2); - const _isRef = reactivity.isRef(ref2); - if (_isString || _isRef) { - const doSet = () => { - if (rawRef.f) { - const existing = _isString ? canSetSetupRef(ref2) ? setupState[ref2] : refs[ref2] : canSetRef(ref2) || !rawRef.k ? ref2.value : refs[rawRef.k]; - if (isUnmount) { - shared.isArray(existing) && shared.remove(existing, refValue); - } else { - if (!shared.isArray(existing)) { - if (_isString) { - refs[ref2] = [refValue]; - if (canSetSetupRef(ref2)) { - setupState[ref2] = refs[ref2]; - } - } else { - const newVal = [refValue]; - if (canSetRef(ref2, rawRef.k)) { - ref2.value = newVal; - } - if (rawRef.k) refs[rawRef.k] = newVal; - } - } else if (!existing.includes(refValue)) { - existing.push(refValue); - } - } - } else if (_isString) { - refs[ref2] = value; - if (canSetSetupRef(ref2)) { - setupState[ref2] = value; - } - } else if (_isRef) { - if (canSetRef(ref2, rawRef.k)) { - ref2.value = value; - } - if (rawRef.k) refs[rawRef.k] = value; - } else { - warn$1("Invalid template ref type:", ref2, `(${typeof ref2})`); - } - }; - if (value) { - const job = () => { - doSet(); - pendingSetRefMap.delete(rawRef); - }; - job.id = -1; - pendingSetRefMap.set(rawRef, job); - queuePostRenderEffect(job, parentSuspense); - } else { - invalidatePendingSetRef(rawRef); - doSet(); - } - } else { - warn$1("Invalid template ref type:", ref2, `(${typeof ref2})`); - } - } - } - function invalidatePendingSetRef(rawRef) { - const pendingSetRef = pendingSetRefMap.get(rawRef); - if (pendingSetRef) { - pendingSetRef.flags |= 8; - pendingSetRefMap.delete(rawRef); - } - } - var hasLoggedMismatchError = false; - var logMismatchError = () => { - if (hasLoggedMismatchError) { - return; - } - console.error("Hydration completed but contains mismatches."); - hasLoggedMismatchError = true; - }; - var isSVGContainer = (container) => container.namespaceURI.includes("svg") && container.tagName !== "foreignObject"; - var isMathMLContainer = (container) => container.namespaceURI.includes("MathML"); - var getContainerType = (container) => { - if (container.nodeType !== 1) return void 0; - if (isSVGContainer(container)) return "svg"; - if (isMathMLContainer(container)) return "mathml"; - return void 0; - }; - var isComment = (node) => node.nodeType === 8; - function createHydrationFunctions(rendererInternals) { - const { - mt: mountComponent, - p: patch, - o: { - patchProp, - createText, - nextSibling, - parentNode, - remove: remove2, - insert, - createComment - } - } = rendererInternals; - const hydrate = (vnode, container) => { - if (!container.hasChildNodes()) { - warn$1( - `Attempting to hydrate existing markup but container is empty. Performing full mount instead.` - ); - patch(null, vnode, container); - flushPostFlushCbs(); - container._vnode = vnode; - return; - } - hydrateNode(container.firstChild, vnode, null, null, null); - flushPostFlushCbs(); - container._vnode = vnode; - }; - const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => { - optimized = optimized || !!vnode.dynamicChildren; - const isFragmentStart = isComment(node) && node.data === "["; - const onMismatch = () => handleMismatch( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - isFragmentStart - ); - const { type, ref: ref2, shapeFlag, patchFlag } = vnode; - let domType = node.nodeType; - vnode.el = node; - { - shared.def(node, "__vnode", vnode, true); - shared.def(node, "__vueParentComponent", parentComponent, true); - } - if (patchFlag === -2) { - optimized = false; - vnode.dynamicChildren = null; - } - let nextNode = null; - switch (type) { - case Text: - if (domType !== 3) { - if (vnode.children === "") { - insert(vnode.el = createText(""), parentNode(node), node); - nextNode = node; - } else { - nextNode = onMismatch(); - } - } else { - if (node.data !== vnode.children) { - warn$1( - `Hydration text mismatch in`, - node.parentNode, - ` - - rendered on server: ${JSON.stringify( - node.data - )} - - expected on client: ${JSON.stringify(vnode.children)}` - ); - logMismatchError(); - node.data = vnode.children; - } - nextNode = nextSibling(node); - } - break; - case Comment: - if (isTemplateNode(node)) { - nextNode = nextSibling(node); - replaceNode( - vnode.el = node.content.firstChild, - node, - parentComponent - ); - } else if (domType !== 8 || isFragmentStart) { - nextNode = onMismatch(); - } else { - nextNode = nextSibling(node); - } - break; - case Static: - if (isFragmentStart) { - node = nextSibling(node); - domType = node.nodeType; - } - if (domType === 1 || domType === 3) { - nextNode = node; - const needToAdoptContent = !vnode.children.length; - for (let i = 0; i < vnode.staticCount; i++) { - if (needToAdoptContent) - vnode.children += nextNode.nodeType === 1 ? nextNode.outerHTML : nextNode.data; - if (i === vnode.staticCount - 1) { - vnode.anchor = nextNode; - } - nextNode = nextSibling(nextNode); - } - return isFragmentStart ? nextSibling(nextNode) : nextNode; - } else { - onMismatch(); - } - break; - case Fragment: - if (!isFragmentStart) { - nextNode = onMismatch(); - } else { - nextNode = hydrateFragment( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - break; - default: - if (shapeFlag & 1) { - if ((domType !== 1 || vnode.type.toLowerCase() !== node.tagName.toLowerCase()) && !isTemplateNode(node)) { - nextNode = onMismatch(); - } else { - nextNode = hydrateElement( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } - } else if (shapeFlag & 6) { - vnode.slotScopeIds = slotScopeIds; - const container = parentNode(node); - if (isFragmentStart) { - nextNode = locateClosingAnchor(node); - } else if (isComment(node) && node.data === "teleport start") { - nextNode = locateClosingAnchor(node, node.data, "teleport end"); - } else { - nextNode = nextSibling(node); - } - mountComponent( - vnode, - container, - null, - parentComponent, - parentSuspense, - getContainerType(container), - optimized - ); - if ((isAsyncWrapper(vnode) || vnode.component.asyncDep) && !vnode.component.subTree) { - let subTree; - if (isFragmentStart) { - subTree = createVNode(Static); - subTree.anchor = nextNode ? nextNode.previousSibling : container.lastChild; - } else { - subTree = node.nodeType === 3 ? createTextVNode("") : createVNode( - node.nodeType === 8 ? Comment : "div" - ); - } - subTree.el = node; - vnode.component.subTree = subTree; - } - } else if (shapeFlag & 64) { - if (domType !== 8) { - nextNode = onMismatch(); - } else { - nextNode = vnode.type.hydrate( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized, - rendererInternals, - hydrateChildren - ); - } - } else if (shapeFlag & 128) { - nextNode = vnode.type.hydrate( - node, - vnode, - parentComponent, - parentSuspense, - getContainerType(parentNode(node)), - slotScopeIds, - optimized, - rendererInternals, - hydrateNode - ); - } else { - warn$1("Invalid HostVNode type:", type, `(${typeof type})`); - } - } - if (ref2 != null) { - setRef(ref2, null, parentSuspense, vnode); - } - return nextNode; - }; - const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => { - optimized = optimized || !!vnode.dynamicChildren; - const { - type, - dynamicProps, - props, - patchFlag, - shapeFlag, - dirs, - transition - } = vnode; - const forcePatch = type === "input" || type === "option"; - { - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "created"); - } - let needCallTransitionHooks = false; - if (isTemplateNode(el)) { - needCallTransitionHooks = needTransition( - null, - // no need check parentSuspense in hydration - transition - ) && parentComponent && parentComponent.vnode.props && parentComponent.vnode.props.appear; - const content = el.content.firstChild; - if (needCallTransitionHooks) { - const cls = content.getAttribute("class"); - if (cls) content.$cls = cls; - transition.beforeEnter(content); - } - replaceNode(content, el, parentComponent); - vnode.el = el = content; - } - if (shapeFlag & 16 && // skip if element has innerHTML / textContent - !(props && (props.innerHTML || props.textContent))) { - let next = hydrateChildren( - el.firstChild, - vnode, - el, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - if (next && !isMismatchAllowed( - el, - 1 - /* CHILDREN */ - )) { - warn$1( - `Hydration children mismatch on`, - el, - ` -Server rendered element contains more child nodes than client vdom.` - ); - logMismatchError(); - } - while (next) { - const cur = next; - next = next.nextSibling; - remove2(cur); - } - } else if (shapeFlag & 8) { - let clientText = vnode.children; - if (clientText[0] === "\n" && (el.tagName === "PRE" || el.tagName === "TEXTAREA")) { - clientText = clientText.slice(1); - } - const { textContent } = el; - if (textContent !== clientText && // innerHTML normalize \r\n or \r into a single \n in the DOM - textContent !== clientText.replace(/\r\n|\r/g, "\n")) { - if (!isMismatchAllowed( - el, - 0 - /* TEXT */ - )) { - warn$1( - `Hydration text content mismatch on`, - el, - ` - - rendered on server: ${textContent} - - expected on client: ${clientText}` - ); - logMismatchError(); - } - el.textContent = vnode.children; - } - } - if (props) { - { - const isCustomElement = el.tagName.includes("-"); - const namespace = el.namespaceURI.includes("svg") ? "svg" : el.namespaceURI.includes("MathML") ? "mathml" : void 0; - for (const key in props) { - if ( - // #11189 skip if this node has directives that have created hooks - // as it could have mutated the DOM in any possible way - !(dirs && dirs.some((d) => d.dir.created)) && propHasMismatch(el, key, props[key], vnode, parentComponent) - ) { - logMismatchError(); - } - if (forcePatch && (key.endsWith("value") || key === "indeterminate") || shared.isOn(key) && !shared.isReservedProp(key) || // force hydrate v-bind with .prop modifiers - key[0] === "." || isCustomElement && !shared.isReservedProp(key) || dynamicProps && dynamicProps.includes(key)) { - if (isUnchangedResourceProp(el, key, props[key])) { - continue; - } - patchProp(el, key, null, props[key], namespace, parentComponent); - } - } - } - } - let vnodeHooks; - if (vnodeHooks = props && props.onVnodeBeforeMount) { - invokeVNodeHook(vnodeHooks, parentComponent, vnode); - } - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "beforeMount"); - } - if ((vnodeHooks = props && props.onVnodeMounted) || dirs || needCallTransitionHooks) { - queueEffectWithSuspense(() => { - vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode); - needCallTransitionHooks && transition.enter(el); - dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted"); - }, parentSuspense); - } - } - return el.nextSibling; - }; - const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => { - optimized = optimized || !!parentVNode.dynamicChildren; - const children = parentVNode.children; - const l = children.length; - let hasCheckedMismatch = false; - for (let i = 0; i < l; i++) { - const vnode = optimized ? children[i] : children[i] = normalizeVNode(children[i]); - const isText = vnode.type === Text; - if (node) { - if (isText && !optimized) { - if (i + 1 < l && normalizeVNode(children[i + 1]).type === Text) { - insert( - createText( - node.data.slice(vnode.children.length) - ), - container, - nextSibling(node) - ); - node.data = vnode.children; - } - } - node = hydrateNode( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - } else if (isText && !vnode.children) { - insert(vnode.el = createText(""), container); - } else { - if (!hasCheckedMismatch) { - hasCheckedMismatch = true; - if (!isMismatchAllowed( - container, - 1 - /* CHILDREN */ - )) { - warn$1( - `Hydration children mismatch on`, - container, - ` -Server rendered element contains fewer child nodes than client vdom.` - ); - logMismatchError(); - } - } - patch( - null, - vnode, - container, - null, - parentComponent, - parentSuspense, - getContainerType(container), - slotScopeIds - ); - } - } - return node; - }; - const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => { - const { slotScopeIds: fragmentSlotScopeIds } = vnode; - if (fragmentSlotScopeIds) { - slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds; - } - const container = parentNode(node); - const next = hydrateChildren( - nextSibling(node), - vnode, - container, - parentComponent, - parentSuspense, - slotScopeIds, - optimized - ); - if (next && isComment(next) && next.data === "]") { - return nextSibling(vnode.anchor = next); - } else { - logMismatchError(); - insert(vnode.anchor = createComment(`]`), container, next); - return next; - } - }; - const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => { - if (!isNodeMismatchAllowed(node, vnode)) { - warn$1( - `Hydration node mismatch: -- rendered on server:`, - node, - node.nodeType === 3 ? `(text)` : isComment(node) && node.data === "[" ? `(start of fragment)` : ``, - ` -- expected on client:`, - vnode.type - ); - logMismatchError(); - } - vnode.el = null; - if (isFragment) { - const end = locateClosingAnchor(node); - while (true) { - const next2 = nextSibling(node); - if (next2 && next2 !== end) { - remove2(next2); - } else { - break; - } - } - } - const next = nextSibling(node); - const container = parentNode(node); - remove2(node); - patch( - null, - vnode, - container, - next, - parentComponent, - parentSuspense, - getContainerType(container), - slotScopeIds - ); - if (parentComponent) { - parentComponent.vnode.el = vnode.el; - updateHOCHostEl(parentComponent, vnode.el); - } - return next; - }; - const locateClosingAnchor = (node, open = "[", close = "]") => { - let match = 0; - while (node) { - node = nextSibling(node); - if (node && isComment(node)) { - if (node.data === open) match++; - if (node.data === close) { - if (match === 0) { - return nextSibling(node); - } else { - match--; - } - } - } - } - return node; - }; - const replaceNode = (newNode, oldNode, parentComponent) => { - const parentNode2 = oldNode.parentNode; - if (parentNode2) { - parentNode2.replaceChild(newNode, oldNode); - } - let parent = parentComponent; - while (parent) { - if (parent.vnode.el === oldNode) { - parent.vnode.el = parent.subTree.el = newNode; - } - parent = parent.parent; - } - }; - const isTemplateNode = (node) => { - return node.nodeType === 1 && node.tagName === "TEMPLATE"; - }; - return [hydrate, hydrateNode]; - } - var resourceProps = /* @__PURE__ */ new Set(["src", "srcset", "href", "poster"]); - function isUnchangedResourceProp(el, key, clientValue) { - if (!resourceProps.has(key)) { - return false; - } - return el.getAttribute(key) === (clientValue == null ? null : `${clientValue}`); - } - function propHasMismatch(el, key, clientValue, vnode, instance) { - let mismatchType; - let mismatchKey; - let actual; - let expected; - if (key === "class") { - if (el.$cls) { - actual = el.$cls; - delete el.$cls; - } else { - actual = el.getAttribute("class"); - } - expected = shared.normalizeClass(clientValue); - if (!isSetEqual(toClassSet(actual || ""), toClassSet(expected))) { - mismatchType = 2; - mismatchKey = `class`; - } - } else if (key === "style") { - actual = el.getAttribute("style") || ""; - expected = shared.isString(clientValue) ? clientValue : shared.stringifyStyle(shared.normalizeStyle(clientValue)); - const actualMap = toStyleMap(actual); - const expectedMap = toStyleMap(expected); - if (vnode.dirs) { - for (const { dir, value } of vnode.dirs) { - if (dir.name === "show" && !value) { - expectedMap.set("display", "none"); - } - } - } - if (instance) { - resolveCssVars(instance, vnode, expectedMap); - } - if (!isMapEqual(actualMap, expectedMap)) { - mismatchType = 3; - mismatchKey = "style"; - } - } else if (el instanceof SVGElement && shared.isKnownSvgAttr(key) || el instanceof HTMLElement && (shared.isBooleanAttr(key) || shared.isKnownHtmlAttr(key))) { - if (key === "hidden") { - actual = normalizeHiddenValue(el.getAttribute(key)); - expected = normalizeHiddenValue(clientValue); - } else if (shared.isBooleanAttr(key)) { - actual = el.hasAttribute(key); - expected = shared.includeBooleanAttr(clientValue); - } else if (clientValue == null) { - actual = el.hasAttribute(key); - expected = false; - } else { - if (el.hasAttribute(key)) { - actual = el.getAttribute(key); - } else if (key === "value" && el.tagName === "TEXTAREA") { - actual = el.value; - } else { - actual = false; - } - expected = shared.isRenderableAttrValue(clientValue) ? String(clientValue) : false; - } - if (actual !== expected) { - mismatchType = 4; - mismatchKey = key; - } - } - if (mismatchType != null && !isMismatchAllowed(el, mismatchType)) { - const format = (v) => v === false ? `(not rendered)` : `${mismatchKey}="${v}"`; - const preSegment = `Hydration ${MismatchTypeString[mismatchType]} mismatch on`; - const postSegment = ` - - rendered on server: ${format(actual)} - - expected on client: ${format(expected)} - Note: this mismatch is check-only. The DOM will not be rectified in production due to performance overhead. - You should fix the source of the mismatch.`; - { - warn$1(preSegment, el, postSegment); - } - return true; - } - return false; - } - function normalizeHiddenValue(value) { - if (!shared.isRenderableAttrValue(value)) { - return false; - } - if (shared.isString(value)) { - return value.toLowerCase() === "until-found" ? "until-found" : ""; - } - return shared.includeBooleanAttr(value) ? "" : false; - } - function toClassSet(str) { - return new Set(str.trim().split(/\s+/)); - } - function isSetEqual(a, b) { - if (a.size !== b.size) { - return false; - } - for (const s of a) { - if (!b.has(s)) { - return false; - } - } - return true; - } - function toStyleMap(str) { - const styleMap = /* @__PURE__ */ new Map(); - for (const item of str.split(";")) { - let [key, value] = item.split(":"); - key = key.trim(); - value = value && value.trim(); - if (key && value) { - styleMap.set(key, value); - } - } - return styleMap; - } - function isMapEqual(a, b) { - if (a.size !== b.size) { - return false; - } - for (const [key, value] of a) { - if (value !== b.get(key)) { - return false; - } - } - return true; - } - function resolveCssVars(instance, vnode, expectedMap) { - const root = instance.subTree; - if (instance.getCssVars && (vnode === root || root && root.type === Fragment && root.children.includes(vnode))) { - const cssVars = instance.getCssVars(); - for (const key in cssVars) { - const value = shared.normalizeCssVarValue(cssVars[key]); - expectedMap.set(`--${shared.getEscapedCssVarName(key, false)}`, value); - } - } - if (vnode === root && instance.parent) { - resolveCssVars(instance.parent, instance.vnode, expectedMap); - } - } - var allowMismatchAttr = "data-allow-mismatch"; - var MismatchTypeString = { - [ - 0 - /* TEXT */ - ]: "text", - [ - 1 - /* CHILDREN */ - ]: "children", - [ - 2 - /* CLASS */ - ]: "class", - [ - 3 - /* STYLE */ - ]: "style", - [ - 4 - /* ATTRIBUTE */ - ]: "attribute" - }; - function isMismatchAllowed(el, allowedType) { - if (allowedType === 0 || allowedType === 1) { - while (el && !el.hasAttribute(allowMismatchAttr)) { - el = el.parentElement; - } - } - return isMismatchAllowedByAttr( - el && el.getAttribute(allowMismatchAttr), - allowedType - ); - } - function isMismatchAllowedByAttr(allowedAttr, allowedType) { - if (allowedAttr == null) { - return false; - } else if (allowedAttr === "") { - return true; - } else { - const list = allowedAttr.split(","); - if (allowedType === 0 && list.includes("children")) { - return true; - } - return list.includes(MismatchTypeString[allowedType]); - } - } - function isNodeMismatchAllowed(node, vnode) { - return isMismatchAllowed( - node.parentElement, - 1 - /* CHILDREN */ - ) || isMismatchAllowedByNode(node) || isMismatchAllowedByVNode(vnode); - } - function isMismatchAllowedByNode(node) { - return node.nodeType === 1 && isMismatchAllowedByAttr( - node.getAttribute(allowMismatchAttr), - 1 - /* CHILDREN */ - ); - } - function isMismatchAllowedByVNode({ props }) { - const allowedAttr = props && props[allowMismatchAttr]; - return typeof allowedAttr === "string" && isMismatchAllowedByAttr( - allowedAttr, - 1 - /* CHILDREN */ - ); - } - var requestIdleCallback = shared.getGlobalThis().requestIdleCallback || ((cb) => setTimeout(cb, 1)); - var cancelIdleCallback = shared.getGlobalThis().cancelIdleCallback || ((id) => clearTimeout(id)); - var hydrateOnIdle = (timeout = 1e4) => (hydrate) => { - const id = requestIdleCallback(hydrate, { timeout }); - return () => cancelIdleCallback(id); - }; - function elementIsVisibleInViewport(el) { - const { top, left, bottom, right } = el.getBoundingClientRect(); - const { innerHeight, innerWidth } = window; - return (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth); - } - var hydrateOnVisible = (opts) => (hydrate, forEach) => { - const ob = new IntersectionObserver((entries) => { - for (const e of entries) { - if (!e.isIntersecting) continue; - ob.disconnect(); - hydrate(); - break; - } - }, opts); - const observe = (el) => { - if (elementIsVisibleInViewport(el)) { - hydrate(); - ob.disconnect(); - return false; - } - if (getComputedStyle(el).display === "contents") { - for (let i = 0; i < el.children.length; i++) { - if (observe(el.children[i]) === false) return false; - } - } - ob.observe(el); - }; - forEach((el) => { - if (!(el instanceof Element)) return; - return observe(el); - }); - return () => ob.disconnect(); - }; - var hydrateOnMediaQuery = (query) => (hydrate) => { - if (query) { - const mql = matchMedia(query); - if (mql.matches) { - hydrate(); - } else { - mql.addEventListener("change", hydrate, { once: true }); - return () => mql.removeEventListener("change", hydrate); - } - } - }; - var hydrateOnInteraction = (interactions = []) => (hydrate, forEach) => { - if (shared.isString(interactions)) interactions = [interactions]; - let hasHydrated = false; - const doHydrate = (e) => { - if (!hasHydrated) { - hasHydrated = true; - teardown(); - hydrate(); - e.target.dispatchEvent(new e.constructor(e.type, e)); - } - }; - const teardown = () => { - forEach((el) => { - for (const i of interactions) { - el.removeEventListener(i, doHydrate); - } - }); - }; - forEach((el) => { - for (const i of interactions) { - el.addEventListener(i, doHydrate, { once: true }); - } - }); - return teardown; - }; - function forEachElement(node, cb) { - if (isComment(node) && node.data === "[") { - let depth = 1; - let next = node.nextSibling; - while (next) { - if (next.nodeType === 1) { - const result = cb(next); - if (result === false) { - break; - } - } else if (isComment(next)) { - if (next.data === "]") { - if (--depth === 0) break; - } else if (next.data === "[") { - depth++; - } - } - next = next.nextSibling; - } - } else { - cb(node); - } - } - var isAsyncWrapper = (i) => !!i.type.__asyncLoader; - // @__NO_SIDE_EFFECTS__ - function defineAsyncComponent(source) { - if (shared.isFunction(source)) { - source = { loader: source }; - } - const { - loader, - loadingComponent, - errorComponent, - delay = 200, - hydrate: hydrateStrategy, - timeout, - // undefined = never times out - suspensible = true, - onError: userOnError - } = source; - let pendingRequest = null; - let resolvedComp; - let retries = 0; - const retry = () => { - retries++; - pendingRequest = null; - return load(); - }; - const load = () => { - let thisRequest; - return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { - err = err instanceof Error ? err : new Error(String(err)); - if (userOnError) { - return new Promise((resolve2, reject) => { - const userRetry = () => resolve2(retry()); - const userFail = () => reject(err); - userOnError(err, userRetry, userFail, retries + 1); - }); - } else { - throw err; - } - }).then((comp) => { - if (thisRequest !== pendingRequest && pendingRequest) { - return pendingRequest; - } - if (!comp) { - warn$1( - `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` - ); - } - if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { - comp = comp.default; - } - if (comp && !shared.isObject(comp) && !shared.isFunction(comp)) { - throw new Error(`Invalid async component load result: ${comp}`); - } - resolvedComp = comp; - return comp; - })); - }; - return /* @__PURE__ */ defineComponent({ - name: "AsyncComponentWrapper", - __asyncLoader: load, - __asyncHydrate(el, instance, hydrate) { - const wasConnected = el.isConnected; - let patched = false; - (instance.bu || (instance.bu = [])).push(() => patched = true); - const performHydrate = () => { - if (patched) { - { - warn$1( - `Skipping lazy hydration for component '${getComponentName(resolvedComp) || resolvedComp.__file}': it was updated before lazy hydration performed.` - ); - } - return; - } - if (!el.parentNode || wasConnected && !el.isConnected) return; - hydrate(); - }; - const doHydrate = hydrateStrategy ? () => { - const teardown = hydrateStrategy( - performHydrate, - (cb) => forEachElement(el, cb) - ); - if (teardown) { - (instance.bum || (instance.bum = [])).push(teardown); - } - } : performHydrate; - if (resolvedComp) { - doHydrate(); - } else { - load().then(() => !instance.isUnmounted && doHydrate()); - } - }, - get __asyncResolved() { - return resolvedComp; - }, - setup() { - const instance = currentInstance; - markAsyncBoundary(instance); - if (resolvedComp) { - return () => createInnerComp(resolvedComp, instance); - } - const onError = (err) => { - pendingRequest = null; - handleError( - err, - instance, - 13, - !errorComponent - ); - }; - if (suspensible && instance.suspense || isInSSRComponentSetup) { - return load().then((comp) => { - return () => createInnerComp(comp, instance); - }).catch((err) => { - onError(err); - return () => errorComponent ? createVNode(errorComponent, { - error: err - }) : null; - }); - } - const loaded = reactivity.ref(false); - const error = reactivity.ref(); - const delayed = reactivity.ref(!!delay); - let timeoutTimer; - let delayTimer; - onUnmounted(() => { - if (timeoutTimer != null) clearTimeout(timeoutTimer); - if (delayTimer != null) clearTimeout(delayTimer); - }); - if (delay) { - delayTimer = setTimeout(() => { - if (instance.isUnmounted) return; - delayed.value = false; - }, delay); - } - if (timeout != null) { - timeoutTimer = setTimeout(() => { - if (instance.isUnmounted) return; - if (!loaded.value && !error.value) { - const err = new Error( - `Async component timed out after ${timeout}ms.` - ); - onError(err); - error.value = err; - } - }, timeout); - } - load().then(() => { - if (instance.isUnmounted) return; - loaded.value = true; - if (instance.parent && isKeepAlive(instance.parent.vnode)) { - instance.parent.update(); - } - }).catch((err) => { - if (instance.isUnmounted) { - pendingRequest = null; - return; - } - onError(err); - error.value = err; - }); - return () => { - if (loaded.value && resolvedComp) { - return createInnerComp(resolvedComp, instance); - } else if (error.value && errorComponent) { - return createVNode(errorComponent, { - error: error.value - }); - } else if (loadingComponent && !delayed.value) { - return createInnerComp( - loadingComponent, - instance - ); - } - }; - } - }); - } - function createInnerComp(comp, parent) { - const { ref: ref2, props, children, ce } = parent.vnode; - const vnode = createVNode(comp, props, children); - vnode.ref = ref2; - vnode.ce = ce; - delete parent.vnode.ce; - return vnode; - } - var isKeepAlive = (vnode) => vnode.type.__isKeepAlive; - var KeepAliveImpl = { - name: `KeepAlive`, - // Marker for special handling inside the renderer. We are not using a === - // check directly on KeepAlive in the renderer, because importing it directly - // would prevent it from being tree-shaken. - __isKeepAlive: true, - props: { - include: [String, RegExp, Array], - exclude: [String, RegExp, Array], - max: [String, Number] - }, - setup(props, { slots }) { - const instance = getCurrentInstance(); - const sharedContext = instance.ctx; - if (!sharedContext.renderer) { - return () => { - const children = slots.default && slots.default(); - return children && children.length === 1 ? children[0] : children; - }; - } - const cache = /* @__PURE__ */ new Map(); - const keys = /* @__PURE__ */ new Set(); - let current = null; - { - instance.__v_cache = cache; - } - const parentSuspense = instance.suspense; - const { - renderer: { - p: patch, - m: move, - um: _unmount, - o: { createElement } - } - } = sharedContext; - const storageContainer = createElement("div"); - sharedContext.activate = (vnode, container, anchor, namespace, optimized) => { - const instance2 = vnode.component; - move(vnode, container, anchor, 0, parentSuspense); - patch( - instance2.vnode, - vnode, - container, - anchor, - instance2, - parentSuspense, - namespace, - vnode.slotScopeIds, - optimized - ); - queuePostRenderEffect(() => { - instance2.isDeactivated = false; - if (instance2.a) { - shared.invokeArrayFns(instance2.a); - } - const vnodeHook = vnode.props && vnode.props.onVnodeMounted; - if (vnodeHook) { - invokeVNodeHook(vnodeHook, instance2.parent, vnode); - } - }, parentSuspense); - { - devtoolsComponentAdded(instance2); - } - }; - sharedContext.deactivate = (vnode) => { - const instance2 = vnode.component; - invalidateMount(instance2.m); - invalidateMount(instance2.a); - move(vnode, storageContainer, null, 1, parentSuspense); - queuePostRenderEffect(() => { - if (instance2.da) { - shared.invokeArrayFns(instance2.da); - } - const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted; - if (vnodeHook) { - invokeVNodeHook(vnodeHook, instance2.parent, vnode); - } - instance2.isDeactivated = true; - }, parentSuspense); - { - devtoolsComponentAdded(instance2); - } - }; - function unmount(vnode) { - resetShapeFlag(vnode); - _unmount(vnode, instance, parentSuspense, true); - } - function pruneCache(filter) { - cache.forEach((vnode, key) => { - const name = getComponentName( - isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : vnode.type - ); - if (name && !filter(name)) { - pruneCacheEntry(key); - } - }); - } - function pruneCacheEntry(key) { - const cached = cache.get(key); - if (cached && (!current || !isSameVNodeType(cached, current))) { - unmount(cached); - } else if (current) { - resetShapeFlag(current); - if (cached) resetShapeFlag(cached); - } - cache.delete(key); - keys.delete(key); - } - watch( - () => [props.include, props.exclude], - ([include, exclude]) => { - include && pruneCache((name) => matches(include, name)); - exclude && pruneCache((name) => !matches(exclude, name)); - }, - // prune post-render after `current` has been updated - { flush: "post", deep: true } - ); - let pendingCacheKey = null; - const cacheSubtree = () => { - if (pendingCacheKey != null) { - if (isSuspense(instance.subTree.type)) { - queuePostRenderEffect(() => { - const vnode = getInnerChild(instance.subTree); - if (vnode.component) { - cache.set(pendingCacheKey, vnode); - } - }, instance.subTree.suspense); - } else { - cache.set(pendingCacheKey, getInnerChild(instance.subTree)); - } - } - }; - onMounted(cacheSubtree); - onUpdated(cacheSubtree); - onBeforeUnmount(() => { - cache.forEach((cached) => { - const { subTree, suspense } = instance; - const vnode = getInnerChild(subTree); - if (cached.type === vnode.type && cached.key === vnode.key) { - resetShapeFlag(vnode); - const da = vnode.component.da; - da && queuePostRenderEffect(da, suspense); - return; - } - unmount(cached); - }); - }); - return () => { - pendingCacheKey = null; - if (!slots.default) { - return current = null; - } - const children = slots.default(); - const rawVNode = children[0]; - if (children.length > 1) { - { - warn$1(`KeepAlive should contain exactly one component child.`); - } - current = null; - return children; - } else if (!isVNode(rawVNode) || !(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) { - current = null; - return rawVNode; - } - let vnode = getInnerChild(rawVNode); - if (vnode.type === Comment) { - current = null; - return vnode; - } - const comp = vnode.type; - const name = getComponentName( - isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp - ); - const { include, exclude, max } = props; - if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) { - vnode.shapeFlag &= -257; - current = vnode; - return rawVNode; - } - const key = vnode.key == null ? comp : vnode.key; - const cachedVNode = cache.get(key); - if (vnode.el) { - vnode = cloneVNode(vnode); - if (rawVNode.shapeFlag & 128) { - rawVNode.ssContent = vnode; - } - } - pendingCacheKey = key; - if (cachedVNode) { - vnode.el = cachedVNode.el; - vnode.component = cachedVNode.component; - if (vnode.transition) { - setTransitionHooks(vnode, vnode.transition); - } - vnode.shapeFlag |= 512; - keys.delete(key); - keys.add(key); - } else { - keys.add(key); - if (max && keys.size > parseInt(max, 10)) { - pruneCacheEntry(keys.values().next().value); - } - } - vnode.shapeFlag |= 256; - current = vnode; - return isSuspense(rawVNode.type) ? rawVNode : vnode; - }; - } - }; - var KeepAlive = KeepAliveImpl; - function matches(pattern, name) { - if (shared.isArray(pattern)) { - return pattern.some((p) => matches(p, name)); - } else if (shared.isString(pattern)) { - return pattern.split(",").includes(name); - } else if (shared.isRegExp(pattern)) { - pattern.lastIndex = 0; - return pattern.test(name); - } - return false; - } - function onActivated(hook, target) { - registerKeepAliveHook(hook, "a", target); - } - function onDeactivated(hook, target) { - registerKeepAliveHook(hook, "da", target); - } - function registerKeepAliveHook(hook, type, target = currentInstance) { - const wrappedHook = hook.__wdc || (hook.__wdc = () => { - let current = target; - while (current) { - if (current.isDeactivated) { - return; - } - current = current.parent; - } - return hook(); - }); - injectHook(type, wrappedHook, target); - if (target) { - let current = target.parent; - while (current && current.parent) { - if (isKeepAlive(current.parent.vnode)) { - injectToKeepAliveRoot(wrappedHook, type, target, current); - } - current = current.parent; - } - } - } - function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { - const injected = injectHook( - type, - hook, - keepAliveRoot, - true - /* prepend */ - ); - onUnmounted(() => { - shared.remove(keepAliveRoot[type], injected); - }, target); - } - function resetShapeFlag(vnode) { - vnode.shapeFlag &= -257; - vnode.shapeFlag &= -513; - } - function getInnerChild(vnode) { - return vnode.shapeFlag & 128 ? vnode.ssContent : vnode; - } - function injectHook(type, hook, target = currentInstance, prepend = false) { - if (target) { - const hooks = target[type] || (target[type] = []); - const wrappedHook = hook.__weh || (hook.__weh = (...args) => { - reactivity.pauseTracking(); - const reset = setCurrentInstance(target); - const res = callWithAsyncErrorHandling(hook, target, type, args); - reset(); - reactivity.resetTracking(); - return res; - }); - if (prepend) { - hooks.unshift(wrappedHook); - } else { - hooks.push(wrappedHook); - } - return wrappedHook; - } else { - const apiName = shared.toHandlerKey(ErrorTypeStrings$1[type].replace(/ hook$/, "")); - warn$1( - `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` - ); - } - } - var createHook = (lifecycle) => (hook, target = currentInstance) => { - if (!isInSSRComponentSetup || lifecycle === "sp") { - injectHook(lifecycle, (...args) => hook(...args), target); - } - }; - var onBeforeMount = createHook("bm"); - var onMounted = createHook("m"); - var onBeforeUpdate = createHook( - "bu" - ); - var onUpdated = createHook("u"); - var onBeforeUnmount = createHook( - "bum" - ); - var onUnmounted = createHook("um"); - var onServerPrefetch = createHook( - "sp" - ); - var onRenderTriggered = createHook("rtg"); - var onRenderTracked = createHook("rtc"); - function onErrorCaptured(hook, target = currentInstance) { - injectHook("ec", hook, target); - } - var COMPONENTS = "components"; - var DIRECTIVES = "directives"; - function resolveComponent(name, maybeSelfReference) { - return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; - } - var NULL_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol.for("v-ndc"); - function resolveDynamicComponent(component) { - if (shared.isString(component)) { - return resolveAsset(COMPONENTS, component, false) || component; - } else { - return component || NULL_DYNAMIC_COMPONENT; - } - } - function resolveDirective(name) { - return resolveAsset(DIRECTIVES, name); - } - function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { - const instance = currentRenderingInstance || currentInstance; - if (instance) { - const Component = instance.type; - if (type === COMPONENTS) { - const selfName = getComponentName( - Component, - false - ); - if (selfName && (selfName === name || selfName === shared.camelize(name) || selfName === shared.capitalize(shared.camelize(name)))) { - return Component; - } - } - const res = ( - // local registration - // check instance[type] first which is resolved for options API - resolve(instance[type] || Component[type], name) || // global registration - resolve(instance.appContext[type], name) - ); - if (!res && maybeSelfReference) { - return Component; - } - if (warnMissing && !res) { - const extra = type === COMPONENTS ? ` -If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``; - warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`); - } - return res; - } else { - warn$1( - `resolve${shared.capitalize(type.slice(0, -1))} can only be used in render() or setup().` - ); - } - } - function resolve(registry2, name) { - return registry2 && (registry2[name] || registry2[shared.camelize(name)] || registry2[shared.capitalize(shared.camelize(name))]); - } - function renderList(source, renderItem, cache, index) { - let ret; - const cached = cache && cache[index]; - const sourceIsArray = shared.isArray(source); - if (sourceIsArray || shared.isString(source)) { - const sourceIsReactiveArray = sourceIsArray && reactivity.isReactive(source); - let needsWrap = false; - let isReadonlySource = false; - if (sourceIsReactiveArray) { - needsWrap = !reactivity.isShallow(source); - isReadonlySource = reactivity.isReadonly(source); - source = reactivity.shallowReadArray(source); - } - ret = new Array(source.length); - for (let i = 0, l = source.length; i < l; i++) { - ret[i] = renderItem( - needsWrap ? isReadonlySource ? reactivity.toReadonly(reactivity.toReactive(source[i])) : reactivity.toReactive(source[i]) : source[i], - i, - void 0, - cached && cached[i] - ); - } - } else if (typeof source === "number") { - if (!Number.isInteger(source) || source < 0) { - { - warn$1( - `The v-for range expects a positive integer value but got ${source}.` - ); - } - ret = []; - } else { - ret = new Array(source); - for (let i = 0; i < source; i++) { - ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]); - } - } - } else if (shared.isObject(source)) { - if (source[Symbol.iterator]) { - ret = Array.from( - source, - (item, i) => renderItem(item, i, void 0, cached && cached[i]) - ); - } else { - const keys = Object.keys(source); - ret = new Array(keys.length); - for (let i = 0, l = keys.length; i < l; i++) { - const key = keys[i]; - ret[i] = renderItem(source[key], key, i, cached && cached[i]); - } - } - } else { - ret = []; - } - if (cache) { - cache[index] = ret; - } - return ret; - } - function createSlots(slots, dynamicSlots) { - for (let i = 0; i < dynamicSlots.length; i++) { - const slot = dynamicSlots[i]; - if (shared.isArray(slot)) { - for (let j = 0; j < slot.length; j++) { - slots[slot[j].name] = slot[j].fn; - } - } else if (slot) { - slots[slot.name] = slot.key ? (...args) => { - const res = slot.fn(...args); - if (res) res.key = slot.key; - return res; - } : slot.fn; - } - } - return slots; - } - function renderSlot(slots, name, props, fallback, noSlotted, branchKey) { - if (props == null) props = {}; - if (currentRenderingInstance.ce || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.ce) { - const slotProps = branchKey != null && props.key == null ? shared.extend({}, props, { key: branchKey }) : props; - const hasProps = Object.keys(slotProps).length > 0; - if (name !== "default") slotProps.name = name; - return openBlock(), createBlock( - Fragment, - null, - [createVNode("slot", slotProps, fallback && fallback())], - hasProps ? -2 : 64 - ); - } - let slot = slots[name]; - if (slot && slot.length > 1) { - warn$1( - `SSR-optimized slot function detected in a non-SSR-optimized render function. You need to mark this component with $dynamic-slots in the parent template.` - ); - slot = () => []; - } - if (slot && slot._c) { - slot._d = false; - } - const prevStackSize = blockStack.length; - openBlock(); - let rendered; - try { - const validSlotContent = slot && ensureValidVNode(slot(props)); - const slotKey = props.key || branchKey || // slot content array of a dynamic conditional slot may have a branch - // key attached in the `createSlots` helper, respect that - validSlotContent && validSlotContent.key; - rendered = createBlock( - Fragment, - { - key: (slotKey && !shared.isSymbol(slotKey) ? slotKey : `_${name}`) + // #7256 force differentiate fallback content from actual content - (!validSlotContent && fallback ? "_fb" : "") - }, - validSlotContent || (fallback ? fallback() : []), - validSlotContent && slots._ === 1 ? 64 : -2 - ); - } catch (err) { - for (let i = blockStack.length; i > prevStackSize; i--) closeBlock(); - throw err; - } finally { - if (slot && slot._c) { - slot._d = true; - } - } - if (!noSlotted && rendered.scopeId) { - rendered.slotScopeIds = [rendered.scopeId + "-s"]; - } - return rendered; - } - function ensureValidVNode(vnodes) { - return vnodes.some((child) => { - if (!isVNode(child)) return true; - if (child.type === Comment) return false; - if (child.type === Fragment && !ensureValidVNode(child.children)) - return false; - return true; - }) ? vnodes : null; - } - function toHandlers(obj, preserveCaseIfNecessary) { - const ret = {}; - if (!shared.isObject(obj)) { - warn$1(`v-on with no argument expects an object value.`); - return ret; - } - for (const key in obj) { - ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : shared.toHandlerKey(key)] = obj[key]; - } - return ret; - } - var getPublicInstance = (i) => { - if (!i) return null; - if (isStatefulComponent(i)) return getComponentPublicInstance(i); - return getPublicInstance(i.parent); - }; - var resolveDevRootEl = (vnode) => { - let found = false; - while (true) { - if (vnode.patchFlag > 0 && vnode.patchFlag & 2048) { - const root = filterSingleRoot(vnode.children); - if (!root) { - return; - } - vnode = root; - found = true; - continue; - } - const component = vnode.component; - if (component && component.subTree) { - vnode = component.subTree; - continue; - } - const suspense = vnode.suspense; - if (suspense && suspense.activeBranch) { - vnode = suspense.activeBranch; - continue; - } - return found ? vnode.el : void 0; - } - }; - var getDevRootFragmentEl = (i) => { - const el = i.subTree && resolveDevRootEl(i.subTree); - return el === void 0 ? i.vnode.el : el; - }; - var publicPropertiesMap = ( - // Move PURE marker to new line to workaround compiler discarding it - // due to type annotation - /* @__PURE__ */ shared.extend(/* @__PURE__ */ Object.create(null), { - $: (i) => i, - $el: (i) => getDevRootFragmentEl(i), - $data: (i) => i.data, - $props: (i) => reactivity.shallowReadonly(i.props), - $attrs: (i) => reactivity.shallowReadonly(i.attrs), - $slots: (i) => reactivity.shallowReadonly(i.slots), - $refs: (i) => reactivity.shallowReadonly(i.refs), - $parent: (i) => getPublicInstance(i.parent), - $root: (i) => getPublicInstance(i.root), - $host: (i) => i.ce, - $emit: (i) => i.emit, - $options: (i) => resolveMergedOptions(i), - $forceUpdate: (i) => i.f || (i.f = () => { - queueJob(i.update); - }), - $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)), - $watch: (i) => instanceWatch.bind(i) - }) - ); - var isReservedPrefix = (key) => key === "_" || key === "$"; - var hasSetupBinding = (state, key) => state !== shared.EMPTY_OBJ && !state.__isScriptSetup && shared.hasOwn(state, key); - var PublicInstanceProxyHandlers = { - get({ _: instance }, key) { - if (key === "__v_skip") { - return true; - } - const { ctx, setupState, data, props, accessCache, type, appContext } = instance; - if (key === "__isVue") { - return true; - } - if (key[0] !== "$") { - const n = accessCache[key]; - if (n !== void 0) { - switch (n) { - case 1: - return setupState[key]; - case 2: - return data[key]; - case 4: - return ctx[key]; - case 3: - return props[key]; - } - } else if (hasSetupBinding(setupState, key)) { - accessCache[key] = 1; - return setupState[key]; - } else if (data !== shared.EMPTY_OBJ && shared.hasOwn(data, key)) { - accessCache[key] = 2; - return data[key]; - } else if (shared.hasOwn(props, key)) { - accessCache[key] = 3; - return props[key]; - } else if (ctx !== shared.EMPTY_OBJ && shared.hasOwn(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if (shouldCacheAccess) { - accessCache[key] = 0; - } - } - const publicGetter = publicPropertiesMap[key]; - let cssModule, globalProperties; - if (publicGetter) { - if (key === "$attrs") { - reactivity.track(instance.attrs, "get", ""); - markAttrsAccessed(); - } else if (key === "$slots") { - reactivity.track(instance, "get", key); - } - return publicGetter(instance); - } else if ( - // css module (injected by vue-loader) - (cssModule = type.__cssModules) && (cssModule = cssModule[key]) - ) { - return cssModule; - } else if (ctx !== shared.EMPTY_OBJ && shared.hasOwn(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if ( - // global properties - globalProperties = appContext.config.globalProperties, shared.hasOwn(globalProperties, key) - ) { - { - return globalProperties[key]; - } - } else if (currentRenderingInstance && (!shared.isString(key) || // #1091 avoid internal isRef/isVNode checks on component instance leading - // to infinite warning loop - key.indexOf("__v") !== 0)) { - if (data !== shared.EMPTY_OBJ && isReservedPrefix(key[0]) && shared.hasOwn(data, key)) { - warn$1( - `Property ${JSON.stringify( - key - )} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.` - ); - } else if (instance === currentRenderingInstance) { - warn$1( - `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.` - ); - } - } - }, - set({ _: instance }, key, value) { - const { data, setupState, ctx } = instance; - if (hasSetupBinding(setupState, key)) { - setupState[key] = value; - return true; - } else if (setupState.__isScriptSetup && shared.hasOwn(setupState, key)) { - warn$1(`Cannot mutate <script setup> binding "${key}" from Options API.`); - return false; - } else if (data !== shared.EMPTY_OBJ && shared.hasOwn(data, key)) { - data[key] = value; - return true; - } else if (shared.hasOwn(instance.props, key)) { - warn$1(`Attempting to mutate prop "${key}". Props are readonly.`); - return false; - } - if (key[0] === "$" && key.slice(1) in instance) { - warn$1( - `Attempting to mutate public property "${key}". Properties starting with $ are reserved and readonly.` - ); - return false; - } else { - if (key in instance.appContext.config.globalProperties) { - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - value - }); - } else { - ctx[key] = value; - } - } - return true; - }, - has({ - _: { data, setupState, accessCache, ctx, appContext, props, type } - }, key) { - let cssModules; - return !!(accessCache[key] || data !== shared.EMPTY_OBJ && key[0] !== "$" && shared.hasOwn(data, key) || hasSetupBinding(setupState, key) || shared.hasOwn(props, key) || shared.hasOwn(ctx, key) || shared.hasOwn(publicPropertiesMap, key) || shared.hasOwn(appContext.config.globalProperties, key) || (cssModules = type.__cssModules) && cssModules[key]); - }, - defineProperty(target, key, descriptor) { - if (descriptor.get != null) { - target._.accessCache[key] = 0; - } else if (shared.hasOwn(descriptor, "value")) { - this.set(target, key, descriptor.value, null); - } - return Reflect.defineProperty(target, key, descriptor); - } - }; - { - PublicInstanceProxyHandlers.ownKeys = (target) => { - warn$1( - `Avoid app logic that relies on enumerating keys on a component instance. The keys will be empty in production mode to avoid performance overhead.` - ); - return Reflect.ownKeys(target); - }; - } - var RuntimeCompiledPublicInstanceProxyHandlers = /* @__PURE__ */ shared.extend({}, PublicInstanceProxyHandlers, { - get(target, key) { - if (key === Symbol.unscopables) { - return; - } - return PublicInstanceProxyHandlers.get(target, key, target); - }, - has(_, key) { - const has = key[0] !== "_" && !shared.isGloballyAllowed(key); - if (!has && PublicInstanceProxyHandlers.has(_, key)) { - warn$1( - `Property ${JSON.stringify( - key - )} should not start with _ which is a reserved prefix for Vue internals.` - ); - } - return has; - } - }); - function createDevRenderContext(instance) { - const target = {}; - Object.defineProperty(target, `_`, { - configurable: true, - enumerable: false, - get: () => instance - }); - Object.keys(publicPropertiesMap).forEach((key) => { - Object.defineProperty(target, key, { - configurable: true, - enumerable: false, - get: () => publicPropertiesMap[key](instance), - // intercepted by the proxy so no need for implementation, - // but needed to prevent set errors - set: shared.NOOP - }); - }); - return target; - } - function exposePropsOnRenderContext(instance) { - const { - ctx, - propsOptions: [propsOptions] - } = instance; - if (propsOptions) { - Object.keys(propsOptions).forEach((key) => { - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => instance.props[key], - set: shared.NOOP - }); - }); - } - } - function exposeSetupStateOnRenderContext(instance) { - const { ctx, setupState } = instance; - Object.keys(reactivity.toRaw(setupState)).forEach((key) => { - if (!setupState.__isScriptSetup) { - if (isReservedPrefix(key[0])) { - warn$1( - `setup() return property ${JSON.stringify( - key - )} should not start with "$" or "_" which are reserved prefixes for Vue internals.` - ); - return; - } - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => setupState[key], - set: shared.NOOP - }); - } - }); - } - var warnRuntimeUsage = (method) => warn$1( - `${method}() is a compiler-hint helper that is only usable inside <script setup> of a single file component. Its arguments should be compiled away and passing it at runtime has no effect.` - ); - function defineProps() { - { - warnRuntimeUsage(`defineProps`); - } - return null; - } - function defineEmits() { - { - warnRuntimeUsage(`defineEmits`); - } - return null; - } - function defineExpose(exposed) { - { - warnRuntimeUsage(`defineExpose`); - } - } - function defineOptions(options) { - { - warnRuntimeUsage(`defineOptions`); - } - } - function defineSlots() { - { - warnRuntimeUsage(`defineSlots`); - } - return null; - } - function defineModel() { - { - warnRuntimeUsage("defineModel"); - } - } - function withDefaults(props, defaults) { - { - warnRuntimeUsage(`withDefaults`); - } - return null; - } - function useSlots() { - return getContext("useSlots").slots; - } - function useAttrs() { - return getContext("useAttrs").attrs; - } - function getContext(calledFunctionName) { - const i = getCurrentInstance(); - if (!i) { - warn$1(`${calledFunctionName}() called without active instance.`); - } - return i.setupContext || (i.setupContext = createSetupContext(i)); - } - function normalizePropsOrEmits(props) { - return shared.isArray(props) ? props.reduce( - (normalized, p) => (normalized[p] = null, normalized), - {} - ) : props; - } - function mergeDefaults(raw, defaults) { - const props = normalizePropsOrEmits(raw); - for (const key in defaults) { - if (key.startsWith("__skip")) continue; - let opt = props[key]; - if (opt) { - if (shared.isArray(opt) || shared.isFunction(opt)) { - opt = props[key] = { type: opt, default: defaults[key] }; - } else { - opt.default = defaults[key]; - } - } else if (opt === null) { - opt = props[key] = { default: defaults[key] }; - } else { - warn$1(`props default key "${key}" has no corresponding declaration.`); - } - if (opt && defaults[`__skip_${key}`]) { - opt.skipFactory = true; - } - } - return props; - } - function mergeModels(a, b) { - if (!a || !b) return a || b; - if (shared.isArray(a) && shared.isArray(b)) return a.concat(b); - return shared.extend({}, normalizePropsOrEmits(a), normalizePropsOrEmits(b)); - } - function createPropsRestProxy(props, excludedKeys) { - const ret = {}; - for (const key in props) { - if (!excludedKeys.includes(key)) { - Object.defineProperty(ret, key, { - enumerable: true, - get: () => props[key] - }); - } - } - return ret; - } - function withAsyncContext(getAwaitable) { - const ctx = getCurrentInstance(); - const inSSRSetup = isInSSRComponentSetup; - if (!ctx) { - warn$1( - `withAsyncContext called without active current instance. This is likely a bug.` - ); - } - let awaitable = getAwaitable(); - unsetCurrentInstance(); - if (inSSRSetup) { - setInSSRSetupState(false); - } - const restore = () => { - setCurrentInstance(ctx); - if (inSSRSetup) { - setInSSRSetupState(true); - } - }; - const cleanup = () => { - if (getCurrentInstance() !== ctx) ctx.scope.off(); - unsetCurrentInstance(); - if (inSSRSetup) { - setInSSRSetupState(false); - } - }; - if (shared.isPromise(awaitable)) { - awaitable = awaitable.catch((e) => { - restore(); - Promise.resolve().then(() => Promise.resolve().then(cleanup)); - throw e; - }); - } - return [ - awaitable, - () => { - restore(); - Promise.resolve().then(cleanup); - } - ]; - } - function createDuplicateChecker() { - const cache = /* @__PURE__ */ Object.create(null); - return (type, key) => { - if (cache[key]) { - warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`); - } else { - cache[key] = type; - } - }; - } - var shouldCacheAccess = true; - function applyOptions(instance) { - const options = resolveMergedOptions(instance); - const publicThis = instance.proxy; - const ctx = instance.ctx; - shouldCacheAccess = false; - if (options.beforeCreate) { - callHook(options.beforeCreate, instance, "bc"); - } - const { - // state - data: dataOptions, - computed: computedOptions, - methods, - watch: watchOptions, - provide: provideOptions, - inject: injectOptions, - // lifecycle - created, - beforeMount, - mounted, - beforeUpdate, - updated, - activated, - deactivated, - beforeDestroy, - beforeUnmount, - destroyed, - unmounted, - render, - renderTracked, - renderTriggered, - errorCaptured, - serverPrefetch, - // public API - expose, - inheritAttrs, - // assets - components, - directives, - filters - } = options; - const checkDuplicateProperties = createDuplicateChecker(); - { - const [propsOptions] = instance.propsOptions; - if (propsOptions) { - for (const key in propsOptions) { - checkDuplicateProperties("Props", key); - } - } - } - if (injectOptions) { - resolveInjections(injectOptions, ctx, checkDuplicateProperties); - } - if (methods) { - for (const key in methods) { - const methodHandler = methods[key]; - if (shared.isFunction(methodHandler)) { - { - Object.defineProperty(ctx, key, { - value: methodHandler.bind(publicThis), - configurable: true, - enumerable: true, - writable: true - }); - } - { - checkDuplicateProperties("Methods", key); - } - } else { - warn$1( - `Method "${key}" has type "${typeof methodHandler}" in the component definition. Did you reference the function correctly?` - ); - } - } - } - if (dataOptions) { - if (!shared.isFunction(dataOptions)) { - warn$1( - `The data option must be a function. Plain object usage is no longer supported.` - ); - } - const data = dataOptions.call(publicThis, publicThis); - if (shared.isPromise(data)) { - warn$1( - `data() returned a Promise - note data() cannot be async; If you intend to perform data fetching before component renders, use async setup() + <Suspense>.` - ); - } - if (!shared.isObject(data)) { - warn$1(`data() should return an object.`); - } else { - instance.data = reactivity.reactive(data); - { - for (const key in data) { - checkDuplicateProperties("Data", key); - if (!isReservedPrefix(key[0])) { - Object.defineProperty(ctx, key, { - configurable: true, - enumerable: true, - get: () => data[key], - set: shared.NOOP - }); - } - } - } - } - } - shouldCacheAccess = true; - if (computedOptions) { - for (const key in computedOptions) { - const opt = computedOptions[key]; - const get = shared.isFunction(opt) ? opt.bind(publicThis, publicThis) : shared.isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : shared.NOOP; - if (get === shared.NOOP) { - warn$1(`Computed property "${key}" has no getter.`); - } - const set = !shared.isFunction(opt) && shared.isFunction(opt.set) ? opt.set.bind(publicThis) : () => { - warn$1( - `Write operation failed: computed property "${key}" is readonly.` - ); - }; - const c = computed({ - get, - set - }); - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => c.value, - set: (v) => c.value = v - }); - { - checkDuplicateProperties("Computed", key); - } - } - } - if (watchOptions) { - for (const key in watchOptions) { - createWatcher(watchOptions[key], ctx, publicThis, key); - } - } - if (provideOptions) { - const provides = shared.isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions; - Reflect.ownKeys(provides).forEach((key) => { - provide(key, provides[key]); - }); - } - if (created) { - callHook(created, instance, "c"); - } - function registerLifecycleHook(register, hook) { - if (shared.isArray(hook)) { - hook.forEach((_hook) => register(_hook.bind(publicThis))); - } else if (hook) { - register(hook.bind(publicThis)); - } - } - registerLifecycleHook(onBeforeMount, beforeMount); - registerLifecycleHook(onMounted, mounted); - registerLifecycleHook(onBeforeUpdate, beforeUpdate); - registerLifecycleHook(onUpdated, updated); - registerLifecycleHook(onActivated, activated); - registerLifecycleHook(onDeactivated, deactivated); - registerLifecycleHook(onErrorCaptured, errorCaptured); - registerLifecycleHook(onRenderTracked, renderTracked); - registerLifecycleHook(onRenderTriggered, renderTriggered); - registerLifecycleHook(onBeforeUnmount, beforeUnmount); - registerLifecycleHook(onUnmounted, unmounted); - registerLifecycleHook(onServerPrefetch, serverPrefetch); - if (shared.isArray(expose)) { - if (expose.length) { - const exposed = instance.exposed || (instance.exposed = {}); - expose.forEach((key) => { - Object.defineProperty(exposed, key, { - get: () => publicThis[key], - set: (val) => publicThis[key] = val, - enumerable: true - }); - }); - } else if (!instance.exposed) { - instance.exposed = {}; - } - } - if (render && instance.render === shared.NOOP) { - instance.render = render; - } - if (inheritAttrs != null) { - instance.inheritAttrs = inheritAttrs; - } - if (components) instance.components = components; - if (directives) instance.directives = directives; - if (serverPrefetch) { - markAsyncBoundary(instance); - } - } - function resolveInjections(injectOptions, ctx, checkDuplicateProperties = shared.NOOP) { - if (shared.isArray(injectOptions)) { - injectOptions = normalizeInject(injectOptions); - } - for (const key in injectOptions) { - const opt = injectOptions[key]; - let injected; - if (shared.isObject(opt)) { - if ("default" in opt) { - injected = inject( - opt.from || key, - opt.default, - true - ); - } else { - injected = inject(opt.from || key); - } - } else { - injected = inject(opt); - } - if (reactivity.isRef(injected)) { - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => injected.value, - set: (v) => injected.value = v - }); - } else { - ctx[key] = injected; - } - { - checkDuplicateProperties("Inject", key); - } - } - } - function callHook(hook, instance, type) { - callWithAsyncErrorHandling( - shared.isArray(hook) ? hook.map((h2) => h2.bind(instance.proxy)) : hook.bind(instance.proxy), - instance, - type - ); - } - function createWatcher(raw, ctx, publicThis, key) { - let getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key]; - if (shared.isString(raw)) { - const handler = ctx[raw]; - if (shared.isFunction(handler)) { - { - watch(getter, handler); - } - } else { - warn$1(`Invalid watch handler specified by key "${raw}"`, handler); - } - } else if (shared.isFunction(raw)) { - { - watch(getter, raw.bind(publicThis)); - } - } else if (shared.isObject(raw)) { - if (shared.isArray(raw)) { - raw.forEach((r) => createWatcher(r, ctx, publicThis, key)); - } else { - const handler = shared.isFunction(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler]; - if (shared.isFunction(handler)) { - watch(getter, handler, raw); - } else { - warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler); - } - } - } else { - warn$1(`Invalid watch option: "${key}"`, raw); - } - } - function resolveMergedOptions(instance) { - const base = instance.type; - const { mixins, extends: extendsOptions } = base; - const { - mixins: globalMixins, - optionsCache: cache, - config: { optionMergeStrategies } - } = instance.appContext; - const cached = cache.get(base); - let resolved; - if (cached) { - resolved = cached; - } else if (!globalMixins.length && !mixins && !extendsOptions) { - { - resolved = base; - } - } else { - resolved = {}; - if (globalMixins.length) { - globalMixins.forEach( - (m) => mergeOptions(resolved, m, optionMergeStrategies, true) - ); - } - mergeOptions(resolved, base, optionMergeStrategies); - } - if (shared.isObject(base)) { - cache.set(base, resolved); - } - return resolved; - } - function mergeOptions(to, from, strats, asMixin = false) { - const { mixins, extends: extendsOptions } = from; - if (extendsOptions) { - mergeOptions(to, extendsOptions, strats, true); - } - if (mixins) { - mixins.forEach( - (m) => mergeOptions(to, m, strats, true) - ); - } - for (const key in from) { - if (asMixin && key === "expose") { - warn$1( - `"expose" option is ignored when declared in mixins or extends. It should only be declared in the base component itself.` - ); - } else { - const strat = internalOptionMergeStrats[key] || strats && strats[key]; - to[key] = strat ? strat(to[key], from[key]) : from[key]; - } - } - return to; - } - var internalOptionMergeStrats = { - data: mergeDataFn, - props: mergeEmitsOrPropsOptions, - emits: mergeEmitsOrPropsOptions, - // objects - methods: mergeObjectOptions, - computed: mergeObjectOptions, - // lifecycle - beforeCreate: mergeAsArray, - created: mergeAsArray, - beforeMount: mergeAsArray, - mounted: mergeAsArray, - beforeUpdate: mergeAsArray, - updated: mergeAsArray, - beforeDestroy: mergeAsArray, - beforeUnmount: mergeAsArray, - destroyed: mergeAsArray, - unmounted: mergeAsArray, - activated: mergeAsArray, - deactivated: mergeAsArray, - errorCaptured: mergeAsArray, - serverPrefetch: mergeAsArray, - // assets - components: mergeObjectOptions, - directives: mergeObjectOptions, - // watch - watch: mergeWatchOptions, - // provide / inject - provide: mergeDataFn, - inject: mergeInject - }; - function mergeDataFn(to, from) { - if (!from) { - return to; - } - if (!to) { - return from; - } - return function mergedDataFn() { - return shared.extend( - shared.isFunction(to) ? to.call(this, this) : to, - shared.isFunction(from) ? from.call(this, this) : from - ); - }; - } - function mergeInject(to, from) { - return mergeObjectOptions(normalizeInject(to), normalizeInject(from)); - } - function normalizeInject(raw) { - if (shared.isArray(raw)) { - const res = {}; - for (let i = 0; i < raw.length; i++) { - res[raw[i]] = raw[i]; - } - return res; - } - return raw; - } - function mergeAsArray(to, from) { - return to ? [...new Set([].concat(to, from))] : from; - } - function mergeObjectOptions(to, from) { - return to ? shared.extend(/* @__PURE__ */ Object.create(null), to, from) : from; - } - function mergeEmitsOrPropsOptions(to, from) { - if (to) { - if (shared.isArray(to) && shared.isArray(from)) { - return [.../* @__PURE__ */ new Set([...to, ...from])]; - } - return shared.extend( - /* @__PURE__ */ Object.create(null), - normalizePropsOrEmits(to), - normalizePropsOrEmits(from != null ? from : {}) - ); - } else { - return from; - } - } - function mergeWatchOptions(to, from) { - if (!to) return from; - if (!from) return to; - const merged = shared.extend(/* @__PURE__ */ Object.create(null), to); - for (const key in from) { - merged[key] = mergeAsArray(to[key], from[key]); - } - return merged; - } - function createAppContext() { - return { - app: null, - config: { - isNativeTag: shared.NO, - performance: false, - globalProperties: {}, - optionMergeStrategies: {}, - errorHandler: void 0, - warnHandler: void 0, - compilerOptions: {} - }, - mixins: [], - components: {}, - directives: {}, - provides: /* @__PURE__ */ Object.create(null), - optionsCache: /* @__PURE__ */ new WeakMap(), - propsCache: /* @__PURE__ */ new WeakMap(), - emitsCache: /* @__PURE__ */ new WeakMap() - }; - } - var uid$1 = 0; - function createAppAPI(render, hydrate) { - return function createApp(rootComponent, rootProps = null) { - if (!shared.isFunction(rootComponent)) { - rootComponent = shared.extend({}, rootComponent); - } - if (rootProps != null && !shared.isObject(rootProps)) { - warn$1(`root props passed to app.mount() must be an object.`); - rootProps = null; - } - const context = createAppContext(); - const installedPlugins = /* @__PURE__ */ new WeakSet(); - const pluginCleanupFns = []; - let isMounted = false; - const app = context.app = { - _uid: uid$1++, - _component: rootComponent, - _props: rootProps, - _container: null, - _context: context, - _instance: null, - version, - get config() { - return context.config; - }, - set config(v) { - { - warn$1( - `app.config cannot be replaced. Modify individual options instead.` - ); - } - }, - use(plugin, ...options) { - if (installedPlugins.has(plugin)) { - warn$1(`Plugin has already been applied to target app.`); - } else if (plugin && shared.isFunction(plugin.install)) { - installedPlugins.add(plugin); - plugin.install(app, ...options); - } else if (shared.isFunction(plugin)) { - installedPlugins.add(plugin); - plugin(app, ...options); - } else { - warn$1( - `A plugin must either be a function or an object with an "install" function.` - ); - } - return app; - }, - mixin(mixin) { - { - if (!context.mixins.includes(mixin)) { - context.mixins.push(mixin); - } else { - warn$1( - "Mixin has already been applied to target app" + (mixin.name ? `: ${mixin.name}` : "") - ); - } - } - return app; - }, - component(name, component) { - { - validateComponentName(name, context.config); - } - if (!component) { - return context.components[name]; - } - if (context.components[name]) { - warn$1(`Component "${name}" has already been registered in target app.`); - } - context.components[name] = component; - return app; - }, - directive(name, directive) { - { - validateDirectiveName(name); - } - if (!directive) { - return context.directives[name]; - } - if (context.directives[name]) { - warn$1(`Directive "${name}" has already been registered in target app.`); - } - context.directives[name] = directive; - return app; - }, - mount(rootContainer, isHydrate, namespace) { - if (!isMounted) { - if (rootContainer.__vue_app__) { - warn$1( - `There is already an app instance mounted on the host container. - If you want to mount another app on the same host container, you need to unmount the previous app by calling \`app.unmount()\` first.` - ); - } - const vnode = app._ceVNode || createVNode(rootComponent, rootProps); - vnode.appContext = context; - if (namespace === true) { - namespace = "svg"; - } else if (namespace === false) { - namespace = void 0; - } - { - context.reload = () => { - const cloned = cloneVNode(vnode); - cloned.el = null; - render(cloned, rootContainer, namespace); - }; - } - if (isHydrate && hydrate) { - hydrate(vnode, rootContainer); - } else { - render(vnode, rootContainer, namespace); - } - isMounted = true; - app._container = rootContainer; - rootContainer.__vue_app__ = app; - { - app._instance = vnode.component; - devtoolsInitApp(app, version); - } - return getComponentPublicInstance(vnode.component); - } else { - warn$1( - `App has already been mounted. -If you want to remount the same app, move your app creation logic into a factory function and create fresh app instances for each mount - e.g. \`const createMyApp = () => createApp(App)\`` - ); - } - }, - onUnmount(cleanupFn) { - if (typeof cleanupFn !== "function") { - warn$1( - `Expected function as first argument to app.onUnmount(), but got ${typeof cleanupFn}` - ); - } - pluginCleanupFns.push(cleanupFn); - }, - unmount() { - if (isMounted) { - callWithAsyncErrorHandling( - pluginCleanupFns, - app._instance, - 16 - ); - render(null, app._container); - { - app._instance = null; - devtoolsUnmountApp(app); - } - delete app._container.__vue_app__; - } else { - warn$1(`Cannot unmount an app that is not mounted.`); - } - }, - provide(key, value) { - if (key in context.provides) { - if (shared.hasOwn(context.provides, key)) { - warn$1( - `App already provides property with key "${String(key)}". It will be overwritten with the new value.` - ); - } else { - warn$1( - `App already provides property with key "${String(key)}" inherited from its parent element. It will be overwritten with the new value.` - ); - } - } - context.provides[key] = value; - return app; - }, - runWithContext(fn) { - const lastApp = currentApp; - currentApp = app; - try { - return fn(); - } finally { - currentApp = lastApp; - } - } - }; - return app; - }; - } - var currentApp = null; - function useModel(props, name, options = shared.EMPTY_OBJ) { - const i = getCurrentInstance(); - if (!i) { - warn$1(`useModel() called without active instance.`); - return reactivity.ref(); - } - const camelizedName = shared.camelize(name); - if (!i.propsOptions[0][camelizedName]) { - warn$1(`useModel() called with prop "${name}" which is not declared.`); - return reactivity.ref(); - } - const hyphenatedName = shared.hyphenate(name); - const modifiers = getModelModifiers(props, camelizedName); - const res = reactivity.customRef((track, trigger) => { - let localValue; - let prevSetValue = shared.EMPTY_OBJ; - let prevEmittedValue; - watchSyncEffect(() => { - const propValue = props[camelizedName]; - if (shared.hasChanged(localValue, propValue)) { - localValue = propValue; - trigger(); - } - }); - return { - get() { - track(); - return options.get ? options.get(localValue) : localValue; - }, - set(value) { - const emittedValue = options.set ? options.set(value) : value; - if (!shared.hasChanged(emittedValue, localValue) && !(prevSetValue !== shared.EMPTY_OBJ && shared.hasChanged(value, prevSetValue))) { - return; - } - const rawProps = i.vnode.props; - const hasVModel = !!(rawProps && // check if parent has passed v-model - (name in rawProps || camelizedName in rawProps || hyphenatedName in rawProps) && (`onUpdate:${name}` in rawProps || `onUpdate:${camelizedName}` in rawProps || `onUpdate:${hyphenatedName}` in rawProps)); - if (!hasVModel) { - localValue = value; - trigger(); - } - i.emit(`update:${name}`, emittedValue); - if (shared.hasChanged(value, prevSetValue) && (shared.hasChanged(value, emittedValue) && !shared.hasChanged(emittedValue, prevEmittedValue) || // #13524: browsers differ in when they flush microtasks between - // event listeners. If a v-model listener emits an intermediate value - // and a following listener restores the model to its previous prop - // value before parent updates are flushed, the parent render can be - // deduped as having no prop change. Force a local update so DOM state - // such as an input's value is synchronized back to the current model. - hasVModel && prevSetValue !== shared.EMPTY_OBJ && !shared.hasChanged(emittedValue, localValue))) { - trigger(); - } - prevSetValue = value; - prevEmittedValue = emittedValue; - } - }; - }); - res[Symbol.iterator] = () => { - let i2 = 0; - return { - next() { - if (i2 < 2) { - return { value: i2++ ? modifiers || shared.EMPTY_OBJ : res, done: false }; - } else { - return { done: true }; - } - } - }; - }; - return res; - } - var getModelModifiers = (props, modelName) => { - return modelName === "modelValue" || modelName === "model-value" ? props.modelModifiers : props[`${modelName}Modifiers`] || props[`${shared.camelize(modelName)}Modifiers`] || props[`${shared.hyphenate(modelName)}Modifiers`]; - }; - function emit(instance, event, ...rawArgs) { - if (instance.isUnmounted) return; - const props = instance.vnode.props || shared.EMPTY_OBJ; - { - const { - emitsOptions, - propsOptions: [propsOptions] - } = instance; - if (emitsOptions) { - if (!(event in emitsOptions) && true) { - if (!propsOptions || !(shared.toHandlerKey(shared.camelize(event)) in propsOptions)) { - warn$1( - `Component emitted event "${event}" but it is neither declared in the emits option nor as an "${shared.toHandlerKey(shared.camelize(event))}" prop.` - ); - } - } else { - const validator = emitsOptions[event]; - if (shared.isFunction(validator)) { - const isValid = validator(...rawArgs); - if (!isValid) { - warn$1( - `Invalid event arguments: event validation failed for event "${event}".` - ); - } - } - } - } - } - let args = rawArgs; - const isModelListener = event.startsWith("update:"); - const modifiers = isModelListener && getModelModifiers(props, event.slice(7)); - if (modifiers) { - if (modifiers.trim) { - args = rawArgs.map((a) => shared.isString(a) ? a.trim() : a); - } - if (modifiers.number) { - args = args.map(shared.looseToNumber); - } - } - { - devtoolsComponentEmit(instance, event, args); - } - { - const lowerCaseEvent = event.toLowerCase(); - if (lowerCaseEvent !== event && props[shared.toHandlerKey(lowerCaseEvent)]) { - warn$1( - `Event "${lowerCaseEvent}" is emitted in component ${formatComponentName( - instance, - instance.type - )} but the handler is registered for "${event}". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "${shared.hyphenate( - event - )}" instead of "${event}".` - ); - } - } - let handlerName; - let handler = props[handlerName = shared.toHandlerKey(event)] || // also try camelCase event handler (#2249) - props[handlerName = shared.toHandlerKey(shared.camelize(event))]; - if (!handler && isModelListener) { - handler = props[handlerName = shared.toHandlerKey(shared.hyphenate(event))]; - } - if (handler) { - callWithAsyncErrorHandling( - handler, - instance, - 6, - args - ); - } - const onceHandler = props[handlerName + `Once`]; - if (onceHandler) { - if (!instance.emitted) { - instance.emitted = {}; - } else if (instance.emitted[handlerName]) { - return; - } - instance.emitted[handlerName] = true; - callWithAsyncErrorHandling( - onceHandler, - instance, - 6, - args - ); - } - } - var mixinEmitsCache = /* @__PURE__ */ new WeakMap(); - function normalizeEmitsOptions(comp, appContext, asMixin = false) { - const cache = asMixin ? mixinEmitsCache : appContext.emitsCache; - const cached = cache.get(comp); - if (cached !== void 0) { - return cached; - } - const raw = comp.emits; - let normalized = {}; - let hasExtends = false; - if (!shared.isFunction(comp)) { - const extendEmits = (raw2) => { - const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); - if (normalizedFromExtend) { - hasExtends = true; - shared.extend(normalized, normalizedFromExtend); - } - }; - if (!asMixin && appContext.mixins.length) { - appContext.mixins.forEach(extendEmits); - } - if (comp.extends) { - extendEmits(comp.extends); - } - if (comp.mixins) { - comp.mixins.forEach(extendEmits); - } - } - if (!raw && !hasExtends) { - if (shared.isObject(comp)) { - cache.set(comp, null); - } - return null; - } - if (shared.isArray(raw)) { - raw.forEach((key) => normalized[key] = null); - } else { - shared.extend(normalized, raw); - } - if (shared.isObject(comp)) { - cache.set(comp, normalized); - } - return normalized; - } - function isEmitListener(options, key) { - if (!options || !shared.isOn(key)) { - return false; - } - key = key.slice(2); - key = key === "Once" ? key : key.replace(/Once$/, ""); - return shared.hasOwn(options, key[0].toLowerCase() + key.slice(1)) || shared.hasOwn(options, shared.hyphenate(key)) || shared.hasOwn(options, key); - } - var accessedAttrs = false; - function markAttrsAccessed() { - accessedAttrs = true; - } - function renderComponentRoot(instance) { - const { - type: Component, - vnode, - proxy, - withProxy, - propsOptions: [propsOptions], - slots, - attrs, - emit: emit2, - render, - renderCache, - props, - data, - setupState, - ctx, - inheritAttrs - } = instance; - const prev = setCurrentRenderingInstance(instance); - let result; - let fallthroughAttrs; - { - accessedAttrs = false; - } - try { - if (vnode.shapeFlag & 4) { - const proxyToUse = withProxy || proxy; - const thisProxy = setupState.__isScriptSetup ? new Proxy(proxyToUse, { - get(target, key, receiver) { - warn$1( - `Property '${String( - key - )}' was accessed via 'this'. Avoid using 'this' in templates.` - ); - return Reflect.get(target, key, receiver); - } - }) : proxyToUse; - result = normalizeVNode( - render.call( - thisProxy, - proxyToUse, - renderCache, - true ? reactivity.shallowReadonly(props) : props, - setupState, - data, - ctx - ) - ); - fallthroughAttrs = attrs; - } else { - const render2 = Component; - if (attrs === props) { - markAttrsAccessed(); - } - result = normalizeVNode( - render2.length > 1 ? render2( - true ? reactivity.shallowReadonly(props) : props, - true ? { - get attrs() { - markAttrsAccessed(); - return reactivity.shallowReadonly(attrs); - }, - slots, - emit: emit2 - } : { attrs, slots, emit: emit2 } - ) : render2( - true ? reactivity.shallowReadonly(props) : props, - null - ) - ); - fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs); - } - } catch (err) { - blockStack.length = 0; - handleError(err, instance, 1); - result = createVNode(Comment); - } - let root = result; - let setRoot = void 0; - if (result.patchFlag > 0 && result.patchFlag & 2048) { - [root, setRoot] = getChildRoot(result); - } - if (fallthroughAttrs && inheritAttrs !== false) { - const keys = Object.keys(fallthroughAttrs); - const { shapeFlag } = root; - if (keys.length) { - if (shapeFlag & (1 | 6)) { - if (propsOptions && keys.some(shared.isModelListener)) { - fallthroughAttrs = filterModelListeners( - fallthroughAttrs, - propsOptions - ); - } - root = cloneVNode(root, fallthroughAttrs, false, true); - } else if (!accessedAttrs && root.type !== Comment) { - const allAttrs = Object.keys(attrs); - const eventAttrs = []; - const extraAttrs = []; - for (let i = 0, l = allAttrs.length; i < l; i++) { - const key = allAttrs[i]; - if (shared.isOn(key)) { - if (!shared.isModelListener(key)) { - eventAttrs.push(key[2].toLowerCase() + key.slice(3)); - } - } else { - extraAttrs.push(key); - } - } - if (extraAttrs.length) { - warn$1( - `Extraneous non-props attributes (${extraAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text or teleport root nodes.` - ); - } - if (eventAttrs.length) { - warn$1( - `Extraneous non-emits event listeners (${eventAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.` - ); - } - } - } - } - if (vnode.dirs) { - if (!isElementRoot(root)) { - warn$1( - `Runtime directive used on component with non-element root node. The directives will not function as intended.` - ); - } - root = cloneVNode(root, null, false, true); - root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs; - } - if (vnode.transition) { - const child = isTeleport(root.type) ? getInnerChild$1(root) || root : root; - if (!isElementRoot(child)) { - warn$1( - `Component inside <Transition> renders non-element root node that cannot be animated.` - ); - } - setTransitionHooks(child, vnode.transition); - } - if (setRoot) { - setRoot(root); - } else { - result = root; - } - setCurrentRenderingInstance(prev); - return result; - } - var getChildRoot = (vnode) => { - const rawChildren = vnode.children; - const dynamicChildren = vnode.dynamicChildren; - const childRoot = filterSingleRoot(rawChildren, false); - if (!childRoot) { - return [vnode, void 0]; - } else if (childRoot.patchFlag > 0 && childRoot.patchFlag & 2048) { - return getChildRoot(childRoot); - } - const index = rawChildren.indexOf(childRoot); - const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1; - const setRoot = (updatedRoot) => { - rawChildren[index] = updatedRoot; - if (dynamicChildren) { - if (dynamicIndex > -1) { - dynamicChildren[dynamicIndex] = updatedRoot; - } else if (updatedRoot.patchFlag > 0) { - vnode.dynamicChildren = [...dynamicChildren, updatedRoot]; - } - } - }; - return [normalizeVNode(childRoot), setRoot]; - }; - function filterSingleRoot(children, recurse = true) { - let singleRoot; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (isVNode(child)) { - if (child.type !== Comment || child.children === "v-if") { - if (singleRoot) { - return; - } else { - singleRoot = child; - if (recurse && singleRoot.patchFlag > 0 && singleRoot.patchFlag & 2048) { - return filterSingleRoot(singleRoot.children); - } - } - } - } else { - return; - } - } - return singleRoot; - } - var getFunctionalFallthrough = (attrs) => { - let res; - for (const key in attrs) { - if (key === "class" || key === "style" || shared.isOn(key)) { - (res || (res = {}))[key] = attrs[key]; - } - } - return res; - }; - var filterModelListeners = (attrs, props) => { - const res = {}; - for (const key in attrs) { - if (!shared.isModelListener(key) || !(key.slice(9) in props)) { - res[key] = attrs[key]; - } - } - return res; - }; - var isElementRoot = (vnode) => { - return vnode.shapeFlag & (6 | 1) || vnode.type === Comment; - }; - function shouldUpdateComponent(prevVNode, nextVNode, optimized) { - const { props: prevProps, children: prevChildren, component } = prevVNode; - const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; - const emits = component.emitsOptions; - if ((prevChildren || nextChildren) && isHmrUpdating) { - return true; - } - if (nextVNode.dirs || nextVNode.transition) { - return true; - } - if (optimized && patchFlag >= 0) { - if (patchFlag & 1024) { - return true; - } - if (patchFlag & 16) { - if (!prevProps) { - return !!nextProps; - } - return hasPropsChanged(prevProps, nextProps, emits); - } else if (patchFlag & 8) { - const dynamicProps = nextVNode.dynamicProps; - for (let i = 0; i < dynamicProps.length; i++) { - const key = dynamicProps[i]; - if (hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emits, key)) { - return true; - } - } - } - } else { - if (prevChildren || nextChildren) { - if (!nextChildren || !nextChildren.$stable) { - return true; - } - } - if (prevProps === nextProps) { - return false; - } - if (!prevProps) { - return !!nextProps; - } - if (!nextProps) { - return true; - } - return hasPropsChanged(prevProps, nextProps, emits); - } - return false; - } - function hasPropsChanged(prevProps, nextProps, emitsOptions) { - const nextKeys = Object.keys(nextProps); - if (nextKeys.length !== Object.keys(prevProps).length) { - return true; - } - for (let i = 0; i < nextKeys.length; i++) { - const key = nextKeys[i]; - if (!shared.hasOwn(prevProps, key) || hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emitsOptions, key)) { - return true; - } - } - return false; - } - function hasPropValueChanged(nextProps, prevProps, key) { - const nextProp = nextProps[key]; - const prevProp = prevProps[key]; - if (key === "style" && shared.isObject(nextProp) && shared.isObject(prevProp)) { - return !shared.looseEqual(nextProp, prevProp); - } - return nextProp !== prevProp; - } - function updateHOCHostEl({ vnode, parent, suspense }, el) { - while (parent) { - const root = parent.subTree; - if (root.suspense && root.suspense.activeBranch === vnode) { - root.suspense.vnode.el = root.el = el; - vnode = root; - } - if (root === vnode) { - (vnode = parent.vnode).el = el; - parent = parent.parent; - } else { - break; - } - } - if (suspense && suspense.activeBranch === vnode) { - suspense.vnode.el = el; - } - } - var internalObjectProto = {}; - var createInternalObject = () => Object.create(internalObjectProto); - var isInternalObject = (obj) => Object.getPrototypeOf(obj) === internalObjectProto; - function initProps(instance, rawProps, isStateful, isSSR = false) { - const props = {}; - const attrs = createInternalObject(); - instance.propsDefaults = /* @__PURE__ */ Object.create(null); - setFullProps(instance, rawProps, props, attrs); - for (const key in instance.propsOptions[0]) { - if (!(key in props)) { - props[key] = void 0; - } - } - { - validateProps(rawProps || {}, props, instance); - } - if (isStateful) { - instance.props = isSSR ? props : reactivity.shallowReactive(props); - } else { - if (!instance.type.props) { - instance.props = attrs; - } else { - instance.props = props; - } - } - instance.attrs = attrs; - } - function isInHmrContext(instance) { - while (instance) { - if (instance.type.__hmrId) return true; - instance = instance.parent; - } - } - function updateProps(instance, rawProps, rawPrevProps, optimized) { - const { - props, - attrs, - vnode: { patchFlag } - } = instance; - const rawCurrentProps = reactivity.toRaw(props); - const [options] = instance.propsOptions; - let hasAttrsChanged = false; - if ( - // always force full diff in dev - // - #1942 if hmr is enabled with sfc component - // - vite#872 non-sfc component used by sfc component - !isInHmrContext(instance) && (optimized || patchFlag > 0) && !(patchFlag & 16) - ) { - if (patchFlag & 8) { - const propsToUpdate = instance.vnode.dynamicProps; - for (let i = 0; i < propsToUpdate.length; i++) { - let key = propsToUpdate[i]; - if (isEmitListener(instance.emitsOptions, key)) { - continue; - } - const value = rawProps[key]; - if (options) { - if (shared.hasOwn(attrs, key)) { - if (value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } else { - const camelizedKey = shared.camelize(key); - props[camelizedKey] = resolvePropValue( - options, - rawCurrentProps, - camelizedKey, - value, - instance, - false - ); - } - } else { - if (value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } - } - } - } else { - if (setFullProps(instance, rawProps, props, attrs)) { - hasAttrsChanged = true; - } - let kebabKey; - for (const key in rawCurrentProps) { - if (!rawProps || // for camelCase - !shared.hasOwn(rawProps, key) && // it's possible the original props was passed in as kebab-case - // and converted to camelCase (#955) - ((kebabKey = shared.hyphenate(key)) === key || !shared.hasOwn(rawProps, kebabKey))) { - if (options) { - if (rawPrevProps && // for camelCase - (rawPrevProps[key] !== void 0 || // for kebab-case - rawPrevProps[kebabKey] !== void 0)) { - props[key] = resolvePropValue( - options, - rawCurrentProps, - key, - void 0, - instance, - true - ); - } - } else { - delete props[key]; - } - } - } - if (attrs !== rawCurrentProps) { - for (const key in attrs) { - if (!rawProps || !shared.hasOwn(rawProps, key) && true) { - delete attrs[key]; - hasAttrsChanged = true; - } - } - } - } - if (hasAttrsChanged) { - reactivity.trigger(instance.attrs, "set", ""); - } - { - validateProps(rawProps || {}, props, instance); - } - } - function setFullProps(instance, rawProps, props, attrs) { - const [options, needCastKeys] = instance.propsOptions; - let hasAttrsChanged = false; - let rawCastValues; - if (rawProps) { - for (let key in rawProps) { - if (shared.isReservedProp(key)) { - continue; - } - const value = rawProps[key]; - let camelKey; - if (options && shared.hasOwn(options, camelKey = shared.camelize(key))) { - if (!needCastKeys || !needCastKeys.includes(camelKey)) { - props[camelKey] = value; - } else { - (rawCastValues || (rawCastValues = {}))[camelKey] = value; - } - } else if (!isEmitListener(instance.emitsOptions, key)) { - if (!(key in attrs) || value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } - } - } - if (needCastKeys) { - const rawCurrentProps = reactivity.toRaw(props); - const castValues = rawCastValues || shared.EMPTY_OBJ; - for (let i = 0; i < needCastKeys.length; i++) { - const key = needCastKeys[i]; - props[key] = resolvePropValue( - options, - rawCurrentProps, - key, - castValues[key], - instance, - !shared.hasOwn(castValues, key) - ); - } - } - return hasAttrsChanged; - } - function resolvePropValue(options, props, key, value, instance, isAbsent) { - const opt = options[key]; - if (opt != null) { - const hasDefault = shared.hasOwn(opt, "default"); - if (hasDefault && value === void 0) { - const defaultValue = opt.default; - if (opt.type !== Function && !opt.skipFactory && shared.isFunction(defaultValue)) { - const { propsDefaults } = instance; - if (key in propsDefaults) { - value = propsDefaults[key]; - } else { - const reset = setCurrentInstance(instance); - value = propsDefaults[key] = defaultValue.call( - null, - props - ); - reset(); - } - } else { - value = defaultValue; - } - if (instance.ce) { - instance.ce._setProp(key, value); - } - } - if (opt[ - 0 - /* shouldCast */ - ]) { - if (isAbsent && !hasDefault) { - value = false; - } else if (opt[ - 1 - /* shouldCastTrue */ - ] && (value === "" || value === shared.hyphenate(key))) { - value = true; - } - } - } - return value; - } - var mixinPropsCache = /* @__PURE__ */ new WeakMap(); - function normalizePropsOptions(comp, appContext, asMixin = false) { - const cache = asMixin ? mixinPropsCache : appContext.propsCache; - const cached = cache.get(comp); - if (cached) { - return cached; - } - const raw = comp.props; - const normalized = {}; - const needCastKeys = []; - let hasExtends = false; - if (!shared.isFunction(comp)) { - const extendProps = (raw2) => { - hasExtends = true; - const [props, keys] = normalizePropsOptions(raw2, appContext, true); - shared.extend(normalized, props); - if (keys) needCastKeys.push(...keys); - }; - if (!asMixin && appContext.mixins.length) { - appContext.mixins.forEach(extendProps); - } - if (comp.extends) { - extendProps(comp.extends); - } - if (comp.mixins) { - comp.mixins.forEach(extendProps); - } - } - if (!raw && !hasExtends) { - if (shared.isObject(comp)) { - cache.set(comp, shared.EMPTY_ARR); - } - return shared.EMPTY_ARR; - } - if (shared.isArray(raw)) { - for (let i = 0; i < raw.length; i++) { - if (!shared.isString(raw[i])) { - warn$1(`props must be strings when using array syntax.`, raw[i]); - } - const normalizedKey = shared.camelize(raw[i]); - if (validatePropName(normalizedKey)) { - normalized[normalizedKey] = shared.EMPTY_OBJ; - } - } - } else if (raw) { - if (!shared.isObject(raw)) { - warn$1(`invalid props options`, raw); - } - for (const key in raw) { - const normalizedKey = shared.camelize(key); - if (validatePropName(normalizedKey)) { - const opt = raw[key]; - const prop = normalized[normalizedKey] = shared.isArray(opt) || shared.isFunction(opt) ? { type: opt } : shared.extend({}, opt); - const propType = prop.type; - let shouldCast = false; - let shouldCastTrue = true; - if (shared.isArray(propType)) { - for (let index = 0; index < propType.length; ++index) { - const type = propType[index]; - const typeName = shared.isFunction(type) && type.name; - if (typeName === "Boolean") { - shouldCast = true; - break; - } else if (typeName === "String") { - shouldCastTrue = false; - } - } - } else { - shouldCast = shared.isFunction(propType) && propType.name === "Boolean"; - } - prop[ - 0 - /* shouldCast */ - ] = shouldCast; - prop[ - 1 - /* shouldCastTrue */ - ] = shouldCastTrue; - if (shouldCast || shared.hasOwn(prop, "default")) { - needCastKeys.push(normalizedKey); - } - } - } - } - const res = [normalized, needCastKeys]; - if (shared.isObject(comp)) { - cache.set(comp, res); - } - return res; - } - function validatePropName(key) { - if (key[0] !== "$" && !shared.isReservedProp(key)) { - return true; - } else { - warn$1(`Invalid prop name: "${key}" is a reserved property.`); - } - return false; - } - function getType2(ctor) { - if (ctor === null) { - return "null"; - } - if (typeof ctor === "function") { - return ctor.name || ""; - } else if (typeof ctor === "object") { - const name = ctor.constructor && ctor.constructor.name; - return name || ""; - } - return ""; - } - function validateProps(rawProps, props, instance) { - const resolvedValues = reactivity.toRaw(props); - const options = instance.propsOptions[0]; - const camelizePropsKey = Object.keys(rawProps).map((key) => shared.camelize(key)); - for (const key in options) { - let opt = options[key]; - if (opt == null) continue; - validateProp( - key, - resolvedValues[key], - opt, - reactivity.shallowReadonly(resolvedValues), - !camelizePropsKey.includes(key) - ); - } - } - function validateProp(name, value, prop, props, isAbsent) { - const { type, required, validator, skipCheck } = prop; - if (required && isAbsent) { - warn$1('Missing required prop: "' + name + '"'); - return; - } - if (value == null && !required) { - return; - } - if (type != null && type !== true && !skipCheck) { - let isValid = false; - const types = shared.isArray(type) ? type : [type]; - const expectedTypes = []; - for (let i = 0; i < types.length && !isValid; i++) { - const { valid, expectedType } = assertType(value, types[i]); - expectedTypes.push(expectedType || ""); - isValid = valid; - } - if (!isValid) { - warn$1(getInvalidTypeMessage(name, value, expectedTypes)); - return; - } - } - if (validator && !validator(value, props)) { - warn$1('Invalid prop: custom validator check failed for prop "' + name + '".'); - } - } - var isSimpleType = /* @__PURE__ */ shared.makeMap( - "String,Number,Boolean,Function,Symbol,BigInt" - ); - function assertType(value, type) { - let valid; - const expectedType = getType2(type); - if (expectedType === "null") { - valid = value === null; - } else if (isSimpleType(expectedType)) { - const t = typeof value; - valid = t === expectedType.toLowerCase(); - if (!valid && t === "object") { - valid = value instanceof type; - } - } else if (expectedType === "Object") { - valid = shared.isObject(value); - } else if (expectedType === "Array") { - valid = shared.isArray(value); - } else { - valid = value instanceof type; - } - return { - valid, - expectedType - }; - } - function getInvalidTypeMessage(name, value, expectedTypes) { - if (expectedTypes.length === 0) { - return `Prop type [] for prop "${name}" won't match anything. Did you mean to use type Array instead?`; - } - let message = `Invalid prop: type check failed for prop "${name}". Expected ${expectedTypes.map(shared.capitalize).join(" | ")}`; - const expectedType = expectedTypes[0]; - const receivedType = shared.toRawType(value); - const expectedValue = styleValue(value, expectedType); - const receivedValue = styleValue(value, receivedType); - if (expectedTypes.length === 1 && isExplicable(expectedType) && isCoercible(expectedType, receivedType)) { - message += ` with value ${expectedValue}`; - } - message += `, got ${receivedType} `; - if (isExplicable(receivedType)) { - message += `with value ${receivedValue}.`; - } - return message; - } - function styleValue(value, type) { - if (shared.isSymbol(value)) { - return value.toString(); - } else if (type === "String") { - return `"${value}"`; - } else if (type === "Number") { - return `${Number(value)}`; - } else { - return `${value}`; - } - } - function isExplicable(type) { - const explicitTypes = ["string", "number", "boolean"]; - return explicitTypes.some((elem) => type.toLowerCase() === elem); - } - function isCoercible(...args) { - return args.every((elem) => { - const value = elem.toLowerCase(); - return value !== "boolean" && value !== "symbol"; - }); - } - var isInternalKey = (key) => key === "_" || key === "_ctx" || key === "$stable"; - var normalizeSlotValue = (value) => shared.isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)]; - var normalizeSlot = (key, rawSlot, ctx) => { - if (rawSlot._n) { - return rawSlot; - } - const normalized = withCtx((...args) => { - if (currentInstance && !(ctx === null && currentRenderingInstance) && !(ctx && ctx.root !== currentInstance.root)) { - warn$1( - `Slot "${key}" invoked outside of the render function: this will not track dependencies used in the slot. Invoke the slot function inside the render function instead.` - ); - } - return normalizeSlotValue(rawSlot(...args)); - }, ctx); - normalized._c = false; - return normalized; - }; - var normalizeObjectSlots = (rawSlots, slots, instance) => { - const ctx = rawSlots._ctx; - for (const key in rawSlots) { - if (isInternalKey(key)) continue; - const value = rawSlots[key]; - if (shared.isFunction(value)) { - slots[key] = normalizeSlot(key, value, ctx); - } else if (value != null) { - { - warn$1( - `Non-function value encountered for slot "${key}". Prefer function slots for better performance.` - ); - } - const normalized = normalizeSlotValue(value); - slots[key] = () => normalized; - } - } - }; - var normalizeVNodeSlots = (instance, children) => { - if (!isKeepAlive(instance.vnode) && true) { - warn$1( - `Non-function value encountered for default slot. Prefer function slots for better performance.` - ); - } - const normalized = normalizeSlotValue(children); - instance.slots.default = () => normalized; - }; - var assignSlots = (slots, children, optimized) => { - for (const key in children) { - if (optimized || !isInternalKey(key)) { - slots[key] = children[key]; - } - } - }; - var initSlots = (instance, children, optimized) => { - const slots = instance.slots = createInternalObject(); - if (instance.vnode.shapeFlag & 32) { - const type = children._; - if (type) { - assignSlots(slots, children, optimized); - if (optimized) { - shared.def(slots, "_", type, true); - } - } else { - normalizeObjectSlots(children, slots); - } - } else if (children) { - normalizeVNodeSlots(instance, children); - } - }; - var updateSlots = (instance, children, optimized) => { - const { vnode, slots } = instance; - let needDeletionCheck = true; - let deletionComparisonTarget = shared.EMPTY_OBJ; - if (vnode.shapeFlag & 32) { - const type = children._; - if (type) { - if (isHmrUpdating) { - assignSlots(slots, children, optimized); - reactivity.trigger(instance, "set", "$slots"); - } else if (optimized && type === 1) { - needDeletionCheck = false; - } else { - assignSlots(slots, children, optimized); - } - } else { - needDeletionCheck = !children.$stable; - normalizeObjectSlots(children, slots); - } - deletionComparisonTarget = children; - } else if (children) { - normalizeVNodeSlots(instance, children); - deletionComparisonTarget = { default: 1 }; - } - if (needDeletionCheck) { - for (const key in slots) { - if (!isInternalKey(key) && deletionComparisonTarget[key] == null) { - delete slots[key]; - } - } - } - }; - var supported; - var perf; - function startMeasure(instance, type) { - if (instance.appContext.config.performance && isSupported()) { - perf.mark(`vue-${type}-${instance.uid}`); - } - { - devtoolsPerfStart(instance, type, isSupported() ? perf.now() : Date.now()); - } - } - function endMeasure(instance, type) { - if (instance.appContext.config.performance && isSupported()) { - const startTag = `vue-${type}-${instance.uid}`; - const endTag = startTag + `:end`; - const measureName = `<${formatComponentName(instance, instance.type)}> ${type}`; - perf.mark(endTag); - perf.measure(measureName, startTag, endTag); - perf.clearMeasures(measureName); - perf.clearMarks(startTag); - perf.clearMarks(endTag); - } - { - devtoolsPerfEnd(instance, type, isSupported() ? perf.now() : Date.now()); - } - } - function isSupported() { - if (supported !== void 0) { - return supported; - } - if (typeof window !== "undefined" && window.performance) { - supported = true; - perf = window.performance; - } else { - supported = false; - } - return supported; - } - var queuePostRenderEffect = queueEffectWithSuspense; - function createRenderer(options) { - return baseCreateRenderer(options); - } - function createHydrationRenderer(options) { - return baseCreateRenderer(options, createHydrationFunctions); - } - function baseCreateRenderer(options, createHydrationFns) { - const target = shared.getGlobalThis(); - target.__VUE__ = true; - { - setDevtoolsHook$1(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target); - } - const { - insert: hostInsert, - remove: hostRemove, - patchProp: hostPatchProp, - createElement: hostCreateElement, - createText: hostCreateText, - createComment: hostCreateComment, - setText: hostSetText, - setElementText: hostSetElementText, - parentNode: hostParentNode, - nextSibling: hostNextSibling, - setScopeId: hostSetScopeId = shared.NOOP, - insertStaticContent: hostInsertStaticContent - } = options; - const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = void 0, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => { - if (n1 === n2) { - return; - } - if (n1 && !isSameVNodeType(n1, n2)) { - anchor = getNextHostNode(n1); - unmount(n1, parentComponent, parentSuspense, true); - n1 = null; - } - if (n2.patchFlag === -2) { - optimized = false; - n2.dynamicChildren = null; - } - if (n2.dynamicChildren && n1 && n1.dynamicChildren && n1.dynamicChildren.hasOnce) { - if (n2.dynamicChildren === shared.EMPTY_ARR) { - n2.dynamicChildren = []; - } - n2.dynamicChildren.hasOnce = true; - } - const { type, ref: ref2, shapeFlag } = n2; - switch (type) { - case Text: - processText(n1, n2, container, anchor); - break; - case Comment: - processCommentNode(n1, n2, container, anchor); - break; - case Static: - if (n1 == null) { - mountStaticNode(n2, container, anchor, namespace); - } else { - patchStaticNode(n1, n2, container, namespace); - } - break; - case Fragment: - processFragment( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - break; - default: - if (shapeFlag & 1) { - processElement( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else if (shapeFlag & 6) { - processComponent( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else if (shapeFlag & 64) { - type.process( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - internals - ); - } else if (shapeFlag & 128) { - type.process( - n1, - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - internals - ); - } else { - warn$1("Invalid VNode type:", type, `(${typeof type})`); - } - } - if (ref2 != null && parentComponent) { - setRef(ref2, n1 && n1.ref, parentSuspense, n2 || n1, !n2); - } else if (ref2 == null && n1 && n1.ref != null) { - setRef(n1.ref, null, parentSuspense, n1, true); - } - }; - const processText = (n1, n2, container, anchor) => { - if (n1 == null) { - hostInsert( - n2.el = hostCreateText(n2.children), - container, - anchor - ); - } else { - const el = n2.el = n1.el; - if (n2.children !== n1.children) { - hostSetText(el, n2.children); - } - } - }; - const processCommentNode = (n1, n2, container, anchor) => { - if (n1 == null) { - hostInsert( - n2.el = hostCreateComment(n2.children || ""), - container, - anchor - ); - } else { - n2.el = n1.el; - } - }; - const mountStaticNode = (n2, container, anchor, namespace) => { - [n2.el, n2.anchor] = hostInsertStaticContent( - n2.children, - container, - anchor, - namespace, - n2.el, - n2.anchor - ); - }; - const patchStaticNode = (n1, n2, container, namespace) => { - if (n2.children !== n1.children) { - const anchor = hostNextSibling(n1.anchor); - removeStaticNode(n1); - [n2.el, n2.anchor] = hostInsertStaticContent( - n2.children, - container, - anchor, - namespace - ); - } else { - n2.el = n1.el; - n2.anchor = n1.anchor; - } - }; - const moveStaticNode = ({ el, anchor }, container, nextSibling) => { - let next; - while (el && el !== anchor) { - next = hostNextSibling(el); - hostInsert(el, container, nextSibling); - el = next; - } - hostInsert(anchor, container, nextSibling); - }; - const removeStaticNode = ({ el, anchor }) => { - let next; - while (el && el !== anchor) { - next = hostNextSibling(el); - hostRemove(el); - el = next; - } - hostRemove(anchor); - }; - const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - if (n2.type === "svg") { - namespace = "svg"; - } else if (n2.type === "math") { - namespace = "mathml"; - } - if (n1 == null) { - mountElement( - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - const customElement = n1.el && n1.el._isVueCE ? n1.el : null; - try { - if (customElement) { - customElement._beginPatch(); - } - patchElement( - n1, - n2, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } finally { - if (customElement) { - customElement._endPatch(); - } - } - } - }; - const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - let el; - let vnodeHook; - const { props, shapeFlag, transition, dirs } = vnode; - el = vnode.el = hostCreateElement( - vnode.type, - namespace, - props && props.is, - props - ); - if (shapeFlag & 8) { - hostSetElementText(el, vnode.children); - } else if (shapeFlag & 16) { - mountChildren( - vnode.children, - el, - null, - parentComponent, - parentSuspense, - resolveChildrenNamespace(vnode, namespace), - slotScopeIds, - optimized - ); - } - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "created"); - } - setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent); - if (props) { - for (const key in props) { - if (key !== "value" && !shared.isReservedProp(key)) { - hostPatchProp(el, key, null, props[key], namespace, parentComponent); - } - } - if ("value" in props) { - hostPatchProp(el, "value", null, props.value, namespace); - } - if (vnodeHook = props.onVnodeBeforeMount) { - invokeVNodeHook(vnodeHook, parentComponent, vnode); - } - } - { - shared.def(el, "__vnode", vnode, true); - shared.def(el, "__vueParentComponent", parentComponent, true); - } - if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "beforeMount"); - } - const needCallTransitionHooks = needTransition(parentSuspense, transition); - if (needCallTransitionHooks) { - transition.beforeEnter(el); - } - hostInsert(el, container, anchor); - if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) { - const isHmr = isHmrUpdating; - queuePostRenderEffect(() => { - let prev; - prev = setHmrUpdating(isHmr); - try { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); - needCallTransitionHooks && transition.enter(el); - dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted"); - } finally { - setHmrUpdating(prev); - } - }, parentSuspense); - } - }; - const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => { - if (scopeId) { - hostSetScopeId(el, scopeId); - } - if (slotScopeIds) { - for (let i = 0; i < slotScopeIds.length; i++) { - hostSetScopeId(el, slotScopeIds[i]); - } - } - if (parentComponent) { - let subTree = parentComponent.subTree; - if (subTree.patchFlag > 0 && subTree.patchFlag & 2048) { - subTree = filterSingleRoot(subTree.children) || subTree; - } - if (vnode === subTree || isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) { - const parentVNode = parentComponent.vnode; - setScopeId( - el, - parentVNode, - parentVNode.scopeId, - parentVNode.slotScopeIds, - parentComponent.parent - ); - } - } - }; - const mountChildren = (children, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, start = 0) => { - for (let i = start; i < children.length; i++) { - const child = children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]); - patch( - null, - child, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - }; - const patchElement = (n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - const el = n2.el = n1.el; - { - el.__vnode = n2; - } - let { patchFlag, dynamicChildren, dirs } = n2; - patchFlag |= n1.patchFlag & 16; - const oldProps = n1.props || shared.EMPTY_OBJ; - const newProps = n2.props || shared.EMPTY_OBJ; - let vnodeHook; - parentComponent && toggleRecurse(parentComponent, false); - if (vnodeHook = newProps.onVnodeBeforeUpdate) { - invokeVNodeHook(vnodeHook, parentComponent, n2, n1); - } - if (dirs) { - invokeDirectiveHook(n2, n1, parentComponent, "beforeUpdate"); - } - parentComponent && toggleRecurse(parentComponent, true); - if ( - // HMR updated, force full diff - isHmrUpdating || // #6385 the old vnode may be a user-wrapped non-isomorphic block - // Force full diff when block metadata is unstable. - dynamicChildren && (!n1.dynamicChildren || n1.dynamicChildren.length !== dynamicChildren.length) - ) { - patchFlag = 0; - optimized = false; - dynamicChildren = null; - } - if (oldProps.innerHTML && newProps.innerHTML == null || oldProps.textContent && newProps.textContent == null) { - hostSetElementText(el, ""); - } - if (dynamicChildren) { - patchBlockChildren( - n1.dynamicChildren, - dynamicChildren, - el, - parentComponent, - parentSuspense, - resolveChildrenNamespace(n2, namespace), - slotScopeIds - ); - { - traverseStaticChildren(n1, n2); - } - } else if (!optimized) { - patchChildren( - n1, - n2, - el, - null, - parentComponent, - parentSuspense, - resolveChildrenNamespace(n2, namespace), - slotScopeIds, - false - ); - } - if (patchFlag > 0) { - if (patchFlag & 16) { - patchProps(el, oldProps, newProps, parentComponent, namespace); - } else { - if (patchFlag & 2) { - if (oldProps.class !== newProps.class) { - hostPatchProp(el, "class", null, newProps.class, namespace); - } - } - if (patchFlag & 4) { - hostPatchProp(el, "style", oldProps.style, newProps.style, namespace); - } - if (patchFlag & 8) { - const propsToUpdate = n2.dynamicProps; - for (let i = 0; i < propsToUpdate.length; i++) { - const key = propsToUpdate[i]; - const prev = oldProps[key]; - const next = newProps[key]; - if (next !== prev || key === "value") { - hostPatchProp(el, key, prev, next, namespace, parentComponent); - } - } - } - } - if (patchFlag & 1) { - if (n1.children !== n2.children) { - hostSetElementText(el, n2.children); - } - } - } else if (!optimized && dynamicChildren == null) { - patchProps(el, oldProps, newProps, parentComponent, namespace); - } - if ((vnodeHook = newProps.onVnodeUpdated) || dirs) { - queuePostRenderEffect(() => { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1); - dirs && invokeDirectiveHook(n2, n1, parentComponent, "updated"); - }, parentSuspense); - } - }; - const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace, slotScopeIds) => { - for (let i = 0; i < newChildren.length; i++) { - const oldVNode = oldChildren[i]; - const newVNode = newChildren[i]; - const oldEl = oldVNode.el || resolveAsyncComponentPlaceholder(oldVNode); - const container = ( - // oldVNode may be an errored async setup() component inside Suspense - // which will not have a mounted element - oldEl && // - In the case of a Fragment, we need to provide the actual parent - // of the Fragment itself so it can move its children. - (oldVNode.type === Fragment || // - In the case of different nodes, there is going to be a replacement - // which also requires the correct parent container - !isSameVNodeType(oldVNode, newVNode) || // - In the case of a component, it could contain anything. - oldVNode.shapeFlag & (6 | 64 | 128)) ? hostParentNode(oldEl) : ( - // In other cases, the parent container is not actually used so we - // just pass the block element here to avoid a DOM parentNode call. - fallbackContainer - ) - ); - patch( - oldVNode, - newVNode, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - true - ); - } - }; - const patchProps = (el, oldProps, newProps, parentComponent, namespace) => { - if (oldProps !== newProps) { - if (oldProps !== shared.EMPTY_OBJ) { - for (const key in oldProps) { - if (!shared.isReservedProp(key) && !(key in newProps)) { - hostPatchProp( - el, - key, - oldProps[key], - null, - namespace, - parentComponent - ); - } - } - } - for (const key in newProps) { - if (shared.isReservedProp(key)) continue; - const next = newProps[key]; - const prev = oldProps[key]; - if (next !== prev && key !== "value") { - hostPatchProp(el, key, prev, next, namespace, parentComponent); - } - } - if ("value" in newProps) { - hostPatchProp(el, "value", oldProps.value, newProps.value, namespace); - } - } - }; - const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText(""); - const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText(""); - let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2; - if ( - // #5523 dev root fragment may inherit directives - isHmrUpdating || patchFlag & 2048 - ) { - patchFlag = 0; - optimized = false; - dynamicChildren = null; - } - if (fragmentSlotScopeIds) { - slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds; - } - if (n1 == null) { - hostInsert(fragmentStartAnchor, container, anchor); - hostInsert(fragmentEndAnchor, container, anchor); - mountChildren( - // #10007 - // such fragment like `<></>` will be compiled into - // a fragment which doesn't have a children. - // In this case fallback to an empty array - n2.children || [], - container, - fragmentEndAnchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && // #2715 the previous fragment could've been a BAILed one as a result - // of renderSlot() with no valid children - n1.dynamicChildren && n1.dynamicChildren.length === dynamicChildren.length) { - patchBlockChildren( - n1.dynamicChildren, - dynamicChildren, - container, - parentComponent, - parentSuspense, - namespace, - slotScopeIds - ); - { - traverseStaticChildren(n1, n2); - } - } else { - patchChildren( - n1, - n2, - container, - fragmentEndAnchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - } - }; - const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - n2.slotScopeIds = slotScopeIds; - if (n1 == null) { - if (n2.shapeFlag & 512) { - parentComponent.ctx.activate( - n2, - container, - anchor, - namespace, - optimized - ); - } else { - mountComponent( - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - optimized - ); - } - } else { - updateComponent(n1, n2, optimized); - } - }; - const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, namespace, optimized) => { - const instance = initialVNode.component = createComponentInstance( - initialVNode, - parentComponent, - parentSuspense - ); - if (instance.type.__hmrId) { - registerHMR(instance); - } - { - pushWarningContext(initialVNode); - startMeasure(instance, `mount`); - } - if (isKeepAlive(initialVNode)) { - instance.ctx.renderer = internals; - } - { - { - startMeasure(instance, `init`); - } - setupComponent(instance, false, optimized); - { - endMeasure(instance, `init`); - } - } - if (isHmrUpdating) initialVNode.el = null; - if (instance.asyncDep) { - parentSuspense && parentSuspense.registerDep( - instance, - setupRenderEffect, - optimized, - namespace - ); - if (!initialVNode.el) { - const placeholder = instance.subTree = createVNode(Comment); - processCommentNode(null, placeholder, container, anchor); - initialVNode.placeholder = placeholder.el; - } - } else { - setupRenderEffect( - instance, - initialVNode, - container, - anchor, - parentSuspense, - namespace, - optimized - ); - } - { - popWarningContext(); - endMeasure(instance, `mount`); - } - }; - const updateComponent = (n1, n2, optimized) => { - const instance = n2.component = n1.component; - if (shouldUpdateComponent(n1, n2, optimized)) { - if (instance.asyncDep && !instance.asyncResolved) { - { - pushWarningContext(n2); - } - n2.el = n1.el; - n2.placeholder = n1.placeholder; - updateComponentPreRender(instance, n2, optimized); - { - popWarningContext(); - } - return; - } else { - instance.next = n2; - instance.update(); - } - } else { - n2.el = n1.el; - n2.placeholder = n1.placeholder; - instance.vnode = n2; - } - }; - const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, namespace, optimized) => { - const componentUpdateFn = () => { - if (!instance.isMounted) { - let vnodeHook; - const { el, props } = initialVNode; - const { bm, m, parent, root, type } = instance; - const isAsyncWrapperVNode = isAsyncWrapper(initialVNode); - toggleRecurse(instance, false); - if (bm) { - shared.invokeArrayFns(bm); - } - if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) { - invokeVNodeHook(vnodeHook, parent, initialVNode); - } - toggleRecurse(instance, true); - if (el && hydrateNode) { - const hydrateSubTree = () => { - { - startMeasure(instance, `render`); - } - instance.subTree = renderComponentRoot(instance); - { - endMeasure(instance, `render`); - } - { - startMeasure(instance, `hydrate`); - } - hydrateNode( - el, - instance.subTree, - instance, - parentSuspense, - null - ); - { - endMeasure(instance, `hydrate`); - } - }; - if (isAsyncWrapperVNode && type.__asyncHydrate) { - type.__asyncHydrate( - el, - instance, - hydrateSubTree - ); - } else { - hydrateSubTree(); - } - } else { - if (root.ce && root.ce._hasShadowRoot()) { - root.ce._injectChildStyle( - type, - instance.parent ? instance.parent.type : void 0 - ); - } - { - startMeasure(instance, `render`); - } - const subTree = instance.subTree = renderComponentRoot(instance); - { - endMeasure(instance, `render`); - } - { - startMeasure(instance, `patch`); - } - patch( - null, - subTree, - container, - anchor, - instance, - parentSuspense, - namespace - ); - { - endMeasure(instance, `patch`); - } - initialVNode.el = subTree.el; - } - if (m) { - queuePostRenderEffect(m, parentSuspense); - } - if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) { - const scopedInitialVNode = initialVNode; - queuePostRenderEffect( - () => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), - parentSuspense - ); - } - if (initialVNode.shapeFlag & 256 || parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & 256) { - instance.a && queuePostRenderEffect(instance.a, parentSuspense); - } - instance.isMounted = true; - { - devtoolsComponentAdded(instance); - } - initialVNode = container = anchor = null; - } else { - let { next, bu, u, parent, vnode } = instance; - { - const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance); - if (nonHydratedAsyncRoot) { - if (next) { - next.el = vnode.el; - updateComponentPreRender(instance, next, optimized); - } - nonHydratedAsyncRoot.asyncDep.then(() => { - queuePostRenderEffect(() => { - if (!instance.isUnmounted) update(); - }, parentSuspense); - }); - return; - } - } - let originNext = next; - let vnodeHook; - { - pushWarningContext(next || instance.vnode); - } - toggleRecurse(instance, false); - if (next) { - next.el = vnode.el; - updateComponentPreRender(instance, next, optimized); - } else { - next = vnode; - } - if (bu) { - shared.invokeArrayFns(bu); - } - if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) { - invokeVNodeHook(vnodeHook, parent, next, vnode); - } - toggleRecurse(instance, true); - { - startMeasure(instance, `render`); - } - const nextTree = renderComponentRoot(instance); - { - endMeasure(instance, `render`); - } - const prevTree = instance.subTree; - instance.subTree = nextTree; - { - startMeasure(instance, `patch`); - } - patch( - prevTree, - nextTree, - // parent may have changed if it's in a teleport - hostParentNode(prevTree.el), - // anchor may have changed if it's in a fragment - getNextHostNode(prevTree), - instance, - parentSuspense, - namespace - ); - { - endMeasure(instance, `patch`); - } - next.el = nextTree.el; - if (originNext === null) { - updateHOCHostEl(instance, nextTree.el); - } - if (u) { - queuePostRenderEffect(u, parentSuspense); - } - if (vnodeHook = next.props && next.props.onVnodeUpdated) { - queuePostRenderEffect( - () => invokeVNodeHook(vnodeHook, parent, next, vnode), - parentSuspense - ); - } - { - devtoolsComponentUpdated(instance); - } - { - popWarningContext(); - } - } - }; - instance.scope.on(); - const effect = instance.effect = new reactivity.ReactiveEffect(componentUpdateFn); - instance.scope.off(); - const update = instance.update = effect.run.bind(effect); - const job = instance.job = effect.runIfDirty.bind(effect); - job.i = instance; - job.id = instance.uid; - effect.scheduler = () => queueJob(job); - toggleRecurse(instance, true); - { - effect.onTrack = instance.rtc ? (e) => shared.invokeArrayFns(instance.rtc, e) : void 0; - effect.onTrigger = instance.rtg ? (e) => shared.invokeArrayFns(instance.rtg, e) : void 0; - } - update(); - }; - const updateComponentPreRender = (instance, nextVNode, optimized) => { - nextVNode.component = instance; - const prevProps = instance.vnode.props; - instance.vnode = nextVNode; - instance.next = null; - updateProps(instance, nextVNode.props, prevProps, optimized); - updateSlots(instance, nextVNode.children, optimized); - reactivity.pauseTracking(); - flushPreFlushCbs(instance); - reactivity.resetTracking(); - }; - const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized = false) => { - const c1 = n1 && n1.children; - const prevShapeFlag = n1 ? n1.shapeFlag : 0; - const c2 = n2.children; - const { patchFlag, shapeFlag } = n2; - if (patchFlag > 0) { - if (patchFlag & 128) { - patchKeyedChildren( - c1, - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - return; - } else if (patchFlag & 256) { - patchUnkeyedChildren( - c1, - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - return; - } - } - if (shapeFlag & 8) { - if (prevShapeFlag & 16) { - unmountChildren(c1, parentComponent, parentSuspense); - } - if (c2 !== c1) { - hostSetElementText(container, c2); - } - } else { - if (prevShapeFlag & 16) { - if (shapeFlag & 16) { - patchKeyedChildren( - c1, - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - unmountChildren(c1, parentComponent, parentSuspense, true); - } - } else { - if (prevShapeFlag & 8) { - hostSetElementText(container, ""); - } - if (shapeFlag & 16) { - mountChildren( - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - } - } - }; - const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - c1 = c1 || shared.EMPTY_ARR; - c2 = c2 || shared.EMPTY_ARR; - const oldLength = c1.length; - const newLength = c2.length; - const commonLength = Math.min(oldLength, newLength); - let i; - for (i = 0; i < commonLength; i++) { - const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - patch( - c1[i], - nextChild, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } - if (oldLength > newLength) { - unmountChildren( - c1, - parentComponent, - parentSuspense, - true, - false, - commonLength - ); - } else { - mountChildren( - c2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - commonLength - ); - } - }; - const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - let i = 0; - const l2 = c2.length; - let e1 = c1.length - 1; - let e2 = l2 - 1; - while (i <= e1 && i <= e2) { - const n1 = c1[i]; - const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - if (isSameVNodeType(n1, n2)) { - patch( - n1, - n2, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - break; - } - i++; - } - while (i <= e1 && i <= e2) { - const n1 = c1[e1]; - const n2 = c2[e2] = optimized ? cloneIfMounted(c2[e2]) : normalizeVNode(c2[e2]); - if (isSameVNodeType(n1, n2)) { - patch( - n1, - n2, - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else { - break; - } - e1--; - e2--; - } - if (i > e1) { - if (i <= e2) { - const nextPos = e2 + 1; - const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor; - while (i <= e2) { - patch( - null, - c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]), - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - i++; - } - } - } else if (i > e2) { - while (i <= e1) { - unmount(c1[i], parentComponent, parentSuspense, true); - i++; - } - } else { - const s1 = i; - const s2 = i; - const keyToNewIndexMap = /* @__PURE__ */ new Map(); - for (i = s2; i <= e2; i++) { - const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - if (nextChild.key != null) { - if (keyToNewIndexMap.has(nextChild.key)) { - warn$1( - `Duplicate keys found during update:`, - JSON.stringify(nextChild.key), - `Make sure keys are unique.` - ); - } - keyToNewIndexMap.set(nextChild.key, i); - } - } - let j; - let patched = 0; - const toBePatched = e2 - s2 + 1; - let moved = false; - let maxNewIndexSoFar = 0; - const newIndexToOldIndexMap = new Array(toBePatched); - for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0; - for (i = s1; i <= e1; i++) { - const prevChild = c1[i]; - if (patched >= toBePatched) { - unmount(prevChild, parentComponent, parentSuspense, true); - continue; - } - let newIndex; - if (prevChild.key != null) { - newIndex = keyToNewIndexMap.get(prevChild.key); - } else { - for (j = s2; j <= e2; j++) { - if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j])) { - newIndex = j; - break; - } - } - } - if (newIndex === void 0) { - unmount(prevChild, parentComponent, parentSuspense, true); - } else { - newIndexToOldIndexMap[newIndex - s2] = i + 1; - if (newIndex >= maxNewIndexSoFar) { - maxNewIndexSoFar = newIndex; - } else { - moved = true; - } - patch( - prevChild, - c2[newIndex], - container, - null, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - patched++; - } - } - const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : shared.EMPTY_ARR; - j = increasingNewIndexSequence.length - 1; - for (i = toBePatched - 1; i >= 0; i--) { - const nextIndex = s2 + i; - const nextChild = c2[nextIndex]; - const anchorVNode = c2[nextIndex + 1]; - const anchor = nextIndex + 1 < l2 ? ( - // #13559, #14173 fallback to el placeholder for unresolved async component - anchorVNode.el || resolveAsyncComponentPlaceholder(anchorVNode) - ) : parentAnchor; - if (newIndexToOldIndexMap[i] === 0) { - patch( - null, - nextChild, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized - ); - } else if (moved) { - if (j < 0 || i !== increasingNewIndexSequence[j]) { - move(nextChild, container, anchor, 2); - } else { - j--; - } - } - } - } - }; - const move = (vnode, container, anchor, moveType, parentSuspense = null) => { - const { el, type, transition, children, shapeFlag } = vnode; - if (shapeFlag & 6) { - move(vnode.component.subTree, container, anchor, moveType); - return; - } - if (shapeFlag & 128) { - vnode.suspense.move(container, anchor, moveType); - return; - } - if (shapeFlag & 64) { - type.move(vnode, container, anchor, internals); - return; - } - if (type === Fragment) { - hostInsert(el, container, anchor); - for (let i = 0; i < children.length; i++) { - move(children[i], container, anchor, moveType); - } - hostInsert(vnode.anchor, container, anchor); - return; - } - if (type === Static) { - moveStaticNode(vnode, container, anchor); - return; - } - const needTransition2 = moveType !== 2 && shapeFlag & 1 && transition; - if (needTransition2) { - if (moveType === 0) { - if (transition.persisted && !el[leaveCbKey]) { - hostInsert(el, container, anchor); - } else { - transition.beforeEnter(el); - hostInsert(el, container, anchor); - queuePostRenderEffect(() => transition.enter(el), parentSuspense); - } - } else { - const { leave, delayLeave, afterLeave } = transition; - const remove22 = () => { - if (vnode.ctx.isUnmounted) { - hostRemove(el); - } else { - hostInsert(el, container, anchor); - } - }; - const performLeave = () => { - const wasLeaving = el._isLeaving || !!el[leaveCbKey]; - if (el._isLeaving) { - el[leaveCbKey]( - true - /* cancelled */ - ); - } - if (transition.persisted && !wasLeaving) { - remove22(); - } else { - leave(el, () => { - remove22(); - afterLeave && afterLeave(); - }); - } - }; - if (delayLeave) { - delayLeave(el, remove22, performLeave); - } else { - performLeave(); - } - } - } else { - hostInsert(el, container, anchor); - } - }; - const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => { - const { - type, - props, - ref: ref2, - children, - dynamicChildren, - shapeFlag, - patchFlag, - dirs, - cacheIndex, - memo - } = vnode; - if (patchFlag === -2 || dynamicChildren && dynamicChildren.hasOnce) { - optimized = false; - } - if (ref2 != null) { - reactivity.pauseTracking(); - setRef(ref2, null, parentSuspense, vnode, true); - reactivity.resetTracking(); - } - if (cacheIndex != null && (!vnode.ctx || vnode.ctx === parentComponent)) { - parentComponent.renderCache[cacheIndex] = void 0; - } - if (shapeFlag & 256) { - parentComponent.ctx.deactivate(vnode); - return; - } - const shouldInvokeDirs = shapeFlag & 1 && dirs; - const shouldInvokeVnodeHook = !isAsyncWrapper(vnode); - let vnodeHook; - if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) { - invokeVNodeHook(vnodeHook, parentComponent, vnode); - } - if (shapeFlag & 6) { - unmountComponent(vnode.component, parentSuspense, doRemove); - } else { - if (shapeFlag & 128) { - vnode.suspense.unmount(parentSuspense, doRemove); - return; - } - if (shouldInvokeDirs) { - invokeDirectiveHook(vnode, null, parentComponent, "beforeUnmount"); - } - if (shapeFlag & 64) { - vnode.type.remove( - vnode, - parentComponent, - parentSuspense, - internals, - doRemove - ); - } else if (dynamicChildren && // #5154 - // when v-once is used inside a block, setBlockTracking(-1) marks the - // parent block with hasOnce: true - // so that it doesn't take the fast path during unmount - otherwise - // components nested in v-once are never unmounted. - !dynamicChildren.hasOnce && // #1153: fast path should not be taken for non-stable (v-for) fragments - (type !== Fragment || patchFlag > 0 && patchFlag & 64)) { - unmountChildren( - dynamicChildren, - parentComponent, - parentSuspense, - false, - true - ); - } else if (type === Fragment && patchFlag & (128 | 256) || !optimized && shapeFlag & 16) { - unmountChildren(children, parentComponent, parentSuspense); - } - if (doRemove) { - remove2(vnode); - } - } - const shouldInvalidateMemo = memo != null && cacheIndex == null; - if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs || shouldInvalidateMemo) { - queuePostRenderEffect(() => { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); - shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, "unmounted"); - if (shouldInvalidateMemo) { - vnode.el = null; - } - }, parentSuspense); - } - }; - const remove2 = (vnode) => { - const { type, el, anchor, transition } = vnode; - const isFragment = type === Fragment; - if (isFragment && !transition) { - removeFragment(el, anchor); - return; - } - if (type === Static) { - removeStaticNode(vnode); - if (transition && !transition.persisted && transition.afterLeave) { - transition.afterLeave(); - } - return; - } - const leavingNode = isFragment ? getTransitionRoot(vnode) : vnode; - const performRemove = () => { - if (isFragment) { - if (hostParentNode(el)) { - removeFragment(el, anchor); - } - } else { - hostRemove(el); - } - if (transition && !transition.persisted && transition.afterLeave) { - transition.afterLeave(); - } - }; - if (leavingNode && leavingNode.shapeFlag & 1 && transition && !transition.persisted) { - const { leave, delayLeave } = transition; - const leavingEl = leavingNode.el; - const performLeave = () => leave(leavingEl, performRemove); - if (delayLeave) { - delayLeave(leavingEl, performRemove, performLeave); - } else { - performLeave(); - } - } else { - performRemove(); - } - }; - const removeFragment = (cur, end) => { - let next; - while (cur !== end) { - next = hostNextSibling(cur); - hostRemove(cur); - cur = next; - } - hostRemove(end); - }; - const unmountComponent = (instance, parentSuspense, doRemove) => { - if (instance.type.__hmrId) { - unregisterHMR(instance); - } - const { bum, scope, job, subTree, um, m, a } = instance; - invalidateMount(m); - invalidateMount(a); - if (bum) { - shared.invokeArrayFns(bum); - } - scope.stop(); - if (job) { - job.flags |= 8; - unmount(subTree, instance, parentSuspense, doRemove); - } else if (instance.vnode.el && subTree) { - subTree.transition = instance.vnode.transition; - unmount(subTree, instance, parentSuspense, doRemove); - } - if (um) { - queuePostRenderEffect(um, parentSuspense); - } - queuePostRenderEffect(() => { - instance.isUnmounted = true; - }, parentSuspense); - { - devtoolsComponentRemoved(instance); - } - }; - const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => { - for (let i = start; i < children.length; i++) { - unmount(children[i], parentComponent, parentSuspense, doRemove, optimized); - } - }; - const getNextHostNode = (vnode) => { - if (vnode.shapeFlag & 6) { - return getNextHostNode(vnode.component.subTree); - } - if (vnode.shapeFlag & 128) { - return vnode.suspense.next(); - } - const el = hostNextSibling(vnode.anchor || vnode.el); - const teleportEnd = el && el[TeleportEndKey]; - return teleportEnd ? hostNextSibling(teleportEnd) : el; - }; - const render = (vnode, container, namespace) => { - const minUid = vnode && container._vnode ? void 0 : vnode && vnode.component ? vnode.component.uid : getNextUid(); - flushOnAppMount(() => { - if (vnode == null) { - if (container._vnode) { - unmount(container._vnode, null, null, true); - } - } else { - patch( - container._vnode || null, - vnode, - container, - null, - null, - null, - namespace - ); - } - container._vnode = vnode; - }, minUid); - }; - const internals = { - p: patch, - um: unmount, - m: move, - r: remove2, - mt: mountComponent, - mc: mountChildren, - pc: patchChildren, - pbc: patchBlockChildren, - n: getNextHostNode, - o: options - }; - let hydrate; - let hydrateNode; - if (createHydrationFns) { - [hydrate, hydrateNode] = createHydrationFns( - internals - ); - } - return { - render, - hydrate, - createApp: createAppAPI(render, hydrate) - }; - } - function resolveChildrenNamespace({ type, props }, currentNamespace) { - return currentNamespace === "svg" && type === "foreignObject" || currentNamespace === "mathml" && type === "annotation-xml" && props && props.encoding && props.encoding.includes("html") ? void 0 : currentNamespace; - } - function toggleRecurse({ effect, job }, allowed) { - if (allowed) { - effect.flags |= 32; - job.flags |= 4; - } else { - effect.flags &= -33; - job.flags &= -5; - } - } - function needTransition(parentSuspense, transition) { - return (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted; - } - function traverseStaticChildren(n1, n2, shallow = false) { - const ch1 = n1.children; - const ch2 = n2.children; - if (shared.isArray(ch1) && shared.isArray(ch2)) { - for (let i = 0; i < ch1.length; i++) { - const c1 = ch1[i]; - let c2 = ch2[i]; - if (c2.shapeFlag & 1 && !c2.dynamicChildren) { - if (c2.patchFlag <= 0 || c2.patchFlag === 32) { - c2 = ch2[i] = cloneIfMounted(ch2[i]); - c2.el = c1.el; - } - if (!shallow && c2.patchFlag !== -2) - traverseStaticChildren(c1, c2); - } - if (c2.type === Text) { - if (c2.patchFlag === -1) { - c2 = ch2[i] = cloneIfMounted(c2); - } - c2.el = c1.el; - } - if (c2.type === Comment && !c2.el) { - c2.el = c1.el; - } - { - c2.el && (c2.el.__vnode = c2); - } - } - } - } - function getSequence(arr) { - const p = arr.slice(); - const result = [0]; - let i, j, u, v, c; - const len = arr.length; - for (i = 0; i < len; i++) { - const arrI = arr[i]; - if (arrI !== 0) { - j = result[result.length - 1]; - if (arr[j] < arrI) { - p[i] = j; - result.push(i); - continue; - } - u = 0; - v = result.length - 1; - while (u < v) { - c = u + v >> 1; - if (arr[result[c]] < arrI) { - u = c + 1; - } else { - v = c; - } - } - if (arrI < arr[result[u]]) { - if (u > 0) { - p[i] = result[u - 1]; - } - result[u] = i; - } - } - } - u = result.length; - v = result[u - 1]; - while (u-- > 0) { - result[u] = v; - v = p[v]; - } - return result; - } - function locateNonHydratedAsyncRoot(instance) { - const subComponent = instance.subTree.component; - if (subComponent) { - if (subComponent.asyncDep && !subComponent.asyncResolved) { - return subComponent; - } else { - return locateNonHydratedAsyncRoot(subComponent); - } - } - } - function invalidateMount(hooks) { - if (hooks) { - for (let i = 0; i < hooks.length; i++) - hooks[i].flags |= 8; - } - } - function resolveAsyncComponentPlaceholder(anchorVnode) { - if (anchorVnode.placeholder) { - return anchorVnode.placeholder; - } - const instance = anchorVnode.component; - if (instance) { - return resolveAsyncComponentPlaceholder(instance.subTree); - } - return null; - } - var isSuspense = (type) => type.__isSuspense; - var suspenseId = 0; - var SuspenseImpl = { - name: "Suspense", - // In order to make Suspense tree-shakable, we need to avoid importing it - // directly in the renderer. The renderer checks for the __isSuspense flag - // on a vnode's type and calls the `process` method, passing in renderer - // internals. - __isSuspense: true, - process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { - if (n1 == null) { - mountSuspense( - n2, - container, - anchor, - parentComponent, - parentSuspense, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - } else { - if (parentSuspense && parentSuspense.deps > 0 && !n1.suspense.isInFallback && !parentSuspense.isHydrating) { - n2.suspense = n1.suspense; - n2.suspense.vnode = n2; - n2.el = n1.el; - return; - } - patchSuspense( - n1, - n2, - container, - anchor, - parentComponent, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - } - }, - hydrate: hydrateSuspense, - normalize: normalizeSuspenseChildren - }; - var Suspense = SuspenseImpl; - function triggerEvent(vnode, name) { - const eventListener = vnode.props && vnode.props[name]; - if (shared.isFunction(eventListener)) { - eventListener(); - } - } - function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { - const { - p: patch, - o: { createElement } - } = rendererInternals; - const hiddenContainer = createElement("div"); - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - container, - hiddenContainer, - anchor, - namespace, - slotScopeIds, - optimized, - rendererInternals - ); - patch( - null, - suspense.pendingBranch = vnode.ssContent, - hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds - ); - if (suspense.deps > 0) { - triggerEvent(vnode, "onPending"); - triggerEvent(vnode, "onFallback"); - patch( - null, - vnode.ssFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds - ); - setActiveBranch(suspense, vnode.ssFallback); - } else { - suspense.resolve(false, true); - } - } - function patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) { - const suspense = n2.suspense = n1.suspense; - suspense.vnode = n2; - n2.el = n1.el; - const newBranch = n2.ssContent; - const newFallback = n2.ssFallback; - const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense; - if (pendingBranch) { - suspense.pendingBranch = newBranch; - if (isSameVNodeType(pendingBranch, newBranch)) { - suspense.deps++; - patch( - pendingBranch, - newBranch, - // a hydrating pending branch is adopted SSR DOM, already in place - isHydrating ? container : suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - suspense.deps--; - if (suspense.deps <= 0) { - suspense.resolve(); - } else if (isInFallback) { - if (!isHydrating && !suspense.isFallbackMountPending) { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } - } else { - suspense.pendingId = suspenseId++; - if (isHydrating) { - suspense.isHydrating = false; - suspense.activeBranch = pendingBranch; - } else { - unmount(pendingBranch, parentComponent, suspense); - } - suspense.deps = 0; - suspense.effects.length = 0; - suspense.hiddenContainer = createElement("div"); - if (isInFallback) { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else if (!suspense.isFallbackMountPending) { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } else if (activeBranch && isSameVNodeType(activeBranch, newBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - suspense.resolve(true); - } else { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } - } - } - } else { - if (activeBranch && isSameVNodeType(activeBranch, newBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newBranch); - } else { - triggerEvent(n2, "onPending"); - suspense.pendingBranch = newBranch; - if (newBranch.shapeFlag & 512) { - suspense.pendingId = newBranch.component.suspenseId; - } else { - suspense.pendingId = suspenseId++; - } - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - namespace, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else { - const { timeout, pendingId } = suspense; - if (timeout > 0) { - setTimeout(() => { - if (suspense.pendingId === pendingId) { - suspense.fallback(newFallback); - } - }, timeout); - } else if (timeout === 0) { - suspense.fallback(newFallback); - } - } - } - } - } - var hasWarned = false; - function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) { - if (!hasWarned) { - hasWarned = true; - console[console.info ? "info" : "log"]( - `<Suspense> is an experimental feature and its API will likely change.` - ); - } - const { - p: patch, - m: move, - um: unmount, - n: next, - o: { parentNode, remove: remove2 } - } = rendererInternals; - let parentSuspenseId; - const isSuspensible = isVNodeSuspensible(vnode); - if (isSuspensible) { - if (parentSuspense && parentSuspense.pendingBranch) { - parentSuspenseId = parentSuspense.pendingId; - parentSuspense.deps++; - } - } - const timeout = vnode.props ? shared.toNumber(vnode.props.timeout) : void 0; - { - assertNumber(timeout, `Suspense timeout`); - } - const initialAnchor = anchor; - const suspense = { - vnode, - parent: parentSuspense, - parentComponent, - namespace, - container, - hiddenContainer, - deps: 0, - pendingId: suspenseId++, - timeout: typeof timeout === "number" ? timeout : -1, - activeBranch: null, - isFallbackMountPending: false, - pendingBranch: null, - isInFallback: !isHydrating, - isHydrating, - isUnmounted: false, - effects: [], - resolve(resume = false, sync = false) { - { - if (!resume && !suspense.pendingBranch) { - throw new Error( - `suspense.resolve() is called without a pending branch.` - ); - } - if (suspense.isUnmounted) { - throw new Error( - `suspense.resolve() is called on an already unmounted suspense boundary.` - ); - } - } - const { - vnode: vnode2, - activeBranch, - pendingBranch, - pendingId, - effects, - parentComponent: parentComponent2, - container: container2, - isInFallback - } = suspense; - let delayEnter = false; - if (suspense.isHydrating) { - suspense.isHydrating = false; - } else if (!resume) { - delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in"; - let hasUpdatedAnchor = false; - if (delayEnter) { - activeBranch.transition.afterLeave = () => { - if (pendingId === suspense.pendingId) { - move( - pendingBranch, - container2, - anchor === initialAnchor && !hasUpdatedAnchor ? next(activeBranch) : anchor, - 0 - ); - queuePostFlushCb(effects); - if (isInFallback && vnode2.ssFallback) { - vnode2.ssFallback.el = null; - } - } - }; - } - if (activeBranch && !suspense.isFallbackMountPending) { - if (parentNode(activeBranch.el) === container2) { - anchor = next(activeBranch); - hasUpdatedAnchor = true; - } - unmount(activeBranch, parentComponent2, suspense, true); - if (!delayEnter && isInFallback && vnode2.ssFallback) { - queuePostRenderEffect(() => vnode2.ssFallback.el = null, suspense); - } - } - if (!delayEnter) { - move(pendingBranch, container2, anchor, 0); - } - } - suspense.isFallbackMountPending = false; - setActiveBranch(suspense, pendingBranch); - suspense.pendingBranch = null; - suspense.isInFallback = false; - let parent = suspense.parent; - let hasUnresolvedAncestor = false; - while (parent) { - if (parent.pendingBranch) { - for (let i = 0; i < effects.length; i++) { - parent.effects.push(effects[i]); - } - hasUnresolvedAncestor = true; - break; - } - parent = parent.parent; - } - if (!hasUnresolvedAncestor && !delayEnter) { - queuePostFlushCb(effects); - } - suspense.effects = []; - if (isSuspensible) { - if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) { - parentSuspenseId = void 0; - parentSuspense.deps--; - if (parentSuspense.deps === 0 && !sync) { - parentSuspense.resolve(); - } - } - } - triggerEvent(vnode2, "onResolve"); - }, - fallback(fallbackVNode) { - if (!suspense.pendingBranch) { - return; - } - const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense; - triggerEvent(vnode2, "onFallback"); - const anchor2 = next(activeBranch); - const mountFallback = () => { - suspense.isFallbackMountPending = false; - if (!suspense.isInFallback) { - return; - } - const latestFallback = suspense.vnode.ssFallback; - patch( - null, - latestFallback, - container2, - anchor2, - parentComponent2, - null, - // fallback tree will not have suspense context - namespace2, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, latestFallback); - }; - const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in"; - if (delayEnter) { - suspense.isFallbackMountPending = true; - activeBranch.transition.afterLeave = mountFallback; - } - suspense.isInFallback = true; - unmount( - activeBranch, - parentComponent2, - null, - // no suspense so unmount hooks fire now - true - // shouldRemove - ); - if (!delayEnter) { - mountFallback(); - } - }, - move(container2, anchor2, type) { - suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type); - suspense.container = container2; - }, - next() { - return suspense.activeBranch && next(suspense.activeBranch); - }, - // `namespace` intentionally shadows the boundary's own: the dep must be - // mounted with the namespace of the position it was rendered at, which can - // differ from the boundary's (e.g. a component nested inside an <svg>). - registerDep(instance, setupRenderEffect, optimized2, namespace2) { - const isInPendingSuspense = !!suspense.pendingBranch; - if (isInPendingSuspense) { - suspense.deps++; - } - const hydratedEl = instance.vnode.el; - instance.asyncDep.catch((err) => { - handleError(err, instance, 0); - }).then((asyncSetupResult) => { - if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { - return; - } - unsetCurrentInstance(); - if (!instance.scope.active) { - if (isInPendingSuspense && --suspense.deps === 0) { - suspense.resolve(); - } - return; - } - instance.asyncResolved = true; - const { vnode: vnode2 } = instance; - { - pushWarningContext(vnode2); - } - handleSetupResult(instance, asyncSetupResult, false); - if (hydratedEl) { - vnode2.el = hydratedEl; - } - const placeholder = !hydratedEl && instance.subTree.el; - setupRenderEffect( - instance, - vnode2, - // component may have been moved before resolve. - // if this is not a hydration, instance.subTree will be the comment - // placeholder. - parentNode(hydratedEl || instance.subTree.el), - // anchor will not be used if this is hydration, so only need to - // consider the comment placeholder case. - hydratedEl ? null : next(instance.subTree), - suspense, - namespace2, - optimized2 - ); - if (placeholder) { - vnode2.placeholder = null; - remove2(placeholder); - } - updateHOCHostEl(instance, vnode2.el); - { - popWarningContext(); - } - if (isInPendingSuspense && --suspense.deps === 0) { - suspense.resolve(); - } - }); - }, - unmount(parentSuspense2, doRemove) { - suspense.isUnmounted = true; - if (suspense.activeBranch) { - unmount( - suspense.activeBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - if (suspense.pendingBranch) { - unmount( - suspense.pendingBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - } - }; - return suspense; - } - function hydrateSuspense(node, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) { - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - node.parentNode, - // eslint-disable-next-line no-restricted-globals - document.createElement("div"), - null, - namespace, - slotScopeIds, - optimized, - rendererInternals, - true - ); - const result = hydrateNode( - node, - suspense.pendingBranch = vnode.ssContent, - parentComponent, - suspense, - slotScopeIds, - optimized - ); - if (suspense.deps === 0) { - suspense.resolve(false, true); - } - return result; - } - function normalizeSuspenseChildren(vnode) { - const { shapeFlag, children } = vnode; - const isSlotChildren = shapeFlag & 32; - vnode.ssContent = normalizeSuspenseSlot( - isSlotChildren ? children.default : children - ); - vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment); - } - function normalizeSuspenseSlot(s) { - let block; - if (shared.isFunction(s)) { - const trackBlock = isBlockTreeEnabled && s._c; - if (trackBlock) { - s._d = false; - openBlock(); - } - s = s(); - if (trackBlock) { - s._d = true; - block = currentBlock; - closeBlock(); - } - } - if (shared.isArray(s)) { - const singleChild = filterSingleRoot(s); - if (!singleChild && s.filter((child) => child !== NULL_DYNAMIC_COMPONENT).length > 0) { - warn$1(`<Suspense> slots expect a single root node.`); - } - s = singleChild; - } - s = normalizeVNode(s); - if (block && !s.dynamicChildren) { - s.dynamicChildren = block.filter((c) => c !== s); - } - return s; - } - function queueEffectWithSuspense(fn, suspense) { - if (suspense && suspense.pendingBranch) { - if (shared.isArray(fn)) { - suspense.effects.push(...fn); - } else { - suspense.effects.push(fn); - } - } else { - queuePostFlushCb(fn); - } - } - function setActiveBranch(suspense, branch) { - suspense.activeBranch = branch; - const { vnode, parentComponent } = suspense; - let el = branch.el; - while (!el && branch.component) { - branch = branch.component.subTree; - el = branch.el; - } - vnode.el = el; - if (parentComponent && parentComponent.subTree === vnode) { - parentComponent.vnode.el = el; - updateHOCHostEl(parentComponent, el); - } - } - function isVNodeSuspensible(vnode) { - const suspensible = vnode.props && vnode.props.suspensible; - return suspensible != null && suspensible !== false; - } - var Fragment = /* @__PURE__ */ Symbol.for("v-fgt"); - var Text = /* @__PURE__ */ Symbol.for("v-txt"); - var Comment = /* @__PURE__ */ Symbol.for("v-cmt"); - var Static = /* @__PURE__ */ Symbol.for("v-stc"); - var blockStack = []; - var currentBlock = null; - function openBlock(disableTracking = false) { - blockStack.push(currentBlock = disableTracking ? null : []); - } - function closeBlock() { - blockStack.pop(); - currentBlock = blockStack[blockStack.length - 1] || null; - } - var isBlockTreeEnabled = 1; - function setBlockTracking(value, inVOnce = false) { - isBlockTreeEnabled += value; - if (value < 0 && currentBlock && inVOnce) { - currentBlock.hasOnce = true; - } - } - function setupBlock(vnode) { - vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || shared.EMPTY_ARR : null; - closeBlock(); - if (isBlockTreeEnabled > 0 && currentBlock) { - currentBlock.push(vnode); - } - return vnode; - } - function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) { - return setupBlock( - createBaseVNode( - type, - props, - children, - patchFlag, - dynamicProps, - shapeFlag, - true - ) - ); - } - function createBlock(type, props, children, patchFlag, dynamicProps) { - return setupBlock( - createVNode( - type, - props, - children, - patchFlag, - dynamicProps, - true - ) - ); - } - function isVNode(value) { - return value ? value.__v_isVNode === true : false; - } - function isSameVNodeType(n1, n2) { - if (n2.shapeFlag & 6 && n1.component) { - const dirtyInstances = hmrDirtyComponents.get(n2.type); - if (dirtyInstances && dirtyInstances.has(n1.component)) { - n1.shapeFlag &= -257; - n2.shapeFlag &= -513; - return false; - } - } - return n1.type === n2.type && n1.key === n2.key; - } - var vnodeArgsTransformer; - function transformVNodeArgs(transformer) { - vnodeArgsTransformer = transformer; - } - var createVNodeWithArgsTransform = (...args) => { - return _createVNode( - ...vnodeArgsTransformer ? vnodeArgsTransformer(args, currentRenderingInstance) : args - ); - }; - var normalizeKey = ({ key }) => key != null ? key : null; - var normalizeRef = ({ - ref: ref2, - ref_key, - ref_for - }) => { - if (typeof ref2 === "number") { - ref2 = "" + ref2; - } - return ref2 != null ? shared.isString(ref2) || reactivity.isRef(ref2) || shared.isFunction(ref2) ? { i: currentRenderingInstance, r: ref2, k: ref_key, f: !!ref_for } : ref2 : null; - }; - function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1, isBlockNode = false, needFullChildrenNormalization = false) { - const vnode = { - __v_isVNode: true, - __v_skip: true, - type, - props, - key: props && normalizeKey(props), - ref: props && normalizeRef(props), - scopeId: currentScopeId, - slotScopeIds: null, - children, - component: null, - suspense: null, - ssContent: null, - ssFallback: null, - dirs: null, - transition: null, - el: null, - anchor: null, - target: null, - targetStart: null, - targetAnchor: null, - staticCount: 0, - shapeFlag, - patchFlag, - dynamicProps, - dynamicChildren: null, - appContext: null, - ctx: currentRenderingInstance - }; - if (needFullChildrenNormalization) { - normalizeChildren(vnode, children); - if (shapeFlag & 128) { - type.normalize(vnode); - } - } else if (children) { - vnode.shapeFlag |= shared.isString(children) ? 8 : 16; - } - if (vnode.key !== vnode.key) { - warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type); - } - if (props && vnode.shapeFlag & 1) { - const overwritingProp = props.innerHTML != null ? "innerHTML" : props.textContent != null ? "textContent" : null; - if (overwritingProp && hasContentChildren(vnode.children)) { - warn$1( - `The \`${overwritingProp}\` prop on <${vnode.type}> will override its children. Remove either the \`${overwritingProp}\` prop or the children.` - ); - } - } - if (isBlockTreeEnabled > 0 && // avoid a block node from tracking itself - !isBlockNode && // has current parent block - currentBlock && // presence of a patch flag indicates this node needs patching on updates. - // component nodes also should always be patched, because even if the - // component doesn't need to update, it needs to persist the instance on to - // the next vnode so that it can be properly unmounted later. - (vnode.patchFlag > 0 || shapeFlag & 6) && // the EVENTS flag is only for hydration and if it is the only flag, the - // vnode should not be considered dynamic due to handler caching. - vnode.patchFlag !== 32) { - currentBlock.push(vnode); - } - return vnode; - } - function hasContentChildren(children) { - if (shared.isString(children)) return children !== ""; - if (shared.isArray(children)) return children.length > 0; - return false; - } - var createVNode = createVNodeWithArgsTransform; - function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) { - if (!type || type === NULL_DYNAMIC_COMPONENT) { - if (!type) { - warn$1(`Invalid vnode type when creating vnode: ${type}.`); - } - type = Comment; - } - if (isVNode(type)) { - const cloned = cloneVNode( - type, - props, - true - /* mergeRef: true */ - ); - if (children) { - normalizeChildren(cloned, children); - } - if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) { - if (cloned.shapeFlag & 6) { - currentBlock[currentBlock.indexOf(type)] = cloned; - } else { - currentBlock.push(cloned); - } - } - cloned.patchFlag = -2; - return cloned; - } - if (isClassComponent(type)) { - type = type.__vccOpts; - } - if (props) { - props = guardReactiveProps(props); - let { class: klass, style } = props; - if (klass && !shared.isString(klass)) { - props.class = shared.normalizeClass(klass); - } - if (shared.isObject(style)) { - if (reactivity.isProxy(style) && !shared.isArray(style)) { - style = shared.extend({}, style); - } - props.style = shared.normalizeStyle(style); - } - } - const shapeFlag = shared.isString(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : shared.isObject(type) ? 4 : shared.isFunction(type) ? 2 : 0; - if (shapeFlag & 4 && reactivity.isProxy(type)) { - type = reactivity.toRaw(type); - warn$1( - `Vue received a Component that was made a reactive object. This can lead to unnecessary performance overhead and should be avoided by marking the component with \`markRaw\` or using \`shallowRef\` instead of \`ref\`.`, - ` -Component that was made reactive: `, - type - ); - } - return createBaseVNode( - type, - props, - children, - patchFlag, - dynamicProps, - shapeFlag, - isBlockNode, - true - ); - } - function guardReactiveProps(props) { - if (!props) return null; - return reactivity.isProxy(props) || isInternalObject(props) ? shared.extend({}, props) : props; - } - function cloneVNode(vnode, extraProps, mergeRef = false, cloneTransition = false) { - const { props, ref: ref2, patchFlag, children, transition } = vnode; - const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props; - const cloned = { - __v_isVNode: true, - __v_skip: true, - type: vnode.type, - props: mergedProps, - key: mergedProps && normalizeKey(mergedProps), - ref: extraProps && extraProps.ref ? ( - // #2078 in the case of <component :is="vnode" ref="extra"/> - // if the vnode itself already has a ref, cloneVNode will need to merge - // the refs so the single vnode can be set on multiple refs - mergeRef && ref2 ? shared.isArray(ref2) ? ref2.concat(normalizeRef(extraProps)) : [ref2, normalizeRef(extraProps)] : normalizeRef(extraProps) - ) : ref2, - scopeId: vnode.scopeId, - slotScopeIds: vnode.slotScopeIds, - children: patchFlag === -1 && shared.isArray(children) ? children.map(deepCloneVNode) : children, - target: vnode.target, - targetStart: vnode.targetStart, - targetAnchor: vnode.targetAnchor, - staticCount: vnode.staticCount, - shapeFlag: vnode.shapeFlag, - // if the vnode is cloned with extra props, we can no longer assume its - // existing patch flag to be reliable and need to add the FULL_PROPS flag. - // note: preserve flag for fragments since they use the flag for children - // fast paths only. - patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag, - dynamicProps: vnode.dynamicProps, - dynamicChildren: vnode.dynamicChildren, - appContext: vnode.appContext, - dirs: vnode.dirs, - transition, - // These should technically only be non-null on mounted VNodes. However, - // they *should* be copied for kept-alive vnodes. So we just always copy - // them since them being non-null during a mount doesn't affect the logic as - // they will simply be overwritten. - component: vnode.component, - suspense: vnode.suspense, - ssContent: vnode.ssContent && cloneVNode(vnode.ssContent), - ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback), - placeholder: vnode.placeholder, - el: vnode.el, - anchor: vnode.anchor, - ctx: vnode.ctx, - ce: vnode.ce, - cacheIndex: vnode.cacheIndex - }; - if (transition && cloneTransition) { - setTransitionHooks( - cloned, - transition.clone(cloned) - ); - } - return cloned; - } - function deepCloneVNode(vnode) { - const cloned = cloneVNode(vnode); - if (shared.isArray(vnode.children)) { - cloned.children = vnode.children.map(deepCloneVNode); - } - return cloned; - } - function createTextVNode(text = " ", flag = 0) { - return createVNode(Text, null, text, flag); - } - function createStaticVNode(content, numberOfNodes) { - const vnode = createVNode(Static, null, content); - vnode.staticCount = numberOfNodes; - return vnode; - } - function createCommentVNode(text = "", asBlock = false) { - return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text); - } - function normalizeVNode(child) { - if (child == null || typeof child === "boolean") { - return createVNode(Comment); - } else if (shared.isArray(child)) { - return createVNode( - Fragment, - null, - // #3666, avoid reference pollution when reusing vnode - child.slice() - ); - } else if (isVNode(child)) { - return cloneIfMounted(child); - } else { - return createVNode(Text, null, String(child)); - } - } - function cloneIfMounted(child) { - return child.el === null && child.patchFlag !== -1 || child.memo ? child : cloneVNode(child); - } - function normalizeChildren(vnode, children) { - let type = 0; - const { shapeFlag } = vnode; - if (children == null) { - children = null; - } else if (shared.isArray(children)) { - type = 16; - } else if (typeof children === "object") { - if (shapeFlag & (1 | 64)) { - const slot = children.default; - if (slot) { - slot._c && (slot._d = false); - normalizeChildren(vnode, slot()); - slot._c && (slot._d = true); - } - return; - } else { - type = 32; - const slotFlag = children._; - if (!slotFlag && !isInternalObject(children)) { - children._ctx = currentRenderingInstance; - } else if (slotFlag === 3 && currentRenderingInstance) { - if (currentRenderingInstance.slots._ === 1) { - children._ = 1; - } else { - children._ = 2; - vnode.patchFlag |= 1024; - } - } - } - } else if (shared.isFunction(children)) { - if (shapeFlag & (1 | 64)) { - normalizeChildren(vnode, { default: children }); - return; - } - children = { default: children, _ctx: currentRenderingInstance }; - type = 32; - } else { - children = String(children); - if (shapeFlag & 64) { - type = 16; - children = [createTextVNode(children)]; - } else { - type = 8; - } - } - vnode.children = children; - vnode.shapeFlag |= type; - } - function mergeProps(...args) { - const ret = {}; - for (let i = 0; i < args.length; i++) { - const toMerge = args[i]; - for (const key in toMerge) { - if (key === "class") { - if (ret.class !== toMerge.class) { - ret.class = shared.normalizeClass([ret.class, toMerge.class]); - } - } else if (key === "style") { - ret.style = shared.normalizeStyle([ret.style, toMerge.style]); - } else if (shared.isOn(key)) { - const existing = ret[key]; - const incoming = toMerge[key]; - if (incoming && existing !== incoming && !(shared.isArray(existing) && existing.includes(incoming))) { - ret[key] = existing ? [].concat(existing, incoming) : incoming; - } else if (incoming == null && existing == null && // mergeProps({ 'onUpdate:modelValue': undefined }) should not retain - // the model listener. - !shared.isModelListener(key)) { - ret[key] = incoming; - } - } else if (key !== "") { - ret[key] = toMerge[key]; - } - } - } - return ret; - } - function invokeVNodeHook(hook, instance, vnode, prevVNode = null) { - callWithAsyncErrorHandling(hook, instance, 7, [ - vnode, - prevVNode - ]); - } - var emptyAppContext = createAppContext(); - var uid = 0; - function getNextUid() { - return uid; - } - function createComponentInstance(vnode, parent, suspense) { - const type = vnode.type; - const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext; - const instance = { - uid: uid++, - vnode, - type, - parent, - appContext, - root: null, - // to be immediately set - next: null, - subTree: null, - // will be set synchronously right after creation - effect: null, - update: null, - // will be set synchronously right after creation - job: null, - scope: new reactivity.EffectScope( - true - /* detached */ - ), - render: null, - proxy: null, - exposed: null, - exposeProxy: null, - withProxy: null, - provides: parent ? parent.provides : Object.create(appContext.provides), - ids: parent ? parent.ids : ["", 0, 0], - accessCache: null, - renderCache: [], - // local resolved assets - components: null, - directives: null, - // resolved props and emits options - propsOptions: normalizePropsOptions(type, appContext), - emitsOptions: normalizeEmitsOptions(type, appContext), - // emit - emit: null, - // to be set immediately - emitted: null, - // props default value - propsDefaults: shared.EMPTY_OBJ, - // inheritAttrs - inheritAttrs: type.inheritAttrs, - // state - ctx: shared.EMPTY_OBJ, - data: shared.EMPTY_OBJ, - props: shared.EMPTY_OBJ, - attrs: shared.EMPTY_OBJ, - slots: shared.EMPTY_OBJ, - refs: shared.EMPTY_OBJ, - setupState: shared.EMPTY_OBJ, - setupContext: null, - // suspense related - suspense, - suspenseId: suspense ? suspense.pendingId : 0, - asyncDep: null, - asyncResolved: false, - // lifecycle hooks - // not using enums here because it results in computed properties - isMounted: false, - isUnmounted: false, - isDeactivated: false, - bc: null, - c: null, - bm: null, - m: null, - bu: null, - u: null, - um: null, - bum: null, - da: null, - a: null, - rtg: null, - rtc: null, - ec: null, - sp: null - }; - { - instance.ctx = createDevRenderContext(instance); - } - instance.root = parent ? parent.root : instance; - instance.emit = emit.bind(null, instance); - if (vnode.ce) { - vnode.ce(instance); - } - return instance; - } - var currentInstance = null; - var getCurrentInstance = () => currentInstance || currentRenderingInstance; - var internalSetCurrentInstance; - var setInSSRSetupState; - { - const g = shared.getGlobalThis(); - const registerGlobalSetter = (key, setter) => { - let setters; - if (!(setters = g[key])) setters = g[key] = []; - setters.push(setter); - return (v) => { - if (setters.length > 1) setters.forEach((set) => set(v)); - else setters[0](v); - }; - }; - internalSetCurrentInstance = registerGlobalSetter( - `__VUE_INSTANCE_SETTERS__`, - (v) => currentInstance = v - ); - setInSSRSetupState = registerGlobalSetter( - `__VUE_SSR_SETTERS__`, - (v) => isInSSRComponentSetup = v - ); - } - var setCurrentInstance = (instance) => { - const prev = currentInstance; - internalSetCurrentInstance(instance); - instance.scope.on(); - return () => { - instance.scope.off(); - internalSetCurrentInstance(prev); - }; - }; - var unsetCurrentInstance = () => { - currentInstance && currentInstance.scope.off(); - internalSetCurrentInstance(null); - }; - var isBuiltInTag = /* @__PURE__ */ shared.makeMap("slot,component"); - function validateComponentName(name, { isNativeTag }) { - if (isBuiltInTag(name) || isNativeTag(name)) { - warn$1( - "Do not use built-in or reserved HTML elements as component id: " + name - ); - } - } - function isStatefulComponent(instance) { - return instance.vnode.shapeFlag & 4; - } - var isInSSRComponentSetup = false; - function setupComponent(instance, isSSR = false, optimized = false) { - isSSR && setInSSRSetupState(isSSR); - const { props, children } = instance.vnode; - const isStateful = isStatefulComponent(instance); - initProps(instance, props, isStateful, isSSR); - initSlots(instance, children, optimized || isSSR); - const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0; - isSSR && setInSSRSetupState(false); - return setupResult; - } - function setupStatefulComponent(instance, isSSR) { - const Component = instance.type; - { - if (Component.name) { - validateComponentName(Component.name, instance.appContext.config); - } - if (Component.components) { - const names = Object.keys(Component.components); - for (let i = 0; i < names.length; i++) { - validateComponentName(names[i], instance.appContext.config); - } - } - if (Component.directives) { - const names = Object.keys(Component.directives); - for (let i = 0; i < names.length; i++) { - validateDirectiveName(names[i]); - } - } - if (Component.compilerOptions && isRuntimeOnly()) { - warn$1( - `"compilerOptions" is only supported when using a build of Vue that includes the runtime compiler. Since you are using a runtime-only build, the options should be passed via your build tool config instead.` - ); - } - } - instance.accessCache = /* @__PURE__ */ Object.create(null); - instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers); - { - exposePropsOnRenderContext(instance); - } - const { setup } = Component; - if (setup) { - reactivity.pauseTracking(); - const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null; - const reset = setCurrentInstance(instance); - const setupResult = callWithErrorHandling( - setup, - instance, - 0, - [ - reactivity.shallowReadonly(instance.props), - setupContext - ] - ); - const isAsyncSetup = shared.isPromise(setupResult); - reactivity.resetTracking(); - reset(); - if ((isAsyncSetup || instance.sp) && !isAsyncWrapper(instance)) { - markAsyncBoundary(instance); - } - if (isAsyncSetup) { - setupResult.then(unsetCurrentInstance, unsetCurrentInstance); - if (isSSR) { - return setupResult.then((resolvedResult) => { - setInSSRSetupState(true); - try { - handleSetupResult(instance, resolvedResult, isSSR); - } finally { - setInSSRSetupState(false); - } - }).catch((e) => { - handleError(e, instance, 0); - }); - } else { - instance.asyncDep = setupResult; - if (!instance.suspense) { - const name = formatComponentName(instance, Component); - warn$1( - `Component <${name}>: setup function returned a promise, but no <Suspense> boundary was found in the parent component tree. A component with async setup() must be nested in a <Suspense> in order to be rendered.` - ); - } - } - } else { - handleSetupResult(instance, setupResult, isSSR); - } - } else { - finishComponentSetup(instance, isSSR); - } - } - function handleSetupResult(instance, setupResult, isSSR) { - if (shared.isFunction(setupResult)) { - if (instance.type.__ssrInlineRender) { - instance.ssrRender = setupResult; - } else { - instance.render = setupResult; - } - } else if (shared.isObject(setupResult)) { - if (isVNode(setupResult)) { - warn$1( - `setup() should not return VNodes directly - return a render function instead.` - ); - } - { - instance.devtoolsRawSetupState = setupResult; - } - instance.setupState = reactivity.proxyRefs(setupResult); - { - exposeSetupStateOnRenderContext(instance); - } - } else if (setupResult !== void 0) { - warn$1( - `setup() should return an object. Received: ${setupResult === null ? "null" : typeof setupResult}` - ); - } - finishComponentSetup(instance, isSSR); - } - var compile; - var installWithProxy; - function registerRuntimeCompiler(_compile) { - compile = _compile; - installWithProxy = (i) => { - if (i.render._rc) { - i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers); - } - }; - } - var isRuntimeOnly = () => !compile; - function finishComponentSetup(instance, isSSR, skipOptions) { - const Component = instance.type; - if (!instance.render) { - if (!isSSR && compile && !Component.render) { - const template = Component.template || resolveMergedOptions(instance).template; - if (template) { - { - startMeasure(instance, `compile`); - } - const { isCustomElement, compilerOptions } = instance.appContext.config; - const { delimiters, compilerOptions: componentCompilerOptions } = Component; - const finalCompilerOptions = shared.extend( - shared.extend( - { - isCustomElement, - delimiters - }, - compilerOptions - ), - componentCompilerOptions - ); - Component.render = compile(template, finalCompilerOptions); - { - endMeasure(instance, `compile`); - } - } - } - instance.render = Component.render || shared.NOOP; - if (installWithProxy) { - installWithProxy(instance); - } - } - { - const reset = setCurrentInstance(instance); - reactivity.pauseTracking(); - try { - applyOptions(instance); - } finally { - reactivity.resetTracking(); - reset(); - } - } - if (!Component.render && instance.render === shared.NOOP && !isSSR) { - if (!compile && Component.template) { - warn$1( - `Component provided template option but runtime compilation is not supported in this build of Vue.` - ); - } else { - warn$1(`Component is missing template or render function: `, Component); - } - } - } - var attrsProxyHandlers = { - get(target, key) { - markAttrsAccessed(); - reactivity.track(target, "get", ""); - return target[key]; - }, - set() { - warn$1(`setupContext.attrs is readonly.`); - return false; - }, - deleteProperty() { - warn$1(`setupContext.attrs is readonly.`); - return false; - } - }; - function getSlotsProxy(instance) { - return new Proxy(instance.slots, { - get(target, key) { - reactivity.track(instance, "get", "$slots"); - return target[key]; - } - }); - } - function createSetupContext(instance) { - const expose = (exposed) => { - { - if (instance.exposed) { - warn$1(`expose() should be called only once per setup().`); - } - if (exposed != null) { - let exposedType = typeof exposed; - if (exposedType === "object") { - if (shared.isArray(exposed)) { - exposedType = "array"; - } else if (reactivity.isRef(exposed)) { - exposedType = "ref"; - } - } - if (exposedType !== "object") { - warn$1( - `expose() should be passed a plain object, received ${exposedType}.` - ); - } - } - } - instance.exposed = exposed || {}; - }; - { - let attrsProxy; - let slotsProxy; - return Object.freeze({ - get attrs() { - return attrsProxy || (attrsProxy = new Proxy(instance.attrs, attrsProxyHandlers)); - }, - get slots() { - return slotsProxy || (slotsProxy = getSlotsProxy(instance)); - }, - get emit() { - return (event, ...args) => instance.emit(event, ...args); - }, - expose - }); - } - } - function getComponentPublicInstance(instance) { - if (instance.exposed) { - return instance.exposeProxy || (instance.exposeProxy = new Proxy(reactivity.proxyRefs(reactivity.markRaw(instance.exposed)), { - get(target, key) { - if (key in target) { - return target[key]; - } else if (key in publicPropertiesMap) { - return publicPropertiesMap[key](instance); - } - }, - has(target, key) { - return key in target || key in publicPropertiesMap; - } - })); - } else { - return instance.proxy; - } - } - var classifyRE = /(?:^|[-_])\w/g; - var classify = (str) => str.replace(classifyRE, (c) => c.toUpperCase()).replace(/[-_]/g, ""); - function getComponentName(Component, includeInferred = true) { - return shared.isFunction(Component) ? Component.displayName || Component.name : Component.name || includeInferred && Component.__name; - } - function formatComponentName(instance, Component, isRoot = false) { - let name = getComponentName(Component); - if (!name && Component.__file) { - const match = Component.__file.match(/([^/\\]+)\.\w+$/); - if (match) { - name = match[1]; - } - } - if (!name && instance) { - const inferFromRegistry = (registry2) => { - for (const key in registry2) { - if (registry2[key] === Component) { - return key; - } - } - }; - name = inferFromRegistry(instance.components) || instance.parent && inferFromRegistry( - instance.parent.type.components - ) || inferFromRegistry(instance.appContext.components); - } - return name ? classify(name) : isRoot ? `App` : `Anonymous`; - } - function isClassComponent(value) { - return shared.isFunction(value) && "__vccOpts" in value; - } - var computed = (getterOrOptions, debugOptions) => { - const c = reactivity.computed(getterOrOptions, debugOptions, isInSSRComponentSetup); - { - const i = getCurrentInstance(); - if (i && i.appContext.config.warnRecursiveComputed) { - c._warnRecursive = true; - } - } - return c; - }; - function h(type, propsOrChildren, children) { - try { - setBlockTracking(-1); - const l = arguments.length; - if (l === 2) { - if (shared.isObject(propsOrChildren) && !shared.isArray(propsOrChildren)) { - if (isVNode(propsOrChildren)) { - return createVNode(type, null, [propsOrChildren]); - } - return createVNode(type, propsOrChildren); - } else { - return createVNode(type, null, propsOrChildren); - } - } else { - if (l > 3) { - children = Array.prototype.slice.call(arguments, 2); - } else if (l === 3 && isVNode(children)) { - children = [children]; - } - return createVNode(type, propsOrChildren, children); - } - } finally { - setBlockTracking(1); - } - } - function initCustomFormatter() { - if (typeof window === "undefined") { - return; - } - const vueStyle = { style: "color:#3ba776" }; - const numberStyle = { style: "color:#1677ff" }; - const stringStyle = { style: "color:#f5222d" }; - const keywordStyle = { style: "color:#eb2f96" }; - const formatter = { - __vue_custom_formatter: true, - header(obj) { - if (!shared.isObject(obj)) { - return null; - } - if (obj.__isVue) { - return ["div", vueStyle, `VueInstance`]; - } else if (reactivity.isRef(obj)) { - reactivity.pauseTracking(); - const value = obj.value; - reactivity.resetTracking(); - return [ - "div", - {}, - ["span", vueStyle, genRefFlag(obj)], - "<", - formatValue(value), - `>` - ]; - } else if (reactivity.isReactive(obj)) { - return [ - "div", - {}, - ["span", vueStyle, reactivity.isShallow(obj) ? "ShallowReactive" : "Reactive"], - "<", - formatValue(obj), - `>${reactivity.isReadonly(obj) ? ` (readonly)` : ``}` - ]; - } else if (reactivity.isReadonly(obj)) { - return [ - "div", - {}, - ["span", vueStyle, reactivity.isShallow(obj) ? "ShallowReadonly" : "Readonly"], - "<", - formatValue(obj), - ">" - ]; - } - return null; - }, - hasBody(obj) { - return obj && obj.__isVue; - }, - body(obj) { - if (obj && obj.__isVue) { - return [ - "div", - {}, - ...formatInstance(obj.$) - ]; - } - } - }; - function formatInstance(instance) { - const blocks = []; - if (instance.type.props && instance.props) { - blocks.push(createInstanceBlock("props", reactivity.toRaw(instance.props))); - } - if (instance.setupState !== shared.EMPTY_OBJ) { - blocks.push(createInstanceBlock("setup", instance.setupState)); - } - if (instance.data !== shared.EMPTY_OBJ) { - blocks.push(createInstanceBlock("data", reactivity.toRaw(instance.data))); - } - const computed2 = extractKeys(instance, "computed"); - if (computed2) { - blocks.push(createInstanceBlock("computed", computed2)); - } - const injected = extractKeys(instance, "inject"); - if (injected) { - blocks.push(createInstanceBlock("injected", injected)); - } - blocks.push([ - "div", - {}, - [ - "span", - { - style: keywordStyle.style + ";opacity:0.66" - }, - "$ (internal): " - ], - ["object", { object: instance }] - ]); - return blocks; - } - function createInstanceBlock(type, target) { - target = shared.extend({}, target); - if (!Object.keys(target).length) { - return ["span", {}]; - } - return [ - "div", - { style: "line-height:1.25em;margin-bottom:0.6em" }, - [ - "div", - { - style: "color:#476582" - }, - type - ], - [ - "div", - { - style: "padding-left:1.25em" - }, - ...Object.keys(target).map((key) => { - return [ - "div", - {}, - ["span", keywordStyle, key + ": "], - formatValue(target[key], false) - ]; - }) - ] - ]; - } - function formatValue(v, asRaw = true) { - if (typeof v === "number") { - return ["span", numberStyle, v]; - } else if (typeof v === "string") { - return ["span", stringStyle, JSON.stringify(v)]; - } else if (typeof v === "boolean") { - return ["span", keywordStyle, v]; - } else if (shared.isObject(v)) { - return ["object", { object: asRaw ? reactivity.toRaw(v) : v }]; - } else { - return ["span", stringStyle, String(v)]; - } - } - function extractKeys(instance, type) { - const Comp = instance.type; - if (shared.isFunction(Comp)) { - return; - } - const extracted = {}; - for (const key in instance.ctx) { - if (isKeyOfType(Comp, key, type)) { - extracted[key] = instance.ctx[key]; - } - } - return extracted; - } - function isKeyOfType(Comp, key, type) { - const opts = Comp[type]; - if (shared.isArray(opts) && opts.includes(key) || shared.isObject(opts) && key in opts) { - return true; - } - if (Comp.extends && isKeyOfType(Comp.extends, key, type)) { - return true; - } - if (Comp.mixins && Comp.mixins.some((m) => isKeyOfType(m, key, type))) { - return true; - } - } - function genRefFlag(v) { - if (reactivity.isShallow(v)) { - return `ShallowRef`; - } - if (v.effect) { - return `ComputedRef`; - } - return `Ref`; - } - if (window.devtoolsFormatters) { - window.devtoolsFormatters.push(formatter); - } else { - window.devtoolsFormatters = [formatter]; - } - } - function withMemo(memo, render, cache, index) { - const cached = cache[index]; - if (cached && isMemoSame(cached, memo)) { - return cached; - } - const ret = render(); - ret.memo = memo.slice(); - ret.cacheIndex = index; - return cache[index] = ret; - } - function isMemoSame(cached, memo) { - const prev = cached.memo; - if (prev.length != memo.length) { - return false; - } - for (let i = 0; i < prev.length; i++) { - if (shared.hasChanged(prev[i], memo[i])) { - return false; - } - } - if (isBlockTreeEnabled > 0 && currentBlock) { - currentBlock.push(cached); - } - return true; - } - var version = "3.5.44"; - var warn2 = warn$1; - var ErrorTypeStrings = ErrorTypeStrings$1; - var devtools = devtools$1; - var setDevtoolsHook = setDevtoolsHook$1; - var _ssrUtils = { - createComponentInstance, - setupComponent, - renderComponentRoot, - setCurrentRenderingInstance, - isVNode, - normalizeVNode, - getComponentPublicInstance, - ensureValidVNode, - pushWarningContext, - popWarningContext - }; - var ssrUtils = _ssrUtils; - var resolveFilter = null; - var compatUtils = null; - var DeprecationTypes = null; - exports2.EffectScope = reactivity.EffectScope; - exports2.ReactiveEffect = reactivity.ReactiveEffect; - exports2.TrackOpTypes = reactivity.TrackOpTypes; - exports2.TriggerOpTypes = reactivity.TriggerOpTypes; - exports2.customRef = reactivity.customRef; - exports2.effect = reactivity.effect; - exports2.effectScope = reactivity.effectScope; - exports2.getCurrentScope = reactivity.getCurrentScope; - exports2.getCurrentWatcher = reactivity.getCurrentWatcher; - exports2.isProxy = reactivity.isProxy; - exports2.isReactive = reactivity.isReactive; - exports2.isReadonly = reactivity.isReadonly; - exports2.isRef = reactivity.isRef; - exports2.isShallow = reactivity.isShallow; - exports2.markRaw = reactivity.markRaw; - exports2.onScopeDispose = reactivity.onScopeDispose; - exports2.onWatcherCleanup = reactivity.onWatcherCleanup; - exports2.proxyRefs = reactivity.proxyRefs; - exports2.reactive = reactivity.reactive; - exports2.readonly = reactivity.readonly; - exports2.ref = reactivity.ref; - exports2.shallowReactive = reactivity.shallowReactive; - exports2.shallowReadonly = reactivity.shallowReadonly; - exports2.shallowRef = reactivity.shallowRef; - exports2.stop = reactivity.stop; - exports2.toRaw = reactivity.toRaw; - exports2.toRef = reactivity.toRef; - exports2.toRefs = reactivity.toRefs; - exports2.toValue = reactivity.toValue; - exports2.triggerRef = reactivity.triggerRef; - exports2.unref = reactivity.unref; - exports2.camelize = shared.camelize; - exports2.capitalize = shared.capitalize; - exports2.normalizeClass = shared.normalizeClass; - exports2.normalizeProps = shared.normalizeProps; - exports2.normalizeStyle = shared.normalizeStyle; - exports2.toDisplayString = shared.toDisplayString; - exports2.toHandlerKey = shared.toHandlerKey; - exports2.BaseTransition = BaseTransition; - exports2.BaseTransitionPropsValidators = BaseTransitionPropsValidators; - exports2.Comment = Comment; - exports2.DeprecationTypes = DeprecationTypes; - exports2.ErrorCodes = ErrorCodes; - exports2.ErrorTypeStrings = ErrorTypeStrings; - exports2.Fragment = Fragment; - exports2.KeepAlive = KeepAlive; - exports2.Static = Static; - exports2.Suspense = Suspense; - exports2.Teleport = Teleport; - exports2.Text = Text; - exports2.assertNumber = assertNumber; - exports2.callWithAsyncErrorHandling = callWithAsyncErrorHandling; - exports2.callWithErrorHandling = callWithErrorHandling; - exports2.cloneVNode = cloneVNode; - exports2.compatUtils = compatUtils; - exports2.computed = computed; - exports2.createBlock = createBlock; - exports2.createCommentVNode = createCommentVNode; - exports2.createElementBlock = createElementBlock; - exports2.createElementVNode = createBaseVNode; - exports2.createHydrationRenderer = createHydrationRenderer; - exports2.createPropsRestProxy = createPropsRestProxy; - exports2.createRenderer = createRenderer; - exports2.createSlots = createSlots; - exports2.createStaticVNode = createStaticVNode; - exports2.createTextVNode = createTextVNode; - exports2.createVNode = createVNode; - exports2.defineAsyncComponent = defineAsyncComponent; - exports2.defineComponent = defineComponent; - exports2.defineEmits = defineEmits; - exports2.defineExpose = defineExpose; - exports2.defineModel = defineModel; - exports2.defineOptions = defineOptions; - exports2.defineProps = defineProps; - exports2.defineSlots = defineSlots; - exports2.devtools = devtools; - exports2.getCurrentInstance = getCurrentInstance; - exports2.getTransitionRawChildren = getTransitionRawChildren; - exports2.guardReactiveProps = guardReactiveProps; - exports2.h = h; - exports2.handleError = handleError; - exports2.hasInjectionContext = hasInjectionContext; - exports2.hydrateOnIdle = hydrateOnIdle; - exports2.hydrateOnInteraction = hydrateOnInteraction; - exports2.hydrateOnMediaQuery = hydrateOnMediaQuery; - exports2.hydrateOnVisible = hydrateOnVisible; - exports2.initCustomFormatter = initCustomFormatter; - exports2.inject = inject; - exports2.isMemoSame = isMemoSame; - exports2.isRuntimeOnly = isRuntimeOnly; - exports2.isVNode = isVNode; - exports2.mergeDefaults = mergeDefaults; - exports2.mergeModels = mergeModels; - exports2.mergeProps = mergeProps; - exports2.nextTick = nextTick; - exports2.onActivated = onActivated; - exports2.onBeforeMount = onBeforeMount; - exports2.onBeforeUnmount = onBeforeUnmount; - exports2.onBeforeUpdate = onBeforeUpdate; - exports2.onDeactivated = onDeactivated; - exports2.onErrorCaptured = onErrorCaptured; - exports2.onMounted = onMounted; - exports2.onRenderTracked = onRenderTracked; - exports2.onRenderTriggered = onRenderTriggered; - exports2.onServerPrefetch = onServerPrefetch; - exports2.onUnmounted = onUnmounted; - exports2.onUpdated = onUpdated; - exports2.openBlock = openBlock; - exports2.popScopeId = popScopeId; - exports2.provide = provide; - exports2.pushScopeId = pushScopeId; - exports2.queuePostFlushCb = queuePostFlushCb; - exports2.registerRuntimeCompiler = registerRuntimeCompiler; - exports2.renderList = renderList; - exports2.renderSlot = renderSlot; - exports2.resolveComponent = resolveComponent; - exports2.resolveDirective = resolveDirective; - exports2.resolveDynamicComponent = resolveDynamicComponent; - exports2.resolveFilter = resolveFilter; - exports2.resolveTransitionHooks = resolveTransitionHooks; - exports2.setBlockTracking = setBlockTracking; - exports2.setDevtoolsHook = setDevtoolsHook; - exports2.setTransitionHooks = setTransitionHooks; - exports2.ssrContextKey = ssrContextKey; - exports2.ssrUtils = ssrUtils; - exports2.toHandlers = toHandlers; - exports2.transformVNodeArgs = transformVNodeArgs; - exports2.useAttrs = useAttrs; - exports2.useId = useId; - exports2.useModel = useModel; - exports2.useSSRContext = useSSRContext; - exports2.useSlots = useSlots; - exports2.useTemplateRef = useTemplateRef; - exports2.useTransitionState = useTransitionState; - exports2.version = version; - exports2.warn = warn2; - exports2.watch = watch; - exports2.watchEffect = watchEffect; - exports2.watchPostEffect = watchPostEffect; - exports2.watchSyncEffect = watchSyncEffect; - exports2.withAsyncContext = withAsyncContext; - exports2.withCtx = withCtx; - exports2.withDefaults = withDefaults; - exports2.withDirectives = withDirectives; - exports2.withMemo = withMemo; - exports2.withScopeId = withScopeId; - } -}); - -// intern-log/node_modules/.pnpm/@vue+runtime-core@3.5.44/node_modules/@vue/runtime-core/index.js -var require_runtime_core = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+runtime-core@3.5.44/node_modules/@vue/runtime-core/index.js"(exports2, module2) { - "use strict"; - if (process.env.NODE_ENV === "production") { - module2.exports = require_runtime_core_cjs_prod(); - } else { - module2.exports = require_runtime_core_cjs(); - } - } -}); - -// intern-log/node_modules/.pnpm/@vue+runtime-dom@3.5.44/node_modules/@vue/runtime-dom/dist/runtime-dom.cjs.prod.js -var require_runtime_dom_cjs_prod = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+runtime-dom@3.5.44/node_modules/@vue/runtime-dom/dist/runtime-dom.cjs.prod.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var runtimeCore = require_runtime_core(); - var shared = require_shared(); - var policy = void 0; - var tt = typeof window !== "undefined" && window.trustedTypes; - if (tt) { - try { - policy = /* @__PURE__ */ tt.createPolicy("vue", { - createHTML: (val) => val - }); - } catch (e) { - } - } - var unsafeToTrustedHTML = policy ? (val) => policy.createHTML(val) : (val) => val; - var svgNS = "http://www.w3.org/2000/svg"; - var mathmlNS = "http://www.w3.org/1998/Math/MathML"; - var doc = typeof document !== "undefined" ? document : null; - var templateContainer = doc && /* @__PURE__ */ doc.createElement("template"); - var nodeOps = { - insert: (child, parent, anchor) => { - parent.insertBefore(child, anchor || null); - }, - remove: (child) => { - const parent = child.parentNode; - if (parent) { - parent.removeChild(child); - } - }, - createElement: (tag, namespace, is, props) => { - const el = namespace === "svg" ? doc.createElementNS(svgNS, tag) : namespace === "mathml" ? doc.createElementNS(mathmlNS, tag) : is ? doc.createElement(tag, { is }) : doc.createElement(tag); - if (tag === "select" && props && props.multiple != null) { - el.setAttribute("multiple", props.multiple); - } - return el; - }, - createText: (text) => doc.createTextNode(text), - createComment: (text) => doc.createComment(text), - setText: (node, text) => { - node.nodeValue = text; - }, - setElementText: (el, text) => { - el.textContent = text; - }, - parentNode: (node) => node.parentNode, - nextSibling: (node) => node.nextSibling, - querySelector: (selector) => doc.querySelector(selector), - setScopeId(el, id) { - el.setAttribute(id, ""); - }, - // __UNSAFE__ - // Reason: innerHTML. - // Static content here can only come from compiled templates. - // As long as the user only uses trusted templates, this is safe. - insertStaticContent(content, parent, anchor, namespace, start, end) { - const before = anchor ? anchor.previousSibling : parent.lastChild; - if (start && (start === end || start.nextSibling)) { - while (true) { - parent.insertBefore(start.cloneNode(true), anchor); - if (start === end || !(start = start.nextSibling)) break; - } - } else { - templateContainer.innerHTML = unsafeToTrustedHTML( - namespace === "svg" ? `<svg>${content}</svg>` : namespace === "mathml" ? `<math>${content}</math>` : content - ); - const template = templateContainer.content; - if (namespace === "svg" || namespace === "mathml") { - const wrapper = template.firstChild; - while (wrapper.firstChild) { - template.appendChild(wrapper.firstChild); - } - template.removeChild(wrapper); - } - parent.insertBefore(template, anchor); - } - return [ - // first - before ? before.nextSibling : parent.firstChild, - // last - anchor ? anchor.previousSibling : parent.lastChild - ]; - } - }; - var TRANSITION = "transition"; - var ANIMATION = "animation"; - var vtcKey = /* @__PURE__ */ Symbol("_vtc"); - var DOMTransitionPropsValidators = { - name: String, - type: String, - css: { - type: Boolean, - default: true - }, - duration: [String, Number, Object], - enterFromClass: String, - enterActiveClass: String, - enterToClass: String, - appearFromClass: String, - appearActiveClass: String, - appearToClass: String, - leaveFromClass: String, - leaveActiveClass: String, - leaveToClass: String - }; - var TransitionPropsValidators = /* @__PURE__ */ shared.extend( - {}, - runtimeCore.BaseTransitionPropsValidators, - DOMTransitionPropsValidators - ); - var decorate$1 = (t) => { - t.displayName = "Transition"; - t.props = TransitionPropsValidators; - return t; - }; - var Transition = /* @__PURE__ */ decorate$1( - (props, { slots }) => runtimeCore.h(runtimeCore.BaseTransition, resolveTransitionProps(props), slots) - ); - var callHook = (hook, args = []) => { - if (shared.isArray(hook)) { - hook.forEach((h2) => h2(...args)); - } else if (hook) { - hook(...args); - } - }; - var hasExplicitCallback = (hook) => { - return hook ? shared.isArray(hook) ? hook.some((h2) => h2.length > 1) : hook.length > 1 : false; - }; - function resolveTransitionProps(rawProps) { - const baseProps = {}; - for (const key in rawProps) { - if (!(key in DOMTransitionPropsValidators)) { - baseProps[key] = rawProps[key]; - } - } - if (rawProps.css === false) { - return baseProps; - } - const { - name = "v", - type, - duration, - enterFromClass = `${name}-enter-from`, - enterActiveClass = `${name}-enter-active`, - enterToClass = `${name}-enter-to`, - appearFromClass = enterFromClass, - appearActiveClass = enterActiveClass, - appearToClass = enterToClass, - leaveFromClass = `${name}-leave-from`, - leaveActiveClass = `${name}-leave-active`, - leaveToClass = `${name}-leave-to` - } = rawProps; - const durations = normalizeDuration(duration); - const enterDuration = durations && durations[0]; - const leaveDuration = durations && durations[1]; - const { - onBeforeEnter, - onEnter, - onEnterCancelled, - onLeave, - onLeaveCancelled, - onBeforeAppear = onBeforeEnter, - onAppear = onEnter, - onAppearCancelled = onEnterCancelled - } = baseProps; - const finishEnter = (el, isAppear, done, isCancelled) => { - el._enterCancelled = isCancelled; - removeTransitionClass(el, isAppear ? appearToClass : enterToClass); - removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass); - done && done(); - }; - const finishLeave = (el, done) => { - el._isLeaving = false; - removeTransitionClass(el, leaveFromClass); - removeTransitionClass(el, leaveToClass); - removeTransitionClass(el, leaveActiveClass); - done && done(); - }; - const makeEnterHook = (isAppear) => { - return (el, done) => { - const hook = isAppear ? onAppear : onEnter; - const resolve = () => finishEnter(el, isAppear, done); - callHook(hook, [el, resolve]); - nextFrame(() => { - removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass); - addTransitionClass(el, isAppear ? appearToClass : enterToClass); - if (!hasExplicitCallback(hook)) { - whenTransitionEnds(el, type, enterDuration, resolve); - } - }); - }; - }; - return shared.extend(baseProps, { - onBeforeEnter(el) { - callHook(onBeforeEnter, [el]); - addTransitionClass(el, enterFromClass); - addTransitionClass(el, enterActiveClass); - }, - onBeforeAppear(el) { - callHook(onBeforeAppear, [el]); - addTransitionClass(el, appearFromClass); - addTransitionClass(el, appearActiveClass); - }, - onEnter: makeEnterHook(false), - onAppear: makeEnterHook(true), - onLeave(el, done) { - el._isLeaving = true; - const resolve = () => finishLeave(el, done); - addTransitionClass(el, leaveFromClass); - if (!el._enterCancelled) { - forceReflow(el); - addTransitionClass(el, leaveActiveClass); - } else { - addTransitionClass(el, leaveActiveClass); - forceReflow(el); - } - nextFrame(() => { - if (!el._isLeaving) { - return; - } - removeTransitionClass(el, leaveFromClass); - addTransitionClass(el, leaveToClass); - if (!hasExplicitCallback(onLeave)) { - whenTransitionEnds(el, type, leaveDuration, resolve); - } - }); - callHook(onLeave, [el, resolve]); - }, - onEnterCancelled(el) { - finishEnter(el, false, void 0, true); - callHook(onEnterCancelled, [el]); - }, - onAppearCancelled(el) { - finishEnter(el, true, void 0, true); - callHook(onAppearCancelled, [el]); - }, - onLeaveCancelled(el) { - finishLeave(el); - callHook(onLeaveCancelled, [el]); - } - }); - } - function normalizeDuration(duration) { - if (duration == null) { - return null; - } else if (shared.isObject(duration)) { - return [NumberOf(duration.enter), NumberOf(duration.leave)]; - } else { - const n = NumberOf(duration); - return [n, n]; - } - } - function NumberOf(val) { - const res = shared.toNumber(val); - return res; - } - function addTransitionClass(el, cls) { - cls.split(/\s+/).forEach((c) => c && el.classList.add(c)); - (el[vtcKey] || (el[vtcKey] = /* @__PURE__ */ new Set())).add(cls); - } - function removeTransitionClass(el, cls) { - cls.split(/\s+/).forEach((c) => c && el.classList.remove(c)); - const _vtc = el[vtcKey]; - if (_vtc) { - _vtc.delete(cls); - if (!_vtc.size) { - el[vtcKey] = void 0; - } - } - } - function nextFrame(cb) { - requestAnimationFrame(() => { - requestAnimationFrame(cb); - }); - } - var endId = 0; - function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) { - const id = el._endId = ++endId; - const resolveIfNotStale = () => { - if (id === el._endId) { - resolve(); - } - }; - if (explicitTimeout != null) { - return setTimeout(resolveIfNotStale, explicitTimeout); - } - const { type, timeout, propCount } = getTransitionInfo(el, expectedType); - if (!type) { - return resolve(); - } - const endEvent = type + "end"; - let ended = 0; - const end = () => { - el.removeEventListener(endEvent, onEnd); - resolveIfNotStale(); - }; - const onEnd = (e) => { - if (e.target === el && ++ended >= propCount) { - end(); - } - }; - setTimeout(() => { - if (ended < propCount) { - end(); - } - }, timeout + 1); - el.addEventListener(endEvent, onEnd); - } - function getTransitionInfo(el, expectedType) { - const styles = window.getComputedStyle(el); - const getStyleProperties = (key) => (styles[key] || "").split(", "); - const transitionDelays = getStyleProperties(`${TRANSITION}Delay`); - const transitionDurations = getStyleProperties(`${TRANSITION}Duration`); - const transitionTimeout = getTimeout(transitionDelays, transitionDurations); - const animationDelays = getStyleProperties(`${ANIMATION}Delay`); - const animationDurations = getStyleProperties(`${ANIMATION}Duration`); - const animationTimeout = getTimeout(animationDelays, animationDurations); - let type = null; - let timeout = 0; - let propCount = 0; - if (expectedType === TRANSITION) { - if (transitionTimeout > 0) { - type = TRANSITION; - timeout = transitionTimeout; - propCount = transitionDurations.length; - } - } else if (expectedType === ANIMATION) { - if (animationTimeout > 0) { - type = ANIMATION; - timeout = animationTimeout; - propCount = animationDurations.length; - } - } else { - timeout = Math.max(transitionTimeout, animationTimeout); - type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; - propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; - } - const hasTransform = type === TRANSITION && /\b(?:transform|all)(?:,|$)/.test( - getStyleProperties(`${TRANSITION}Property`).toString() - ); - return { - type, - timeout, - propCount, - hasTransform - }; - } - function getTimeout(delays, durations) { - while (delays.length < durations.length) { - delays = delays.concat(delays); - } - return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i]))); - } - function toMs(s) { - if (s === "auto") return 0; - return Number(s.slice(0, -1).replace(",", ".")) * 1e3; - } - function forceReflow(el) { - const targetDocument = el ? el.ownerDocument : document; - return targetDocument.body.offsetHeight; - } - function patchClass(el, value, isSVG) { - const transitionClasses = el[vtcKey]; - if (transitionClasses) { - value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(" "); - } - if (value == null) { - el.removeAttribute("class"); - } else if (isSVG) { - el.setAttribute("class", value); - } else { - el.className = value; - } - } - var vShowOriginalDisplay = /* @__PURE__ */ Symbol("_vod"); - var vShowHidden = /* @__PURE__ */ Symbol("_vsh"); - var vShow = { - // used for prop mismatch check during hydration - name: "show", - beforeMount(el, { value }, { transition }) { - el[vShowOriginalDisplay] = el.style.display === "none" ? "" : el.style.display; - if (transition && value) { - transition.beforeEnter(el); - } else { - setDisplay(el, value); - } - }, - mounted(el, { value }, { transition }) { - if (transition && value) { - transition.enter(el); - } - }, - updated(el, { value, oldValue }, { transition }) { - if (!value === !oldValue) return; - if (transition) { - if (value) { - transition.beforeEnter(el); - setDisplay(el, true); - transition.enter(el); - } else { - transition.leave(el, () => { - setDisplay(el, false); - }); - } - } else { - setDisplay(el, value); - } - }, - beforeUnmount(el, { value }) { - setDisplay(el, value); - } - }; - function setDisplay(el, value) { - el.style.display = value ? el[vShowOriginalDisplay] : "none"; - el[vShowHidden] = !value; - } - function initVShowForSSR() { - vShow.getSSRProps = ({ value }) => { - if (!value) { - return { style: { display: "none" } }; - } - }; - } - var CSS_VAR_TEXT = /* @__PURE__ */ Symbol(""); - function useCssVars(getter) { - return; - } - var displayRE = /(?:^|;)\s*display\s*:/; - function patchStyle(el, prev, next) { - const style = el.style; - const isCssString = shared.isString(next); - let hasControlledDisplay = false; - if (next && !isCssString) { - if (prev) { - if (!shared.isString(prev)) { - for (const key in prev) { - if (next[key] == null) { - setStyle(style, key, ""); - } - } - } else { - for (const prevStyle of prev.split(";")) { - const key = prevStyle.slice(0, prevStyle.indexOf(":")).trim(); - if (next[key] == null) { - setStyle(style, key, ""); - } - } - } - } - for (const key in next) { - if (key === "display") { - hasControlledDisplay = true; - } - const value = next[key]; - if (value != null) { - if (!shouldPreserveTextareaResizeStyle( - el, - key, - !shared.isString(prev) && prev ? prev[key] : void 0, - value - )) { - setStyle(style, key, value); - } - } else { - setStyle(style, key, ""); - } - } - } else { - if (isCssString) { - if (prev !== next) { - const cssVarText = style[CSS_VAR_TEXT]; - if (cssVarText) { - next += ";" + cssVarText; - } - style.cssText = next; - hasControlledDisplay = displayRE.test(next); - } - } else if (prev) { - el.removeAttribute("style"); - } - } - if (vShowOriginalDisplay in el) { - if (!isCssString || prev !== next) { - el[vShowOriginalDisplay] = hasControlledDisplay ? style.display : ""; - } - if (el[vShowHidden]) { - style.display = "none"; - } - } - } - var importantRE = /\s*!important$/; - function setStyle(style, name, val) { - if (shared.isArray(val)) { - val.forEach((v) => setStyle(style, name, v)); - } else { - if (val == null) val = ""; - if (name.startsWith("--")) { - if (importantRE.test(val)) { - style.setProperty(name, val.replace(importantRE, ""), "important"); - } else { - style.setProperty(name, val); - } - } else { - const prefixed = autoPrefix(style, name); - if (importantRE.test(val)) { - style.setProperty( - shared.hyphenate(prefixed), - val.replace(importantRE, ""), - "important" - ); - } else { - style[prefixed] = val; - } - } - } - } - var prefixes = ["Webkit", "Moz", "ms"]; - var prefixCache = {}; - function autoPrefix(style, rawName) { - const cached = prefixCache[rawName]; - if (cached) { - return cached; - } - let name = runtimeCore.camelize(rawName); - if (name !== "filter" && name in style) { - return prefixCache[rawName] = name; - } - name = shared.capitalize(name); - for (let i = 0; i < prefixes.length; i++) { - const prefixed = prefixes[i] + name; - if (prefixed in style) { - return prefixCache[rawName] = prefixed; - } - } - return rawName; - } - function shouldPreserveTextareaResizeStyle(el, key, prev, next) { - return el.tagName === "TEXTAREA" && (key === "width" || key === "height") && shared.isString(next) && prev === next; - } - var xlinkNS = "http://www.w3.org/1999/xlink"; - function patchAttr(el, key, value, isSVG, instance, isBoolean = shared.isSpecialBooleanAttr(key)) { - if (isSVG && key.startsWith("xlink:")) { - if (value == null) { - el.removeAttributeNS(xlinkNS, key.slice(6, key.length)); - } else { - el.setAttributeNS(xlinkNS, key, value); - } - } else { - if (value == null || isBoolean && !shared.includeBooleanAttr(value)) { - el.removeAttribute(key); - } else { - el.setAttribute( - key, - isBoolean ? "" : shared.isSymbol(value) ? String(value) : value - ); - } - } - } - function patchDOMProp(el, key, value, parentComponent, attrName) { - if (key === "innerHTML" || key === "textContent") { - if (value != null) { - el[key] = key === "innerHTML" ? unsafeToTrustedHTML(value) : value; - } - return; - } - const tag = el.tagName; - if (key === "value" && tag !== "PROGRESS" && // custom elements may use _value internally - !tag.includes("-")) { - const oldValue = tag === "OPTION" ? el.getAttribute("value") || "" : el.value; - const newValue = value == null ? ( - // #11647: value should be set as empty string for null and undefined, - // but <input type="checkbox"> should be set as 'on'. - el.type === "checkbox" ? "on" : "" - ) : String(value); - if (oldValue !== newValue || !("_value" in el)) { - el.value = newValue; - } - if (value == null) { - el.removeAttribute(key); - } - el._value = value; - return; - } - let needRemove = false; - if (value === "" || value == null) { - const type = typeof el[key]; - if (type === "boolean") { - value = shared.includeBooleanAttr(value); - } else if (value == null && type === "string") { - value = ""; - needRemove = true; - } else if (type === "number") { - value = 0; - needRemove = true; - } - } - try { - el[key] = value; - } catch (e) { - } - needRemove && el.removeAttribute(attrName || key); - } - function addEventListener2(el, event, handler, options) { - el.addEventListener(event, handler, options); - } - function removeEventListener(el, event, handler, options) { - el.removeEventListener(event, handler, options); - } - var veiKey = /* @__PURE__ */ Symbol("_vei"); - function patchEvent(el, rawName, prevValue, nextValue, instance = null) { - const invokers = el[veiKey] || (el[veiKey] = {}); - const existingInvoker = invokers[rawName]; - if (nextValue && existingInvoker) { - existingInvoker.value = nextValue; - } else { - const [name, options] = parseName(rawName); - if (nextValue) { - const invoker = invokers[rawName] = createInvoker( - nextValue, - instance - ); - addEventListener2(el, name, invoker, options); - } else if (existingInvoker) { - removeEventListener(el, name, existingInvoker, options); - invokers[rawName] = void 0; - } - } - } - var optionsModifierRE = /(Once|Passive|Capture)$/; - var optionsModifierEventRE = /^on:?(?:Once|Passive|Capture)$/; - function parseName(name) { - let options; - let m; - while ((m = name.match(optionsModifierRE)) && !optionsModifierEventRE.test(name)) { - if (!options) options = {}; - name = name.slice(0, name.length - m[1].length); - options[m[1].toLowerCase()] = true; - } - const event = name[2] === ":" ? name.slice(3) : shared.hyphenate(name.slice(2)); - return [event, options]; - } - var cachedNow = 0; - var p = /* @__PURE__ */ Promise.resolve(); - var getNow = () => cachedNow || (p.then(() => cachedNow = 0), cachedNow = Date.now()); - function createInvoker(initialValue, instance) { - const invoker = (e) => { - if (!e._vts) { - e._vts = Date.now(); - } else if (e._vts <= invoker.attached) { - return; - } - const value = invoker.value; - if (shared.isArray(value)) { - const originalStop = e.stopImmediatePropagation; - e.stopImmediatePropagation = () => { - originalStop.call(e); - e._stopped = true; - }; - const handlers = value.slice(); - const args = [e]; - for (let i = 0; i < handlers.length; i++) { - if (e._stopped) { - break; - } - const handler = handlers[i]; - if (handler) { - runtimeCore.callWithAsyncErrorHandling( - handler, - instance, - 5, - args - ); - } - } - } else { - runtimeCore.callWithAsyncErrorHandling( - value, - instance, - 5, - [e] - ); - } - }; - invoker.value = initialValue; - invoker.attached = getNow(); - return invoker; - } - var isNativeOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // lowercase letter - key.charCodeAt(2) > 96 && key.charCodeAt(2) < 123; - var patchProp = (el, key, prevValue, nextValue, namespace, parentComponent) => { - const isSVG = namespace === "svg"; - if (key === "class") { - patchClass(el, nextValue, isSVG); - } else if (key === "style") { - patchStyle(el, prevValue, nextValue); - } else if (shared.isOn(key)) { - if (!shared.isModelListener(key)) { - patchEvent(el, key, prevValue, nextValue, parentComponent); - } - } else if (key[0] === "." ? (key = key.slice(1), true) : key[0] === "^" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) { - patchDOMProp(el, key, nextValue); - if (!el.tagName.includes("-") && (key === "value" || key === "checked" || key === "selected")) { - patchAttr(el, key, nextValue, isSVG, parentComponent, key !== "value"); - } - } else if ( - // #11081 force set props for possible async custom element - el._isVueCE && // #12408 check if it's declared prop or it's async custom element - (shouldSetAsPropForVueCE(el, key) || // @ts-expect-error _def is private - el._def.__asyncLoader && (/[A-Z]/.test(key) || !shared.isString(nextValue))) - ) { - patchDOMProp(el, shared.camelize(key), nextValue, parentComponent, key); - } else { - if (key === "true-value") { - el._trueValue = nextValue; - } else if (key === "false-value") { - el._falseValue = nextValue; - } - patchAttr(el, key, nextValue, isSVG); - } - }; - function shouldSetAsProp(el, key, value, isSVG) { - if (isSVG) { - if (key === "innerHTML" || key === "textContent") { - return true; - } - if (key in el && isNativeOn(key) && shared.isFunction(value)) { - return true; - } - return false; - } - if (key === "spellcheck" || key === "draggable" || key === "translate" || key === "autocorrect") { - return false; - } - if (key === "sandbox" && el.tagName === "IFRAME") { - return false; - } - if (key === "form") { - return false; - } - if (key === "list" && el.tagName === "INPUT") { - return false; - } - if (key === "type" && el.tagName === "TEXTAREA") { - return false; - } - if (key === "width" || key === "height") { - const tag = el.tagName; - if (tag === "IMG" || tag === "VIDEO" || tag === "CANVAS" || tag === "SOURCE") { - return false; - } - } - if (isNativeOn(key) && shared.isString(value)) { - return false; - } - return key in el; - } - function shouldSetAsPropForVueCE(el, key) { - const props = ( - // @ts-expect-error _def is private - el._def.props - ); - if (!props) { - return false; - } - const camelKey = shared.camelize(key); - return Array.isArray(props) ? props.some((prop) => shared.camelize(prop) === camelKey) : Object.keys(props).some((prop) => shared.camelize(prop) === camelKey); - } - var REMOVAL = {}; - // @__NO_SIDE_EFFECTS__ - function defineCustomElement(options, extraOptions, _createApp) { - let Comp = runtimeCore.defineComponent(options, extraOptions); - if (shared.isPlainObject(Comp)) Comp = shared.extend({}, Comp, extraOptions); - class VueCustomElement extends VueElement { - constructor(initialProps) { - super(Comp, initialProps, _createApp); - } - } - VueCustomElement.def = Comp; - return VueCustomElement; - } - var defineSSRCustomElement = /* @__NO_SIDE_EFFECTS__ */ (options, extraOptions) => { - return /* @__PURE__ */ defineCustomElement(options, extraOptions, createSSRApp); - }; - var BaseClass = typeof HTMLElement !== "undefined" ? HTMLElement : class { - }; - var VueElement = class _VueElement extends BaseClass { - constructor(_def, _props = {}, _createApp = createApp) { - super(); - this._def = _def; - this._props = _props; - this._createApp = _createApp; - this._isVueCE = true; - this._instance = null; - this._app = null; - this._nonce = this._def.nonce; - this._connected = false; - this._resolved = false; - this._patching = false; - this._dirty = false; - this._numberProps = null; - this._styleChildren = /* @__PURE__ */ new WeakSet(); - this._styleAnchors = /* @__PURE__ */ new WeakMap(); - this._ob = null; - if (this.shadowRoot && _createApp !== createApp) { - this._root = this.shadowRoot; - } else { - if (_def.shadowRoot !== false) { - this.attachShadow( - shared.extend({}, _def.shadowRootOptions, { - mode: "open" - }) - ); - this._root = this.shadowRoot; - } else { - this._root = this; - } - } - } - connectedCallback() { - if (!this.isConnected) return; - if (!this.shadowRoot && !this._resolved) { - this._parseSlots(); - } - this._connected = true; - let parent = this; - while (parent = parent && // #12479 should check assignedSlot first to get correct parent - (parent.assignedSlot || parent.parentNode || parent.host)) { - if (parent instanceof _VueElement) { - this._parent = parent; - break; - } - } - if (!this._instance) { - if (this._resolved) { - this._mount(this._def); - } else { - if (parent && parent._pendingResolve) { - this._pendingResolve = parent._pendingResolve.then(() => { - this._pendingResolve = void 0; - if (this.isConnected) { - return this._resolveDef(); - } - }); - } else { - this._resolveDef(); - } - } - } - } - _setParent(parent = this._parent) { - if (parent) { - this._instance.parent = parent._instance; - this._inheritParentContext(parent); - } - } - _inheritParentContext(parent = this._parent) { - if (parent && this._app) { - Object.setPrototypeOf( - this._app._context.provides, - parent._instance.provides - ); - } - } - disconnectedCallback() { - this._connected = false; - runtimeCore.nextTick(() => { - if (!this._connected) { - if (this._ob) { - this._ob.disconnect(); - this._ob = null; - } - this._app && this._app.unmount(); - if (this._instance) this._instance.ce = void 0; - this._app = this._instance = null; - if (this._teleportTargets) { - this._teleportTargets.clear(); - this._teleportTargets = void 0; - } - } - }); - } - _processMutations(mutations) { - for (const m of mutations) { - this._setAttr(m.attributeName); - } - } - /** - * resolve inner component definition (handle possible async component) - */ - _resolveDef() { - if (this._pendingResolve) { - return this._pendingResolve; - } - for (let i = 0; i < this.attributes.length; i++) { - this._setAttr(this.attributes[i].name); - } - this._ob = new MutationObserver(this._processMutations.bind(this)); - this._ob.observe(this, { attributes: true }); - const resolve = (def, isAsync = false) => { - this._resolved = true; - this._pendingResolve = void 0; - const { props, styles } = def; - let numberProps; - if (props && !shared.isArray(props)) { - for (const key in props) { - const opt = props[key]; - if (opt === Number || opt && opt.type === Number) { - if (key in this._props) { - this._props[key] = shared.toNumber(this._props[key]); - } - (numberProps || (numberProps = /* @__PURE__ */ Object.create(null)))[shared.camelize(key)] = true; - } - } - } - this._numberProps = numberProps; - this._resolveProps(def); - if (this.shadowRoot) { - this._applyStyles(styles); - } - if (this._connected) { - this._mount(def); - } - }; - const asyncDef = this._def.__asyncLoader; - if (asyncDef) { - this._pendingResolve = asyncDef().then((def) => { - def.configureApp = this._def.configureApp; - resolve(this._def = def, true); - }); - return this._pendingResolve; - } else { - resolve(this._def); - } - } - _mount(def) { - this._app = this._createApp(def); - this._inheritParentContext(); - if (def.configureApp) { - def.configureApp(this._app); - } - this._app._ceVNode = this._createVNode(); - this._app.mount(this._root); - const exposed = this._instance && this._instance.exposed; - if (!exposed) return; - for (const key in exposed) { - if (!shared.hasOwn(this, key)) { - Object.defineProperty(this, key, { - // unwrap ref to be consistent with public instance behavior - get: () => runtimeCore.unref(exposed[key]) - }); - } - } - } - _resolveProps(def) { - const { props } = def; - const declaredPropKeys = shared.isArray(props) ? props : Object.keys(props || {}); - for (const key of Object.keys(this)) { - if (key[0] !== "_" && declaredPropKeys.includes(key)) { - this._setProp(key, this[key]); - } - } - for (const key of declaredPropKeys.map(shared.camelize)) { - Object.defineProperty(this, key, { - get() { - return this._getProp(key); - }, - set(val) { - this._setProp(key, val, true, !this._patching); - } - }); - } - } - _setAttr(key) { - if (key.startsWith("data-v-")) return; - const has = this.hasAttribute(key); - let value = has ? this.getAttribute(key) : REMOVAL; - const camelKey = shared.camelize(key); - if (has && this._numberProps && this._numberProps[camelKey]) { - value = shared.toNumber(value); - } - this._setProp(camelKey, value, false, true); - } - /** - * @internal - */ - _getProp(key) { - return this._props[key]; - } - /** - * @internal - */ - _setProp(key, val, shouldReflect = true, shouldUpdate = false) { - if (val !== this._props[key]) { - this._dirty = true; - if (val === REMOVAL) { - delete this._props[key]; - } else { - this._props[key] = val; - if (key === "key" && this._app) { - this._app._ceVNode.key = val; - } - } - if (shouldUpdate && this._instance) { - this._update(); - } - if (shouldReflect) { - const ob = this._ob; - if (ob) { - this._processMutations(ob.takeRecords()); - ob.disconnect(); - } - if (val === true) { - this.setAttribute(shared.hyphenate(key), ""); - } else if (typeof val === "string" || typeof val === "number") { - this.setAttribute(shared.hyphenate(key), val + ""); - } else if (!val) { - this.removeAttribute(shared.hyphenate(key)); - } - ob && ob.observe(this, { attributes: true }); - } - } - } - _update() { - const vnode = this._createVNode(); - if (this._app) vnode.appContext = this._app._context; - render(vnode, this._root); - } - _createVNode() { - const baseProps = {}; - if (!this.shadowRoot) { - baseProps.onVnodeMounted = baseProps.onVnodeUpdated = this._renderSlots.bind(this); - } - const vnode = runtimeCore.createVNode(this._def, shared.extend(baseProps, this._props)); - if (!this._instance) { - vnode.ce = (instance) => { - this._instance = instance; - instance.ce = this; - instance.isCE = true; - const dispatch = (event, args) => { - this.dispatchEvent( - new CustomEvent( - event, - shared.isPlainObject(args[0]) ? shared.extend({ detail: args }, args[0]) : { detail: args } - ) - ); - }; - instance.emit = (event, ...args) => { - dispatch(event, args); - if (shared.hyphenate(event) !== event) { - dispatch(shared.hyphenate(event), args); - } - }; - this._setParent(); - }; - } - return vnode; - } - _applyStyles(styles, owner, parentComp) { - if (!styles) return; - if (owner) { - if (owner === this._def || this._styleChildren.has(owner)) { - return; - } - this._styleChildren.add(owner); - } - const nonce = this._nonce; - const root = this.shadowRoot; - const insertionAnchor = parentComp ? this._getStyleAnchor(parentComp) || this._getStyleAnchor(this._def) : this._getRootStyleInsertionAnchor(root); - let last = null; - for (let i = styles.length - 1; i >= 0; i--) { - const s = document.createElement("style"); - if (nonce) s.setAttribute("nonce", nonce); - s.textContent = styles[i]; - root.insertBefore(s, last || insertionAnchor); - last = s; - if (i === 0) { - if (!parentComp) this._styleAnchors.set(this._def, s); - if (owner) this._styleAnchors.set(owner, s); - } - } - } - _getStyleAnchor(comp) { - if (!comp) { - return null; - } - const anchor = this._styleAnchors.get(comp); - if (anchor && anchor.parentNode === this.shadowRoot) { - return anchor; - } - if (anchor) { - this._styleAnchors.delete(comp); - } - return null; - } - _getRootStyleInsertionAnchor(root) { - for (let i = 0; i < root.childNodes.length; i++) { - const node = root.childNodes[i]; - if (!(node instanceof HTMLStyleElement)) { - return node; - } - } - return null; - } - /** - * Only called when shadowRoot is false - */ - _parseSlots() { - const slots = this._slots = {}; - let n; - while (n = this.firstChild) { - const slotName = n.nodeType === 1 && n.getAttribute("slot") || "default"; - (slots[slotName] || (slots[slotName] = [])).push(n); - this.removeChild(n); - } - } - /** - * Only called when shadowRoot is false - */ - _renderSlots() { - const outlets = this._getSlots(); - const scopeId = this._instance.type.__scopeId; - for (let i = 0; i < outlets.length; i++) { - const o = outlets[i]; - const slotName = o.getAttribute("name") || "default"; - const content = this._slots[slotName]; - const parent = o.parentNode; - if (content) { - for (const n of content) { - if (scopeId && n.nodeType === 1) { - const id = scopeId + "-s"; - const walker = document.createTreeWalker(n, 1); - n.setAttribute(id, ""); - let child; - while (child = walker.nextNode()) { - child.setAttribute(id, ""); - } - } - parent.insertBefore(n, o); - } - } else { - while (o.firstChild) parent.insertBefore(o.firstChild, o); - } - parent.removeChild(o); - } - } - /** - * @internal - */ - _getSlots() { - const roots = [this]; - if (this._teleportTargets) { - roots.push(...this._teleportTargets); - } - const slots = /* @__PURE__ */ new Set(); - for (const root of roots) { - const found = root.querySelectorAll("slot"); - for (let i = 0; i < found.length; i++) { - slots.add(found[i]); - } - } - return Array.from(slots); - } - /** - * @internal - */ - _injectChildStyle(comp, parentComp) { - this._applyStyles(comp.styles, comp, parentComp); - } - /** - * @internal - */ - _beginPatch() { - this._patching = true; - this._dirty = false; - } - /** - * @internal - */ - _endPatch() { - this._patching = false; - if (this._dirty && this._instance) { - this._update(); - } - } - /** - * @internal - */ - _hasShadowRoot() { - return this._def.shadowRoot !== false; - } - /** - * @internal - */ - _removeChildStyle(comp) { - } - }; - function useHost(caller) { - const instance = runtimeCore.getCurrentInstance(); - const el = instance && instance.ce; - if (el) { - return el; - } - return null; - } - function useShadowRoot() { - const el = useHost(); - return el && el.shadowRoot; - } - function useCssModule(name = "$style") { - { - const instance = runtimeCore.getCurrentInstance(); - if (!instance) { - return shared.EMPTY_OBJ; - } - const modules = instance.type.__cssModules; - if (!modules) { - return shared.EMPTY_OBJ; - } - const mod = modules[name]; - if (!mod) { - return shared.EMPTY_OBJ; - } - return mod; - } - } - var positionMap = /* @__PURE__ */ new WeakMap(); - var newPositionMap = /* @__PURE__ */ new WeakMap(); - var moveCbKey = /* @__PURE__ */ Symbol("_moveCb"); - var enterCbKey = /* @__PURE__ */ Symbol("_enterCb"); - var pendingGroups = /* @__PURE__ */ new WeakMap(); - var decorate = (t) => { - delete t.props.mode; - return t; - }; - var TransitionGroupImpl = /* @__PURE__ */ decorate({ - name: "TransitionGroup", - props: /* @__PURE__ */ shared.extend({}, TransitionPropsValidators, { - tag: String, - moveClass: String - }), - setup(props, { slots }) { - const instance = runtimeCore.getCurrentInstance(); - const state = runtimeCore.useTransitionState(); - let prevChildren; - let children; - let origins; - let moves; - const willMove = () => { - if (moves === void 0) { - moves = prevChildren.length > 0 && hasCSSTransform( - prevChildren[0].el, - instance.vnode.el, - resolveMoveClass(props) - ); - } - return moves; - }; - runtimeCore.onUpdated(() => { - pendingGroups.delete(instance); - if (!willMove()) { - prevChildren = []; - origins = void 0; - return; - } - const moveClass = resolveMoveClass(props); - prevChildren.forEach(callPendingCbs); - const shift = origins && getOriginShift(origins, instance.vnode.el); - origins = void 0; - prevChildren.forEach((c) => recordPosition(c, shift)); - const movedChildren = prevChildren.filter(applyTranslation); - forceReflow(instance.vnode.el); - movedChildren.forEach((c) => { - const el = c.el; - const style = el.style; - addTransitionClass(el, moveClass); - style.transform = style.webkitTransform = style.transitionDuration = ""; - const cb = el[moveCbKey] = (e) => { - if (e && e.target !== el) { - return; - } - if (!e || e.propertyName.endsWith("transform")) { - el.removeEventListener("transitionend", cb); - el[moveCbKey] = null; - removeTransitionClass(el, moveClass); - } - }; - el.addEventListener("transitionend", cb); - }); - prevChildren = []; - }); - return () => { - const rawProps = runtimeCore.toRaw(props); - const cssTransitionProps = resolveTransitionProps(rawProps); - let tag = rawProps.tag || runtimeCore.Fragment; - prevChildren = []; - moves = void 0; - if (children) { - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (child.el && child.el instanceof Element && // Hidden v-show nodes have no previous layout box to animate from. - !child.el[vShowHidden]) { - prevChildren.push(child); - runtimeCore.setTransitionHooks( - child, - runtimeCore.resolveTransitionHooks( - child, - cssTransitionProps, - state, - instance - ) - ); - positionMap.set(child, getPosition(child.el)); - } - } - } - children = slots.default ? runtimeCore.getTransitionRawChildren(slots.default()) : []; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (child.key != null) { - runtimeCore.setTransitionHooks( - child, - runtimeCore.resolveTransitionHooks(child, cssTransitionProps, state, instance) - ); - } - } - if (prevChildren.length) { - origins = getOrigins(instance); - pendingGroups.set(instance, willMove); - } - return runtimeCore.createVNode(tag, null, children); - }; - } - }); - var TransitionGroup = TransitionGroupImpl; - function callPendingCbs(c) { - const el = c.el; - if (el[moveCbKey]) { - el[moveCbKey](); - } - if (el[enterCbKey]) { - el[enterCbKey](); - } - } - function resolveMoveClass(props) { - return props.moveClass || `${props.name || "v"}-move`; - } - function recordPosition(c, shift) { - newPositionMap.set(c, getPosition(c.el, shift)); - } - function applyTranslation(c) { - const oldPos = positionMap.get(c); - const newPos = newPositionMap.get(c); - const dx = oldPos.left - newPos.left; - const dy = oldPos.top - newPos.top; - if (dx || dy) { - const el = c.el; - const s = el.style; - const rect = el.getBoundingClientRect(); - let scaleX = 1; - let scaleY = 1; - if (el.offsetWidth) scaleX = rect.width / el.offsetWidth; - if (el.offsetHeight) scaleY = rect.height / el.offsetHeight; - if (!Number.isFinite(scaleX) || scaleX === 0) scaleX = 1; - if (!Number.isFinite(scaleY) || scaleY === 0) scaleY = 1; - if (Math.abs(scaleX - 1) < 0.01) scaleX = 1; - if (Math.abs(scaleY - 1) < 0.01) scaleY = 1; - s.transform = s.webkitTransform = `translate(${dx / scaleX}px,${dy / scaleY}px)`; - s.transitionDuration = "0s"; - return c; - } - } - function getPosition(el, shift) { - const rect = el.getBoundingClientRect(); - return { - left: rect.left - (shift ? shift.left : 0), - top: rect.top - (shift ? shift.top : 0) - }; - } - function getOrigins(instance) { - let origins; - for (let group = instance.parent; group; group = group.parent) { - const willMove = pendingGroups.get(group); - if (willMove) { - const item = findItem(group.vnode.el, instance.vnode.el); - if (item) { - (origins || (origins = [])).push( - shared.extend(getPosition(item), { item, willMove }) - ); - } - } - } - return origins; - } - function findItem(root, node) { - const container = root.nodeType === 1 ? root : root.parentNode; - while (node && node.parentNode !== container) { - node = node.parentNode; - } - if (node && node.nodeType === 1) { - return node; - } - } - function getOriginShift(origins, root) { - const origin = origins.find((o) => o.willMove() && o.item.contains(root)); - return origin && getPosition(origin.item, origin); - } - function hasCSSTransform(el, root, moveClass) { - const clone = el.cloneNode(); - const _vtc = el[vtcKey]; - if (_vtc) { - _vtc.forEach((cls) => { - cls.split(/\s+/).forEach((c) => c && clone.classList.remove(c)); - }); - } - moveClass.split(/\s+/).forEach((c) => c && clone.classList.add(c)); - clone.style.display = "none"; - const container = root.nodeType === 1 ? root : root.parentNode; - container.appendChild(clone); - const { hasTransform } = getTransitionInfo(clone); - container.removeChild(clone); - return hasTransform; - } - var getModelAssigner = (vnode) => { - const fn = vnode.props["onUpdate:modelValue"] || false; - return shared.isArray(fn) ? (value) => shared.invokeArrayFns(fn, value) : fn; - }; - function onCompositionStart(e) { - e.target.composing = true; - } - function onCompositionEnd(e) { - const target = e.target; - if (target.composing) { - target.composing = false; - target.dispatchEvent(new Event("input")); - } - } - var assignKey = /* @__PURE__ */ Symbol("_assign"); - var initialValueKey = /* @__PURE__ */ Symbol("_initialValue"); - function castValue(value, trim, number) { - if (trim) value = value.trim(); - if (number) value = shared.looseToNumber(value); - return value; - } - var vModelText = { - created(el, { modifiers: { lazy, trim, number } }, vnode) { - if (el.parentNode) { - if (el.type === "text") { - el[initialValueKey] = el.defaultValue.replace(/[\r\n]/g, ""); - } else if (el.type === "textarea") { - el[initialValueKey] = el.defaultValue.replace(/\r\n?/g, "\n"); - } - } - el[assignKey] = getModelAssigner(vnode); - const castToNumber = number || vnode.props && vnode.props.type === "number"; - addEventListener2(el, lazy ? "change" : "input", (e) => { - if (e.target.composing) return; - el[assignKey](castValue(el.value, trim, castToNumber)); - }); - if (trim || castToNumber) { - addEventListener2(el, "change", () => { - el.value = castValue(el.value, trim, castToNumber); - }); - } - if (!lazy) { - addEventListener2(el, "compositionstart", onCompositionStart); - addEventListener2(el, "compositionend", onCompositionEnd); - addEventListener2(el, "change", onCompositionEnd); - } - }, - // set value on mounted so it's after min/max for type="range" - mounted(el, { value, modifiers: { trim, number } }) { - const newValue = value == null ? "" : value; - const initialValue = el[initialValueKey]; - delete el[initialValueKey]; - if (initialValue !== void 0 && (el.type === "text" || el.type === "textarea") && el.value !== initialValue) { - el[assignKey](castValue(el.value, trim, number)); - } else { - el.value = newValue; - } - }, - beforeUpdate(el, { value, oldValue, modifiers: { lazy, trim, number } }, vnode) { - el[assignKey] = getModelAssigner(vnode); - if (el.composing) return; - const elValue = (number || el.type === "number") && !/^0\d/.test(el.value) ? shared.looseToNumber(el.value) : el.value; - const newValue = value == null ? "" : value; - if (elValue === newValue) { - return; - } - const rootNode = el.getRootNode(); - if ((rootNode instanceof Document || rootNode instanceof ShadowRoot) && rootNode.activeElement === el && el.type !== "range") { - if (lazy && value === oldValue) { - return; - } - if (trim && el.value.trim() === newValue) { - return; - } - } - el.value = newValue; - } - }; - var vModelCheckbox = { - // #4096 array checkboxes need to be deep traversed - deep: true, - created(el, _, vnode) { - el[assignKey] = getModelAssigner(vnode); - addEventListener2(el, "change", () => { - const modelValue = el._modelValue; - const elementValue = getValue(el); - const checked = el.checked; - const assign = el[assignKey]; - if (shared.isArray(modelValue)) { - const index = shared.looseIndexOf(modelValue, elementValue); - const found = index !== -1; - if (checked && !found) { - assign(modelValue.concat(elementValue)); - } else if (!checked && found) { - const filtered = [...modelValue]; - filtered.splice(index, 1); - assign(filtered); - } - } else if (shared.isSet(modelValue)) { - const cloned = new Set(modelValue); - if (checked) { - cloned.add(elementValue); - } else { - cloned.delete(elementValue); - } - assign(cloned); - } else { - assign(getCheckboxValue(el, checked)); - } - }); - }, - // set initial checked on mount to wait for true-value/false-value - mounted: setChecked, - beforeUpdate(el, binding, vnode) { - el[assignKey] = getModelAssigner(vnode); - setChecked(el, binding, vnode); - } - }; - function setChecked(el, { value, oldValue }, vnode) { - el._modelValue = value; - let checked; - if (shared.isArray(value)) { - checked = shared.looseIndexOf(value, vnode.props.value) > -1; - } else if (shared.isSet(value)) { - checked = value.has(vnode.props.value); - } else { - if (value === oldValue) return; - checked = shared.looseEqual(value, getCheckboxValue(el, true)); - } - if (el.checked !== checked) { - el.checked = checked; - } - } - var vModelRadio = { - created(el, { value }, vnode) { - el.checked = shared.looseEqual(value, vnode.props.value); - el[assignKey] = getModelAssigner(vnode); - addEventListener2(el, "change", () => { - el[assignKey](getValue(el)); - }); - }, - beforeUpdate(el, { value, oldValue }, vnode) { - el[assignKey] = getModelAssigner(vnode); - if (value !== oldValue) { - el.checked = shared.looseEqual(value, vnode.props.value); - } - } - }; - var vModelSelect = { - // <select multiple> value need to be deep traversed - deep: true, - created(el, { value, modifiers: { number } }, vnode) { - el._modelValue = value; - addEventListener2(el, "change", () => { - const selectedVal = Array.prototype.filter.call(el.options, (o) => o.selected).map( - (o) => number ? shared.looseToNumber(getValue(o)) : getValue(o) - ); - const multiple = el.multiple; - const assignedValue = multiple ? shared.isSet(el._modelValue) ? new Set(selectedVal) : selectedVal : selectedVal[0]; - const pending = el._pendingValue = [ - multiple, - multiple ? shared.isArray(assignedValue) ? selectedVal.slice() : selectedVal : assignedValue - ]; - try { - el[assignKey](assignedValue); - } finally { - runtimeCore.nextTick(() => { - if (el._pendingValue === pending) { - el._pendingValue = void 0; - } - }); - } - }); - el[assignKey] = getModelAssigner(vnode); - }, - // set value in mounted & updated because <select> relies on its children - // <option>s. - mounted(el, { value }) { - setSelected(el, value); - }, - beforeUpdate(el, { value }, vnode) { - el._modelValue = value; - el[assignKey] = getModelAssigner(vnode); - }, - updated(el, { value }) { - const pending = el._pendingValue; - el._pendingValue = void 0; - if (!pending || pending[0] !== el.multiple || !isSameSelectValue(value, pending[1], pending[0])) { - setSelected(el, value); - } - } - }; - function isSameSelectValue(value, assignedValue, multiple) { - if (!multiple) return shared.looseEqual(value, assignedValue); - if (shared.isArray(value)) return shared.looseEqual(value, assignedValue); - if (shared.isSet(value)) { - if (value.size !== assignedValue.length) return false; - for (const item of assignedValue) { - if (!value.has(item)) return false; - } - return true; - } - return false; - } - function setSelected(el, value) { - const isMultiple = el.multiple; - const isArrayValue = shared.isArray(value); - if (isMultiple && !isArrayValue && !shared.isSet(value)) { - return; - } - for (let i = 0, l = el.options.length; i < l; i++) { - const option = el.options[i]; - const optionValue = getValue(option); - if (isMultiple) { - if (isArrayValue) { - const optionType = typeof optionValue; - if (optionType === "string" || optionType === "number") { - option.selected = value.some((v) => String(v) === String(optionValue)); - } else { - option.selected = shared.looseIndexOf(value, optionValue) > -1; - } - } else { - option.selected = value.has(optionValue); - } - } else if (shared.looseEqual(getValue(option), value)) { - if (el.selectedIndex !== i) el.selectedIndex = i; - return; - } - } - if (!isMultiple && el.selectedIndex !== -1) { - el.selectedIndex = -1; - } - } - function getValue(el) { - return "_value" in el ? el._value : el.value; - } - function getCheckboxValue(el, checked) { - const key = checked ? "_trueValue" : "_falseValue"; - return key in el ? el[key] : checked; - } - var vModelDynamic = { - created(el, binding, vnode) { - callModelHook(el, binding, vnode, null, "created"); - }, - mounted(el, binding, vnode) { - callModelHook(el, binding, vnode, null, "mounted"); - }, - beforeUpdate(el, binding, vnode, prevVNode) { - callModelHook(el, binding, vnode, prevVNode, "beforeUpdate"); - }, - updated(el, binding, vnode, prevVNode) { - callModelHook(el, binding, vnode, prevVNode, "updated"); - } - }; - function resolveDynamicModel(tagName, type) { - switch (tagName) { - case "SELECT": - return vModelSelect; - case "TEXTAREA": - return vModelText; - default: - switch (type) { - case "checkbox": - return vModelCheckbox; - case "radio": - return vModelRadio; - default: - return vModelText; - } - } - } - function callModelHook(el, binding, vnode, prevVNode, hook) { - const modelToUse = resolveDynamicModel( - el.tagName, - vnode.props && vnode.props.type - ); - const fn = modelToUse[hook]; - fn && fn(el, binding, vnode, prevVNode); - } - function initVModelForSSR() { - vModelText.getSSRProps = ({ value }) => ({ value }); - vModelRadio.getSSRProps = ({ value }, vnode) => { - if (vnode.props && shared.looseEqual(vnode.props.value, value)) { - return { checked: true }; - } - }; - vModelCheckbox.getSSRProps = ({ value }, vnode) => { - if (shared.isArray(value)) { - if (vnode.props && shared.looseIndexOf(value, vnode.props.value) > -1) { - return { checked: true }; - } - } else if (shared.isSet(value)) { - if (vnode.props && value.has(vnode.props.value)) { - return { checked: true }; - } - } else if (value) { - return { checked: true }; - } - }; - vModelDynamic.getSSRProps = (binding, vnode) => { - if (typeof vnode.type !== "string") { - return; - } - const modelToUse = resolveDynamicModel( - // resolveDynamicModel expects an uppercase tag name, but vnode.type is lowercase - vnode.type.toUpperCase(), - vnode.props && vnode.props.type - ); - if (modelToUse.getSSRProps) { - return modelToUse.getSSRProps(binding, vnode); - } - }; - } - var systemModifiers = ["ctrl", "shift", "alt", "meta"]; - var modifierGuards = { - stop: (e) => e.stopPropagation(), - prevent: (e) => e.preventDefault(), - self: (e) => e.target !== e.currentTarget, - ctrl: (e) => !e.ctrlKey, - shift: (e) => !e.shiftKey, - alt: (e) => !e.altKey, - meta: (e) => !e.metaKey, - left: (e) => "button" in e && e.button !== 0, - middle: (e) => "button" in e && e.button !== 1, - right: (e) => "button" in e && e.button !== 2, - exact: (e, modifiers) => systemModifiers.some((m) => e[`${m}Key`] && !modifiers.includes(m)) - }; - var withModifiers = (fn, modifiers) => { - if (!fn) return fn; - const cache = fn._withMods || (fn._withMods = {}); - const cacheKey = modifiers.join("."); - return cache[cacheKey] || (cache[cacheKey] = (event, ...args) => { - for (let i = 0; i < modifiers.length; i++) { - const guard = modifierGuards[modifiers[i]]; - if (guard && guard(event, modifiers)) return; - } - return fn(event, ...args); - }); - }; - var keyNames = { - esc: "escape", - space: " ", - up: "arrow-up", - left: "arrow-left", - right: "arrow-right", - down: "arrow-down", - delete: "backspace" - }; - var withKeys = (fn, modifiers) => { - const cache = fn._withKeys || (fn._withKeys = {}); - const cacheKey = modifiers.join("."); - return cache[cacheKey] || (cache[cacheKey] = (event) => { - if (!("key" in event)) { - return; - } - const eventKey = shared.hyphenate(event.key); - if (modifiers.some( - (k) => k === eventKey || keyNames[k] === eventKey - )) { - return fn(event); - } - }); - }; - var rendererOptions = /* @__PURE__ */ shared.extend({ patchProp }, nodeOps); - var renderer; - var enabledHydration = false; - function ensureRenderer() { - return renderer || (renderer = runtimeCore.createRenderer(rendererOptions)); - } - function ensureHydrationRenderer() { - renderer = enabledHydration ? renderer : runtimeCore.createHydrationRenderer(rendererOptions); - enabledHydration = true; - return renderer; - } - var render = (...args) => { - ensureRenderer().render(...args); - }; - var hydrate = (...args) => { - ensureHydrationRenderer().hydrate(...args); - }; - var createApp = (...args) => { - const app = ensureRenderer().createApp(...args); - const { mount } = app; - app.mount = (containerOrSelector) => { - const container = normalizeContainer(containerOrSelector); - if (!container) return; - const component = app._component; - if (!shared.isFunction(component) && !component.render && !component.template) { - component.template = container.innerHTML; - } - if (container.nodeType === 1) { - container.textContent = ""; - } - const proxy = mount(container, false, resolveRootNamespace(container)); - if (container instanceof Element) { - container.removeAttribute("v-cloak"); - container.setAttribute("data-v-app", ""); - } - return proxy; - }; - return app; - }; - var createSSRApp = (...args) => { - const app = ensureHydrationRenderer().createApp(...args); - const { mount } = app; - app.mount = (containerOrSelector) => { - const container = normalizeContainer(containerOrSelector); - if (container) { - return mount(container, true, resolveRootNamespace(container)); - } - }; - return app; - }; - function resolveRootNamespace(container) { - if (container instanceof SVGElement) { - return "svg"; - } - if (typeof MathMLElement === "function" && container instanceof MathMLElement) { - return "mathml"; - } - } - function normalizeContainer(container) { - if (shared.isString(container)) { - const res = document.querySelector(container); - return res; - } - return container; - } - var ssrDirectiveInitialized = false; - var initDirectivesForSSR = () => { - if (!ssrDirectiveInitialized) { - ssrDirectiveInitialized = true; - initVModelForSSR(); - initVShowForSSR(); - } - }; - exports2.Transition = Transition; - exports2.TransitionGroup = TransitionGroup; - exports2.VueElement = VueElement; - exports2.createApp = createApp; - exports2.createSSRApp = createSSRApp; - exports2.defineCustomElement = defineCustomElement; - exports2.defineSSRCustomElement = defineSSRCustomElement; - exports2.hydrate = hydrate; - exports2.initDirectivesForSSR = initDirectivesForSSR; - exports2.nodeOps = nodeOps; - exports2.patchProp = patchProp; - exports2.render = render; - exports2.useCssModule = useCssModule; - exports2.useCssVars = useCssVars; - exports2.useHost = useHost; - exports2.useShadowRoot = useShadowRoot; - exports2.vModelCheckbox = vModelCheckbox; - exports2.vModelDynamic = vModelDynamic; - exports2.vModelRadio = vModelRadio; - exports2.vModelSelect = vModelSelect; - exports2.vModelText = vModelText; - exports2.vShow = vShow; - exports2.withKeys = withKeys; - exports2.withModifiers = withModifiers; - Object.keys(runtimeCore).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports2, k)) exports2[k] = runtimeCore[k]; - }); - } -}); - -// intern-log/node_modules/.pnpm/@vue+runtime-dom@3.5.44/node_modules/@vue/runtime-dom/dist/runtime-dom.cjs.js -var require_runtime_dom_cjs = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+runtime-dom@3.5.44/node_modules/@vue/runtime-dom/dist/runtime-dom.cjs.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var runtimeCore = require_runtime_core(); - var shared = require_shared(); - var policy = void 0; - var tt = typeof window !== "undefined" && window.trustedTypes; - if (tt) { - try { - policy = /* @__PURE__ */ tt.createPolicy("vue", { - createHTML: (val) => val - }); - } catch (e) { - runtimeCore.warn(`Error creating trusted types policy: ${e}`); - } - } - var unsafeToTrustedHTML = policy ? (val) => policy.createHTML(val) : (val) => val; - var svgNS = "http://www.w3.org/2000/svg"; - var mathmlNS = "http://www.w3.org/1998/Math/MathML"; - var doc = typeof document !== "undefined" ? document : null; - var templateContainer = doc && /* @__PURE__ */ doc.createElement("template"); - var nodeOps = { - insert: (child, parent, anchor) => { - parent.insertBefore(child, anchor || null); - }, - remove: (child) => { - const parent = child.parentNode; - if (parent) { - parent.removeChild(child); - } - }, - createElement: (tag, namespace, is, props) => { - const el = namespace === "svg" ? doc.createElementNS(svgNS, tag) : namespace === "mathml" ? doc.createElementNS(mathmlNS, tag) : is ? doc.createElement(tag, { is }) : doc.createElement(tag); - if (tag === "select" && props && props.multiple != null) { - el.setAttribute("multiple", props.multiple); - } - return el; - }, - createText: (text) => doc.createTextNode(text), - createComment: (text) => doc.createComment(text), - setText: (node, text) => { - node.nodeValue = text; - }, - setElementText: (el, text) => { - el.textContent = text; - }, - parentNode: (node) => node.parentNode, - nextSibling: (node) => node.nextSibling, - querySelector: (selector) => doc.querySelector(selector), - setScopeId(el, id) { - el.setAttribute(id, ""); - }, - // __UNSAFE__ - // Reason: innerHTML. - // Static content here can only come from compiled templates. - // As long as the user only uses trusted templates, this is safe. - insertStaticContent(content, parent, anchor, namespace, start, end) { - const before = anchor ? anchor.previousSibling : parent.lastChild; - if (start && (start === end || start.nextSibling)) { - while (true) { - parent.insertBefore(start.cloneNode(true), anchor); - if (start === end || !(start = start.nextSibling)) break; - } - } else { - templateContainer.innerHTML = unsafeToTrustedHTML( - namespace === "svg" ? `<svg>${content}</svg>` : namespace === "mathml" ? `<math>${content}</math>` : content - ); - const template = templateContainer.content; - if (namespace === "svg" || namespace === "mathml") { - const wrapper = template.firstChild; - while (wrapper.firstChild) { - template.appendChild(wrapper.firstChild); - } - template.removeChild(wrapper); - } - parent.insertBefore(template, anchor); - } - return [ - // first - before ? before.nextSibling : parent.firstChild, - // last - anchor ? anchor.previousSibling : parent.lastChild - ]; - } - }; - var TRANSITION = "transition"; - var ANIMATION = "animation"; - var vtcKey = /* @__PURE__ */ Symbol("_vtc"); - var DOMTransitionPropsValidators = { - name: String, - type: String, - css: { - type: Boolean, - default: true - }, - duration: [String, Number, Object], - enterFromClass: String, - enterActiveClass: String, - enterToClass: String, - appearFromClass: String, - appearActiveClass: String, - appearToClass: String, - leaveFromClass: String, - leaveActiveClass: String, - leaveToClass: String - }; - var TransitionPropsValidators = /* @__PURE__ */ shared.extend( - {}, - runtimeCore.BaseTransitionPropsValidators, - DOMTransitionPropsValidators - ); - var decorate$1 = (t) => { - t.displayName = "Transition"; - t.props = TransitionPropsValidators; - return t; - }; - var Transition = /* @__PURE__ */ decorate$1( - (props, { slots }) => runtimeCore.h(runtimeCore.BaseTransition, resolveTransitionProps(props), slots) - ); - var callHook = (hook, args = []) => { - if (shared.isArray(hook)) { - hook.forEach((h2) => h2(...args)); - } else if (hook) { - hook(...args); - } - }; - var hasExplicitCallback = (hook) => { - return hook ? shared.isArray(hook) ? hook.some((h2) => h2.length > 1) : hook.length > 1 : false; - }; - function resolveTransitionProps(rawProps) { - const baseProps = {}; - for (const key in rawProps) { - if (!(key in DOMTransitionPropsValidators)) { - baseProps[key] = rawProps[key]; - } - } - if (rawProps.css === false) { - return baseProps; - } - const { - name = "v", - type, - duration, - enterFromClass = `${name}-enter-from`, - enterActiveClass = `${name}-enter-active`, - enterToClass = `${name}-enter-to`, - appearFromClass = enterFromClass, - appearActiveClass = enterActiveClass, - appearToClass = enterToClass, - leaveFromClass = `${name}-leave-from`, - leaveActiveClass = `${name}-leave-active`, - leaveToClass = `${name}-leave-to` - } = rawProps; - const durations = normalizeDuration(duration); - const enterDuration = durations && durations[0]; - const leaveDuration = durations && durations[1]; - const { - onBeforeEnter, - onEnter, - onEnterCancelled, - onLeave, - onLeaveCancelled, - onBeforeAppear = onBeforeEnter, - onAppear = onEnter, - onAppearCancelled = onEnterCancelled - } = baseProps; - const finishEnter = (el, isAppear, done, isCancelled) => { - el._enterCancelled = isCancelled; - removeTransitionClass(el, isAppear ? appearToClass : enterToClass); - removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass); - done && done(); - }; - const finishLeave = (el, done) => { - el._isLeaving = false; - removeTransitionClass(el, leaveFromClass); - removeTransitionClass(el, leaveToClass); - removeTransitionClass(el, leaveActiveClass); - done && done(); - }; - const makeEnterHook = (isAppear) => { - return (el, done) => { - const hook = isAppear ? onAppear : onEnter; - const resolve = () => finishEnter(el, isAppear, done); - callHook(hook, [el, resolve]); - nextFrame(() => { - removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass); - addTransitionClass(el, isAppear ? appearToClass : enterToClass); - if (!hasExplicitCallback(hook)) { - whenTransitionEnds(el, type, enterDuration, resolve); - } - }); - }; - }; - return shared.extend(baseProps, { - onBeforeEnter(el) { - callHook(onBeforeEnter, [el]); - addTransitionClass(el, enterFromClass); - addTransitionClass(el, enterActiveClass); - }, - onBeforeAppear(el) { - callHook(onBeforeAppear, [el]); - addTransitionClass(el, appearFromClass); - addTransitionClass(el, appearActiveClass); - }, - onEnter: makeEnterHook(false), - onAppear: makeEnterHook(true), - onLeave(el, done) { - el._isLeaving = true; - const resolve = () => finishLeave(el, done); - addTransitionClass(el, leaveFromClass); - if (!el._enterCancelled) { - forceReflow(el); - addTransitionClass(el, leaveActiveClass); - } else { - addTransitionClass(el, leaveActiveClass); - forceReflow(el); - } - nextFrame(() => { - if (!el._isLeaving) { - return; - } - removeTransitionClass(el, leaveFromClass); - addTransitionClass(el, leaveToClass); - if (!hasExplicitCallback(onLeave)) { - whenTransitionEnds(el, type, leaveDuration, resolve); - } - }); - callHook(onLeave, [el, resolve]); - }, - onEnterCancelled(el) { - finishEnter(el, false, void 0, true); - callHook(onEnterCancelled, [el]); - }, - onAppearCancelled(el) { - finishEnter(el, true, void 0, true); - callHook(onAppearCancelled, [el]); - }, - onLeaveCancelled(el) { - finishLeave(el); - callHook(onLeaveCancelled, [el]); - } - }); - } - function normalizeDuration(duration) { - if (duration == null) { - return null; - } else if (shared.isObject(duration)) { - return [NumberOf(duration.enter), NumberOf(duration.leave)]; - } else { - const n = NumberOf(duration); - return [n, n]; - } - } - function NumberOf(val) { - const res = shared.toNumber(val); - { - runtimeCore.assertNumber(res, "<transition> explicit duration"); - } - return res; - } - function addTransitionClass(el, cls) { - cls.split(/\s+/).forEach((c) => c && el.classList.add(c)); - (el[vtcKey] || (el[vtcKey] = /* @__PURE__ */ new Set())).add(cls); - } - function removeTransitionClass(el, cls) { - cls.split(/\s+/).forEach((c) => c && el.classList.remove(c)); - const _vtc = el[vtcKey]; - if (_vtc) { - _vtc.delete(cls); - if (!_vtc.size) { - el[vtcKey] = void 0; - } - } - } - function nextFrame(cb) { - requestAnimationFrame(() => { - requestAnimationFrame(cb); - }); - } - var endId = 0; - function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) { - const id = el._endId = ++endId; - const resolveIfNotStale = () => { - if (id === el._endId) { - resolve(); - } - }; - if (explicitTimeout != null) { - return setTimeout(resolveIfNotStale, explicitTimeout); - } - const { type, timeout, propCount } = getTransitionInfo(el, expectedType); - if (!type) { - return resolve(); - } - const endEvent = type + "end"; - let ended = 0; - const end = () => { - el.removeEventListener(endEvent, onEnd); - resolveIfNotStale(); - }; - const onEnd = (e) => { - if (e.target === el && ++ended >= propCount) { - end(); - } - }; - setTimeout(() => { - if (ended < propCount) { - end(); - } - }, timeout + 1); - el.addEventListener(endEvent, onEnd); - } - function getTransitionInfo(el, expectedType) { - const styles = window.getComputedStyle(el); - const getStyleProperties = (key) => (styles[key] || "").split(", "); - const transitionDelays = getStyleProperties(`${TRANSITION}Delay`); - const transitionDurations = getStyleProperties(`${TRANSITION}Duration`); - const transitionTimeout = getTimeout(transitionDelays, transitionDurations); - const animationDelays = getStyleProperties(`${ANIMATION}Delay`); - const animationDurations = getStyleProperties(`${ANIMATION}Duration`); - const animationTimeout = getTimeout(animationDelays, animationDurations); - let type = null; - let timeout = 0; - let propCount = 0; - if (expectedType === TRANSITION) { - if (transitionTimeout > 0) { - type = TRANSITION; - timeout = transitionTimeout; - propCount = transitionDurations.length; - } - } else if (expectedType === ANIMATION) { - if (animationTimeout > 0) { - type = ANIMATION; - timeout = animationTimeout; - propCount = animationDurations.length; - } - } else { - timeout = Math.max(transitionTimeout, animationTimeout); - type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; - propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; - } - const hasTransform = type === TRANSITION && /\b(?:transform|all)(?:,|$)/.test( - getStyleProperties(`${TRANSITION}Property`).toString() - ); - return { - type, - timeout, - propCount, - hasTransform - }; - } - function getTimeout(delays, durations) { - while (delays.length < durations.length) { - delays = delays.concat(delays); - } - return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i]))); - } - function toMs(s) { - if (s === "auto") return 0; - return Number(s.slice(0, -1).replace(",", ".")) * 1e3; - } - function forceReflow(el) { - const targetDocument = el ? el.ownerDocument : document; - return targetDocument.body.offsetHeight; - } - function patchClass(el, value, isSVG) { - const transitionClasses = el[vtcKey]; - if (transitionClasses) { - value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(" "); - } - if (value == null) { - el.removeAttribute("class"); - } else if (isSVG) { - el.setAttribute("class", value); - } else { - el.className = value; - } - } - var vShowOriginalDisplay = /* @__PURE__ */ Symbol("_vod"); - var vShowHidden = /* @__PURE__ */ Symbol("_vsh"); - var vShow = { - // used for prop mismatch check during hydration - name: "show", - beforeMount(el, { value }, { transition }) { - el[vShowOriginalDisplay] = el.style.display === "none" ? "" : el.style.display; - if (transition && value) { - transition.beforeEnter(el); - } else { - setDisplay(el, value); - } - }, - mounted(el, { value }, { transition }) { - if (transition && value) { - transition.enter(el); - } - }, - updated(el, { value, oldValue }, { transition }) { - if (!value === !oldValue) return; - if (transition) { - if (value) { - transition.beforeEnter(el); - setDisplay(el, true); - transition.enter(el); - } else { - transition.leave(el, () => { - setDisplay(el, false); - }); - } - } else { - setDisplay(el, value); - } - }, - beforeUnmount(el, { value }) { - setDisplay(el, value); - } - }; - function setDisplay(el, value) { - el.style.display = value ? el[vShowOriginalDisplay] : "none"; - el[vShowHidden] = !value; - } - function initVShowForSSR() { - vShow.getSSRProps = ({ value }) => { - if (!value) { - return { style: { display: "none" } }; - } - }; - } - var CSS_VAR_TEXT = /* @__PURE__ */ Symbol("CSS_VAR_TEXT"); - function useCssVars(getter) { - return; - } - var displayRE = /(?:^|;)\s*display\s*:/; - function patchStyle(el, prev, next) { - const style = el.style; - const isCssString = shared.isString(next); - let hasControlledDisplay = false; - if (next && !isCssString) { - if (prev) { - if (!shared.isString(prev)) { - for (const key in prev) { - if (next[key] == null) { - setStyle(style, key, ""); - } - } - } else { - for (const prevStyle of prev.split(";")) { - const key = prevStyle.slice(0, prevStyle.indexOf(":")).trim(); - if (next[key] == null) { - setStyle(style, key, ""); - } - } - } - } - for (const key in next) { - if (key === "display") { - hasControlledDisplay = true; - } - const value = next[key]; - if (value != null) { - if (!shouldPreserveTextareaResizeStyle( - el, - key, - !shared.isString(prev) && prev ? prev[key] : void 0, - value - )) { - setStyle(style, key, value); - } - } else { - setStyle(style, key, ""); - } - } - } else { - if (isCssString) { - if (prev !== next) { - const cssVarText = style[CSS_VAR_TEXT]; - if (cssVarText) { - next += ";" + cssVarText; - } - style.cssText = next; - hasControlledDisplay = displayRE.test(next); - } - } else if (prev) { - el.removeAttribute("style"); - } - } - if (vShowOriginalDisplay in el) { - if (!isCssString || prev !== next) { - el[vShowOriginalDisplay] = hasControlledDisplay ? style.display : ""; - } - if (el[vShowHidden]) { - style.display = "none"; - } - } - } - var semicolonRE = /[^\\];\s*$/; - var importantRE = /\s*!important$/; - function setStyle(style, name, val) { - if (shared.isArray(val)) { - val.forEach((v) => setStyle(style, name, v)); - } else { - if (val == null) val = ""; - { - if (semicolonRE.test(val)) { - runtimeCore.warn( - `Unexpected semicolon at the end of '${name}' style value: '${val}'` - ); - } - } - if (name.startsWith("--")) { - if (importantRE.test(val)) { - style.setProperty(name, val.replace(importantRE, ""), "important"); - } else { - style.setProperty(name, val); - } - } else { - const prefixed = autoPrefix(style, name); - if (importantRE.test(val)) { - style.setProperty( - shared.hyphenate(prefixed), - val.replace(importantRE, ""), - "important" - ); - } else { - style[prefixed] = val; - } - } - } - } - var prefixes = ["Webkit", "Moz", "ms"]; - var prefixCache = {}; - function autoPrefix(style, rawName) { - const cached = prefixCache[rawName]; - if (cached) { - return cached; - } - let name = runtimeCore.camelize(rawName); - if (name !== "filter" && name in style) { - return prefixCache[rawName] = name; - } - name = shared.capitalize(name); - for (let i = 0; i < prefixes.length; i++) { - const prefixed = prefixes[i] + name; - if (prefixed in style) { - return prefixCache[rawName] = prefixed; - } - } - return rawName; - } - function shouldPreserveTextareaResizeStyle(el, key, prev, next) { - return el.tagName === "TEXTAREA" && (key === "width" || key === "height") && shared.isString(next) && prev === next; - } - var xlinkNS = "http://www.w3.org/1999/xlink"; - function patchAttr(el, key, value, isSVG, instance, isBoolean = shared.isSpecialBooleanAttr(key)) { - if (isSVG && key.startsWith("xlink:")) { - if (value == null) { - el.removeAttributeNS(xlinkNS, key.slice(6, key.length)); - } else { - el.setAttributeNS(xlinkNS, key, value); - } - } else { - if (value == null || isBoolean && !shared.includeBooleanAttr(value)) { - el.removeAttribute(key); - } else { - el.setAttribute( - key, - isBoolean ? "" : shared.isSymbol(value) ? String(value) : value - ); - } - } - } - function patchDOMProp(el, key, value, parentComponent, attrName) { - if (key === "innerHTML" || key === "textContent") { - if (value != null) { - el[key] = key === "innerHTML" ? unsafeToTrustedHTML(value) : value; - } - return; - } - const tag = el.tagName; - if (key === "value" && tag !== "PROGRESS" && // custom elements may use _value internally - !tag.includes("-")) { - const oldValue = tag === "OPTION" ? el.getAttribute("value") || "" : el.value; - const newValue = value == null ? ( - // #11647: value should be set as empty string for null and undefined, - // but <input type="checkbox"> should be set as 'on'. - el.type === "checkbox" ? "on" : "" - ) : String(value); - if (oldValue !== newValue || !("_value" in el)) { - el.value = newValue; - } - if (value == null) { - el.removeAttribute(key); - } - el._value = value; - return; - } - let needRemove = false; - if (value === "" || value == null) { - const type = typeof el[key]; - if (type === "boolean") { - value = shared.includeBooleanAttr(value); - } else if (value == null && type === "string") { - value = ""; - needRemove = true; - } else if (type === "number") { - value = 0; - needRemove = true; - } - } - try { - el[key] = value; - } catch (e) { - if (!needRemove) { - runtimeCore.warn( - `Failed setting prop "${key}" on <${tag.toLowerCase()}>: value ${value} is invalid.`, - e - ); - } - } - needRemove && el.removeAttribute(attrName || key); - } - function addEventListener2(el, event, handler, options) { - el.addEventListener(event, handler, options); - } - function removeEventListener(el, event, handler, options) { - el.removeEventListener(event, handler, options); - } - var veiKey = /* @__PURE__ */ Symbol("_vei"); - function patchEvent(el, rawName, prevValue, nextValue, instance = null) { - const invokers = el[veiKey] || (el[veiKey] = {}); - const existingInvoker = invokers[rawName]; - if (nextValue && existingInvoker) { - existingInvoker.value = sanitizeEventValue(nextValue, rawName); - } else { - const [name, options] = parseName(rawName); - if (nextValue) { - const invoker = invokers[rawName] = createInvoker( - sanitizeEventValue(nextValue, rawName), - instance - ); - addEventListener2(el, name, invoker, options); - } else if (existingInvoker) { - removeEventListener(el, name, existingInvoker, options); - invokers[rawName] = void 0; - } - } - } - var optionsModifierRE = /(Once|Passive|Capture)$/; - var optionsModifierEventRE = /^on:?(?:Once|Passive|Capture)$/; - function parseName(name) { - let options; - let m; - while ((m = name.match(optionsModifierRE)) && !optionsModifierEventRE.test(name)) { - if (!options) options = {}; - name = name.slice(0, name.length - m[1].length); - options[m[1].toLowerCase()] = true; - } - const event = name[2] === ":" ? name.slice(3) : shared.hyphenate(name.slice(2)); - return [event, options]; - } - var cachedNow = 0; - var p = /* @__PURE__ */ Promise.resolve(); - var getNow = () => cachedNow || (p.then(() => cachedNow = 0), cachedNow = Date.now()); - function createInvoker(initialValue, instance) { - const invoker = (e) => { - if (!e._vts) { - e._vts = Date.now(); - } else if (e._vts <= invoker.attached) { - return; - } - const value = invoker.value; - if (shared.isArray(value)) { - const originalStop = e.stopImmediatePropagation; - e.stopImmediatePropagation = () => { - originalStop.call(e); - e._stopped = true; - }; - const handlers = value.slice(); - const args = [e]; - for (let i = 0; i < handlers.length; i++) { - if (e._stopped) { - break; - } - const handler = handlers[i]; - if (handler) { - runtimeCore.callWithAsyncErrorHandling( - handler, - instance, - 5, - args - ); - } - } - } else { - runtimeCore.callWithAsyncErrorHandling( - value, - instance, - 5, - [e] - ); - } - }; - invoker.value = initialValue; - invoker.attached = getNow(); - return invoker; - } - function sanitizeEventValue(value, propName) { - if (shared.isFunction(value) || shared.isArray(value)) { - return value; - } - runtimeCore.warn( - `Wrong type passed as event handler to ${propName} - did you forget @ or : in front of your prop? -Expected function or array of functions, received type ${typeof value}.` - ); - return shared.NOOP; - } - var isNativeOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // lowercase letter - key.charCodeAt(2) > 96 && key.charCodeAt(2) < 123; - var patchProp = (el, key, prevValue, nextValue, namespace, parentComponent) => { - const isSVG = namespace === "svg"; - if (key === "class") { - patchClass(el, nextValue, isSVG); - } else if (key === "style") { - patchStyle(el, prevValue, nextValue); - } else if (shared.isOn(key)) { - if (!shared.isModelListener(key)) { - patchEvent(el, key, prevValue, nextValue, parentComponent); - } - } else if (key[0] === "." ? (key = key.slice(1), true) : key[0] === "^" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) { - patchDOMProp(el, key, nextValue); - if (!el.tagName.includes("-") && (key === "value" || key === "checked" || key === "selected")) { - patchAttr(el, key, nextValue, isSVG, parentComponent, key !== "value"); - } - } else if ( - // #11081 force set props for possible async custom element - el._isVueCE && // #12408 check if it's declared prop or it's async custom element - (shouldSetAsPropForVueCE(el, key) || // @ts-expect-error _def is private - el._def.__asyncLoader && (/[A-Z]/.test(key) || !shared.isString(nextValue))) - ) { - patchDOMProp(el, shared.camelize(key), nextValue, parentComponent, key); - } else { - if (key === "true-value") { - el._trueValue = nextValue; - } else if (key === "false-value") { - el._falseValue = nextValue; - } - patchAttr(el, key, nextValue, isSVG); - } - }; - function shouldSetAsProp(el, key, value, isSVG) { - if (isSVG) { - if (key === "innerHTML" || key === "textContent") { - return true; - } - if (key in el && isNativeOn(key) && shared.isFunction(value)) { - return true; - } - return false; - } - if (key === "spellcheck" || key === "draggable" || key === "translate" || key === "autocorrect") { - return false; - } - if (key === "sandbox" && el.tagName === "IFRAME") { - return false; - } - if (key === "form") { - return false; - } - if (key === "list" && el.tagName === "INPUT") { - return false; - } - if (key === "type" && el.tagName === "TEXTAREA") { - return false; - } - if (key === "width" || key === "height") { - const tag = el.tagName; - if (tag === "IMG" || tag === "VIDEO" || tag === "CANVAS" || tag === "SOURCE") { - return false; - } - } - if (isNativeOn(key) && shared.isString(value)) { - return false; - } - return key in el; - } - function shouldSetAsPropForVueCE(el, key) { - const props = ( - // @ts-expect-error _def is private - el._def.props - ); - if (!props) { - return false; - } - const camelKey = shared.camelize(key); - return Array.isArray(props) ? props.some((prop) => shared.camelize(prop) === camelKey) : Object.keys(props).some((prop) => shared.camelize(prop) === camelKey); - } - var REMOVAL = {}; - // @__NO_SIDE_EFFECTS__ - function defineCustomElement(options, extraOptions, _createApp) { - let Comp = runtimeCore.defineComponent(options, extraOptions); - if (shared.isPlainObject(Comp)) Comp = shared.extend({}, Comp, extraOptions); - class VueCustomElement extends VueElement { - constructor(initialProps) { - super(Comp, initialProps, _createApp); - } - } - VueCustomElement.def = Comp; - return VueCustomElement; - } - var defineSSRCustomElement = /* @__NO_SIDE_EFFECTS__ */ (options, extraOptions) => { - return /* @__PURE__ */ defineCustomElement(options, extraOptions, createSSRApp); - }; - var BaseClass = typeof HTMLElement !== "undefined" ? HTMLElement : class { - }; - var VueElement = class _VueElement extends BaseClass { - constructor(_def, _props = {}, _createApp = createApp) { - super(); - this._def = _def; - this._props = _props; - this._createApp = _createApp; - this._isVueCE = true; - this._instance = null; - this._app = null; - this._nonce = this._def.nonce; - this._connected = false; - this._resolved = false; - this._patching = false; - this._dirty = false; - this._numberProps = null; - this._styleChildren = /* @__PURE__ */ new WeakSet(); - this._styleAnchors = /* @__PURE__ */ new WeakMap(); - this._ob = null; - if (this.shadowRoot && _createApp !== createApp) { - this._root = this.shadowRoot; - } else { - if (this.shadowRoot) { - runtimeCore.warn( - `Custom element has pre-rendered declarative shadow root but is not defined as hydratable. Use \`defineSSRCustomElement\`.` - ); - } - if (_def.shadowRoot !== false) { - this.attachShadow( - shared.extend({}, _def.shadowRootOptions, { - mode: "open" - }) - ); - this._root = this.shadowRoot; - } else { - this._root = this; - } - } - } - connectedCallback() { - if (!this.isConnected) return; - if (!this.shadowRoot && !this._resolved) { - this._parseSlots(); - } - this._connected = true; - let parent = this; - while (parent = parent && // #12479 should check assignedSlot first to get correct parent - (parent.assignedSlot || parent.parentNode || parent.host)) { - if (parent instanceof _VueElement) { - this._parent = parent; - break; - } - } - if (!this._instance) { - if (this._resolved) { - this._mount(this._def); - } else { - if (parent && parent._pendingResolve) { - this._pendingResolve = parent._pendingResolve.then(() => { - this._pendingResolve = void 0; - if (this.isConnected) { - return this._resolveDef(); - } - }); - } else { - this._resolveDef(); - } - } - } - } - _setParent(parent = this._parent) { - if (parent) { - this._instance.parent = parent._instance; - this._inheritParentContext(parent); - } - } - _inheritParentContext(parent = this._parent) { - if (parent && this._app) { - Object.setPrototypeOf( - this._app._context.provides, - parent._instance.provides - ); - } - } - disconnectedCallback() { - this._connected = false; - runtimeCore.nextTick(() => { - if (!this._connected) { - if (this._ob) { - this._ob.disconnect(); - this._ob = null; - } - this._app && this._app.unmount(); - if (this._instance) this._instance.ce = void 0; - this._app = this._instance = null; - if (this._teleportTargets) { - this._teleportTargets.clear(); - this._teleportTargets = void 0; - } - } - }); - } - _processMutations(mutations) { - for (const m of mutations) { - this._setAttr(m.attributeName); - } - } - /** - * resolve inner component definition (handle possible async component) - */ - _resolveDef() { - if (this._pendingResolve) { - return this._pendingResolve; - } - for (let i = 0; i < this.attributes.length; i++) { - this._setAttr(this.attributes[i].name); - } - this._ob = new MutationObserver(this._processMutations.bind(this)); - this._ob.observe(this, { attributes: true }); - const resolve = (def, isAsync = false) => { - this._resolved = true; - this._pendingResolve = void 0; - const { props, styles } = def; - let numberProps; - if (props && !shared.isArray(props)) { - for (const key in props) { - const opt = props[key]; - if (opt === Number || opt && opt.type === Number) { - if (key in this._props) { - this._props[key] = shared.toNumber(this._props[key]); - } - (numberProps || (numberProps = /* @__PURE__ */ Object.create(null)))[shared.camelize(key)] = true; - } - } - } - this._numberProps = numberProps; - this._resolveProps(def); - if (this.shadowRoot) { - this._applyStyles(styles); - } else if (styles) { - runtimeCore.warn( - "Custom element style injection is not supported when using shadowRoot: false" - ); - } - if (this._connected) { - this._mount(def); - } - }; - const asyncDef = this._def.__asyncLoader; - if (asyncDef) { - this._pendingResolve = asyncDef().then((def) => { - def.configureApp = this._def.configureApp; - resolve(this._def = def, true); - }); - return this._pendingResolve; - } else { - resolve(this._def); - } - } - _mount(def) { - if (!def.name) { - def.name = "VueElement"; - } - this._app = this._createApp(def); - this._inheritParentContext(); - if (def.configureApp) { - def.configureApp(this._app); - } - this._app._ceVNode = this._createVNode(); - this._app.mount(this._root); - const exposed = this._instance && this._instance.exposed; - if (!exposed) return; - for (const key in exposed) { - if (!shared.hasOwn(this, key)) { - Object.defineProperty(this, key, { - // unwrap ref to be consistent with public instance behavior - get: () => runtimeCore.unref(exposed[key]) - }); - } else { - runtimeCore.warn(`Exposed property "${key}" already exists on custom element.`); - } - } - } - _resolveProps(def) { - const { props } = def; - const declaredPropKeys = shared.isArray(props) ? props : Object.keys(props || {}); - for (const key of Object.keys(this)) { - if (key[0] !== "_" && declaredPropKeys.includes(key)) { - this._setProp(key, this[key]); - } - } - for (const key of declaredPropKeys.map(shared.camelize)) { - if (key in Object.getPrototypeOf(this)) { - runtimeCore.warn( - `Custom element prop "${key}" conflicts with an existing property on the element and will overwrite it.` - ); - } - Object.defineProperty(this, key, { - get() { - return this._getProp(key); - }, - set(val) { - this._setProp(key, val, true, !this._patching); - } - }); - } - } - _setAttr(key) { - if (key.startsWith("data-v-")) return; - const has = this.hasAttribute(key); - let value = has ? this.getAttribute(key) : REMOVAL; - const camelKey = shared.camelize(key); - if (has && this._numberProps && this._numberProps[camelKey]) { - value = shared.toNumber(value); - } - this._setProp(camelKey, value, false, true); - } - /** - * @internal - */ - _getProp(key) { - return this._props[key]; - } - /** - * @internal - */ - _setProp(key, val, shouldReflect = true, shouldUpdate = false) { - if (val !== this._props[key]) { - this._dirty = true; - if (val === REMOVAL) { - delete this._props[key]; - } else { - this._props[key] = val; - if (key === "key" && this._app) { - this._app._ceVNode.key = val; - } - } - if (shouldUpdate && this._instance) { - this._update(); - } - if (shouldReflect) { - const ob = this._ob; - if (ob) { - this._processMutations(ob.takeRecords()); - ob.disconnect(); - } - if (val === true) { - this.setAttribute(shared.hyphenate(key), ""); - } else if (typeof val === "string" || typeof val === "number") { - this.setAttribute(shared.hyphenate(key), val + ""); - } else if (!val) { - this.removeAttribute(shared.hyphenate(key)); - } - ob && ob.observe(this, { attributes: true }); - } - } - } - _update() { - const vnode = this._createVNode(); - if (this._app) vnode.appContext = this._app._context; - render(vnode, this._root); - } - _createVNode() { - const baseProps = {}; - if (!this.shadowRoot) { - baseProps.onVnodeMounted = baseProps.onVnodeUpdated = this._renderSlots.bind(this); - } - const vnode = runtimeCore.createVNode(this._def, shared.extend(baseProps, this._props)); - if (!this._instance) { - vnode.ce = (instance) => { - this._instance = instance; - instance.ce = this; - instance.isCE = true; - { - instance.ceReload = (newStyles) => { - if (this._styles) { - this._styles.forEach((s) => this._root.removeChild(s)); - this._styles.length = 0; - } - this._styleAnchors.delete(this._def); - this._applyStyles(newStyles); - this._instance = null; - this._update(); - }; - } - const dispatch = (event, args) => { - this.dispatchEvent( - new CustomEvent( - event, - shared.isPlainObject(args[0]) ? shared.extend({ detail: args }, args[0]) : { detail: args } - ) - ); - }; - instance.emit = (event, ...args) => { - dispatch(event, args); - if (shared.hyphenate(event) !== event) { - dispatch(shared.hyphenate(event), args); - } - }; - this._setParent(); - }; - } - return vnode; - } - _applyStyles(styles, owner, parentComp) { - if (!styles) return; - if (owner) { - if (owner === this._def || this._styleChildren.has(owner)) { - return; - } - this._styleChildren.add(owner); - } - const nonce = this._nonce; - const root = this.shadowRoot; - const insertionAnchor = parentComp ? this._getStyleAnchor(parentComp) || this._getStyleAnchor(this._def) : this._getRootStyleInsertionAnchor(root); - let last = null; - for (let i = styles.length - 1; i >= 0; i--) { - const s = document.createElement("style"); - if (nonce) s.setAttribute("nonce", nonce); - s.textContent = styles[i]; - root.insertBefore(s, last || insertionAnchor); - last = s; - if (i === 0) { - if (!parentComp) this._styleAnchors.set(this._def, s); - if (owner) this._styleAnchors.set(owner, s); - } - { - if (owner) { - if (owner.__hmrId) { - if (!this._childStyles) this._childStyles = /* @__PURE__ */ new Map(); - let entry = this._childStyles.get(owner.__hmrId); - if (!entry) { - this._childStyles.set(owner.__hmrId, entry = []); - } - entry.push(s); - } - } else { - (this._styles || (this._styles = [])).push(s); - } - } - } - } - _getStyleAnchor(comp) { - if (!comp) { - return null; - } - const anchor = this._styleAnchors.get(comp); - if (anchor && anchor.parentNode === this.shadowRoot) { - return anchor; - } - if (anchor) { - this._styleAnchors.delete(comp); - } - return null; - } - _getRootStyleInsertionAnchor(root) { - for (let i = 0; i < root.childNodes.length; i++) { - const node = root.childNodes[i]; - if (!(node instanceof HTMLStyleElement)) { - return node; - } - } - return null; - } - /** - * Only called when shadowRoot is false - */ - _parseSlots() { - const slots = this._slots = {}; - let n; - while (n = this.firstChild) { - const slotName = n.nodeType === 1 && n.getAttribute("slot") || "default"; - (slots[slotName] || (slots[slotName] = [])).push(n); - this.removeChild(n); - } - } - /** - * Only called when shadowRoot is false - */ - _renderSlots() { - const outlets = this._getSlots(); - const scopeId = this._instance.type.__scopeId; - for (let i = 0; i < outlets.length; i++) { - const o = outlets[i]; - const slotName = o.getAttribute("name") || "default"; - const content = this._slots[slotName]; - const parent = o.parentNode; - if (content) { - for (const n of content) { - if (scopeId && n.nodeType === 1) { - const id = scopeId + "-s"; - const walker = document.createTreeWalker(n, 1); - n.setAttribute(id, ""); - let child; - while (child = walker.nextNode()) { - child.setAttribute(id, ""); - } - } - parent.insertBefore(n, o); - } - } else { - while (o.firstChild) parent.insertBefore(o.firstChild, o); - } - parent.removeChild(o); - } - } - /** - * @internal - */ - _getSlots() { - const roots = [this]; - if (this._teleportTargets) { - roots.push(...this._teleportTargets); - } - const slots = /* @__PURE__ */ new Set(); - for (const root of roots) { - const found = root.querySelectorAll("slot"); - for (let i = 0; i < found.length; i++) { - slots.add(found[i]); - } - } - return Array.from(slots); - } - /** - * @internal - */ - _injectChildStyle(comp, parentComp) { - this._applyStyles(comp.styles, comp, parentComp); - } - /** - * @internal - */ - _beginPatch() { - this._patching = true; - this._dirty = false; - } - /** - * @internal - */ - _endPatch() { - this._patching = false; - if (this._dirty && this._instance) { - this._update(); - } - } - /** - * @internal - */ - _hasShadowRoot() { - return this._def.shadowRoot !== false; - } - /** - * @internal - */ - _removeChildStyle(comp) { - { - this._styleChildren.delete(comp); - this._styleAnchors.delete(comp); - if (this._childStyles && comp.__hmrId) { - const oldStyles = this._childStyles.get(comp.__hmrId); - if (oldStyles) { - oldStyles.forEach((s) => this._root.removeChild(s)); - oldStyles.length = 0; - } - } - } - } - }; - function useHost(caller) { - const instance = runtimeCore.getCurrentInstance(); - const el = instance && instance.ce; - if (el) { - return el; - } else { - if (!instance) { - runtimeCore.warn( - `${caller || "useHost"} called without an active component instance.` - ); - } else { - runtimeCore.warn( - `${caller || "useHost"} can only be used in components defined via defineCustomElement.` - ); - } - } - return null; - } - function useShadowRoot() { - const el = useHost("useShadowRoot"); - return el && el.shadowRoot; - } - function useCssModule(name = "$style") { - { - const instance = runtimeCore.getCurrentInstance(); - if (!instance) { - runtimeCore.warn(`useCssModule must be called inside setup()`); - return shared.EMPTY_OBJ; - } - const modules = instance.type.__cssModules; - if (!modules) { - runtimeCore.warn(`Current instance does not have CSS modules injected.`); - return shared.EMPTY_OBJ; - } - const mod = modules[name]; - if (!mod) { - runtimeCore.warn(`Current instance does not have CSS module named "${name}".`); - return shared.EMPTY_OBJ; - } - return mod; - } - } - var positionMap = /* @__PURE__ */ new WeakMap(); - var newPositionMap = /* @__PURE__ */ new WeakMap(); - var moveCbKey = /* @__PURE__ */ Symbol("_moveCb"); - var enterCbKey = /* @__PURE__ */ Symbol("_enterCb"); - var pendingGroups = /* @__PURE__ */ new WeakMap(); - var decorate = (t) => { - delete t.props.mode; - return t; - }; - var TransitionGroupImpl = /* @__PURE__ */ decorate({ - name: "TransitionGroup", - props: /* @__PURE__ */ shared.extend({}, TransitionPropsValidators, { - tag: String, - moveClass: String - }), - setup(props, { slots }) { - const instance = runtimeCore.getCurrentInstance(); - const state = runtimeCore.useTransitionState(); - let prevChildren; - let children; - let origins; - let moves; - const willMove = () => { - if (moves === void 0) { - moves = prevChildren.length > 0 && hasCSSTransform( - prevChildren[0].el, - instance.vnode.el, - resolveMoveClass(props) - ); - } - return moves; - }; - runtimeCore.onUpdated(() => { - pendingGroups.delete(instance); - if (!willMove()) { - prevChildren = []; - origins = void 0; - return; - } - const moveClass = resolveMoveClass(props); - prevChildren.forEach(callPendingCbs); - const shift = origins && getOriginShift(origins, instance.vnode.el); - origins = void 0; - prevChildren.forEach((c) => recordPosition(c, shift)); - const movedChildren = prevChildren.filter(applyTranslation); - forceReflow(instance.vnode.el); - movedChildren.forEach((c) => { - const el = c.el; - const style = el.style; - addTransitionClass(el, moveClass); - style.transform = style.webkitTransform = style.transitionDuration = ""; - const cb = el[moveCbKey] = (e) => { - if (e && e.target !== el) { - return; - } - if (!e || e.propertyName.endsWith("transform")) { - el.removeEventListener("transitionend", cb); - el[moveCbKey] = null; - removeTransitionClass(el, moveClass); - } - }; - el.addEventListener("transitionend", cb); - }); - prevChildren = []; - }); - return () => { - const rawProps = runtimeCore.toRaw(props); - const cssTransitionProps = resolveTransitionProps(rawProps); - let tag = rawProps.tag || runtimeCore.Fragment; - prevChildren = []; - moves = void 0; - if (children) { - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (child.el && child.el instanceof Element && // Hidden v-show nodes have no previous layout box to animate from. - !child.el[vShowHidden]) { - prevChildren.push(child); - runtimeCore.setTransitionHooks( - child, - runtimeCore.resolveTransitionHooks( - child, - cssTransitionProps, - state, - instance - ) - ); - positionMap.set(child, getPosition(child.el)); - } - } - } - children = slots.default ? runtimeCore.getTransitionRawChildren(slots.default()) : []; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (child.key != null) { - runtimeCore.setTransitionHooks( - child, - runtimeCore.resolveTransitionHooks(child, cssTransitionProps, state, instance) - ); - } else if (child.type !== runtimeCore.Text) { - runtimeCore.warn(`<TransitionGroup> children must be keyed.`); - } - } - if (prevChildren.length) { - origins = getOrigins(instance); - pendingGroups.set(instance, willMove); - } - return runtimeCore.createVNode(tag, null, children); - }; - } - }); - var TransitionGroup = TransitionGroupImpl; - function callPendingCbs(c) { - const el = c.el; - if (el[moveCbKey]) { - el[moveCbKey](); - } - if (el[enterCbKey]) { - el[enterCbKey](); - } - } - function resolveMoveClass(props) { - return props.moveClass || `${props.name || "v"}-move`; - } - function recordPosition(c, shift) { - newPositionMap.set(c, getPosition(c.el, shift)); - } - function applyTranslation(c) { - const oldPos = positionMap.get(c); - const newPos = newPositionMap.get(c); - const dx = oldPos.left - newPos.left; - const dy = oldPos.top - newPos.top; - if (dx || dy) { - const el = c.el; - const s = el.style; - const rect = el.getBoundingClientRect(); - let scaleX = 1; - let scaleY = 1; - if (el.offsetWidth) scaleX = rect.width / el.offsetWidth; - if (el.offsetHeight) scaleY = rect.height / el.offsetHeight; - if (!Number.isFinite(scaleX) || scaleX === 0) scaleX = 1; - if (!Number.isFinite(scaleY) || scaleY === 0) scaleY = 1; - if (Math.abs(scaleX - 1) < 0.01) scaleX = 1; - if (Math.abs(scaleY - 1) < 0.01) scaleY = 1; - s.transform = s.webkitTransform = `translate(${dx / scaleX}px,${dy / scaleY}px)`; - s.transitionDuration = "0s"; - return c; - } - } - function getPosition(el, shift) { - const rect = el.getBoundingClientRect(); - return { - left: rect.left - (shift ? shift.left : 0), - top: rect.top - (shift ? shift.top : 0) - }; - } - function getOrigins(instance) { - let origins; - for (let group = instance.parent; group; group = group.parent) { - const willMove = pendingGroups.get(group); - if (willMove) { - const item = findItem(group.vnode.el, instance.vnode.el); - if (item) { - (origins || (origins = [])).push( - shared.extend(getPosition(item), { item, willMove }) - ); - } - } - } - return origins; - } - function findItem(root, node) { - const container = root.nodeType === 1 ? root : root.parentNode; - while (node && node.parentNode !== container) { - node = node.parentNode; - } - if (node && node.nodeType === 1) { - return node; - } - } - function getOriginShift(origins, root) { - const origin = origins.find((o) => o.willMove() && o.item.contains(root)); - return origin && getPosition(origin.item, origin); - } - function hasCSSTransform(el, root, moveClass) { - const clone = el.cloneNode(); - const _vtc = el[vtcKey]; - if (_vtc) { - _vtc.forEach((cls) => { - cls.split(/\s+/).forEach((c) => c && clone.classList.remove(c)); - }); - } - moveClass.split(/\s+/).forEach((c) => c && clone.classList.add(c)); - clone.style.display = "none"; - const container = root.nodeType === 1 ? root : root.parentNode; - container.appendChild(clone); - const { hasTransform } = getTransitionInfo(clone); - container.removeChild(clone); - return hasTransform; - } - var getModelAssigner = (vnode) => { - const fn = vnode.props["onUpdate:modelValue"] || false; - return shared.isArray(fn) ? (value) => shared.invokeArrayFns(fn, value) : fn; - }; - function onCompositionStart(e) { - e.target.composing = true; - } - function onCompositionEnd(e) { - const target = e.target; - if (target.composing) { - target.composing = false; - target.dispatchEvent(new Event("input")); - } - } - var assignKey = /* @__PURE__ */ Symbol("_assign"); - var initialValueKey = /* @__PURE__ */ Symbol("_initialValue"); - function castValue(value, trim, number) { - if (trim) value = value.trim(); - if (number) value = shared.looseToNumber(value); - return value; - } - var vModelText = { - created(el, { modifiers: { lazy, trim, number } }, vnode) { - if (el.parentNode) { - if (el.type === "text") { - el[initialValueKey] = el.defaultValue.replace(/[\r\n]/g, ""); - } else if (el.type === "textarea") { - el[initialValueKey] = el.defaultValue.replace(/\r\n?/g, "\n"); - } - } - el[assignKey] = getModelAssigner(vnode); - const castToNumber = number || vnode.props && vnode.props.type === "number"; - addEventListener2(el, lazy ? "change" : "input", (e) => { - if (e.target.composing) return; - el[assignKey](castValue(el.value, trim, castToNumber)); - }); - if (trim || castToNumber) { - addEventListener2(el, "change", () => { - el.value = castValue(el.value, trim, castToNumber); - }); - } - if (!lazy) { - addEventListener2(el, "compositionstart", onCompositionStart); - addEventListener2(el, "compositionend", onCompositionEnd); - addEventListener2(el, "change", onCompositionEnd); - } - }, - // set value on mounted so it's after min/max for type="range" - mounted(el, { value, modifiers: { trim, number } }) { - const newValue = value == null ? "" : value; - const initialValue = el[initialValueKey]; - delete el[initialValueKey]; - if (initialValue !== void 0 && (el.type === "text" || el.type === "textarea") && el.value !== initialValue) { - el[assignKey](castValue(el.value, trim, number)); - } else { - el.value = newValue; - } - }, - beforeUpdate(el, { value, oldValue, modifiers: { lazy, trim, number } }, vnode) { - el[assignKey] = getModelAssigner(vnode); - if (el.composing) return; - const elValue = (number || el.type === "number") && !/^0\d/.test(el.value) ? shared.looseToNumber(el.value) : el.value; - const newValue = value == null ? "" : value; - if (elValue === newValue) { - return; - } - const rootNode = el.getRootNode(); - if ((rootNode instanceof Document || rootNode instanceof ShadowRoot) && rootNode.activeElement === el && el.type !== "range") { - if (lazy && value === oldValue) { - return; - } - if (trim && el.value.trim() === newValue) { - return; - } - } - el.value = newValue; - } - }; - var vModelCheckbox = { - // #4096 array checkboxes need to be deep traversed - deep: true, - created(el, _, vnode) { - el[assignKey] = getModelAssigner(vnode); - addEventListener2(el, "change", () => { - const modelValue = el._modelValue; - const elementValue = getValue(el); - const checked = el.checked; - const assign = el[assignKey]; - if (shared.isArray(modelValue)) { - const index = shared.looseIndexOf(modelValue, elementValue); - const found = index !== -1; - if (checked && !found) { - assign(modelValue.concat(elementValue)); - } else if (!checked && found) { - const filtered = [...modelValue]; - filtered.splice(index, 1); - assign(filtered); - } - } else if (shared.isSet(modelValue)) { - const cloned = new Set(modelValue); - if (checked) { - cloned.add(elementValue); - } else { - cloned.delete(elementValue); - } - assign(cloned); - } else { - assign(getCheckboxValue(el, checked)); - } - }); - }, - // set initial checked on mount to wait for true-value/false-value - mounted: setChecked, - beforeUpdate(el, binding, vnode) { - el[assignKey] = getModelAssigner(vnode); - setChecked(el, binding, vnode); - } - }; - function setChecked(el, { value, oldValue }, vnode) { - el._modelValue = value; - let checked; - if (shared.isArray(value)) { - checked = shared.looseIndexOf(value, vnode.props.value) > -1; - } else if (shared.isSet(value)) { - checked = value.has(vnode.props.value); - } else { - if (value === oldValue) return; - checked = shared.looseEqual(value, getCheckboxValue(el, true)); - } - if (el.checked !== checked) { - el.checked = checked; - } - } - var vModelRadio = { - created(el, { value }, vnode) { - el.checked = shared.looseEqual(value, vnode.props.value); - el[assignKey] = getModelAssigner(vnode); - addEventListener2(el, "change", () => { - el[assignKey](getValue(el)); - }); - }, - beforeUpdate(el, { value, oldValue }, vnode) { - el[assignKey] = getModelAssigner(vnode); - if (value !== oldValue) { - el.checked = shared.looseEqual(value, vnode.props.value); - } - } - }; - var vModelSelect = { - // <select multiple> value need to be deep traversed - deep: true, - created(el, { value, modifiers: { number } }, vnode) { - el._modelValue = value; - addEventListener2(el, "change", () => { - const selectedVal = Array.prototype.filter.call(el.options, (o) => o.selected).map( - (o) => number ? shared.looseToNumber(getValue(o)) : getValue(o) - ); - const multiple = el.multiple; - const assignedValue = multiple ? shared.isSet(el._modelValue) ? new Set(selectedVal) : selectedVal : selectedVal[0]; - const pending = el._pendingValue = [ - multiple, - multiple ? shared.isArray(assignedValue) ? selectedVal.slice() : selectedVal : assignedValue - ]; - try { - el[assignKey](assignedValue); - } finally { - runtimeCore.nextTick(() => { - if (el._pendingValue === pending) { - el._pendingValue = void 0; - } - }); - } - }); - el[assignKey] = getModelAssigner(vnode); - }, - // set value in mounted & updated because <select> relies on its children - // <option>s. - mounted(el, { value }) { - setSelected(el, value); - }, - beforeUpdate(el, { value }, vnode) { - el._modelValue = value; - el[assignKey] = getModelAssigner(vnode); - }, - updated(el, { value }) { - const pending = el._pendingValue; - el._pendingValue = void 0; - if (!pending || pending[0] !== el.multiple || !isSameSelectValue(value, pending[1], pending[0])) { - setSelected(el, value); - } - } - }; - function isSameSelectValue(value, assignedValue, multiple) { - if (!multiple) return shared.looseEqual(value, assignedValue); - if (shared.isArray(value)) return shared.looseEqual(value, assignedValue); - if (shared.isSet(value)) { - if (value.size !== assignedValue.length) return false; - for (const item of assignedValue) { - if (!value.has(item)) return false; - } - return true; - } - return false; - } - function setSelected(el, value) { - const isMultiple = el.multiple; - const isArrayValue = shared.isArray(value); - if (isMultiple && !isArrayValue && !shared.isSet(value)) { - runtimeCore.warn( - `<select multiple v-model> expects an Array or Set value for its binding, but got ${Object.prototype.toString.call(value).slice(8, -1)}.` - ); - return; - } - for (let i = 0, l = el.options.length; i < l; i++) { - const option = el.options[i]; - const optionValue = getValue(option); - if (isMultiple) { - if (isArrayValue) { - const optionType = typeof optionValue; - if (optionType === "string" || optionType === "number") { - option.selected = value.some((v) => String(v) === String(optionValue)); - } else { - option.selected = shared.looseIndexOf(value, optionValue) > -1; - } - } else { - option.selected = value.has(optionValue); - } - } else if (shared.looseEqual(getValue(option), value)) { - if (el.selectedIndex !== i) el.selectedIndex = i; - return; - } - } - if (!isMultiple && el.selectedIndex !== -1) { - el.selectedIndex = -1; - } - } - function getValue(el) { - return "_value" in el ? el._value : el.value; - } - function getCheckboxValue(el, checked) { - const key = checked ? "_trueValue" : "_falseValue"; - return key in el ? el[key] : checked; - } - var vModelDynamic = { - created(el, binding, vnode) { - callModelHook(el, binding, vnode, null, "created"); - }, - mounted(el, binding, vnode) { - callModelHook(el, binding, vnode, null, "mounted"); - }, - beforeUpdate(el, binding, vnode, prevVNode) { - callModelHook(el, binding, vnode, prevVNode, "beforeUpdate"); - }, - updated(el, binding, vnode, prevVNode) { - callModelHook(el, binding, vnode, prevVNode, "updated"); - } - }; - function resolveDynamicModel(tagName, type) { - switch (tagName) { - case "SELECT": - return vModelSelect; - case "TEXTAREA": - return vModelText; - default: - switch (type) { - case "checkbox": - return vModelCheckbox; - case "radio": - return vModelRadio; - default: - return vModelText; - } - } - } - function callModelHook(el, binding, vnode, prevVNode, hook) { - const modelToUse = resolveDynamicModel( - el.tagName, - vnode.props && vnode.props.type - ); - const fn = modelToUse[hook]; - fn && fn(el, binding, vnode, prevVNode); - } - function initVModelForSSR() { - vModelText.getSSRProps = ({ value }) => ({ value }); - vModelRadio.getSSRProps = ({ value }, vnode) => { - if (vnode.props && shared.looseEqual(vnode.props.value, value)) { - return { checked: true }; - } - }; - vModelCheckbox.getSSRProps = ({ value }, vnode) => { - if (shared.isArray(value)) { - if (vnode.props && shared.looseIndexOf(value, vnode.props.value) > -1) { - return { checked: true }; - } - } else if (shared.isSet(value)) { - if (vnode.props && value.has(vnode.props.value)) { - return { checked: true }; - } - } else if (value) { - return { checked: true }; - } - }; - vModelDynamic.getSSRProps = (binding, vnode) => { - if (typeof vnode.type !== "string") { - return; - } - const modelToUse = resolveDynamicModel( - // resolveDynamicModel expects an uppercase tag name, but vnode.type is lowercase - vnode.type.toUpperCase(), - vnode.props && vnode.props.type - ); - if (modelToUse.getSSRProps) { - return modelToUse.getSSRProps(binding, vnode); - } - }; - } - var systemModifiers = ["ctrl", "shift", "alt", "meta"]; - var modifierGuards = { - stop: (e) => e.stopPropagation(), - prevent: (e) => e.preventDefault(), - self: (e) => e.target !== e.currentTarget, - ctrl: (e) => !e.ctrlKey, - shift: (e) => !e.shiftKey, - alt: (e) => !e.altKey, - meta: (e) => !e.metaKey, - left: (e) => "button" in e && e.button !== 0, - middle: (e) => "button" in e && e.button !== 1, - right: (e) => "button" in e && e.button !== 2, - exact: (e, modifiers) => systemModifiers.some((m) => e[`${m}Key`] && !modifiers.includes(m)) - }; - var withModifiers = (fn, modifiers) => { - if (!fn) return fn; - const cache = fn._withMods || (fn._withMods = {}); - const cacheKey = modifiers.join("."); - return cache[cacheKey] || (cache[cacheKey] = (event, ...args) => { - for (let i = 0; i < modifiers.length; i++) { - const guard = modifierGuards[modifiers[i]]; - if (guard && guard(event, modifiers)) return; - } - return fn(event, ...args); - }); - }; - var keyNames = { - esc: "escape", - space: " ", - up: "arrow-up", - left: "arrow-left", - right: "arrow-right", - down: "arrow-down", - delete: "backspace" - }; - var withKeys = (fn, modifiers) => { - const cache = fn._withKeys || (fn._withKeys = {}); - const cacheKey = modifiers.join("."); - return cache[cacheKey] || (cache[cacheKey] = (event) => { - if (!("key" in event)) { - return; - } - const eventKey = shared.hyphenate(event.key); - if (modifiers.some( - (k) => k === eventKey || keyNames[k] === eventKey - )) { - return fn(event); - } - }); - }; - var rendererOptions = /* @__PURE__ */ shared.extend({ patchProp }, nodeOps); - var renderer; - var enabledHydration = false; - function ensureRenderer() { - return renderer || (renderer = runtimeCore.createRenderer(rendererOptions)); - } - function ensureHydrationRenderer() { - renderer = enabledHydration ? renderer : runtimeCore.createHydrationRenderer(rendererOptions); - enabledHydration = true; - return renderer; - } - var render = (...args) => { - ensureRenderer().render(...args); - }; - var hydrate = (...args) => { - ensureHydrationRenderer().hydrate(...args); - }; - var createApp = (...args) => { - const app = ensureRenderer().createApp(...args); - { - injectNativeTagCheck(app); - injectCompilerOptionsCheck(app); - } - const { mount } = app; - app.mount = (containerOrSelector) => { - const container = normalizeContainer(containerOrSelector); - if (!container) return; - const component = app._component; - if (!shared.isFunction(component) && !component.render && !component.template) { - component.template = container.innerHTML; - } - if (container.nodeType === 1) { - container.textContent = ""; - } - const proxy = mount(container, false, resolveRootNamespace(container)); - if (container instanceof Element) { - container.removeAttribute("v-cloak"); - container.setAttribute("data-v-app", ""); - } - return proxy; - }; - return app; - }; - var createSSRApp = (...args) => { - const app = ensureHydrationRenderer().createApp(...args); - { - injectNativeTagCheck(app); - injectCompilerOptionsCheck(app); - } - const { mount } = app; - app.mount = (containerOrSelector) => { - const container = normalizeContainer(containerOrSelector); - if (container) { - return mount(container, true, resolveRootNamespace(container)); - } - }; - return app; - }; - function resolveRootNamespace(container) { - if (container instanceof SVGElement) { - return "svg"; - } - if (typeof MathMLElement === "function" && container instanceof MathMLElement) { - return "mathml"; - } - } - function injectNativeTagCheck(app) { - Object.defineProperty(app.config, "isNativeTag", { - value: (tag) => shared.isHTMLTag(tag) || shared.isSVGTag(tag) || shared.isMathMLTag(tag), - writable: false - }); - } - function injectCompilerOptionsCheck(app) { - if (runtimeCore.isRuntimeOnly()) { - const isCustomElement = app.config.isCustomElement; - Object.defineProperty(app.config, "isCustomElement", { - get() { - return isCustomElement; - }, - set() { - runtimeCore.warn( - `The \`isCustomElement\` config option is deprecated. Use \`compilerOptions.isCustomElement\` instead.` - ); - } - }); - const compilerOptions = app.config.compilerOptions; - const msg = `The \`compilerOptions\` config option is only respected when using a build of Vue.js that includes the runtime compiler (aka "full build"). Since you are using the runtime-only build, \`compilerOptions\` must be passed to \`@vue/compiler-dom\` in the build setup instead. -- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option. -- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader -- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-sfc`; - Object.defineProperty(app.config, "compilerOptions", { - get() { - runtimeCore.warn(msg); - return compilerOptions; - }, - set() { - runtimeCore.warn(msg); - } - }); - } - } - function normalizeContainer(container) { - if (shared.isString(container)) { - const res = document.querySelector(container); - if (!res) { - runtimeCore.warn( - `Failed to mount app: mount target selector "${container}" returned null.` - ); - } - return res; - } - if (window.ShadowRoot && container instanceof window.ShadowRoot && container.mode === "closed") { - runtimeCore.warn( - `mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs` - ); - } - return container; - } - var ssrDirectiveInitialized = false; - var initDirectivesForSSR = () => { - if (!ssrDirectiveInitialized) { - ssrDirectiveInitialized = true; - initVModelForSSR(); - initVShowForSSR(); - } - }; - exports2.Transition = Transition; - exports2.TransitionGroup = TransitionGroup; - exports2.VueElement = VueElement; - exports2.createApp = createApp; - exports2.createSSRApp = createSSRApp; - exports2.defineCustomElement = defineCustomElement; - exports2.defineSSRCustomElement = defineSSRCustomElement; - exports2.hydrate = hydrate; - exports2.initDirectivesForSSR = initDirectivesForSSR; - exports2.nodeOps = nodeOps; - exports2.patchProp = patchProp; - exports2.render = render; - exports2.useCssModule = useCssModule; - exports2.useCssVars = useCssVars; - exports2.useHost = useHost; - exports2.useShadowRoot = useShadowRoot; - exports2.vModelCheckbox = vModelCheckbox; - exports2.vModelDynamic = vModelDynamic; - exports2.vModelRadio = vModelRadio; - exports2.vModelSelect = vModelSelect; - exports2.vModelText = vModelText; - exports2.vShow = vShow; - exports2.withKeys = withKeys; - exports2.withModifiers = withModifiers; - Object.keys(runtimeCore).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports2, k)) exports2[k] = runtimeCore[k]; - }); - } -}); - -// intern-log/node_modules/.pnpm/@vue+runtime-dom@3.5.44/node_modules/@vue/runtime-dom/index.js -var require_runtime_dom = __commonJS({ - "intern-log/node_modules/.pnpm/@vue+runtime-dom@3.5.44/node_modules/@vue/runtime-dom/index.js"(exports2, module2) { - "use strict"; - if (process.env.NODE_ENV === "production") { - module2.exports = require_runtime_dom_cjs_prod(); - } else { - module2.exports = require_runtime_dom_cjs(); - } - } -}); - -// intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/dist/vue.cjs.prod.js -var require_vue_cjs_prod = __commonJS({ - "intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/dist/vue.cjs.prod.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var compilerDom = require_compiler_dom(); - var runtimeDom = require_runtime_dom(); - var shared = require_shared(); - function _interopNamespaceDefault(e) { - var n = /* @__PURE__ */ Object.create(null); - if (e) { - for (var k in e) { - n[k] = e[k]; - } - } - n.default = e; - return Object.freeze(n); - } - var runtimeDom__namespace = /* @__PURE__ */ _interopNamespaceDefault(runtimeDom); - var compileCache = /* @__PURE__ */ Object.create(null); - function compileToFunction(template, options) { - if (!shared.isString(template)) { - if (template.nodeType) { - template = template.innerHTML; - } else { - return shared.NOOP; - } - } - const key = shared.genCacheKey(template, options); - const cached = compileCache[key]; - if (cached) { - return cached; - } - if (template[0] === "#") { - const el = document.querySelector(template); - template = el ? el.innerHTML : ``; - } - const opts = shared.extend( - { - hoistStatic: true, - onError: void 0, - onWarn: shared.NOOP - }, - options - ); - if (!opts.isCustomElement && typeof customElements !== "undefined") { - opts.isCustomElement = (tag) => !!customElements.get(tag); - } - const { code } = compilerDom.compile(template, opts); - const render = new Function("Vue", code)(runtimeDom__namespace); - render._rc = true; - return compileCache[key] = render; - } - runtimeDom.registerRuntimeCompiler(compileToFunction); - exports2.compile = compileToFunction; - Object.keys(runtimeDom).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports2, k)) exports2[k] = runtimeDom[k]; - }); - } -}); - -// intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/dist/vue.cjs.js -var require_vue_cjs = __commonJS({ - "intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/dist/vue.cjs.js"(exports2) { - "use strict"; - Object.defineProperty(exports2, "__esModule", { value: true }); - var compilerDom = require_compiler_dom(); - var runtimeDom = require_runtime_dom(); - var shared = require_shared(); - function _interopNamespaceDefault(e) { - var n = /* @__PURE__ */ Object.create(null); - if (e) { - for (var k in e) { - n[k] = e[k]; - } - } - n.default = e; - return Object.freeze(n); - } - var runtimeDom__namespace = /* @__PURE__ */ _interopNamespaceDefault(runtimeDom); - var compileCache = /* @__PURE__ */ Object.create(null); - function compileToFunction(template, options) { - if (!shared.isString(template)) { - if (template.nodeType) { - template = template.innerHTML; - } else { - runtimeDom.warn(`invalid template option: `, template); - return shared.NOOP; - } - } - const key = shared.genCacheKey(template, options); - const cached = compileCache[key]; - if (cached) { - return cached; - } - if (template[0] === "#") { - const el = document.querySelector(template); - if (!el) { - runtimeDom.warn(`Template element not found or is empty: ${template}`); - } - template = el ? el.innerHTML : ``; - } - const opts = shared.extend( - { - hoistStatic: true, - onError, - onWarn: (e) => onError(e, true) - }, - options - ); - if (!opts.isCustomElement && typeof customElements !== "undefined") { - opts.isCustomElement = (tag) => !!customElements.get(tag); - } - const { code } = compilerDom.compile(template, opts); - function onError(err, asWarning = false) { - const message = asWarning ? err.message : `Template compilation error: ${err.message}`; - const codeFrame = err.loc && shared.generateCodeFrame( - template, - err.loc.start.offset, - err.loc.end.offset - ); - runtimeDom.warn(codeFrame ? `${message} -${codeFrame}` : message); - } - const render = new Function("Vue", code)(runtimeDom__namespace); - render._rc = true; - return compileCache[key] = render; - } - runtimeDom.registerRuntimeCompiler(compileToFunction); - exports2.compile = compileToFunction; - Object.keys(runtimeDom).forEach(function(k) { - if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports2, k)) exports2[k] = runtimeDom[k]; - }); - } -}); - -// intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/index.js -var require_vue = __commonJS({ - "intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/index.js"(exports2, module2) { - "use strict"; - if (process.env.NODE_ENV === "production") { - module2.exports = require_vue_cjs_prod(); - } else { - module2.exports = require_vue_cjs(); - } - } -}); - -// intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/index.mjs -var vue_exports = {}; -var init_vue = __esm({ - "intern-log/node_modules/.pnpm/vue@3.5.44_typescript@5.6.3/node_modules/vue/index.mjs"() { - __reExport(vue_exports, __toESM(require_vue(), 1)); - } -}); - -// intern-log/src/lib/bus.ts -function notifyAttendanceChanged() { - attendanceChanged.value++; -} -var focusDate, focusMemo, attendanceChanged; -var init_bus = __esm({ - "intern-log/src/lib/bus.ts"() { - "use strict"; - init_vue(); - focusDate = (0, vue_exports.ref)(null); - focusMemo = (0, vue_exports.ref)(null); - attendanceChanged = (0, vue_exports.ref)(0); - } -}); - -// intern-log/src/sync/engine.ts -var engine_exports = {}; -__export(engine_exports, { - DEFAULT_SYNC_BASE: () => DEFAULT_SYNC_BASE, - SYNC_TABLES: () => SYNC_TABLES, - autoSyncNow: () => autoSyncNow, - enableRealtimeSync: () => enableRealtimeSync, - ensureCloudBinding: () => ensureCloudBinding, - getCloudUser: () => getCloudUser, - getSyncBase: () => getSyncBase, - getSyncLastTime: () => getSyncLastTime, - isSyncConfigured: () => isSyncConfigured, - registerCloudAccount: () => registerCloudAccount, - runSync: () => runSync, - stopRealtime: () => stopRealtime, - syncWithStoredConfig: () => syncWithStoredConfig -}); -function newUuid() { - if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID(); - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = Math.random() * 16 | 0; - return (c === "x" ? r : r & 3 | 8).toString(16); - }); -} -function rowHash(row) { - return JSON.stringify(row); -} -async function getTable(name) { - return db.table(name).toArray(); -} -function pkOf(t, row) { - return t === "setting" ? row.key : row.id; -} -async function ensureSyncFields() { - for (const t of TABLES) { - const table = db.table(t); - const rows = await table.toArray(); - for (const row of rows) { - if (t === "setting" && EXCLUDE_SETTING_KEYS.has(row.key)) continue; - const patch = {}; - if (!row.uuid) patch.uuid = newUuid(); - if (!row.updated_at) patch.updated_at = row.created_at || nowLocalISO(); - if (Object.keys(patch).length) await table.update(pkOf(t, row), patch); - } - } -} -async function isSyncConfigured() { - return getCloudCreds() != null; -} -async function getSyncLastTime() { - return getSetting("sync_last_time", ""); -} -async function registerCloudAccount(baseUrl, username, password) { - const base = baseUrl.trim().replace(/\/+$/, ""); - if (!base || !username.trim() || password.length < 6) { - throw new Error("\u8BF7\u5B8C\u6574\u586B\u5199\u540C\u6B65\u5730\u5740\u3001\u7528\u6237\u540D\u4E0E\u81F3\u5C11 6 \u4F4D\u7684\u5BC6\u7801"); - } - let resp; - try { - resp = await fetch(base + "/api/auth/register", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ username: username.trim(), password }) - }); - } catch { - throw new Error("\u65E0\u6CD5\u8BBF\u95EE\u540C\u6B65\u670D\u52A1\uFF1A\u8BF7\u68C0\u67E5\u5730\u5740\u3001\u7AEF\u53E3\u4E0E\u7F51\u7EDC"); - } - if (resp.status === 409) throw new Error("\u4E91\u7AEF\u7528\u6237\u540D\u5DF2\u5B58\u5728\uFF0C\u53EF\u76F4\u63A5\u540C\u6B65"); - if (!resp.ok) throw new Error("\u4E91\u7AEF\u6CE8\u518C\u5931\u8D25\uFF1A" + resp.status); -} -async function loginCloud(base, config) { - const resp = await fetch(base + "/api/auth/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ username: config.username.trim(), password: config.password }) - }); - if (!resp.ok) throw new Error("\u4E91\u7AEF\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E"); - const j = await resp.json(); - if (!j || !j.token) throw new Error("\u4E91\u7AEF\u767B\u5F55\u5F02\u5E38"); - return String(j.token); -} -async function ensureToken(base, config) { - let token = await getSetting("sync_token", ""); - if (token) return token; - token = await loginCloud(base, config); - await setSetting("sync_token", token); - return token; -} -async function autoSyncNow() { - if (syncRunning) { - pendingSync = true; - return; - } - try { - if (!await isSyncConfigured()) return; - await runSync(await loadSyncConfig()); - } catch { - } -} -function enableRealtimeSync() { - if (realtimeAttached) return; - realtimeAttached = true; - const sub = liveQuery(async () => { - const counts = {}; - for (const t of TABLES) counts[t] = await db.table(t).count(); - return counts; - }); - realtimeSub = sub.subscribe({ - next: () => { - if (changesSuppressed || syncRunning) return; - if (changeDebounce) globalThis.clearTimeout(changeDebounce); - changeDebounce = globalThis.setTimeout(() => { - void autoSyncNow(); - }, 3e3); - }, - error: () => { - } - }); -} -function stopRealtime() { - if (realtimeSub) { - realtimeSub.unsubscribe(); - realtimeSub = null; - } - if (sse) { - sse.close(); - sse = null; - sseKey = ""; - } - if (changeDebounce) { - globalThis.clearTimeout(changeDebounce); - changeDebounce = null; - } -} -function ensureSSE(base, token) { - const key = base + "|" + token; - if (sse && sseKey === key) return; - if (sse) { - sse.close(); - sse = null; - } - try { - sse = new EventSource(base + "/api/events?token=" + encodeURIComponent(token)); - sseKey = key; - sse.onmessage = () => { - void autoSyncNow(); - }; - } catch { - sse = null; - } -} -async function getSyncBase() { - return await getSetting("sync_base_url", "") || DEFAULT_SYNC_BASE; -} -async function loadSyncConfig() { - const creds = getCloudCreds(); - if (!creds) throw new Error("\u672A\u767B\u5F55\uFF0C\u65E0\u6CD5\u540C\u6B65"); - return { baseUrl: await getSyncBase(), username: creds.username, password: creds.password }; -} -async function ensureCloudBinding() { - const creds = getCloudCreds(); - if (!creds) throw new Error("\u672A\u767B\u5F55"); - const base = await getSyncBase(); - const headers = { "Content-Type": "application/json" }; - const body = JSON.stringify({ username: creds.username, password: creds.password }); - let resp = await fetch(base + "/api/auth/register", { method: "POST", headers, body }); - if (resp.status === 409) { - resp = await fetch(base + "/api/auth/login", { method: "POST", headers, body }); - if (!resp.ok) throw new Error("\u4E91\u7AEF\u5DF2\u5B58\u5728\u540C\u540D\u8D26\u53F7\u4E14\u5BC6\u7801\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u68C0\u67E5"); - } else if (!resp.ok) { - throw new Error("\u4E91\u7AEF\u7ED1\u5B9A\u5931\u8D25\uFF1A" + resp.status); - } -} -function getCloudUser() { - const c = getCloudCreds(); - return c ? c.username : null; -} -async function syncWithStoredConfig() { - return runSync(await loadSyncConfig()); -} -function normalizeRow(t, row, refs) { - const clean = {}; - for (const k of Object.keys(row)) { - if (k === "id") continue; - clean[k] = row[k]; - } - if (t === "log_item") { - delete clean.work_log_id; - delete clean.project_id; - const wl = row.work_log_id ? refs.workLog.get(row.work_log_id) : null; - if (wl && wl.uuid) clean.wuuid = wl.uuid; - const pj = row.project_id ? refs.project.get(row.project_id) : null; - if (pj && pj.uuid) clean.puuid = pj.uuid; - } - return clean; -} -async function buildRefMaps() { - const wlRows = await db.work_log.toArray(); - const pjRows = await db.project.toArray(); - return { - workLog: new Map(wlRows.map((r) => [r.id, r])), - project: new Map(pjRows.map((p) => [p.id, p])) - }; -} -async function runSync(config) { - if (syncRunning) { - pendingSync = true; - return { pushed: 0, pulled: 0, removed: 0, errors: 0, at: "" }; - } - syncRunning = true; - changesSuppressed = true; - applyErrors = 0; - lastApplyError = ""; - try { - const result = await doRunSync(config); - if (pendingSync) { - pendingSync = false; - globalThis.setTimeout(() => { - void autoSyncNow(); - }, 800); - } - return result; - } finally { - syncRunning = false; - changesSuppressed = false; - } -} -async function doRunSync(config) { - const base = config.baseUrl.trim().replace(/\/+$/, ""); - if (!base) throw new Error("\u8BF7\u5148\u914D\u7F6E\u540C\u6B65\u670D\u52A1\u5730\u5740"); - await ensureSyncFields(); - const refs = await buildRefMaps(); - const mirrorRows = await db.sync_mirror.toArray(); - const mirror = /* @__PURE__ */ new Map(); - for (const m of mirrorRows) mirror.set(m.table + "|" + m.uuid, m); - const pushTables = {}; - const tombstones = []; - let pushed = 0; - for (const t of TABLES) { - let rows = await getTable(t); - if (t === "setting") rows = rows.filter((r) => !EXCLUDE_SETTING_KEYS.has(r.key)); - const current = /* @__PURE__ */ new Map(); - for (const row of rows) current.set(row.uuid, row); - for (const [u, row] of current) { - const clean = normalizeRow(t, row, refs); - const h = rowHash(clean); - const m = mirror.get(t + "|" + u); - if (!m || m.hash !== h) { - pushTables[t] = pushTables[t] || []; - pushTables[t].push(clean); - pushed++; - } - } - for (const [key, m] of mirror) { - if (key.startsWith(t + "|") && !current.has(m.uuid)) { - tombstones.push({ table: t, uuid: m.uuid, deleted_at: nowLocalISO() }); - } - } - pushTables[t] = pushTables[t] || []; - } - const localTombs = await db.tombstone.toArray(); - for (const tb of localTombs) { - tombstones.push({ table: tb.table, uuid: tb.uuid, deleted_at: tb.deleted_at }); - } - const token = await ensureToken(base, config); - const doPush = (tk) => fetch(base + "/api/sync", { - method: "POST", - headers: { "Content-Type": "application/json", Authorization: "Bearer " + tk }, - body: JSON.stringify({ device: "client", tables: pushTables, tombstones }) - }); - let resp = await doPush(token); - if (resp.status === 401) { - await setSetting("sync_token", ""); - const token2 = await loginCloud(base, config); - await setSetting("sync_token", token2); - resp = await doPush(token2); - } - if (!resp.ok) throw new Error("\u540C\u6B65\u670D\u52A1\u8FD4\u56DE " + resp.status); - const data = await resp.json(); - const serverTables = data.tables || {}; - const serverTombstones = data.tombstones || []; - const applyResult = await applyServerTables(serverTables, serverTombstones); - const refsNow = await buildRefMaps(); - const finalMirror = []; - for (const t of TABLES) { - const rows = await db.table(t).toArray(); - for (const row of rows) { - if (t === "setting" && EXCLUDE_SETTING_KEYS.has(row.key)) continue; - finalMirror.push({ table: t, uuid: row.uuid, hash: rowHash(normalizeRow(t, row, refsNow)) }); - } - } - await db.sync_mirror.clear(); - if (finalMirror.length) await db.sync_mirror.bulkAdd(finalMirror.map((m) => ({ ...m }))); - ensureSSE(base, token); - const at = nowLocalISO(); - await setSetting("sync_last_time", at); - if (applyResult.pulled > 0 || applyResult.removed > 0) notifyAttendanceChanged(); - if (localTombs.length) { - const pushedIds = new Set(localTombs.map((t) => t.id)); - await db.tombstone.where("id").anyOf(Array.from(pushedIds)).delete(); - } - return { pushed, pulled: applyResult.pulled, removed: applyResult.removed, errors: applyResult.errors, at }; -} -async function applyServerTables(serverTables, serverTombstones) { - let pulled = 0; - let removed = 0; - for (const t of TABLES) { - const table = db.table(t); - const localRows = await table.toArray(); - const byUuid = /* @__PURE__ */ new Map(); - for (const row of localRows) byUuid.set(row.uuid, row); - const nk = NATURAL_KEYS[t] || null; - const byNatural = /* @__PURE__ */ new Map(); - if (nk) { - for (const row of localRows) { - const v = row[nk]; - if (v != null && v !== "") byNatural.set(String(v), row); - } - } - const dead = new Set(serverTombstones.filter((x) => x.table === t).map((x) => x.uuid)); - const serverRows = serverTables[t] || []; - for (const srow of serverRows) { - try { - if (dead.has(srow.uuid)) continue; - const local = byUuid.get(srow.uuid); - if (local) { - const localUa = String(local.updated_at || ""); - const serverUa = String(srow.updated_at || ""); - if (serverUa > localUa) { - const patch = { ...srow }; - if (t === "setting") delete patch.key; - if (t === "log_item") { - const wlId = srow.wuuid ? localWorkLogIdByUuid.get(srow.wuuid) : null; - if (!wlId) continue; - patch.work_log_id = wlId; - delete patch.wuuid; - patch.project_id = srow.puuid ? localProjectIdByUuid.get(srow.puuid) ?? null : local.project_id ?? null; - delete patch.puuid; - } - await table.update(local.id, patch); - pulled++; - } - } else { - const nkVal = nk && srow[nk] != null && srow[nk] !== "" ? String(srow[nk]) : null; - const dup = nkVal ? byNatural.get(nkVal) : void 0; - if (dup && dup.uuid !== srow.uuid) { - const dupUa = String(dup.updated_at || ""); - const serverUa = String(srow.updated_at || ""); - if (serverUa >= dupUa) { - if (t === "work_log") { - await db.log_item.where("work_log_id").equals(dup.id).modify({ work_log_id: -1 }); - } - await table.delete(pkOf(t, dup)); - await db.tombstone.add({ table: t, uuid: dup.uuid, deleted_at: nowLocalISO() }); - const newId = await table.add({ ...srow }); - if (t === "work_log") { - await db.log_item.where("work_log_id").equals(-1).modify({ work_log_id: newId }); - } - byUuid.set(srow.uuid, { ...srow, id: newId }); - if (nk && nkVal) byNatural.set(nkVal, { ...srow, id: newId }); - pulled++; - } else { - await db.tombstone.add({ table: t, uuid: srow.uuid, deleted_at: nowLocalISO() }); - applyConflicts++; - } - } else { - if (t === "log_item") { - const wlId = srow.wuuid ? localWorkLogIdByUuid.get(srow.wuuid) : null; - if (!wlId) continue; - srow.work_log_id = wlId; - delete srow.wuuid; - srow.project_id = srow.puuid ? localProjectIdByUuid.get(srow.puuid) ?? null : null; - delete srow.puuid; - } - const newId = await table.add({ ...srow }); - byUuid.set(srow.uuid, { ...srow, id: newId }); - if (nk && nkVal) byNatural.set(nkVal, { ...srow, id: newId }); - pulled++; - } - } - } catch (err) { - applyErrors++; - lastApplyError = err instanceof Error ? err.message : String(err); - } - } - for (const row of localRows) { - if (!dead.has(row.uuid)) continue; - try { - if (t === "work_log") { - const freshRows = await table.toArray(); - const survivor = freshRows.find((r2) => r2.date === row.date && !dead.has(r2.uuid) && r2.uuid !== row.uuid); - if (survivor && row.id) { - await db.log_item.where("work_log_id").equals(row.id).modify({ work_log_id: survivor.id }); - } - } - await table.delete(pkOf(t, row)); - removed++; - } catch (err) { - applyErrors++; - } - } - if (t === "work_log") { - const fresh = await table.toArray(); - localWorkLogIdByUuid = new Map(fresh.map((r) => [r.uuid, r.id])); - } - if (t === "project") { - const fresh = await table.toArray(); - localProjectIdByUuid = new Map(fresh.map((r) => [r.uuid, r.id])); - } - } - return { pulled, removed, errors: applyErrors }; -} -var TABLES, EXCLUDE_SETTING_KEYS, NATURAL_KEYS, SYNC_TABLES, syncRunning, pendingSync, changesSuppressed, changeDebounce, sse, sseKey, realtimeAttached, realtimeSub, DEFAULT_SYNC_BASE, applyErrors, lastApplyError, localWorkLogIdByUuid, localProjectIdByUuid, applyConflicts; -var init_engine = __esm({ - "intern-log/src/sync/engine.ts"() { - "use strict"; - init_import_wrapper(); - init_schema(); - init_repo(); - init_auth(); - init_date(); - init_bus(); - TABLES = ["project", "work_log", "log_item", "attendance", "weekly_note", "setting", "memo", "credential", "transaction"]; - EXCLUDE_SETTING_KEYS = /* @__PURE__ */ new Set(["sync_cursor", "sync_last_time", "sync_token", "last_project", "last_category"]); - NATURAL_KEYS = { - project: "name", - work_log: "date", - attendance: "date", - weekly_note: "week_start", - setting: "key" - }; - SYNC_TABLES = TABLES; - syncRunning = false; - pendingSync = false; - changesSuppressed = false; - changeDebounce = null; - sse = null; - sseKey = ""; - realtimeAttached = false; - realtimeSub = null; - DEFAULT_SYNC_BASE = "https://daywk.linyux.cn"; - applyErrors = 0; - lastApplyError = ""; - localWorkLogIdByUuid = /* @__PURE__ */ new Map(); - localProjectIdByUuid = /* @__PURE__ */ new Map(); - applyConflicts = 0; - } -}); - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/errors.js -var messages = { - AbortError: "A request was aborted, for example through a call to IDBTransaction.abort.", - ConstraintError: "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one.", - DataCloneError: "The data being stored could not be cloned by the internal structured cloning algorithm.", - DataError: "Data provided to an operation does not meet requirements.", - InvalidAccessError: "An invalid operation was performed on an object. For example transaction creation attempt was made, but an empty scope was provided.", - InvalidStateError: "An operation was called on an object on which it is not allowed or at a time when it is not allowed. Also occurs if a request is made on a source object that has been deleted or removed. Use TransactionInactiveError or ReadOnlyError when possible, as they are more specific variations of InvalidStateError.", - NotFoundError: "The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.", - ReadOnlyError: 'The mutating operation was attempted in a "readonly" transaction.', - TransactionInactiveError: "A request was placed against a transaction which is currently not active, or which is finished.", - SyntaxError: "The keypath argument contains an invalid key path", - VersionError: "An attempt was made to open a database using a lower version than the existing version." -}; -var setErrorCode = (error, value) => { - Object.defineProperty(error, "code", { - value, - writable: false, - enumerable: true, - configurable: false - }); -}; -var AbortError = class extends DOMException { - constructor(message = messages.AbortError) { - super(message, "AbortError"); - } -}; -var ConstraintError = class extends DOMException { - constructor(message = messages.ConstraintError) { - super(message, "ConstraintError"); - } -}; -var DataError = class extends DOMException { - constructor(message = messages.DataError) { - super(message, "DataError"); - setErrorCode(this, 0); - } -}; -var InvalidAccessError = class extends DOMException { - constructor(message = messages.InvalidAccessError) { - super(message, "InvalidAccessError"); - } -}; -var InvalidStateError = class extends DOMException { - constructor(message = messages.InvalidStateError) { - super(message, "InvalidStateError"); - setErrorCode(this, 11); - } -}; -var NotFoundError = class extends DOMException { - constructor(message = messages.NotFoundError) { - super(message, "NotFoundError"); - } -}; -var ReadOnlyError = class extends DOMException { - constructor(message = messages.ReadOnlyError) { - super(message, "ReadOnlyError"); - } -}; -var SyntaxError2 = class extends DOMException { - constructor(message = messages.VersionError) { - super(message, "SyntaxError"); - setErrorCode(this, 12); - } -}; -var TransactionInactiveError = class extends DOMException { - constructor(message = messages.TransactionInactiveError) { - super(message, "TransactionInactiveError"); - setErrorCode(this, 0); - } -}; -var VersionError = class extends DOMException { - constructor(message = messages.VersionError) { - super(message, "VersionError"); - } -}; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/isSharedArrayBuffer.js -function isSharedArrayBuffer(input) { - return typeof SharedArrayBuffer !== "undefined" && input instanceof SharedArrayBuffer; -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKeyWithoutThrowing.js -var INVALID_TYPE = Symbol("INVALID_TYPE"); -var INVALID_VALUE = Symbol("INVALID_VALUE"); -var valueToKeyWithoutThrowing = (input, seen) => { - if (typeof input === "number") { - if (isNaN(input)) { - return INVALID_VALUE; - } - return input; - } else if (Object.prototype.toString.call(input) === "[object Date]") { - const ms = input.valueOf(); - if (isNaN(ms)) { - return INVALID_VALUE; - } - return new Date(ms); - } else if (typeof input === "string") { - return input; - } else if ( - // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type - input instanceof ArrayBuffer || isSharedArrayBuffer(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input) - ) { - if ("detached" in input ? input.detached : input.byteLength === 0) { - return INVALID_VALUE; - } - let arrayBuffer; - let offset = 0; - let length = 0; - if (input instanceof ArrayBuffer || isSharedArrayBuffer(input)) { - arrayBuffer = input; - length = input.byteLength; - } else { - arrayBuffer = input.buffer; - offset = input.byteOffset; - length = input.byteLength; - } - return arrayBuffer.slice(offset, offset + length); - } else if (Array.isArray(input)) { - if (seen === void 0) { - seen = /* @__PURE__ */ new Set(); - } else if (seen.has(input)) { - return INVALID_VALUE; - } - seen.add(input); - let hasInvalid = false; - const keys = Array.from({ - length: input.length - }, (_, i) => { - if (hasInvalid) { - return; - } - const hop = Object.hasOwn(input, i); - if (!hop) { - hasInvalid = true; - return; - } - const entry = input[i]; - const key = valueToKeyWithoutThrowing(entry, seen); - if (key === INVALID_VALUE || key === INVALID_TYPE) { - hasInvalid = true; - return; - } - return key; - }); - if (hasInvalid) { - return INVALID_VALUE; - } - return keys; - } else { - return INVALID_TYPE; - } -}; -var valueToKeyWithoutThrowing_default = valueToKeyWithoutThrowing; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKey.js -var valueToKey = (input, seen) => { - const result = valueToKeyWithoutThrowing_default(input, seen); - if (result === INVALID_VALUE || result === INVALID_TYPE) { - throw new DataError(); - } - return result; -}; -var valueToKey_default = valueToKey; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/cmp.js -var getType = (x) => { - if (typeof x === "number") { - return "Number"; - } - if (Object.prototype.toString.call(x) === "[object Date]") { - return "Date"; - } - if (Array.isArray(x)) { - return "Array"; - } - if (typeof x === "string") { - return "String"; - } - if (x instanceof ArrayBuffer) { - return "Binary"; - } - throw new DataError(); -}; -var cmp = (first, second) => { - if (second === void 0) { - throw new TypeError(); - } - first = valueToKey_default(first); - second = valueToKey_default(second); - const t1 = getType(first); - const t2 = getType(second); - if (t1 !== t2) { - if (t1 === "Array") { - return 1; - } - if (t1 === "Binary" && (t2 === "String" || t2 === "Date" || t2 === "Number")) { - return 1; - } - if (t1 === "String" && (t2 === "Date" || t2 === "Number")) { - return 1; - } - if (t1 === "Date" && t2 === "Number") { - return 1; - } - return -1; - } - if (t1 === "Binary") { - first = new Uint8Array(first); - second = new Uint8Array(second); - } - if (t1 === "Array" || t1 === "Binary") { - const length = Math.min(first.length, second.length); - for (let i = 0; i < length; i++) { - const result = cmp(first[i], second[i]); - if (result !== 0) { - return result; - } - } - if (first.length > second.length) { - return 1; - } - if (first.length < second.length) { - return -1; - } - return 0; - } - if (t1 === "Date") { - if (first.getTime() === second.getTime()) { - return 0; - } - } else { - if (first === second) { - return 0; - } - } - return first > second ? 1 : -1; -}; -var cmp_default = cmp; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBKeyRange.js -var FDBKeyRange = class _FDBKeyRange { - static only(value) { - if (arguments.length === 0) { - throw new TypeError(); - } - value = valueToKey_default(value); - return new _FDBKeyRange(value, value, false, false); - } - static lowerBound(lower, open = false) { - if (arguments.length === 0) { - throw new TypeError(); - } - lower = valueToKey_default(lower); - return new _FDBKeyRange(lower, void 0, open, true); - } - static upperBound(upper, open = false) { - if (arguments.length === 0) { - throw new TypeError(); - } - upper = valueToKey_default(upper); - return new _FDBKeyRange(void 0, upper, true, open); - } - static bound(lower, upper, lowerOpen = false, upperOpen = false) { - if (arguments.length < 2) { - throw new TypeError(); - } - const cmpResult = cmp_default(lower, upper); - if (cmpResult === 1 || cmpResult === 0 && (lowerOpen || upperOpen)) { - throw new DataError(); - } - lower = valueToKey_default(lower); - upper = valueToKey_default(upper); - return new _FDBKeyRange(lower, upper, lowerOpen, upperOpen); - } - constructor(lower, upper, lowerOpen, upperOpen) { - this.lower = lower; - this.upper = upper; - this.lowerOpen = lowerOpen; - this.upperOpen = upperOpen; - } - // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes - includes(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - key = valueToKey_default(key); - if (this.lower !== void 0) { - const cmpResult = cmp_default(this.lower, key); - if (cmpResult === 1 || cmpResult === 0 && this.lowerOpen) { - return false; - } - } - if (this.upper !== void 0) { - const cmpResult = cmp_default(this.upper, key); - if (cmpResult === -1 || cmpResult === 0 && this.upperOpen) { - return false; - } - } - return true; - } - get [Symbol.toStringTag]() { - return "IDBKeyRange"; - } -}; -var FDBKeyRange_default = FDBKeyRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/extractKey.js -var extractKey = (keyPath, value) => { - if (Array.isArray(keyPath)) { - const result = []; - for (let item of keyPath) { - if (item !== void 0 && item !== null && typeof item !== "string" && item.toString) { - item = item.toString(); - } - const key = extractKey(item, value).key; - result.push(valueToKey_default(key)); - } - return { - type: "found", - key: result - }; - } - if (keyPath === "") { - return { - type: "found", - key: value - }; - } - let remainingKeyPath = keyPath; - let object = value; - while (remainingKeyPath !== null) { - let identifier; - const i = remainingKeyPath.indexOf("."); - if (i >= 0) { - identifier = remainingKeyPath.slice(0, i); - remainingKeyPath = remainingKeyPath.slice(i + 1); - } else { - identifier = remainingKeyPath; - remainingKeyPath = null; - } - const isSpecialIdentifier = identifier === "length" && (typeof object === "string" || Array.isArray(object)) || (identifier === "size" || identifier === "type") && typeof Blob !== "undefined" && object instanceof Blob || (identifier === "name" || identifier === "lastModified") && typeof File !== "undefined" && object instanceof File; - if (!isSpecialIdentifier && (typeof object !== "object" || object === null || !Object.hasOwn(object, identifier))) { - return { - type: "notFound" - }; - } - object = object[identifier]; - } - return { - type: "found", - key: object - }; -}; -var extractKey_default = extractKey; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/cloneValueForInsertion.js -function cloneValueForInsertion(value, transaction) { - if (transaction._state !== "active") { - throw new Error("Assert: transaction state is active"); - } - transaction._state = "inactive"; - try { - return structuredClone(value); - } finally { - transaction._state = "active"; - } -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBCursor.js -var getEffectiveObjectStore = (cursor) => { - if (cursor.source instanceof FDBObjectStore_default) { - return cursor.source; - } - return cursor.source.objectStore; -}; -var makeKeyRange = (range, lowers, uppers) => { - let lower = range !== void 0 ? range.lower : void 0; - let upper = range !== void 0 ? range.upper : void 0; - for (const lowerTemp of lowers) { - if (lowerTemp === void 0) { - continue; - } - if (lower === void 0 || cmp_default(lower, lowerTemp) === 1) { - lower = lowerTemp; - } - } - for (const upperTemp of uppers) { - if (upperTemp === void 0) { - continue; - } - if (upper === void 0 || cmp_default(upper, upperTemp) === -1) { - upper = upperTemp; - } - } - if (lower !== void 0 && upper !== void 0) { - return FDBKeyRange_default.bound(lower, upper); - } - if (lower !== void 0) { - return FDBKeyRange_default.lowerBound(lower); - } - if (upper !== void 0) { - return FDBKeyRange_default.upperBound(upper); - } -}; -var FDBCursor = class { - _gotValue = false; - _position = void 0; - // Key of previously returned record - _objectStorePosition = void 0; - _keyOnly = false; - _key = void 0; - _primaryKey = void 0; - constructor(source, range, direction = "next", request, keyOnly = false) { - this._range = range; - this._source = source; - this._direction = direction; - this._request = request; - this._keyOnly = keyOnly; - } - // Read only properties - get source() { - return this._source; - } - set source(val) { - } - get request() { - return this._request; - } - set request(val) { - } - get direction() { - return this._direction; - } - set direction(val) { - } - get key() { - return this._key; - } - set key(val) { - } - get primaryKey() { - return this._primaryKey; - } - set primaryKey(val) { - } - // https://w3c.github.io/IndexedDB/#iterate-a-cursor - _iterate(key, primaryKey) { - const sourceIsObjectStore = this.source instanceof FDBObjectStore_default; - const records = this.source instanceof FDBObjectStore_default ? this.source._rawObjectStore.records : this.source._rawIndex.records; - let foundRecord; - if (this.direction === "next") { - const range = makeKeyRange(this._range, [key, this._position], []); - for (const record of records.values(range)) { - const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0; - const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0; - if (key !== void 0) { - if (cmpResultKey === -1) { - continue; - } - } - if (primaryKey !== void 0) { - if (cmpResultKey === -1) { - continue; - } - const cmpResultPrimaryKey = cmp_default(record.value, primaryKey); - if (cmpResultKey === 0 && cmpResultPrimaryKey === -1) { - continue; - } - } - if (this._position !== void 0 && sourceIsObjectStore) { - if (cmpResultPosition !== 1) { - continue; - } - } - if (this._position !== void 0 && !sourceIsObjectStore) { - if (cmpResultPosition === -1) { - continue; - } - if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== 1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - foundRecord = record; - break; - } - } else if (this.direction === "nextunique") { - const range = makeKeyRange(this._range, [key, this._position], []); - for (const record of records.values(range)) { - if (key !== void 0) { - if (cmp_default(record.key, key) === -1) { - continue; - } - } - if (this._position !== void 0) { - if (cmp_default(record.key, this._position) !== 1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - foundRecord = record; - break; - } - } else if (this.direction === "prev") { - const range = makeKeyRange(this._range, [], [key, this._position]); - for (const record of records.values(range, "prev")) { - const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0; - const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0; - if (key !== void 0) { - if (cmpResultKey === 1) { - continue; - } - } - if (primaryKey !== void 0) { - if (cmpResultKey === 1) { - continue; - } - const cmpResultPrimaryKey = cmp_default(record.value, primaryKey); - if (cmpResultKey === 0 && cmpResultPrimaryKey === 1) { - continue; - } - } - if (this._position !== void 0 && sourceIsObjectStore) { - if (cmpResultPosition !== -1) { - continue; - } - } - if (this._position !== void 0 && !sourceIsObjectStore) { - if (cmpResultPosition === 1) { - continue; - } - if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== -1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - foundRecord = record; - break; - } - } else if (this.direction === "prevunique") { - let tempRecord; - const range = makeKeyRange(this._range, [], [key, this._position]); - for (const record of records.values(range, "prev")) { - if (key !== void 0) { - if (cmp_default(record.key, key) === 1) { - continue; - } - } - if (this._position !== void 0) { - if (cmp_default(record.key, this._position) !== -1) { - continue; - } - } - if (this._range !== void 0) { - if (!this._range.includes(record.key)) { - continue; - } - } - tempRecord = record; - break; - } - if (tempRecord) { - foundRecord = records.get(tempRecord.key); - } - } - let result; - if (!foundRecord) { - this._key = void 0; - if (!sourceIsObjectStore) { - this._objectStorePosition = void 0; - } - if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { - this.value = void 0; - } - result = null; - } else { - this._position = foundRecord.key; - if (!sourceIsObjectStore) { - this._objectStorePosition = foundRecord.value; - } - this._key = foundRecord.key; - if (sourceIsObjectStore) { - this._primaryKey = structuredClone(foundRecord.key); - if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { - this.value = structuredClone(foundRecord.value); - } - } else { - this._primaryKey = structuredClone(foundRecord.value); - if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { - if (this.source instanceof FDBObjectStore_default) { - throw new Error("This should never happen"); - } - const value = this.source.objectStore._rawObjectStore.getValue(foundRecord.value); - this.value = structuredClone(value); - } - } - this._gotValue = true; - result = this; - } - return result; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-update-IDBRequest-any-value - update(value) { - if (value === void 0) { - throw new TypeError(); - } - const effectiveObjectStore = getEffectiveObjectStore(this); - const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue || !Object.hasOwn(this, "value")) { - throw new InvalidStateError(); - } - const clone = cloneValueForInsertion(value, transaction); - if (effectiveObjectStore.keyPath !== null) { - let tempKey; - try { - tempKey = extractKey_default(effectiveObjectStore.keyPath, clone).key; - } catch (err) { - } - if (cmp_default(tempKey, effectiveKey) !== 0) { - throw new DataError(); - } - } - const record = { - key: effectiveKey, - value: clone - }; - return transaction._execRequestAsync({ - operation: effectiveObjectStore._rawObjectStore.storeRecord.bind(effectiveObjectStore._rawObjectStore, record, false, transaction._rollbackLog), - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-advance-void-unsigned-long-count - advance(count) { - if (!Number.isInteger(count) || count <= 0) { - throw new TypeError(); - } - const effectiveObjectStore = getEffectiveObjectStore(this); - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue) { - throw new InvalidStateError(); - } - if (this._request) { - this._request.readyState = "pending"; - } - transaction._execRequestAsync({ - operation: () => { - let result; - for (let i = 0; i < count; i++) { - result = this._iterate(); - if (!result) { - break; - } - } - return result; - }, - request: this._request, - source: this.source - }); - this._gotValue = false; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-continue-void-any-key - continue(key) { - const effectiveObjectStore = getEffectiveObjectStore(this); - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue) { - throw new InvalidStateError(); - } - if (key !== void 0) { - key = valueToKey_default(key); - const cmpResult = cmp_default(key, this._position); - if (cmpResult <= 0 && (this.direction === "next" || this.direction === "nextunique") || cmpResult >= 0 && (this.direction === "prev" || this.direction === "prevunique")) { - throw new DataError(); - } - } - if (this._request) { - this._request.readyState = "pending"; - } - transaction._execRequestAsync({ - operation: this._iterate.bind(this, key), - request: this._request, - source: this.source - }); - this._gotValue = false; - } - // hthttps://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey - continuePrimaryKey(key, primaryKey) { - const effectiveObjectStore = getEffectiveObjectStore(this); - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (this.source instanceof FDBObjectStore_default || this.direction !== "next" && this.direction !== "prev") { - throw new InvalidAccessError(); - } - if (!this._gotValue) { - throw new InvalidStateError(); - } - if (key === void 0 || primaryKey === void 0) { - throw new DataError(); - } - key = valueToKey_default(key); - const cmpResult = cmp_default(key, this._position); - if (cmpResult === -1 && this.direction === "next" || cmpResult === 1 && this.direction === "prev") { - throw new DataError(); - } - const cmpResult2 = cmp_default(primaryKey, this._objectStorePosition); - if (cmpResult === 0) { - if (cmpResult2 <= 0 && this.direction === "next" || cmpResult2 >= 0 && this.direction === "prev") { - throw new DataError(); - } - } - if (this._request) { - this._request.readyState = "pending"; - } - transaction._execRequestAsync({ - operation: this._iterate.bind(this, key, primaryKey), - request: this._request, - source: this.source - }); - this._gotValue = false; - } - delete() { - const effectiveObjectStore = getEffectiveObjectStore(this); - const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; - const transaction = effectiveObjectStore.transaction; - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (effectiveObjectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { - throw new InvalidStateError(); - } - if (!this._gotValue || !Object.hasOwn(this, "value")) { - throw new InvalidStateError(); - } - return transaction._execRequestAsync({ - operation: effectiveObjectStore._rawObjectStore.deleteRecord.bind(effectiveObjectStore._rawObjectStore, effectiveKey, transaction._rollbackLog), - source: this - }); - } - get [Symbol.toStringTag]() { - return "IDBCursor"; - } -}; -var FDBCursor_default = FDBCursor; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBCursorWithValue.js -var FDBCursorWithValue = class extends FDBCursor_default { - value = void 0; - constructor(source, range, direction, request) { - super(source, range, direction, request); - } - get [Symbol.toStringTag]() { - return "IDBCursorWithValue"; - } -}; -var FDBCursorWithValue_default = FDBCursorWithValue; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeEventTarget.js -var stopped = (event, listener) => { - return event.immediatePropagationStopped || event.eventPhase === event.CAPTURING_PHASE && listener.capture === false || event.eventPhase === event.BUBBLING_PHASE && listener.capture === true; -}; -var invokeEventListeners = (event, obj) => { - event.currentTarget = obj; - const errors = []; - const invoke = (callbackOrObject) => { - try { - const callback2 = typeof callbackOrObject === "function" ? callbackOrObject : callbackOrObject.handleEvent; - callback2.call(event.currentTarget, event); - } catch (err) { - errors.push(err); - } - }; - for (const listener of obj.listeners.slice()) { - if (event.type !== listener.type || stopped(event, listener)) { - continue; - } - invoke(listener.callback); - } - const typeToProp = { - abort: "onabort", - blocked: "onblocked", - close: "onclose", - complete: "oncomplete", - error: "onerror", - success: "onsuccess", - upgradeneeded: "onupgradeneeded", - versionchange: "onversionchange" - }; - const prop = typeToProp[event.type]; - if (prop === void 0) { - throw new Error(`Unknown event type: "${event.type}"`); - } - const callback = event.currentTarget[prop]; - if (callback) { - const listener = { - callback, - capture: false, - type: event.type - }; - if (!stopped(event, listener)) { - invoke(listener.callback); - } - } - if (errors.length) { - throw new AggregateError(errors); - } -}; -var FakeEventTarget = class { - listeners = []; - // These will be overridden in individual subclasses and made not readonly - addEventListener(type, callback, options) { - const capture = !!(typeof options === "object" && options ? options.capture : options); - this.listeners.push({ - callback, - capture, - type - }); - } - removeEventListener(type, callback, options) { - const capture = !!(typeof options === "object" && options ? options.capture : options); - const i = this.listeners.findIndex((listener) => { - return listener.type === type && listener.callback === callback && listener.capture === capture; - }); - this.listeners.splice(i, 1); - } - // http://www.w3.org/TR/dom/#dispatching-events - dispatchEvent(event) { - if (event.dispatched || !event.initialized) { - throw new InvalidStateError("The object is in an invalid state."); - } - event.isTrusted = false; - event.dispatched = true; - event.target = this; - event.eventPhase = event.CAPTURING_PHASE; - for (const obj of event.eventPath) { - if (!event.propagationStopped) { - invokeEventListeners(event, obj); - } - } - event.eventPhase = event.AT_TARGET; - if (!event.propagationStopped) { - invokeEventListeners(event, event.target); - } - if (event.bubbles) { - event.eventPath.reverse(); - event.eventPhase = event.BUBBLING_PHASE; - for (const obj of event.eventPath) { - if (!event.propagationStopped) { - invokeEventListeners(event, obj); - } - } - } - event.dispatched = false; - event.eventPhase = event.NONE; - event.currentTarget = null; - if (event.canceled) { - return false; - } - return true; - } -}; -var FakeEventTarget_default = FakeEventTarget; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBRequest.js -var FDBRequest = class extends FakeEventTarget_default { - _result = null; - _error = null; - source = null; - transaction = null; - readyState = "pending"; - onsuccess = null; - onerror = null; - get error() { - if (this.readyState === "pending") { - throw new InvalidStateError(); - } - return this._error; - } - set error(value) { - this._error = value; - } - get result() { - if (this.readyState === "pending") { - throw new InvalidStateError(); - } - return this._result; - } - set result(value) { - this._result = value; - } - get [Symbol.toStringTag]() { - return "IDBRequest"; - } -}; -var FDBRequest_default = FDBRequest; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeDOMStringList.js -var FakeDOMStringList = class { - constructor(...values) { - this._values = values; - for (let i = 0; i < values.length; i++) { - this[i] = values[i]; - } - } - contains(value) { - return this._values.includes(value); - } - item(i) { - if (i < 0 || i >= this._values.length) { - return null; - } - return this._values[i]; - } - get length() { - return this._values.length; - } - [Symbol.iterator]() { - return this._values[Symbol.iterator](); - } - // Handled by proxy - // Used internally, should not be used by others. I could maybe get rid of these and replace rather than mutate, but too lazy to check the spec. - _push(...values) { - for (let i = 0; i < values.length; i++) { - this[this._values.length + i] = values[i]; - } - this._values.push(...values); - } - _sort(...values) { - this._values.sort(...values); - for (let i = 0; i < this._values.length; i++) { - this[i] = this._values[i]; - } - return this; - } -}; -var FakeDOMStringList_default = FakeDOMStringList; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKeyRange.js -var valueToKeyRange = (value, nullDisallowedFlag = false) => { - if (value instanceof FDBKeyRange_default) { - return value; - } - if (value === null || value === void 0) { - if (nullDisallowedFlag) { - throw new DataError(); - } - return new FDBKeyRange_default(void 0, void 0, false, false); - } - const key = valueToKey_default(value); - return FDBKeyRange_default.only(key); -}; -var valueToKeyRange_default = valueToKeyRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/getKeyPath.js -var convertKey = (key) => typeof key === "object" && key ? key + "" : key; -function getKeyPath(keyPath) { - return Array.isArray(keyPath) ? keyPath.map(convertKey) : convertKey(keyPath); -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/isPotentiallyValidKeyRange.js -var isPotentiallyValidKeyRange = (value) => { - if (value instanceof FDBKeyRange_default) { - return true; - } - const key = valueToKeyWithoutThrowing_default(value); - return key !== INVALID_TYPE; -}; -var isPotentiallyValidKeyRange_default = isPotentiallyValidKeyRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/enforceRange.js -var enforceRange = (num, type) => { - const min = 0; - const max = type === "unsigned long" ? 4294967295 : 9007199254740991; - if (isNaN(num) || num < min || num > max) { - throw new TypeError(); - } - if (num >= 0) { - return Math.floor(num); - } -}; -var enforceRange_default = enforceRange; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/extractGetAllOptions.js -var extractGetAllOptions = (queryOrOptions, count, numArguments) => { - let query; - let direction; - if (queryOrOptions === void 0 || queryOrOptions === null || isPotentiallyValidKeyRange_default(queryOrOptions)) { - query = queryOrOptions; - if (numArguments > 1 && count !== void 0) { - count = enforceRange_default(count, "unsigned long"); - } - } else { - const getAllOptions = queryOrOptions; - if (getAllOptions.query !== void 0) { - query = getAllOptions.query; - } - if (getAllOptions.count !== void 0) { - count = enforceRange_default(getAllOptions.count, "unsigned long"); - } - if (getAllOptions.direction !== void 0) { - direction = getAllOptions.direction; - } - } - return { - query, - count, - direction - }; -}; -var extractGetAllOptions_default = extractGetAllOptions; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBIndex.js -var confirmActiveTransaction = (index) => { - if (index._rawIndex.deleted || index.objectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (index.objectStore.transaction._state !== "active") { - throw new TransactionInactiveError(); - } -}; -var FDBIndex = class { - constructor(objectStore, rawIndex) { - this._rawIndex = rawIndex; - this._name = rawIndex.name; - this.objectStore = objectStore; - this.keyPath = getKeyPath(rawIndex.keyPath); - this.multiEntry = rawIndex.multiEntry; - this.unique = rawIndex.unique; - } - get name() { - return this._name; - } - // https://w3c.github.io/IndexedDB/#dom-idbindex-name - set name(name) { - const transaction = this.objectStore.transaction; - if (!transaction.db._runningVersionchangeTransaction) { - throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); - } - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - if (this._rawIndex.deleted || this.objectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - name = String(name); - if (name === this._name) { - return; - } - if (this.objectStore.indexNames.contains(name)) { - throw new ConstraintError(); - } - const oldName = this._name; - const oldIndexNames = [...this.objectStore.indexNames]; - this._name = name; - this._rawIndex.name = name; - this.objectStore._indexesCache.delete(oldName); - this.objectStore._indexesCache.set(name, this); - this.objectStore._rawObjectStore.rawIndexes.delete(oldName); - this.objectStore._rawObjectStore.rawIndexes.set(name, this._rawIndex); - this.objectStore.indexNames = new FakeDOMStringList_default(...Array.from(this.objectStore._rawObjectStore.rawIndexes.keys()).filter((indexName) => { - const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName); - return index && !index.deleted; - }).sort()); - if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) { - transaction._rollbackLog.push(() => { - this._name = oldName; - this._rawIndex.name = oldName; - this.objectStore._indexesCache.delete(name); - this.objectStore._indexesCache.set(oldName, this); - this.objectStore._rawObjectStore.rawIndexes.delete(name); - this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex); - this.objectStore.indexNames = new FakeDOMStringList_default(...oldIndexNames); - }); - } - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction - openCursor(range, direction) { - confirmActiveTransaction(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.objectStore.transaction; - const cursor = new FDBCursorWithValue_default(this, range, direction, request); - return this.objectStore.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openKeyCursor-IDBRequest-any-range-IDBCursorDirection-direction - openKeyCursor(range, direction) { - confirmActiveTransaction(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.objectStore.transaction; - const cursor = new FDBCursor_default(this, range, direction, request, true); - return this.objectStore.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - get(key) { - confirmActiveTransaction(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getValue.bind(this._rawIndex, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbindex-getall - getAll(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction(this); - const range = valueToKeyRange_default(options.query); - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getAllValues.bind(this._rawIndex, range, options.count, options.direction), - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-getKey-IDBRequest-any-key - getKey(key) { - confirmActiveTransaction(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getKey.bind(this._rawIndex, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys - getAllKeys(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction(this); - const range = valueToKeyRange_default(options.query); - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getAllKeys.bind(this._rawIndex, range, options.count, options.direction), - source: this - }); - } - // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords - getAllRecords(options) { - let query; - let count; - let direction; - if (options !== void 0) { - if (options.query !== void 0) { - query = options.query; - } - if (options.count !== void 0) { - count = enforceRange_default(options.count, "unsigned long"); - } - if (options.direction !== void 0) { - direction = options.direction; - } - } - confirmActiveTransaction(this); - const range = valueToKeyRange_default(query); - return this.objectStore.transaction._execRequestAsync({ - operation: this._rawIndex.getAllRecords.bind(this._rawIndex, range, count, direction), - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-count-IDBRequest-any-key - count(key) { - confirmActiveTransaction(this); - if (key === null) { - key = void 0; - } - if (key !== void 0 && !(key instanceof FDBKeyRange_default)) { - key = FDBKeyRange_default.only(valueToKey_default(key)); - } - return this.objectStore.transaction._execRequestAsync({ - operation: () => { - return this._rawIndex.count(key); - }, - source: this - }); - } - get [Symbol.toStringTag]() { - return "IDBIndex"; - } -}; -var FDBIndex_default = FDBIndex; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/canInjectKey.js -var canInjectKey = (keyPath, value) => { - if (Array.isArray(keyPath)) { - throw new Error("The key paths used in this section are always strings and never sequences, since it is not possible to create a object store which has a key generator and also has a key path that is a sequence."); - } - const identifiers = keyPath.split("."); - if (identifiers.length === 0) { - throw new Error("Assert: identifiers is not empty"); - } - identifiers.pop(); - for (const identifier of identifiers) { - if (typeof value !== "object" && !Array.isArray(value)) { - return false; - } - const hop = Object.hasOwn(value, identifier); - if (!hop) { - return true; - } - value = value[identifier]; - } - return typeof value === "object" || Array.isArray(value); -}; -var canInjectKey_default = canInjectKey; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBRecord.js -var FDBRecord = class { - constructor(key, primaryKey, value) { - this._key = key; - this._primaryKey = primaryKey; - this._value = value; - } - get key() { - return this._key; - } - set key(_) { - } - get primaryKey() { - return this._primaryKey; - } - set primaryKey(_) { - } - get value() { - return this._value; - } - set value(_) { - } - get [Symbol.toStringTag]() { - return "IDBRecord"; - } -}; -var FDBRecord_default = FDBRecord; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js -var MAX_TOMBSTONE_FACTOR = 2 / 3; -var EVERYTHING_KEY_RANGE = new FDBKeyRange_default(void 0, void 0, false, false); -var BinarySearchTree = class { - _numTombstones = 0; - _numNodes = 0; - /** - * - * @param keysAreUnique - whether keys can be unique, and thus whether we cn skip checking `record.value` when - * comparing. This is basically used to distinguish ObjectStores (where the value is the entire object, not used - * as a key) from non-unique Indexes (where both the key and the value are meaningful keys used for sorting) - */ - constructor(keysAreUnique) { - this._keysAreUnique = !!keysAreUnique; - } - size() { - return this._numNodes - this._numTombstones; - } - get(record) { - return this._getByComparator(this._root, (otherRecord) => this._compare(record, otherRecord)); - } - contains(record) { - return !!this.get(record); - } - _compare(a, b) { - const keyComparison = cmp_default(a.key, b.key); - if (keyComparison !== 0) { - return keyComparison; - } - return this._keysAreUnique ? 0 : cmp_default(a.value, b.value); - } - _getByComparator(node, comparator) { - let current = node; - while (current) { - const comparison = comparator(current.record); - if (comparison < 0) { - current = current.left; - } else if (comparison > 0) { - current = current.right; - } else { - return current.record; - } - } - } - /** - * Put a new record, and return the overwritten record if an overwrite occurred. - * @param record - * @param noOverwrite - throw a ConstraintError in case of overwrite - */ - put(record, noOverwrite = false) { - if (!this._root) { - this._root = { - record, - left: void 0, - right: void 0, - parent: void 0, - deleted: false, - // the root is always black in a red-black tree - red: false - }; - this._numNodes++; - return; - } - return this._put(this._root, record, noOverwrite); - } - _put(node, record, noOverwrite) { - const comparison = this._compare(record, node.record); - if (comparison < 0) { - if (node.left) { - return this._put(node.left, record, noOverwrite); - } else { - node.left = { - record, - left: void 0, - right: void 0, - parent: node, - deleted: false, - red: true - }; - this._onNewNodeInserted(node.left); - } - } else if (comparison > 0) { - if (node.right) { - return this._put(node.right, record, noOverwrite); - } else { - node.right = { - record, - left: void 0, - right: void 0, - parent: node, - deleted: false, - red: true - }; - this._onNewNodeInserted(node.right); - } - } else if (node.deleted) { - node.deleted = false; - node.record = record; - this._numTombstones--; - } else if (noOverwrite) { - throw new ConstraintError(); - } else { - const overwrittenRecord = node.record; - node.record = record; - return overwrittenRecord; - } - } - delete(record) { - if (!this._root) { - return; - } - this._delete(this._root, record); - if (this._numTombstones > this._numNodes * MAX_TOMBSTONE_FACTOR) { - const records = [...this.getAllRecords()]; - this._root = this._rebuild(records, void 0, false); - this._numNodes = records.length; - this._numTombstones = 0; - } - } - _delete(node, record) { - if (!node) { - return; - } - const comparison = this._compare(record, node.record); - if (comparison < 0) { - this._delete(node.left, record); - } else if (comparison > 0) { - this._delete(node.right, record); - } else if (!node.deleted) { - this._numTombstones++; - node.deleted = true; - } - } - *getAllRecords(descending = false) { - yield* this.getRecords(EVERYTHING_KEY_RANGE, descending); - } - *getRecords(keyRange, descending = false) { - yield* this._getRecordsForNode(this._root, keyRange, descending); - } - *_getRecordsForNode(node, keyRange, descending = false) { - if (!node) { - return; - } - yield* this._findRecords(node, keyRange, descending); - } - *_findRecords(node, keyRange, descending = false) { - const { - lower, - upper, - lowerOpen, - upperOpen - } = keyRange; - const { - record: { - key - } - } = node; - const lowerComparison = lower === void 0 ? -1 : cmp_default(lower, key); - const upperComparison = upper === void 0 ? 1 : cmp_default(upper, key); - const moreLeft = this._keysAreUnique ? lowerComparison < 0 : lowerComparison <= 0; - const moreRight = this._keysAreUnique ? upperComparison > 0 : upperComparison >= 0; - const moreStart = descending ? moreRight : moreLeft; - const moreEnd = descending ? moreLeft : moreRight; - const start = descending ? "right" : "left"; - const end = descending ? "left" : "right"; - const lowerMatches = lowerOpen ? lowerComparison < 0 : lowerComparison <= 0; - const upperMatches = upperOpen ? upperComparison > 0 : upperComparison >= 0; - if (moreStart && node[start]) { - yield* this._findRecords(node[start], keyRange, descending); - } - if (lowerMatches && upperMatches && !node.deleted) { - yield node.record; - } - if (moreEnd && node[end]) { - yield* this._findRecords(node[end], keyRange, descending); - } - } - _onNewNodeInserted(newNode) { - this._numNodes++; - this._rebalanceTree(newNode); - } - // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion - _rebalanceTree(node) { - let parent = node.parent; - do { - if (!parent.red) { - return; - } - const grandparent = parent.parent; - if (!grandparent) { - parent.red = false; - return; - } - const parentIsRightChild = parent === grandparent.right; - const uncle = parentIsRightChild ? grandparent.left : grandparent.right; - if (!uncle || !uncle.red) { - if (node === (parentIsRightChild ? parent.left : parent.right)) { - this._rotateSubtree(parent, parentIsRightChild); - node = parent; - parent = parentIsRightChild ? grandparent.right : grandparent.left; - } - this._rotateSubtree(grandparent, !parentIsRightChild); - parent.red = false; - grandparent.red = true; - return; - } - parent.red = false; - uncle.red = false; - grandparent.red = true; - node = grandparent; - } while (node.parent ? parent = node.parent : false); - } - // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Implementation - _rotateSubtree(node, right) { - const parent = node.parent; - const newRoot = right ? node.left : node.right; - const newChild = right ? newRoot.right : newRoot.left; - node[right ? "left" : "right"] = newChild; - if (newChild) { - newChild.parent = node; - } - newRoot[right ? "right" : "left"] = node; - newRoot.parent = parent; - node.parent = newRoot; - if (parent) { - parent[node === parent.right ? "right" : "left"] = newRoot; - } else { - this._root = newRoot; - } - return newRoot; - } - // rebuild the whole tree from scratch, used to avoid too many deletion tombstones accumulating - _rebuild(records, parent, red) { - const { - length - } = records; - if (!length) { - return void 0; - } - const mid = length >>> 1; - const node = { - record: records[mid], - left: void 0, - right: void 0, - parent, - deleted: false, - red - }; - const left = this._rebuild(records.slice(0, mid), node, !red); - const right = this._rebuild(records.slice(mid + 1), node, !red); - node.left = left; - node.right = right; - return node; - } -}; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/RecordStore.js -var RecordStore = class { - constructor(keysAreUnique) { - this.keysAreUnique = keysAreUnique; - this.records = new BinarySearchTree(this.keysAreUnique); - } - get(key) { - const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); - return this.records.getRecords(range).next().value; - } - /** - * Put a new record, and return the overwritten record if an overwrite occurred. - * @param newRecord - * @param noOverwrite - throw a ConstraintError in case of overwrite - */ - put(newRecord, noOverwrite = false) { - return this.records.put(newRecord, noOverwrite); - } - delete(key) { - const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); - const deletedRecords = [...this.records.getRecords(range)]; - for (const record of deletedRecords) { - this.records.delete(record); - } - return deletedRecords; - } - deleteByValue(key) { - const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); - const deletedRecords = []; - for (const record of this.records.getAllRecords()) { - if (range.includes(record.value)) { - this.records.delete(record); - deletedRecords.push(record); - } - } - return deletedRecords; - } - clear() { - const deletedRecords = [...this.records.getAllRecords()]; - this.records = new BinarySearchTree(this.keysAreUnique); - return deletedRecords; - } - values(range, direction = "next") { - const descending = direction === "prev" || direction === "prevunique"; - const records = range ? this.records.getRecords(range, descending) : this.records.getAllRecords(descending); - return { - [Symbol.iterator]: () => { - const next = () => { - return records.next(); - }; - if (direction === "next" || direction === "prev") { - return { - next - }; - } - if (direction === "nextunique") { - let previousValue = void 0; - return { - next: () => { - let current2 = next(); - while (!current2.done && previousValue !== void 0 && cmp_default(previousValue.key, current2.value.key) === 0) { - current2 = next(); - } - previousValue = current2.value; - return current2; - } - }; - } - let current = next(); - let nextResult = next(); - return { - next: () => { - while (!nextResult.done && cmp_default(current.value.key, nextResult.value.key) === 0) { - current = nextResult; - nextResult = next(); - } - const result = current; - current = nextResult; - nextResult = next(); - return result; - } - }; - } - }; - } - size() { - return this.records.size(); - } -}; -var RecordStore_default = RecordStore; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/Index.js -var Index = class { - deleted = false; - // Initialized should be used to decide whether to throw an error or abort the versionchange transaction when there is a - // constraint - initialized = false; - constructor(rawObjectStore, name, keyPath, multiEntry, unique) { - this.rawObjectStore = rawObjectStore; - this.name = name; - this.keyPath = keyPath; - this.multiEntry = multiEntry; - this.unique = unique; - this.records = new RecordStore_default(unique); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-index - getKey(key) { - const record = this.records.get(key); - return record !== void 0 ? record.value : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index - getAllKeys(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(structuredClone(record.value)); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#index-referenced-value-retrieval-operation - getValue(key) { - const record = this.records.get(key); - return record !== void 0 ? this.rawObjectStore.getValue(record.value) : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index - getAllValues(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(this.rawObjectStore.getValue(record.value)); - if (records.length >= count) { - break; - } - } - return records; - } - // https://www.w3.org/TR/IndexedDB/#dom-idbindex-getallrecords - getAllRecords(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(this.rawObjectStore.getKey(record.value)), this.rawObjectStore.getValue(record.value))); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store (step 7) - storeRecord(newRecord) { - let indexKey; - try { - indexKey = extractKey_default(this.keyPath, newRecord.value).key; - } catch (err) { - if (err.name === "DataError") { - return; - } - throw err; - } - if (!this.multiEntry || !Array.isArray(indexKey)) { - try { - valueToKey_default(indexKey); - } catch (e) { - return; - } - } else { - const keep = []; - for (const part of indexKey) { - if (keep.indexOf(part) < 0) { - try { - keep.push(valueToKey_default(part)); - } catch (err) { - } - } - } - indexKey = keep; - } - if (!this.multiEntry || !Array.isArray(indexKey)) { - if (this.unique) { - const existingRecord = this.records.get(indexKey); - if (existingRecord) { - throw new ConstraintError(); - } - } - } else { - if (this.unique) { - for (const individualIndexKey of indexKey) { - const existingRecord = this.records.get(individualIndexKey); - if (existingRecord) { - throw new ConstraintError(); - } - } - } - } - if (!this.multiEntry || !Array.isArray(indexKey)) { - this.records.put({ - key: indexKey, - value: newRecord.key - }); - } else { - for (const individualIndexKey of indexKey) { - this.records.put({ - key: individualIndexKey, - value: newRecord.key - }); - } - } - } - initialize(transaction) { - if (this.initialized) { - throw new Error("Index already initialized"); - } - transaction._execRequestAsync({ - operation: () => { - try { - for (const record of this.rawObjectStore.records.values()) { - this.storeRecord(record); - } - this.initialized = true; - } catch (err) { - transaction._abort(err.name); - } - }, - source: null - }); - } - count(range) { - let count = 0; - for (const record of this.records.values(range)) { - count += 1; - } - return count; - } -}; -var Index_default = Index; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/validateKeyPath.js -var validateKeyPath = (keyPath, parent) => { - if (keyPath !== void 0 && keyPath !== null && typeof keyPath !== "string" && keyPath.toString && (parent === "array" || !Array.isArray(keyPath))) { - keyPath = keyPath.toString(); - } - if (typeof keyPath === "string") { - if (keyPath === "" && parent !== "string") { - return; - } - try { - const validIdentifierRegex = ( - // eslint-disable-next-line no-misleading-character-class - /^(?:[$A-Z_a-z\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B2\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\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\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\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\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-\uAB5F\uAB64\uAB65\uABC0-\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])(?:[$0-9A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC])*$/ - ); - if (keyPath.length >= 1 && validIdentifierRegex.test(keyPath)) { - return; - } - } catch (err) { - throw new SyntaxError2(err.message); - } - if (keyPath.indexOf(" ") >= 0) { - throw new SyntaxError2("The keypath argument contains an invalid key path (no spaces allowed)."); - } - } - if (Array.isArray(keyPath) && keyPath.length > 0) { - if (parent) { - throw new SyntaxError2("The keypath argument contains an invalid key path (nested arrays)."); - } - for (const part of keyPath) { - validateKeyPath(part, "array"); - } - return; - } else if (typeof keyPath === "string" && keyPath.indexOf(".") >= 0) { - keyPath = keyPath.split("."); - for (const part of keyPath) { - validateKeyPath(part, "string"); - } - return; - } - throw new SyntaxError2(); -}; -var validateKeyPath_default = validateKeyPath; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBObjectStore.js -var confirmActiveTransaction2 = (objectStore) => { - if (objectStore._rawObjectStore.deleted) { - throw new InvalidStateError(); - } - if (objectStore.transaction._state !== "active") { - throw new TransactionInactiveError(); - } -}; -var buildRecordAddPut = (objectStore, value, key) => { - confirmActiveTransaction2(objectStore); - if (objectStore.transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (objectStore.keyPath !== null) { - if (key !== void 0) { - throw new DataError(); - } - } - const clone = cloneValueForInsertion(value, objectStore.transaction); - if (objectStore.keyPath !== null) { - const tempKey = extractKey_default(objectStore.keyPath, clone); - if (tempKey.type === "found") { - valueToKey_default(tempKey.key); - } else { - if (!objectStore._rawObjectStore.keyGenerator) { - throw new DataError(); - } else if (!canInjectKey_default(objectStore.keyPath, clone)) { - throw new DataError(); - } - } - } - if (objectStore.keyPath === null && objectStore._rawObjectStore.keyGenerator === null && key === void 0) { - throw new DataError(); - } - if (key !== void 0) { - key = valueToKey_default(key); - } - return { - key, - value: clone - }; -}; -var FDBObjectStore = class { - _indexesCache = /* @__PURE__ */ new Map(); - constructor(transaction, rawObjectStore) { - this._rawObjectStore = rawObjectStore; - this._name = rawObjectStore.name; - this.keyPath = getKeyPath(rawObjectStore.keyPath); - this.autoIncrement = rawObjectStore.autoIncrement; - this.transaction = transaction; - this.indexNames = new FakeDOMStringList_default(...Array.from(rawObjectStore.rawIndexes.keys()).sort()); - } - get name() { - return this._name; - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-name - set name(name) { - const transaction = this.transaction; - if (!transaction.db._runningVersionchangeTransaction) { - throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); - } - confirmActiveTransaction2(this); - name = String(name); - if (name === this._name) { - return; - } - if (this._rawObjectStore.rawDatabase.rawObjectStores.has(name)) { - throw new ConstraintError(); - } - const oldName = this._name; - const oldObjectStoreNames = [...transaction.db.objectStoreNames]; - this._name = name; - this._rawObjectStore.name = name; - this.transaction._objectStoresCache.delete(oldName); - this.transaction._objectStoresCache.set(name, this); - this._rawObjectStore.rawDatabase.rawObjectStores.delete(oldName); - this._rawObjectStore.rawDatabase.rawObjectStores.set(name, this._rawObjectStore); - transaction.db.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._rawObjectStore.rawDatabase.rawObjectStores.keys()).filter((objectStoreName) => { - const objectStore = this._rawObjectStore.rawDatabase.rawObjectStores.get(objectStoreName); - return objectStore && !objectStore.deleted; - }).sort()); - const oldScope = new Set(transaction._scope); - const oldTransactionObjectStoreNames = [...transaction.objectStoreNames]; - this.transaction._scope.delete(oldName); - transaction._scope.add(name); - transaction.objectStoreNames = new FakeDOMStringList_default(...Array.from(transaction._scope).sort()); - if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) { - transaction._rollbackLog.push(() => { - this._name = oldName; - this._rawObjectStore.name = oldName; - this.transaction._objectStoresCache.delete(name); - this.transaction._objectStoresCache.set(oldName, this); - this._rawObjectStore.rawDatabase.rawObjectStores.delete(name); - this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore); - transaction.db.objectStoreNames = new FakeDOMStringList_default(...oldObjectStoreNames); - transaction._scope = oldScope; - transaction.objectStoreNames = new FakeDOMStringList_default(...oldTransactionObjectStoreNames); - }); - } - } - put(value, key) { - if (arguments.length === 0) { - throw new TypeError(); - } - const record = buildRecordAddPut(this, value, key); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, false, this.transaction._rollbackLog), - source: this - }); - } - add(value, key) { - if (arguments.length === 0) { - throw new TypeError(); - } - const record = buildRecordAddPut(this, value, key); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, true, this.transaction._rollbackLog), - source: this - }); - } - delete(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - confirmActiveTransaction2(this); - if (this.transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.deleteRecord.bind(this._rawObjectStore, key, this.transaction._rollbackLog), - source: this - }); - } - get(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - confirmActiveTransaction2(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getValue.bind(this._rawObjectStore, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall - getAll(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction2(this); - const range = valueToKeyRange_default(options.query); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getAllValues.bind(this._rawObjectStore, range, options.count, options.direction), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey - getKey(key) { - if (arguments.length === 0) { - throw new TypeError(); - } - confirmActiveTransaction2(this); - if (!(key instanceof FDBKeyRange_default)) { - key = valueToKey_default(key); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getKey.bind(this._rawObjectStore, key), - source: this - }); - } - // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys - getAllKeys(queryOrOptions, count) { - const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); - confirmActiveTransaction2(this); - const range = valueToKeyRange_default(options.query); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getAllKeys.bind(this._rawObjectStore, range, options.count, options.direction), - source: this - }); - } - // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords - getAllRecords(options) { - let query; - let count; - let direction; - if (options !== void 0) { - if (options.query !== void 0) { - query = options.query; - } - if (options.count !== void 0) { - count = enforceRange_default(options.count, "unsigned long"); - } - if (options.direction !== void 0) { - direction = options.direction; - } - } - confirmActiveTransaction2(this); - const range = valueToKeyRange_default(query); - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.getAllRecords.bind(this._rawObjectStore, range, count, direction), - source: this - }); - } - clear() { - confirmActiveTransaction2(this); - if (this.transaction.mode === "readonly") { - throw new ReadOnlyError(); - } - return this.transaction._execRequestAsync({ - operation: this._rawObjectStore.clear.bind(this._rawObjectStore, this.transaction._rollbackLog), - source: this - }); - } - openCursor(range, direction) { - confirmActiveTransaction2(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.transaction; - const cursor = new FDBCursorWithValue_default(this, range, direction, request); - return this.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - openKeyCursor(range, direction) { - confirmActiveTransaction2(this); - if (range === null) { - range = void 0; - } - if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { - range = FDBKeyRange_default.only(valueToKey_default(range)); - } - const request = new FDBRequest_default(); - request.source = this; - request.transaction = this.transaction; - const cursor = new FDBCursor_default(this, range, direction, request, true); - return this.transaction._execRequestAsync({ - operation: cursor._iterate.bind(cursor), - request, - source: this - }); - } - // tslint:-next-line max-line-length - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-createIndex-IDBIndex-DOMString-name-DOMString-sequence-DOMString--keyPath-IDBIndexParameters-optionalParameters - createIndex(name, keyPath, optionalParameters = {}) { - if (arguments.length < 2) { - throw new TypeError(); - } - const multiEntry = optionalParameters.multiEntry !== void 0 ? optionalParameters.multiEntry : false; - const unique = optionalParameters.unique !== void 0 ? optionalParameters.unique : false; - if (this.transaction.mode !== "versionchange") { - throw new InvalidStateError(); - } - confirmActiveTransaction2(this); - if (this.indexNames.contains(name)) { - throw new ConstraintError(); - } - validateKeyPath_default(keyPath); - if (Array.isArray(keyPath) && multiEntry) { - throw new InvalidAccessError(); - } - const indexNames = [...this.indexNames]; - const index = new Index_default(this._rawObjectStore, name, keyPath, multiEntry, unique); - this.indexNames._push(name); - this.indexNames._sort(); - this.transaction._createdIndexes.add(index); - this._rawObjectStore.rawIndexes.set(name, index); - index.initialize(this.transaction); - this.transaction._rollbackLog.push(() => { - index.deleted = true; - this.indexNames = new FakeDOMStringList_default(...indexNames); - this._rawObjectStore.rawIndexes.delete(index.name); - }); - return new FDBIndex_default(this, index); - } - // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index - index(name) { - if (arguments.length === 0) { - throw new TypeError(); - } - if (this._rawObjectStore.deleted || this.transaction._state === "finished") { - throw new InvalidStateError(); - } - const index = this._indexesCache.get(name); - if (index !== void 0) { - return index; - } - const rawIndex = this._rawObjectStore.rawIndexes.get(name); - if (!this.indexNames.contains(name) || rawIndex === void 0) { - throw new NotFoundError(); - } - const index2 = new FDBIndex_default(this, rawIndex); - this._indexesCache.set(name, index2); - return index2; - } - deleteIndex(name) { - if (arguments.length === 0) { - throw new TypeError(); - } - if (this.transaction.mode !== "versionchange") { - throw new InvalidStateError(); - } - confirmActiveTransaction2(this); - const rawIndex = this._rawObjectStore.rawIndexes.get(name); - if (rawIndex === void 0) { - throw new NotFoundError(); - } - this.transaction._rollbackLog.push(() => { - rawIndex.deleted = false; - this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex); - this.indexNames._push(rawIndex.name); - this.indexNames._sort(); - }); - this.indexNames = new FakeDOMStringList_default(...Array.from(this.indexNames).filter((indexName) => { - return indexName !== name; - })); - rawIndex.deleted = true; - this.transaction._execRequestAsync({ - operation: () => { - const rawIndex2 = this._rawObjectStore.rawIndexes.get(name); - if (rawIndex === rawIndex2) { - this._rawObjectStore.rawIndexes.delete(name); - } - }, - source: this - }); - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-count-IDBRequest-any-key - count(key) { - confirmActiveTransaction2(this); - if (key === null) { - key = void 0; - } - if (key !== void 0 && !(key instanceof FDBKeyRange_default)) { - key = FDBKeyRange_default.only(valueToKey_default(key)); - } - return this.transaction._execRequestAsync({ - operation: () => { - return this._rawObjectStore.count(key); - }, - source: this - }); - } - get [Symbol.toStringTag]() { - return "IDBObjectStore"; - } -}; -var FDBObjectStore_default = FDBObjectStore; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeEvent.js -var Event2 = class { - eventPath = []; - NONE = 0; - CAPTURING_PHASE = 1; - AT_TARGET = 2; - BUBBLING_PHASE = 3; - // Flags - propagationStopped = false; - immediatePropagationStopped = false; - canceled = false; - initialized = true; - dispatched = false; - target = null; - currentTarget = null; - eventPhase = 0; - defaultPrevented = false; - isTrusted = false; - timeStamp = Date.now(); - constructor(type, eventInitDict = {}) { - this.type = type; - this.bubbles = eventInitDict.bubbles !== void 0 ? eventInitDict.bubbles : false; - this.cancelable = eventInitDict.cancelable !== void 0 ? eventInitDict.cancelable : false; - } - preventDefault() { - if (this.cancelable) { - this.canceled = true; - } - } - stopPropagation() { - this.propagationStopped = true; - } - stopImmediatePropagation() { - this.propagationStopped = true; - this.immediatePropagationStopped = true; - } -}; -var FakeEvent_default = Event2; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/scheduling.js -function getSetImmediateFromJsdom() { - if (typeof navigator !== "undefined" && /jsdom/.test(navigator.userAgent)) { - const outerRealmFunctionConstructor = Node.constructor; - return new outerRealmFunctionConstructor("return setImmediate")(); - } else { - return void 0; - } -} -var schedulerPostTask = typeof scheduler !== "undefined" && ((fn) => scheduler.postTask(fn)); -var doSetTimeout = (fn) => setTimeout(fn, 0); -var queueTask = (fn) => { - const setImmediate2 = globalThis.setImmediate || getSetImmediateFromJsdom() || schedulerPostTask || doSetTimeout; - setImmediate2(fn); -}; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBTransaction.js -var prioritizedListenerTypes = ["error", "abort", "complete"]; -var FDBTransaction = class extends FakeEventTarget_default { - _state = "active"; - _started = false; - _rollbackLog = []; - _objectStoresCache = /* @__PURE__ */ new Map(); - _openRequest = null; - error = null; - onabort = null; - oncomplete = null; - onerror = null; - _prioritizedListeners = /* @__PURE__ */ new Map(); - _requests = []; - _createdIndexes = /* @__PURE__ */ new Set(); - _createdObjectStores = /* @__PURE__ */ new Set(); - constructor(storeNames, mode, durability, db2) { - super(); - this._scope = new Set(storeNames); - this.mode = mode; - this.durability = durability; - this.db = db2; - this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._scope).sort()); - for (const type of prioritizedListenerTypes) { - this.addEventListener(type, () => { - this._prioritizedListeners.get(type)?.(); - }); - } - } - // https://w3c.github.io/IndexedDB/#abort-transaction - _abort(errName) { - for (const f of this._rollbackLog.reverse()) { - f(); - } - if (errName !== null) { - const e = new DOMException(void 0, errName); - this.error = e; - } - for (const { - request - } of this._requests) { - if (request.readyState !== "done") { - request.readyState = "done"; - if (request.source) { - queueTask(() => { - request.result = void 0; - request.error = new AbortError(); - const event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - event.eventPath = [this.db, this]; - try { - request.dispatchEvent(event); - } catch (_err) { - if (this._state === "active") { - this._abort("AbortError"); - } - } - }); - } - } - } - queueTask(() => { - const isUpgradeTransaction = this.mode === "versionchange"; - if (isUpgradeTransaction) { - this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter((connection) => !connection._rawDatabase.transactions.includes(this)); - } - const event = new FakeEvent_default("abort", { - bubbles: true, - cancelable: false - }); - event.eventPath = [this.db]; - this.dispatchEvent(event); - if (isUpgradeTransaction) { - const request = this._openRequest; - request.transaction = null; - request.result = void 0; - } - }); - this._state = "finished"; - } - abort() { - if (this._state === "committing" || this._state === "finished") { - throw new InvalidStateError(); - } - this._state = "active"; - this._abort(null); - } - // http://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore - objectStore(name) { - if (this._state !== "active") { - throw new InvalidStateError(); - } - const objectStore = this._objectStoresCache.get(name); - if (objectStore !== void 0) { - return objectStore; - } - const rawObjectStore = this.db._rawDatabase.rawObjectStores.get(name); - if (!this._scope.has(name) || rawObjectStore === void 0) { - throw new NotFoundError(); - } - const objectStore2 = new FDBObjectStore_default(this, rawObjectStore); - this._objectStoresCache.set(name, objectStore2); - return objectStore2; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-asynchronously-executing-a-request - _execRequestAsync(obj) { - const source = obj.source; - const operation = obj.operation; - let request = Object.hasOwn(obj, "request") ? obj.request : null; - if (this._state !== "active") { - throw new TransactionInactiveError(); - } - if (!request) { - if (!source) { - request = new FDBRequest_default(); - } else { - request = new FDBRequest_default(); - request.source = source; - request.transaction = source.transaction; - } - } - this._requests.push({ - operation, - request - }); - return request; - } - _start() { - this._started = true; - let operation; - let request; - while (this._requests.length > 0) { - const r = this._requests.shift(); - if (r && r.request.readyState !== "done") { - request = r.request; - operation = r.operation; - break; - } - } - if (request && operation) { - if (!request.source) { - operation(); - } else { - let defaultAction; - let event; - try { - const result = operation(); - request.readyState = "done"; - request.result = result; - request.error = void 0; - if (this._state === "inactive") { - this._state = "active"; - } - event = new FakeEvent_default("success", { - bubbles: false, - cancelable: false - }); - } catch (err) { - request.readyState = "done"; - request.result = void 0; - request.error = err; - if (this._state === "inactive") { - this._state = "active"; - } - event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - defaultAction = this._abort.bind(this, err.name); - } - try { - event.eventPath = [this.db, this]; - request.dispatchEvent(event); - } catch (_err) { - if (this._state === "active") { - this._abort("AbortError"); - defaultAction = void 0; - } - } - if (!event.canceled) { - if (defaultAction) { - defaultAction(); - } - } - } - queueTask(this._start.bind(this)); - return; - } - if (this._state !== "finished") { - this._state = "finished"; - if (!this.error) { - const event = new FakeEvent_default("complete"); - this.dispatchEvent(event); - } - } - } - commit() { - if (this._state !== "active") { - throw new InvalidStateError(); - } - this._state = "committing"; - } - get [Symbol.toStringTag]() { - return "IDBTransaction"; - } -}; -var FDBTransaction_default = FDBTransaction; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/KeyGenerator.js -var MAX_KEY = 9007199254740992; -var KeyGenerator = class { - // This is kind of wrong. Should start at 1 and increment only after record is saved - num = 0; - next() { - if (this.num >= MAX_KEY) { - throw new ConstraintError(); - } - this.num += 1; - return this.num; - } - // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator - setIfLarger(num) { - const value = Math.floor(Math.min(num, MAX_KEY)) - 1; - if (value >= this.num) { - this.num = value + 1; - } - } -}; -var KeyGenerator_default = KeyGenerator; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/ObjectStore.js -var ObjectStore = class { - deleted = false; - records = new RecordStore_default(true); - rawIndexes = /* @__PURE__ */ new Map(); - constructor(rawDatabase, name, keyPath, autoIncrement) { - this.rawDatabase = rawDatabase; - this.keyGenerator = autoIncrement === true ? new KeyGenerator_default() : null; - this.deleted = false; - this.name = name; - this.keyPath = keyPath; - this.autoIncrement = autoIncrement; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store - getKey(key) { - const record = this.records.get(key); - return record !== void 0 ? structuredClone(record.key) : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-keys-from-an-object-store - getAllKeys(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(structuredClone(record.key)); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store - getValue(key) { - const record = this.records.get(key); - return record !== void 0 ? structuredClone(record.value) : void 0; - } - // http://w3c.github.io/IndexedDB/#retrieve-multiple-values-from-an-object-store - getAllValues(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(structuredClone(record.value)); - if (records.length >= count) { - break; - } - } - return records; - } - // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords - getAllRecords(range, count, direction) { - if (count === void 0 || count === 0) { - count = Infinity; - } - const records = []; - for (const record of this.records.values(range, direction)) { - records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(record.key), structuredClone(record.value))); - if (records.length >= count) { - break; - } - } - return records; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store - storeRecord(newRecord, noOverwrite, rollbackLog) { - if (this.keyPath !== null) { - const key = extractKey_default(this.keyPath, newRecord.value).key; - if (key !== void 0) { - newRecord.key = key; - } - } - const rollbackLogForThisOperation = []; - if (this.keyGenerator !== null && newRecord.key === void 0) { - let rolledBack2 = false; - const keyGeneratorBefore = this.keyGenerator.num; - const rollbackKeyGenerator = () => { - if (rolledBack2) { - return; - } - rolledBack2 = true; - if (this.keyGenerator) { - this.keyGenerator.num = keyGeneratorBefore; - } - }; - rollbackLogForThisOperation.push(rollbackKeyGenerator); - if (rollbackLog) { - rollbackLog.push(rollbackKeyGenerator); - } - newRecord.key = this.keyGenerator.next(); - if (this.keyPath !== null) { - if (Array.isArray(this.keyPath)) { - throw new Error("Cannot have an array key path in an object store with a key generator"); - } - let remainingKeyPath = this.keyPath; - let object = newRecord.value; - let identifier; - let i = 0; - while (i >= 0) { - if (typeof object !== "object") { - throw new DataError(); - } - i = remainingKeyPath.indexOf("."); - if (i >= 0) { - identifier = remainingKeyPath.slice(0, i); - remainingKeyPath = remainingKeyPath.slice(i + 1); - if (!Object.hasOwn(object, identifier)) { - Object.defineProperty(object, identifier, { - configurable: true, - enumerable: true, - writable: true, - value: {} - }); - } - object = object[identifier]; - } - } - identifier = remainingKeyPath; - Object.defineProperty(object, identifier, { - configurable: true, - enumerable: true, - writable: true, - value: newRecord.key - }); - } - } else if (this.keyGenerator !== null && typeof newRecord.key === "number") { - this.keyGenerator.setIfLarger(newRecord.key); - } - const existingRecord = this.records.put(newRecord, noOverwrite); - let rolledBack = false; - const rollbackStoreRecord = () => { - if (rolledBack) { - return; - } - rolledBack = true; - if (existingRecord) { - this.storeRecord(existingRecord, false); - } else { - this.deleteRecord(newRecord.key); - } - }; - rollbackLogForThisOperation.push(rollbackStoreRecord); - if (rollbackLog) { - rollbackLog.push(rollbackStoreRecord); - } - if (existingRecord) { - for (const rawIndex of this.rawIndexes.values()) { - rawIndex.records.deleteByValue(newRecord.key); - } - } - try { - for (const rawIndex of this.rawIndexes.values()) { - if (rawIndex.initialized) { - rawIndex.storeRecord(newRecord); - } - } - } catch (err) { - if (err.name === "ConstraintError") { - for (const rollback of rollbackLogForThisOperation) { - rollback(); - } - } - throw err; - } - return newRecord.key; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-records-from-an-object-store - deleteRecord(key, rollbackLog) { - const deletedRecords = this.records.delete(key); - if (rollbackLog) { - for (const record of deletedRecords) { - rollbackLog.push(() => { - this.storeRecord(record, true); - }); - } - } - for (const rawIndex of this.rawIndexes.values()) { - rawIndex.records.deleteByValue(key); - } - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-clearing-an-object-store - clear(rollbackLog) { - const deletedRecords = this.records.clear(); - if (rollbackLog) { - for (const record of deletedRecords) { - rollbackLog.push(() => { - this.storeRecord(record, true); - }); - } - } - for (const rawIndex of this.rawIndexes.values()) { - rawIndex.records.clear(); - } - } - count(range) { - if (range === void 0 || range.lower === void 0 && range.upper === void 0) { - return this.records.size(); - } - let count = 0; - for (const record of this.records.values(range)) { - count += 1; - } - return count; - } -}; -var ObjectStore_default = ObjectStore; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/closeConnection.js -var closeConnection = (connection, forced = false) => { - connection._closePending = true; - const transactionsComplete = connection._rawDatabase.transactions.every((transaction) => { - return transaction._state === "finished"; - }); - if (transactionsComplete) { - connection._closed = true; - connection._rawDatabase.connections = connection._rawDatabase.connections.filter((otherConnection) => { - return connection !== otherConnection; - }); - if (forced) { - const event = new FakeEvent_default("close", { - bubbles: false, - cancelable: false - }); - event.eventPath = []; - connection.dispatchEvent(event); - } - } else { - queueTask(() => { - closeConnection(connection, forced); - }); - } -}; -var closeConnection_default = closeConnection; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBDatabase.js -var confirmActiveVersionchangeTransaction = (database) => { - let transaction; - if (database._runningVersionchangeTransaction) { - transaction = database._rawDatabase.transactions.findLast((tx) => { - return tx.mode === "versionchange"; - }); - } - if (!transaction) { - throw new InvalidStateError(); - } - if (transaction._state !== "active") { - throw new TransactionInactiveError(); - } - return transaction; -}; -var FDBDatabase = class extends FakeEventTarget_default { - _closePending = false; - _closed = false; - _runningVersionchangeTransaction = false; - constructor(rawDatabase) { - super(); - this._rawDatabase = rawDatabase; - this._rawDatabase.connections.push(this); - this.name = rawDatabase.name; - this.version = rawDatabase.version; - this.objectStoreNames = new FakeDOMStringList_default(...Array.from(rawDatabase.rawObjectStores.keys()).sort()); - } - // http://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore - createObjectStore(name, options = {}) { - if (name === void 0) { - throw new TypeError(); - } - const transaction = confirmActiveVersionchangeTransaction(this); - const keyPath = options !== null && options.keyPath !== void 0 ? options.keyPath : null; - const autoIncrement = options !== null && options.autoIncrement !== void 0 ? options.autoIncrement : false; - if (keyPath !== null) { - validateKeyPath_default(keyPath); - } - if (this._rawDatabase.rawObjectStores.has(name)) { - throw new ConstraintError(); - } - if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) { - throw new InvalidAccessError(); - } - const objectStoreNames = [...this.objectStoreNames]; - const transactionObjectStoreNames = [...transaction.objectStoreNames]; - const rawObjectStore = new ObjectStore_default(this._rawDatabase, name, keyPath, autoIncrement); - this.objectStoreNames._push(name); - this.objectStoreNames._sort(); - transaction._scope.add(name); - transaction._createdObjectStores.add(rawObjectStore); - this._rawDatabase.rawObjectStores.set(name, rawObjectStore); - transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames); - transaction._rollbackLog.push(() => { - rawObjectStore.deleted = true; - this.objectStoreNames = new FakeDOMStringList_default(...objectStoreNames); - transaction.objectStoreNames = new FakeDOMStringList_default(...transactionObjectStoreNames); - transaction._scope.delete(rawObjectStore.name); - this._rawDatabase.rawObjectStores.delete(rawObjectStore.name); - }); - return transaction.objectStore(name); - } - // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore - deleteObjectStore(name) { - if (name === void 0) { - throw new TypeError(); - } - const transaction = confirmActiveVersionchangeTransaction(this); - const store = this._rawDatabase.rawObjectStores.get(name); - if (store === void 0) { - throw new NotFoundError(); - } - this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this.objectStoreNames).filter((objectStoreName) => { - return objectStoreName !== name; - })); - transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames); - const objectStore = transaction._objectStoresCache.get(name); - let prevIndexNames; - if (objectStore) { - prevIndexNames = [...objectStore.indexNames]; - objectStore.indexNames = new FakeDOMStringList_default(); - } - transaction._rollbackLog.push(() => { - store.deleted = false; - this._rawDatabase.rawObjectStores.set(store.name, store); - this.objectStoreNames._push(store.name); - transaction.objectStoreNames._push(store.name); - this.objectStoreNames._sort(); - if (objectStore && prevIndexNames) { - objectStore.indexNames = new FakeDOMStringList_default(...prevIndexNames); - } - }); - store.deleted = true; - this._rawDatabase.rawObjectStores.delete(name); - transaction._objectStoresCache.delete(name); - } - transaction(storeNames, mode, options) { - mode = mode !== void 0 ? mode : "readonly"; - if (mode !== "readonly" && mode !== "readwrite" && mode !== "versionchange") { - throw new TypeError("Invalid mode: " + mode); - } - const hasActiveVersionchange = this._rawDatabase.transactions.some((transaction) => { - return transaction._state === "active" && transaction.mode === "versionchange" && transaction.db === this; - }); - if (hasActiveVersionchange) { - throw new InvalidStateError(); - } - if (this._closePending) { - throw new InvalidStateError(); - } - if (!Array.isArray(storeNames)) { - storeNames = [storeNames]; - } - if (storeNames.length === 0 && mode !== "versionchange") { - throw new InvalidAccessError(); - } - for (const storeName of storeNames) { - if (!this.objectStoreNames.contains(storeName)) { - throw new NotFoundError("No objectStore named " + storeName + " in this database"); - } - } - const durability = options?.durability ?? "default"; - if (durability !== "default" && durability !== "strict" && durability !== "relaxed") { - throw new TypeError( - // based on Firefox's error message - `'${durability}' (value of 'durability' member of IDBTransactionOptions) is not a valid value for enumeration IDBTransactionDurability` - ); - } - const tx = new FDBTransaction_default(storeNames, mode, durability, this); - this._rawDatabase.transactions.push(tx); - this._rawDatabase.processTransactions(); - return tx; - } - close() { - closeConnection_default(this); - } - get [Symbol.toStringTag]() { - return "IDBDatabase"; - } -}; -var FDBDatabase_default = FDBDatabase; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBOpenDBRequest.js -var FDBOpenDBRequest = class extends FDBRequest_default { - onupgradeneeded = null; - onblocked = null; - get [Symbol.toStringTag]() { - return "IDBOpenDBRequest"; - } -}; -var FDBOpenDBRequest_default = FDBOpenDBRequest; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBVersionChangeEvent.js -var FDBVersionChangeEvent = class extends FakeEvent_default { - constructor(type, parameters = {}) { - super(type); - this.newVersion = parameters.newVersion !== void 0 ? parameters.newVersion : null; - this.oldVersion = parameters.oldVersion !== void 0 ? parameters.oldVersion : 0; - } - get [Symbol.toStringTag]() { - return "IDBVersionChangeEvent"; - } -}; -var FDBVersionChangeEvent_default = FDBVersionChangeEvent; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/intersection.js -function intersection(set1, set2) { - if ("intersection" in set1) { - return set1.intersection(set2); - } - return new Set([...set1].filter((item) => set2.has(item))); -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/Database.js -var Database = class { - transactions = []; - rawObjectStores = /* @__PURE__ */ new Map(); - connections = []; - constructor(name, version) { - this.name = name; - this.version = version; - this.processTransactions = this.processTransactions.bind(this); - } - processTransactions() { - queueTask(() => { - const running = this.transactions.filter((transaction) => transaction._started && transaction._state !== "finished"); - const waiting = this.transactions.filter((transaction) => !transaction._started && transaction._state !== "finished"); - const next = waiting.find((transaction, i) => { - const anyRunning = running.some((other) => !(transaction.mode === "readonly" && other.mode === "readonly") && intersection(other._scope, transaction._scope).size > 0); - if (anyRunning) { - return false; - } - const anyWaiting = waiting.slice(0, i).some((other) => intersection(other._scope, transaction._scope).size > 0); - return !anyWaiting; - }); - if (next) { - next.addEventListener("complete", this.processTransactions); - next.addEventListener("abort", this.processTransactions); - next._start(); - } - }); - } -}; -var Database_default = Database; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/validateRequiredArguments.js -function validateRequiredArguments(numArguments, expectedNumArguments, methodName) { - if (numArguments < expectedNumArguments) { - throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} required, but only ${arguments.length} passed`); - } -} - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBFactory.js -var runTaskInConnectionQueue = (connectionQueues, name, task) => { - const queue = connectionQueues.get(name) ?? Promise.resolve(); - connectionQueues.set(name, queue.then(task)); -}; -var waitForOthersClosedDelete = (databases, name, openDatabases, cb) => { - const anyOpen = openDatabases.some((openDatabase2) => { - return !openDatabase2._closed && !openDatabase2._closePending; - }); - if (anyOpen) { - queueTask(() => waitForOthersClosedDelete(databases, name, openDatabases, cb)); - return; - } - databases.delete(name); - cb(null); -}; -var deleteDatabase = (databases, connectionQueues, name, request, cb) => { - const deleteDBTask = () => { - return new Promise((resolve) => { - const db2 = databases.get(name); - const oldVersion = db2 !== void 0 ? db2.version : 0; - const onComplete = (err) => { - try { - if (err) { - cb(err); - } else { - cb(null, oldVersion); - } - } finally { - resolve(); - } - }; - try { - const db3 = databases.get(name); - if (db3 === void 0) { - onComplete(null); - return; - } - const openConnections = db3.connections.filter((connection) => { - return !connection._closed; - }); - for (const openDatabase2 of openConnections) { - if (!openDatabase2._closePending) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("versionchange", { - newVersion: null, - oldVersion: db3.version - }); - openDatabase2.dispatchEvent(event); - }); - } - } - queueTask(() => { - const anyOpen = openConnections.some((openDatabase3) => { - return !openDatabase3._closed && !openDatabase3._closePending; - }); - if (anyOpen) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("blocked", { - newVersion: null, - oldVersion: db3.version - }); - request.dispatchEvent(event); - }); - } - waitForOthersClosedDelete(databases, name, openConnections, onComplete); - }); - } catch (err) { - onComplete(err); - } - }); - }; - runTaskInConnectionQueue(connectionQueues, name, deleteDBTask); -}; -var runVersionchangeTransaction = (connection, version, request, cb) => { - connection._runningVersionchangeTransaction = true; - const oldVersion = connection._oldVersion = connection.version; - const openConnections = connection._rawDatabase.connections.filter((otherDatabase) => { - return connection !== otherDatabase; - }); - for (const openDatabase2 of openConnections) { - if (!openDatabase2._closed && !openDatabase2._closePending) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("versionchange", { - newVersion: version, - oldVersion - }); - openDatabase2.dispatchEvent(event); - }); - } - } - queueTask(() => { - const anyOpen = openConnections.some((openDatabase3) => { - return !openDatabase3._closed && !openDatabase3._closePending; - }); - if (anyOpen) { - queueTask(() => { - const event = new FDBVersionChangeEvent_default("blocked", { - newVersion: version, - oldVersion - }); - request.dispatchEvent(event); - }); - } - const waitForOthersClosed = () => { - const anyOpen2 = openConnections.some((openDatabase2) => { - return !openDatabase2._closed && !openDatabase2._closePending; - }); - if (anyOpen2) { - queueTask(waitForOthersClosed); - return; - } - connection._rawDatabase.version = version; - connection.version = version; - const transaction = connection.transaction(Array.from(connection.objectStoreNames), "versionchange"); - transaction._openRequest = request; - request.result = connection; - request.readyState = "done"; - request.transaction = transaction; - transaction._rollbackLog.push(() => { - connection._rawDatabase.version = oldVersion; - connection.version = oldVersion; - }); - transaction._state = "active"; - const event = new FDBVersionChangeEvent_default("upgradeneeded", { - newVersion: version, - oldVersion - }); - let didThrow = false; - try { - request.dispatchEvent(event); - } catch (_err) { - didThrow = true; - } - const concludeUpgrade = () => { - if (transaction._state === "active") { - transaction._state = "inactive"; - if (didThrow) { - transaction._abort("AbortError"); - } - } - }; - if (didThrow) { - concludeUpgrade(); - } else { - queueTask(concludeUpgrade); - } - transaction._prioritizedListeners.set("error", () => { - connection._runningVersionchangeTransaction = false; - connection._oldVersion = void 0; - }); - transaction._prioritizedListeners.set("abort", () => { - connection._runningVersionchangeTransaction = false; - connection._oldVersion = void 0; - queueTask(() => { - request.transaction = null; - cb(new AbortError()); - }); - }); - transaction._prioritizedListeners.set("complete", () => { - connection._runningVersionchangeTransaction = false; - connection._oldVersion = void 0; - queueTask(() => { - request.transaction = null; - if (connection._closePending) { - cb(new AbortError()); - } else { - cb(null); - } - }); - }); - }; - waitForOthersClosed(); - }); -}; -var openDatabase = (databases, connectionQueues, name, version, request, cb) => { - const openDBTask = () => { - return new Promise((resolve) => { - const onComplete = (err) => { - try { - if (err) { - cb(err); - } else { - cb(null, connection); - } - } finally { - resolve(); - } - }; - let db2 = databases.get(name); - if (db2 === void 0) { - db2 = new Database_default(name, 0); - databases.set(name, db2); - } - if (version === void 0) { - version = db2.version !== 0 ? db2.version : 1; - } - if (db2.version > version) { - return onComplete(new VersionError()); - } - const connection = new FDBDatabase_default(db2); - if (db2.version < version) { - runVersionchangeTransaction(connection, version, request, (err) => { - onComplete(err); - }); - } else { - onComplete(null); - } - }); - }; - runTaskInConnectionQueue(connectionQueues, name, openDBTask); -}; -var FDBFactory = class { - _databases = /* @__PURE__ */ new Map(); - // https://w3c.github.io/IndexedDB/#connection-queue - _connectionQueues = /* @__PURE__ */ new Map(); - // promise chain as lightweight FIFO task queue - // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp - cmp(first, second) { - validateRequiredArguments(arguments.length, 2, "IDBFactory.cmp"); - return cmp_default(first, second); - } - // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase - deleteDatabase(name) { - validateRequiredArguments(arguments.length, 1, "IDBFactory.deleteDatabase"); - const request = new FDBOpenDBRequest_default(); - request.source = null; - queueTask(() => { - deleteDatabase(this._databases, this._connectionQueues, name, request, (err, oldVersion) => { - if (err) { - request.error = new DOMException(err.message, err.name); - request.readyState = "done"; - const event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - event.eventPath = []; - request.dispatchEvent(event); - return; - } - request.result = void 0; - request.readyState = "done"; - const event2 = new FDBVersionChangeEvent_default("success", { - newVersion: null, - oldVersion - }); - request.dispatchEvent(event2); - }); - }); - return request; - } - // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version - open(name, version) { - validateRequiredArguments(arguments.length, 1, "IDBFactory.open"); - if (arguments.length > 1 && version !== void 0) { - version = enforceRange_default(version, "MAX_SAFE_INTEGER"); - } - if (version === 0) { - throw new TypeError("Database version cannot be 0"); - } - const request = new FDBOpenDBRequest_default(); - request.source = null; - queueTask(() => { - openDatabase(this._databases, this._connectionQueues, name, version, request, (err, connection) => { - if (err) { - request.result = void 0; - request.readyState = "done"; - request.error = new DOMException(err.message, err.name); - const event = new FakeEvent_default("error", { - bubbles: true, - cancelable: true - }); - event.eventPath = []; - request.dispatchEvent(event); - return; - } - request.result = connection; - request.readyState = "done"; - const event2 = new FakeEvent_default("success"); - event2.eventPath = []; - request.dispatchEvent(event2); - }); - }); - return request; - } - // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases - databases() { - return Promise.resolve(Array.from(this._databases.entries(), ([name, database]) => { - const activeVersionChangeConnection = database.connections.find((connection) => connection._runningVersionchangeTransaction); - const version = activeVersionChangeConnection ? activeVersionChangeConnection._oldVersion : database.version; - return { - name, - version - }; - }).filter(({ - version - }) => { - return version > 0; - })); - } - get [Symbol.toStringTag]() { - return "IDBFactory"; - } -}; -var FDBFactory_default = FDBFactory; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/fakeIndexedDB.js -var fakeIndexedDB = new FDBFactory_default(); -var fakeIndexedDB_default = fakeIndexedDB; - -// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/auto/index.mjs -var globalVar = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" ? self : typeof global !== "undefined" ? global : Function("return this;")(); -var createPropertyDescriptor = (value) => { - return { - value, - enumerable: false, - configurable: true, - writable: true - }; -}; -Object.defineProperties(globalVar, { - indexedDB: createPropertyDescriptor(fakeIndexedDB_default), - IDBCursor: createPropertyDescriptor(FDBCursor_default), - IDBCursorWithValue: createPropertyDescriptor(FDBCursorWithValue_default), - IDBDatabase: createPropertyDescriptor(FDBDatabase_default), - IDBFactory: createPropertyDescriptor(FDBFactory_default), - IDBIndex: createPropertyDescriptor(FDBIndex_default), - IDBKeyRange: createPropertyDescriptor(FDBKeyRange_default), - IDBObjectStore: createPropertyDescriptor(FDBObjectStore_default), - IDBOpenDBRequest: createPropertyDescriptor(FDBOpenDBRequest_default), - IDBRecord: createPropertyDescriptor(FDBRecord_default), - IDBRequest: createPropertyDescriptor(FDBRequest_default), - IDBTransaction: createPropertyDescriptor(FDBTransaction_default), - IDBVersionChangeEvent: createPropertyDescriptor(FDBVersionChangeEvent_default) -}); - -// intern-log/repro/two-device.ts -init_schema(); -var BASE = "http://127.0.0.1:3780"; -var pass = 0; -var fail = 0; -function check(name, ok, detail) { - if (ok) { - pass++; - console.log(" PASS " + name); - } else { - fail++; - console.log(" FAIL " + name + (detail ? " -> " + detail : "")); - } -} -async function main() { - await fetch(BASE + "/api/auth/register", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ username: "twodev", password: "dev123456" }) - }).catch(() => { - }); - const engine = await Promise.resolve().then(() => (init_engine(), engine_exports)); - bindDatabase(new WorklogDB("dev_a")); - const a = (await Promise.resolve().then(() => (init_schema(), schema_exports))).db; - await a.project.bulkAdd([{ name: "\u9879\u76EEA", archived: 0, created_at: "2025-01-01T00:00:00" }]); - await a.work_log.bulkAdd([{ date: "2025-01-02", created_at: "2025-01-02T00:00:00" }]); - await a.setting.bulkAdd([{ key: "work_start", value: "09:00" }]); - await a.table("log_item").bulkAdd([{ - work_log_id: 1, - content: "A \u8BBE\u5907\u7684\u65E5\u5FD7", - project_id: 1, - category: "dev", - minutes: 60, - is_milestone: 1, - needs_followup: 0, - takeaway: null, - remark: null, - sort_order: 0, - created_at: "2025-01-02T10:00:00" - }]); - const rA = await engine.runSync({ baseUrl: BASE, username: "twodev", password: "dev123456" }); - console.log("\u8BBE\u5907A \u63A8\u9001:", JSON.stringify({ p: rA.pushed, e: rA.errors })); - bindDatabase(new WorklogDB("dev_b")); - const b = (await Promise.resolve().then(() => (init_schema(), schema_exports))).db; - const rB1 = await engine.runSync({ baseUrl: BASE, username: "twodev", password: "dev123456" }); - console.log("\u8BBE\u5907B \u62C9\u53D6:", JSON.stringify({ p: rB1.pushed, e: rB1.errors })); - const bProjects = await b.project.toArray(); - const bWorkLogs = await b.work_log.toArray(); - const bItems = await b.log_item.toArray(); - const bSettings = await b.setting.toArray(); - check("B \u62C9\u5230\u9879\u76EE", bProjects.length === 1 && bProjects[0].name === "\u9879\u76EEA"); - check("B \u62C9\u5230\u5DE5\u4F5C\u65E5\u5FD7", bWorkLogs.length === 1 && bWorkLogs[0].date === "2025-01-02"); - check("B \u62C9\u5230\u65E5\u5FD7\u6761\u76EE", bItems.length === 1 && bItems[0].content === "A \u8BBE\u5907\u7684\u65E5\u5FD7"); - check("B \u5916\u952E\u91CD\u6620\u5C04(log_item.work_log_id \u6307\u5411\u672C\u5730 work_log)", bItems[0].work_log_id === bWorkLogs[0].id); - check("B \u5916\u952E\u91CD\u6620\u5C04(log_item.project_id \u6307\u5411\u672C\u5730 project)", bItems[0].project_id === bProjects[0].id); - check("B \u62C9\u5230\u8BBE\u7F6E", bSettings.some((s) => s.key === "work_start" && s.value === "09:00")); - await b.attendance.bulkAdd([{ date: "2025-01-02", clock_in_at: "2025-01-02T09:00:00", clock_out_at: null, kind: "normal", note: null, created_at: "2025-01-02T09:00:00" }]); - await b.table("log_item").add({ - work_log_id: bWorkLogs[0].id, - content: "B \u8BBE\u5907\u7684\u65E5\u5FD7", - project_id: null, - category: "dev", - minutes: null, - is_milestone: 0, - needs_followup: 1, - takeaway: null, - remark: null, - sort_order: 0, - created_at: "2025-01-02T11:00:00" - }); - const rB2 = await engine.runSync({ baseUrl: BASE, username: "twodev", password: "dev123456" }); - console.log("\u8BBE\u5907B \u4E8C\u6B21\u63A8\u9001:", JSON.stringify({ p: rB2.pushed, e: rB2.errors })); - bindDatabase(new WorklogDB("dev_a")); - const a2 = (await Promise.resolve().then(() => (init_schema(), schema_exports))).db; - const rA2 = await engine.runSync({ baseUrl: BASE, username: "twodev", password: "dev123456" }); - console.log("\u8BBE\u5907A \u62C9\u53D6:", JSON.stringify({ p: rA2.pushed, e: rA2.errors })); - const aAtt = await a2.attendance.toArray(); - const aItems = await a2.log_item.toArray(); - const aWorkLogs = await a2.work_log.toArray(); - check("A \u62C9\u5230 B \u7684\u8003\u52E4", aAtt.length === 1 && aAtt[0].date === "2025-01-02"); - check("A \u62C9\u5230 B \u7684\u65E5\u5FD7\u6761\u76EE", aItems.some((i) => i.content === "B \u8BBE\u5907\u7684\u65E5\u5FD7")); - check("A \u65E0\u91CD\u590D\u5DE5\u4F5C\u65E5\u5FD7\uFF08\u81EA\u7136\u952E\u53BB\u91CD\uFF09", aWorkLogs.length === 1); - check("A \u7684\u65E5\u5FD7\u6761\u76EE\u4ECD\u7136\u53EF\u89C1\uFF08\u672A\u56E0\u53BB\u91CD\u4E22\u5931\uFF09", aItems.length >= 2); - bindDatabase(new WorklogDB("dev_b")); - const b2 = (await Promise.resolve().then(() => (init_schema(), schema_exports))).db; - await b2.work_log.bulkPut([{ date: "2025-01-03", created_at: "2025-01-03T00:00:00", uuid: "b-day3", updated_at: "2025-01-03T08:00:00" }]); - await b2.table("log_item").add({ - work_log_id: 2, - content: "B \u7684 01-03 \u8BB0\u5F55", - project_id: null, - category: "dev", - minutes: null, - is_milestone: 0, - needs_followup: 0, - takeaway: null, - remark: null, - sort_order: 0, - created_at: "2025-01-03T08:00:00", - uuid: "item-b-day3", - updated_at: "2025-01-03T08:00:00" - }); - await b2.table("log_item").add({ - work_log_id: 999, - content: "B \u7684 01-03 \u8BB0\u5F55(\u91CD\u6620\u5C04\u76EE\u6807)", - project_id: null, - category: "dev", - minutes: null, - is_milestone: 0, - needs_followup: 0, - takeaway: null, - remark: null, - sort_order: 0, - created_at: "2025-01-03T08:30:00", - uuid: "item-b-day3b", - updated_at: "2025-01-03T08:30:00", - wuuid: "b-day3" - }); - await engine.runSync({ baseUrl: BASE, username: "twodev", password: "dev123456" }); - bindDatabase(new WorklogDB("dev_a")); - const a3 = (await Promise.resolve().then(() => (init_schema(), schema_exports))).db; - await a3.work_log.bulkAdd([{ date: "2025-01-03", created_at: "2025-01-03T07:00:00", uuid: "a-day3", updated_at: "2025-01-03T07:00:00" }]); - await engine.runSync({ baseUrl: BASE, username: "twodev", password: "dev123456" }); - const a3Logs = await a3.work_log.toArray(); - const day3 = a3Logs.filter((l) => l.date === "2025-01-03"); - check("\u51B2\u7A81\u5408\u5E76\u540E\u540C\u65E5\u4EC5\u4E00\u6761\u5DE5\u4F5C\u65E5\u5FD7", day3.length === 1); - console.log(" DEBUG day3:", JSON.stringify(day3)); - const a3Items = await a3.log_item.toArray(); - const day3Items = a3Items.filter((i) => i.content.indexOf("01-03") >= 0); - console.log(" DEBUG day3Items:", JSON.stringify(day3Items)); - check("\u51B2\u7A81\u5408\u5E76\u540E B \u7684 01-03 \u6761\u76EE\u4FDD\u7559\u4E14\u5916\u952E\u6B63\u786E", day3Items.length === 2 && day3Items.every((i) => i.work_log_id === day3[0].id)); - console.log("==== \u7ED3\u679C: PASS " + pass + " / FAIL " + fail + " ===="); - process.exit(fail > 0 ? 1 : 0); -} -main().catch((e) => { - console.error("FAILED:", e && (e.stack || e.message) || e); - process.exit(1); -}); -/*! Bundled license information: - -@vue/shared/dist/shared.cjs.prod.js: - (** - * @vue/shared v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/shared/dist/shared.cjs.js: - (** - * @vue/shared v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/compiler-core/dist/compiler-core.cjs.prod.js: - (** - * @vue/compiler-core v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/compiler-core/dist/compiler-core.cjs.js: - (** - * @vue/compiler-core v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/compiler-dom/dist/compiler-dom.cjs.prod.js: - (** - * @vue/compiler-dom v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/compiler-dom/dist/compiler-dom.cjs.js: - (** - * @vue/compiler-dom v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/reactivity/dist/reactivity.cjs.prod.js: - (** - * @vue/reactivity v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/reactivity/dist/reactivity.cjs.js: - (** - * @vue/reactivity v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/runtime-core/dist/runtime-core.cjs.prod.js: - (** - * @vue/runtime-core v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/runtime-core/dist/runtime-core.cjs.js: - (** - * @vue/runtime-core v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/runtime-dom/dist/runtime-dom.cjs.prod.js: - (** - * @vue/runtime-dom v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -@vue/runtime-dom/dist/runtime-dom.cjs.js: - (** - * @vue/runtime-dom v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -vue/dist/vue.cjs.prod.js: - (** - * vue v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) - -vue/dist/vue.cjs.js: - (** - * vue v3.5.44 - * (c) 2018-present Yuxi (Evan) You and Vue contributors - * @license MIT - **) -*/ diff --git a/server/DEPLOY.md b/server/DEPLOY.md index 2c44cc1..49370fe 100644 --- a/server/DEPLOY.md +++ b/server/DEPLOY.md @@ -1,5 +1,8 @@ # 同步服务端部署(daywk.linyux.cn 子域名方案) +服务端是整个系统的**唯一数据权威**:认证、九张业务表、用户管理、每日自动备份都在这里。 +客户端(桌面 / 网页 / 安卓)只是实时缓存,详见仓库根 README。 + ## 一、DNS 解析(先做) 在域名服务商处添加 A 记录: @@ -40,16 +43,32 @@ Caddy 会自动为 daywk.linyux.cn 申请并续期 HTTPS 证书(需 DNS 已生 ## 重要:该域名同时是应用入口 -同步服务容器同时托管了网页应用本体(daywork 仓库中的构建产物)。手机与电脑浏览器直接打开 -https://daywk.linyux.cn 就是应用(可添加到主屏幕作为 PWA),无需另外部署前端;/api 路径为数据接口。 +同步服务容器同时托管了网页应用本体(daywork 仓库 intern-log/dist 的构建产物,随仓库提交以便容器直接 COPY)。 +手机与电脑浏览器直接打开 https://daywk.linyux.cn 就是应用(可添加到主屏幕作为 PWA);/api 路径为数据接口。 -## 五、客户端 +## 五、账号体系 -应用 → 设置 → 多端数据同步:地址填 https://daywk.linyux.cn,注册云端账号后同步。 -手机浏览器打开同一地址登录,添加到主屏幕后即为手机端应用。 +- 注册 / 登录全部经由服务端(POST /api/auth/register、/api/auth/login),密码仅存 PBKDF2 哈希 +- **管理员:用户名 xionglin**(服务启动时自动赋予 role=admin,存量注册表也会自动迁移) +- 管理员专用接口(客户端「用户管理」页使用,非管理员一律 403): + - GET /api/admin/users 用户列表(含数据量) + - POST /api/admin/users/create 新建账号 + - POST /api/admin/users/password 重置任意用户密码 + - POST /api/admin/users/delete 删除账号及其全部数据(不能删自己) +- 客户端"登录密码修改"对应 POST /api/auth/password;"删除此用户"对应 POST /api/auth/delete ## 六、数据与运维 -- 数据目录:/opt/daywork/server/data(用户注册表 + 每用户数据),打包即备份 +- 数据目录:/opt/daywork/server/data + - registry.json 用户注册表(用户名 / 角色 / PBKDF2 哈希) + - users/<id>.json 每用户九张表数据 + 墓碑 + - backups/<日期>/ **每日自动备份**(启动与每次注册表变更也会触发,保留最近 14 天) - 更新版本:cd /opt/daywork && git pull && cd server && docker compose up -d --build -- 接口:POST /api/auth/register、POST /api/auth/login、POST /api/sync、GET /api/health +- 同步协议:POST /api/sync(Bearer token;推送差异并返回权威全量快照) +- 实时通知:GET /api/events?token=...(SSE,同账号任意端有变更即广播 change) +- 手工备份:直接打包 server/data 目录即可(纯 JSON 文件) + +## 七、客户端 + +应用 → 设置 → 多端数据同步:地址填 https://daywk.linyux.cn(默认即是)。 +登录即自动绑定云端并全量拉取;本机仅存加密的自动登录凭据,退出登录后需重新输入密码。