From 134ea608f9a5d965b89ef2289969d5a524c1fd44 Mon Sep 17 00:00:00 2001 From: CrazyJasonwell Date: Fri, 8 Aug 2025 12:24:51 +0800 Subject: [PATCH] vault backup: 2025-08-08 12:24:51 --- .obsidian/community-plugins.json | 3 +- .obsidian/plugins/cubox-sync/data.json | 2 +- .obsidian/plugins/obsidian-clipper/main.js | 10951 ++++++++++++++++ .../plugins/obsidian-clipper/manifest.json | 11 + .obsidian/plugins/obsidian-clipper/styles.css | 127 + .obsidian/plugins/obsidian-readwise/main.js | 9668 ++++++++++++++ .../plugins/obsidian-readwise/manifest.json | 10 + .obsidian/plugins/readwise-official/main.js | 10770 +++++++++++++++ .../plugins/readwise-official/manifest.json | 10 + .../plugins/readwise-official/styles.css | 58 + 01-工作日记/2025-08-08.md | 3 +- 11 files changed, 31610 insertions(+), 3 deletions(-) create mode 100644 .obsidian/plugins/obsidian-clipper/main.js create mode 100644 .obsidian/plugins/obsidian-clipper/manifest.json create mode 100644 .obsidian/plugins/obsidian-clipper/styles.css create mode 100644 .obsidian/plugins/obsidian-readwise/main.js create mode 100644 .obsidian/plugins/obsidian-readwise/manifest.json create mode 100644 .obsidian/plugins/readwise-official/main.js create mode 100644 .obsidian/plugins/readwise-official/manifest.json create mode 100644 .obsidian/plugins/readwise-official/styles.css diff --git a/.obsidian/community-plugins.json b/.obsidian/community-plugins.json index f3494950..1b7cf3f5 100644 --- a/.obsidian/community-plugins.json +++ b/.obsidian/community-plugins.json @@ -47,5 +47,6 @@ "rss-reader", "podnotes", "sheet-plus", - "obsidian-excel-to-markdown-table" + "obsidian-excel-to-markdown-table", + "obsidian-clipper" ] \ No newline at end of file diff --git a/.obsidian/plugins/cubox-sync/data.json b/.obsidian/plugins/cubox-sync/data.json index a49374ca..eb0cf171 100644 --- a/.obsidian/plugins/cubox-sync/data.json +++ b/.obsidian/plugins/cubox-sync/data.json @@ -34,7 +34,7 @@ "contentTemplate": "# {{{title}}}\n\n{{{description}}}\n\n{{{article_title}}} //文章内容标题\n{{{content}}} //文章正文\n\n\n[Read in Cubox]({{{cubox_url}}}) \n[Read Original]({{{url}}}) \n\n---\n\n{{#highlights.length}}\n## Annotations \n\n{{#highlights}}\n> {{{text}}} \n\n{{#note}}\n{{{note}}}\n{{/note}}\n[Link️]({{{cubox_url}}}) \n\n{{/highlights}}\n{{/highlights.length}}", "highlightInContent": true, "dateFormat": "yyyy-MM-dd", - "lastSyncTime": 1754623776077, + "lastSyncTime": 1754625576126, "lastSyncCardId": "7351520724877575515", "lastCardUpdateTime": "2025-08-03T13:52:57.494+0800", "syncing": false diff --git a/.obsidian/plugins/obsidian-clipper/main.js b/.obsidian/plugins/obsidian-clipper/main.js new file mode 100644 index 00000000..034d8a5e --- /dev/null +++ b/.obsidian/plugins/obsidian-clipper/main.js @@ -0,0 +1,10951 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +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 __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(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; +var __privateWrapper = (obj, member, setter, getter) => { + return { + set _(value) { + __privateSet(obj, member, value, setter); + }, + get _() { + return __privateGet(obj, member, getter); + } + }; +}; +var __privateMethod = (obj, member, method) => { + __accessCheck(obj, member, "access private method"); + return method; +}; + +// node_modules/obsidian-daily-notes-interface/dist/main.js +var require_main = __commonJS({ + "node_modules/obsidian-daily-notes-interface/dist/main.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var obsidian = require("obsidian"); + var DEFAULT_DAILY_NOTE_FORMAT = "YYYY-MM-DD"; + var DEFAULT_WEEKLY_NOTE_FORMAT = "gggg-[W]ww"; + var DEFAULT_MONTHLY_NOTE_FORMAT = "YYYY-MM"; + var DEFAULT_QUARTERLY_NOTE_FORMAT = "YYYY-[Q]Q"; + var DEFAULT_YEARLY_NOTE_FORMAT = "YYYY"; + function shouldUsePeriodicNotesSettings(periodicity) { + var _a, _b; + const periodicNotes = window.app.plugins.getPlugin("periodic-notes"); + return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a[periodicity]) == null ? void 0 : _b.enabled); + } + function getDailyNoteSettings() { + var _a, _b, _c, _d; + try { + const { internalPlugins, plugins } = window.app; + if (shouldUsePeriodicNotesSettings("daily")) { + const { format: format3, folder: folder2, template: template2 } = ((_b = (_a = plugins.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.daily) || {}; + return { + format: format3 || DEFAULT_DAILY_NOTE_FORMAT, + folder: (folder2 == null ? void 0 : folder2.trim()) || "", + template: (template2 == null ? void 0 : template2.trim()) || "" + }; + } + const { folder, format: format2, template } = ((_d = (_c = internalPlugins.getPluginById("daily-notes")) == null ? void 0 : _c.instance) == null ? void 0 : _d.options) || {}; + return { + format: format2 || DEFAULT_DAILY_NOTE_FORMAT, + folder: (folder == null ? void 0 : folder.trim()) || "", + template: (template == null ? void 0 : template.trim()) || "" + }; + } catch (err) { + console.info("No custom daily note settings found!", err); + } + } + function getWeeklyNoteSettings() { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pluginManager = window.app.plugins; + const calendarSettings = (_a = pluginManager.getPlugin("calendar")) == null ? void 0 : _a.options; + const periodicNotesSettings = (_c = (_b = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _b.settings) == null ? void 0 : _c.weekly; + if (shouldUsePeriodicNotesSettings("weekly")) { + return { + format: periodicNotesSettings.format || DEFAULT_WEEKLY_NOTE_FORMAT, + folder: ((_d = periodicNotesSettings.folder) == null ? void 0 : _d.trim()) || "", + template: ((_e = periodicNotesSettings.template) == null ? void 0 : _e.trim()) || "" + }; + } + const settings2 = calendarSettings || {}; + return { + format: settings2.weeklyNoteFormat || DEFAULT_WEEKLY_NOTE_FORMAT, + folder: ((_f = settings2.weeklyNoteFolder) == null ? void 0 : _f.trim()) || "", + template: ((_g = settings2.weeklyNoteTemplate) == null ? void 0 : _g.trim()) || "" + }; + } catch (err) { + console.info("No custom weekly note settings found!", err); + } + } + function getMonthlyNoteSettings() { + var _a, _b, _c, _d; + const pluginManager = window.app.plugins; + try { + const settings2 = shouldUsePeriodicNotesSettings("monthly") && ((_b = (_a = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.monthly) || {}; + return { + format: settings2.format || DEFAULT_MONTHLY_NOTE_FORMAT, + folder: ((_c = settings2.folder) == null ? void 0 : _c.trim()) || "", + template: ((_d = settings2.template) == null ? void 0 : _d.trim()) || "" + }; + } catch (err) { + console.info("No custom monthly note settings found!", err); + } + } + function getQuarterlyNoteSettings() { + var _a, _b, _c, _d; + const pluginManager = window.app.plugins; + try { + const settings2 = shouldUsePeriodicNotesSettings("quarterly") && ((_b = (_a = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.quarterly) || {}; + return { + format: settings2.format || DEFAULT_QUARTERLY_NOTE_FORMAT, + folder: ((_c = settings2.folder) == null ? void 0 : _c.trim()) || "", + template: ((_d = settings2.template) == null ? void 0 : _d.trim()) || "" + }; + } catch (err) { + console.info("No custom quarterly note settings found!", err); + } + } + function getYearlyNoteSettings() { + var _a, _b, _c, _d; + const pluginManager = window.app.plugins; + try { + const settings2 = shouldUsePeriodicNotesSettings("yearly") && ((_b = (_a = pluginManager.getPlugin("periodic-notes")) == null ? void 0 : _a.settings) == null ? void 0 : _b.yearly) || {}; + return { + format: settings2.format || DEFAULT_YEARLY_NOTE_FORMAT, + folder: ((_c = settings2.folder) == null ? void 0 : _c.trim()) || "", + template: ((_d = settings2.template) == null ? void 0 : _d.trim()) || "" + }; + } catch (err) { + console.info("No custom yearly note settings found!", err); + } + } + function join(...partSegments) { + let parts = []; + for (let i = 0, l = partSegments.length; i < l; i++) { + parts = parts.concat(partSegments[i].split("/")); + } + const newParts = []; + for (let i = 0, l = parts.length; i < l; i++) { + const part = parts[i]; + if (!part || part === ".") + continue; + else + newParts.push(part); + } + if (parts[0] === "") + newParts.unshift(""); + return newParts.join("/"); + } + function basename(fullPath) { + let base = fullPath.substring(fullPath.lastIndexOf("/") + 1); + if (base.lastIndexOf(".") != -1) + base = base.substring(0, base.lastIndexOf(".")); + return base; + } + async function ensureFolderExists(path) { + const dirs = path.replace(/\\/g, "/").split("/"); + dirs.pop(); + if (dirs.length) { + const dir = join(...dirs); + if (!window.app.vault.getAbstractFileByPath(dir)) { + await window.app.vault.createFolder(dir); + } + } + } + async function getNotePath(directory, filename) { + if (!filename.endsWith(".md")) { + filename += ".md"; + } + const path = obsidian.normalizePath(join(directory, filename)); + await ensureFolderExists(path); + return path; + } + async function getTemplateInfo(template) { + const { metadataCache, vault } = window.app; + const templatePath = obsidian.normalizePath(template); + if (templatePath === "/") { + return Promise.resolve(["", null]); + } + try { + const templateFile = metadataCache.getFirstLinkpathDest(templatePath, ""); + const contents = await vault.cachedRead(templateFile); + const IFoldInfo = window.app.foldManager.load(templateFile); + return [contents, IFoldInfo]; + } catch (err) { + console.error(`Failed to read the daily note template '${templatePath}'`, err); + new obsidian.Notice("Failed to read the daily note template"); + return ["", null]; + } + } + function getDateUID(date, granularity = "day") { + const ts = date.clone().startOf(granularity).format(); + return `${granularity}-${ts}`; + } + function removeEscapedCharacters(format2) { + return format2.replace(/\[[^\]]*\]/g, ""); + } + function isFormatAmbiguous(format2, granularity) { + if (granularity === "week") { + const cleanFormat = removeEscapedCharacters(format2); + return /w{1,2}/i.test(cleanFormat) && (/M{1,4}/.test(cleanFormat) || /D{1,4}/.test(cleanFormat)); + } + return false; + } + function getDateFromFile(file, granularity) { + return getDateFromFilename(file.basename, granularity); + } + function getDateFromPath(path, granularity) { + return getDateFromFilename(basename(path), granularity); + } + function getDateFromFilename(filename, granularity) { + const getSettings = { + day: getDailyNoteSettings, + week: getWeeklyNoteSettings, + month: getMonthlyNoteSettings, + quarter: getQuarterlyNoteSettings, + year: getYearlyNoteSettings + }; + const format2 = getSettings[granularity]().format.split("/").pop(); + const noteDate = window.moment(filename, format2, true); + if (!noteDate.isValid()) { + return null; + } + if (isFormatAmbiguous(format2, granularity)) { + if (granularity === "week") { + const cleanFormat = removeEscapedCharacters(format2); + if (/w{1,2}/i.test(cleanFormat)) { + return window.moment(filename, format2.replace(/M{1,4}/g, "").replace(/D{1,4}/g, ""), false); + } + } + } + return noteDate; + } + var DailyNotesFolderMissingError = class extends Error { + }; + async function createDailyNote2(date) { + const app = window.app; + const { vault } = app; + const moment = window.moment; + const { template, format: format2, folder } = getDailyNoteSettings(); + const [templateContents, IFoldInfo] = await getTemplateInfo(template); + const filename = date.format(format2); + const normalizedPath = await getNotePath(folder, filename); + try { + const createdFile = await vault.create(normalizedPath, templateContents.replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename).replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => { + const now2 = moment(); + const currentDate = date.clone().set({ + hour: now2.get("hour"), + minute: now2.get("minute"), + second: now2.get("second") + }); + if (calc) { + currentDate.add(parseInt(timeDelta, 10), unit); + } + if (momentFormat) { + return currentDate.format(momentFormat.substring(1).trim()); + } + return currentDate.format(format2); + }).replace(/{{\s*yesterday\s*}}/gi, date.clone().subtract(1, "day").format(format2)).replace(/{{\s*tomorrow\s*}}/gi, date.clone().add(1, "d").format(format2))); + app.foldManager.save(createdFile, IFoldInfo); + return createdFile; + } catch (err) { + console.error(`Failed to create file: '${normalizedPath}'`, err); + new obsidian.Notice("Unable to create new file."); + } + } + function getDailyNote2(date, dailyNotes) { + var _a; + return (_a = dailyNotes[getDateUID(date, "day")]) != null ? _a : null; + } + function getAllDailyNotes2() { + const { vault } = window.app; + const { folder } = getDailyNoteSettings(); + const dailyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder)); + if (!dailyNotesFolder) { + throw new DailyNotesFolderMissingError("Failed to find daily notes folder"); + } + const dailyNotes = {}; + obsidian.Vault.recurseChildren(dailyNotesFolder, (note) => { + if (note instanceof obsidian.TFile) { + const date = getDateFromFile(note, "day"); + if (date) { + const dateString = getDateUID(date, "day"); + dailyNotes[dateString] = note; + } + } + }); + return dailyNotes; + } + var WeeklyNotesFolderMissingError = class extends Error { + }; + function getDaysOfWeek() { + const { moment } = window; + let weekStart = moment.localeData()._week.dow; + const daysOfWeek = [ + "sunday", + "monday", + "tuesday", + "wednesday", + "thursday", + "friday", + "saturday" + ]; + while (weekStart) { + daysOfWeek.push(daysOfWeek.shift()); + weekStart--; + } + return daysOfWeek; + } + function getDayOfWeekNumericalValue(dayOfWeekName) { + return getDaysOfWeek().indexOf(dayOfWeekName.toLowerCase()); + } + async function createWeeklyNote2(date) { + const { vault } = window.app; + const { template, format: format2, folder } = getWeeklyNoteSettings(); + const [templateContents, IFoldInfo] = await getTemplateInfo(template); + const filename = date.format(format2); + const normalizedPath = await getNotePath(folder, filename); + try { + const createdFile = await vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => { + const now2 = window.moment(); + const currentDate = date.clone().set({ + hour: now2.get("hour"), + minute: now2.get("minute"), + second: now2.get("second") + }); + if (calc) { + currentDate.add(parseInt(timeDelta, 10), unit); + } + if (momentFormat) { + return currentDate.format(momentFormat.substring(1).trim()); + } + return currentDate.format(format2); + }).replace(/{{\s*title\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi, (_, dayOfWeek, momentFormat) => { + const day = getDayOfWeekNumericalValue(dayOfWeek); + return date.weekday(day).format(momentFormat.trim()); + })); + window.app.foldManager.save(createdFile, IFoldInfo); + return createdFile; + } catch (err) { + console.error(`Failed to create file: '${normalizedPath}'`, err); + new obsidian.Notice("Unable to create new file."); + } + } + function getWeeklyNote2(date, weeklyNotes) { + var _a; + return (_a = weeklyNotes[getDateUID(date, "week")]) != null ? _a : null; + } + function getAllWeeklyNotes2() { + const weeklyNotes = {}; + if (!appHasWeeklyNotesPluginLoaded2()) { + return weeklyNotes; + } + const { vault } = window.app; + const { folder } = getWeeklyNoteSettings(); + const weeklyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder)); + if (!weeklyNotesFolder) { + throw new WeeklyNotesFolderMissingError("Failed to find weekly notes folder"); + } + obsidian.Vault.recurseChildren(weeklyNotesFolder, (note) => { + if (note instanceof obsidian.TFile) { + const date = getDateFromFile(note, "week"); + if (date) { + const dateString = getDateUID(date, "week"); + weeklyNotes[dateString] = note; + } + } + }); + return weeklyNotes; + } + var MonthlyNotesFolderMissingError = class extends Error { + }; + async function createMonthlyNote(date) { + const { vault } = window.app; + const { template, format: format2, folder } = getMonthlyNoteSettings(); + const [templateContents, IFoldInfo] = await getTemplateInfo(template); + const filename = date.format(format2); + const normalizedPath = await getNotePath(folder, filename); + try { + const createdFile = await vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => { + const now2 = window.moment(); + const currentDate = date.clone().set({ + hour: now2.get("hour"), + minute: now2.get("minute"), + second: now2.get("second") + }); + if (calc) { + currentDate.add(parseInt(timeDelta, 10), unit); + } + if (momentFormat) { + return currentDate.format(momentFormat.substring(1).trim()); + } + return currentDate.format(format2); + }).replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename)); + window.app.foldManager.save(createdFile, IFoldInfo); + return createdFile; + } catch (err) { + console.error(`Failed to create file: '${normalizedPath}'`, err); + new obsidian.Notice("Unable to create new file."); + } + } + function getMonthlyNote(date, monthlyNotes) { + var _a; + return (_a = monthlyNotes[getDateUID(date, "month")]) != null ? _a : null; + } + function getAllMonthlyNotes() { + const monthlyNotes = {}; + if (!appHasMonthlyNotesPluginLoaded()) { + return monthlyNotes; + } + const { vault } = window.app; + const { folder } = getMonthlyNoteSettings(); + const monthlyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder)); + if (!monthlyNotesFolder) { + throw new MonthlyNotesFolderMissingError("Failed to find monthly notes folder"); + } + obsidian.Vault.recurseChildren(monthlyNotesFolder, (note) => { + if (note instanceof obsidian.TFile) { + const date = getDateFromFile(note, "month"); + if (date) { + const dateString = getDateUID(date, "month"); + monthlyNotes[dateString] = note; + } + } + }); + return monthlyNotes; + } + var QuarterlyNotesFolderMissingError = class extends Error { + }; + async function createQuarterlyNote(date) { + const { vault } = window.app; + const { template, format: format2, folder } = getQuarterlyNoteSettings(); + const [templateContents, IFoldInfo] = await getTemplateInfo(template); + const filename = date.format(format2); + const normalizedPath = await getNotePath(folder, filename); + try { + const createdFile = await vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => { + const now2 = window.moment(); + const currentDate = date.clone().set({ + hour: now2.get("hour"), + minute: now2.get("minute"), + second: now2.get("second") + }); + if (calc) { + currentDate.add(parseInt(timeDelta, 10), unit); + } + if (momentFormat) { + return currentDate.format(momentFormat.substring(1).trim()); + } + return currentDate.format(format2); + }).replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename)); + window.app.foldManager.save(createdFile, IFoldInfo); + return createdFile; + } catch (err) { + console.error(`Failed to create file: '${normalizedPath}'`, err); + new obsidian.Notice("Unable to create new file."); + } + } + function getQuarterlyNote(date, quarterly) { + var _a; + return (_a = quarterly[getDateUID(date, "quarter")]) != null ? _a : null; + } + function getAllQuarterlyNotes() { + const quarterly = {}; + if (!appHasQuarterlyNotesPluginLoaded()) { + return quarterly; + } + const { vault } = window.app; + const { folder } = getQuarterlyNoteSettings(); + const quarterlyFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder)); + if (!quarterlyFolder) { + throw new QuarterlyNotesFolderMissingError("Failed to find quarterly notes folder"); + } + obsidian.Vault.recurseChildren(quarterlyFolder, (note) => { + if (note instanceof obsidian.TFile) { + const date = getDateFromFile(note, "quarter"); + if (date) { + const dateString = getDateUID(date, "quarter"); + quarterly[dateString] = note; + } + } + }); + return quarterly; + } + var YearlyNotesFolderMissingError = class extends Error { + }; + async function createYearlyNote(date) { + const { vault } = window.app; + const { template, format: format2, folder } = getYearlyNoteSettings(); + const [templateContents, IFoldInfo] = await getTemplateInfo(template); + const filename = date.format(format2); + const normalizedPath = await getNotePath(folder, filename); + try { + const createdFile = await vault.create(normalizedPath, templateContents.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi, (_, _timeOrDate, calc, timeDelta, unit, momentFormat) => { + const now2 = window.moment(); + const currentDate = date.clone().set({ + hour: now2.get("hour"), + minute: now2.get("minute"), + second: now2.get("second") + }); + if (calc) { + currentDate.add(parseInt(timeDelta, 10), unit); + } + if (momentFormat) { + return currentDate.format(momentFormat.substring(1).trim()); + } + return currentDate.format(format2); + }).replace(/{{\s*date\s*}}/gi, filename).replace(/{{\s*time\s*}}/gi, window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi, filename)); + window.app.foldManager.save(createdFile, IFoldInfo); + return createdFile; + } catch (err) { + console.error(`Failed to create file: '${normalizedPath}'`, err); + new obsidian.Notice("Unable to create new file."); + } + } + function getYearlyNote(date, yearlyNotes) { + var _a; + return (_a = yearlyNotes[getDateUID(date, "year")]) != null ? _a : null; + } + function getAllYearlyNotes() { + const yearlyNotes = {}; + if (!appHasYearlyNotesPluginLoaded()) { + return yearlyNotes; + } + const { vault } = window.app; + const { folder } = getYearlyNoteSettings(); + const yearlyNotesFolder = vault.getAbstractFileByPath(obsidian.normalizePath(folder)); + if (!yearlyNotesFolder) { + throw new YearlyNotesFolderMissingError("Failed to find yearly notes folder"); + } + obsidian.Vault.recurseChildren(yearlyNotesFolder, (note) => { + if (note instanceof obsidian.TFile) { + const date = getDateFromFile(note, "year"); + if (date) { + const dateString = getDateUID(date, "year"); + yearlyNotes[dateString] = note; + } + } + }); + return yearlyNotes; + } + function appHasDailyNotesPluginLoaded2() { + var _a, _b; + const { app } = window; + const dailyNotesPlugin = app.internalPlugins.plugins["daily-notes"]; + if (dailyNotesPlugin && dailyNotesPlugin.enabled) { + return true; + } + const periodicNotes = app.plugins.getPlugin("periodic-notes"); + return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.daily) == null ? void 0 : _b.enabled); + } + function appHasWeeklyNotesPluginLoaded2() { + var _a, _b; + const { app } = window; + if (app.plugins.getPlugin("calendar")) { + return true; + } + const periodicNotes = app.plugins.getPlugin("periodic-notes"); + return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.weekly) == null ? void 0 : _b.enabled); + } + function appHasMonthlyNotesPluginLoaded() { + var _a, _b; + const { app } = window; + const periodicNotes = app.plugins.getPlugin("periodic-notes"); + return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.monthly) == null ? void 0 : _b.enabled); + } + function appHasQuarterlyNotesPluginLoaded() { + var _a, _b; + const { app } = window; + const periodicNotes = app.plugins.getPlugin("periodic-notes"); + return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.quarterly) == null ? void 0 : _b.enabled); + } + function appHasYearlyNotesPluginLoaded() { + var _a, _b; + const { app } = window; + const periodicNotes = app.plugins.getPlugin("periodic-notes"); + return periodicNotes && ((_b = (_a = periodicNotes.settings) == null ? void 0 : _a.yearly) == null ? void 0 : _b.enabled); + } + function getPeriodicNoteSettings(granularity) { + const getSettings = { + day: getDailyNoteSettings, + week: getWeeklyNoteSettings, + month: getMonthlyNoteSettings, + quarter: getQuarterlyNoteSettings, + year: getYearlyNoteSettings + }[granularity]; + return getSettings(); + } + function createPeriodicNote(granularity, date) { + const createFn = { + day: createDailyNote2, + month: createMonthlyNote, + week: createWeeklyNote2 + }; + return createFn[granularity](date); + } + exports.DEFAULT_DAILY_NOTE_FORMAT = DEFAULT_DAILY_NOTE_FORMAT; + exports.DEFAULT_MONTHLY_NOTE_FORMAT = DEFAULT_MONTHLY_NOTE_FORMAT; + exports.DEFAULT_QUARTERLY_NOTE_FORMAT = DEFAULT_QUARTERLY_NOTE_FORMAT; + exports.DEFAULT_WEEKLY_NOTE_FORMAT = DEFAULT_WEEKLY_NOTE_FORMAT; + exports.DEFAULT_YEARLY_NOTE_FORMAT = DEFAULT_YEARLY_NOTE_FORMAT; + exports.appHasDailyNotesPluginLoaded = appHasDailyNotesPluginLoaded2; + exports.appHasMonthlyNotesPluginLoaded = appHasMonthlyNotesPluginLoaded; + exports.appHasQuarterlyNotesPluginLoaded = appHasQuarterlyNotesPluginLoaded; + exports.appHasWeeklyNotesPluginLoaded = appHasWeeklyNotesPluginLoaded2; + exports.appHasYearlyNotesPluginLoaded = appHasYearlyNotesPluginLoaded; + exports.createDailyNote = createDailyNote2; + exports.createMonthlyNote = createMonthlyNote; + exports.createPeriodicNote = createPeriodicNote; + exports.createQuarterlyNote = createQuarterlyNote; + exports.createWeeklyNote = createWeeklyNote2; + exports.createYearlyNote = createYearlyNote; + exports.getAllDailyNotes = getAllDailyNotes2; + exports.getAllMonthlyNotes = getAllMonthlyNotes; + exports.getAllQuarterlyNotes = getAllQuarterlyNotes; + exports.getAllWeeklyNotes = getAllWeeklyNotes2; + exports.getAllYearlyNotes = getAllYearlyNotes; + exports.getDailyNote = getDailyNote2; + exports.getDailyNoteSettings = getDailyNoteSettings; + exports.getDateFromFile = getDateFromFile; + exports.getDateFromPath = getDateFromPath; + exports.getDateUID = getDateUID; + exports.getMonthlyNote = getMonthlyNote; + exports.getMonthlyNoteSettings = getMonthlyNoteSettings; + exports.getPeriodicNoteSettings = getPeriodicNoteSettings; + exports.getQuarterlyNote = getQuarterlyNote; + exports.getQuarterlyNoteSettings = getQuarterlyNoteSettings; + exports.getTemplateInfo = getTemplateInfo; + exports.getWeeklyNote = getWeeklyNote2; + exports.getWeeklyNoteSettings = getWeeklyNoteSettings; + exports.getYearlyNote = getYearlyNote; + exports.getYearlyNoteSettings = getYearlyNoteSettings; + } +}); + +// node_modules/@dagrejs/graphlib/lib/graph.js +var require_graph = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/graph.js"(exports, module2) { + "use strict"; + var DEFAULT_EDGE_NAME = "\0"; + var GRAPH_NODE = "\0"; + var EDGE_KEY_DELIM = ""; + var _isDirected, _isMultigraph, _isCompound, _label, _defaultNodeLabelFn, _defaultEdgeLabelFn, _nodes, _in, _preds, _out, _sucs, _edgeObjs, _edgeLabels, _nodeCount, _edgeCount, _parent, _children, _removeFromParentsChildList, removeFromParentsChildList_fn; + var Graph = class { + constructor(opts) { + __privateAdd(this, _removeFromParentsChildList); + __privateAdd(this, _isDirected, true); + __privateAdd(this, _isMultigraph, false); + __privateAdd(this, _isCompound, false); + __privateAdd(this, _label, void 0); + __privateAdd(this, _defaultNodeLabelFn, () => void 0); + __privateAdd(this, _defaultEdgeLabelFn, () => void 0); + __privateAdd(this, _nodes, {}); + __privateAdd(this, _in, {}); + __privateAdd(this, _preds, {}); + __privateAdd(this, _out, {}); + __privateAdd(this, _sucs, {}); + __privateAdd(this, _edgeObjs, {}); + __privateAdd(this, _edgeLabels, {}); + __privateAdd(this, _nodeCount, 0); + __privateAdd(this, _edgeCount, 0); + __privateAdd(this, _parent, void 0); + __privateAdd(this, _children, void 0); + if (opts) { + __privateSet(this, _isDirected, opts.hasOwnProperty("directed") ? opts.directed : true); + __privateSet(this, _isMultigraph, opts.hasOwnProperty("multigraph") ? opts.multigraph : false); + __privateSet(this, _isCompound, opts.hasOwnProperty("compound") ? opts.compound : false); + } + if (__privateGet(this, _isCompound)) { + __privateSet(this, _parent, {}); + __privateSet(this, _children, {}); + __privateGet(this, _children)[GRAPH_NODE] = {}; + } + } + isDirected() { + return __privateGet(this, _isDirected); + } + isMultigraph() { + return __privateGet(this, _isMultigraph); + } + isCompound() { + return __privateGet(this, _isCompound); + } + setGraph(label) { + __privateSet(this, _label, label); + return this; + } + graph() { + return __privateGet(this, _label); + } + setDefaultNodeLabel(newDefault) { + __privateSet(this, _defaultNodeLabelFn, newDefault); + if (typeof newDefault !== "function") { + __privateSet(this, _defaultNodeLabelFn, () => newDefault); + } + return this; + } + nodeCount() { + return __privateGet(this, _nodeCount); + } + nodes() { + return Object.keys(__privateGet(this, _nodes)); + } + sources() { + var self = this; + return this.nodes().filter((v) => Object.keys(__privateGet(self, _in)[v]).length === 0); + } + sinks() { + var self = this; + return this.nodes().filter((v) => Object.keys(__privateGet(self, _out)[v]).length === 0); + } + setNodes(vs, value) { + var args = arguments; + var self = this; + vs.forEach(function(v) { + if (args.length > 1) { + self.setNode(v, value); + } else { + self.setNode(v); + } + }); + return this; + } + setNode(v, value) { + if (__privateGet(this, _nodes).hasOwnProperty(v)) { + if (arguments.length > 1) { + __privateGet(this, _nodes)[v] = value; + } + return this; + } + __privateGet(this, _nodes)[v] = arguments.length > 1 ? value : __privateGet(this, _defaultNodeLabelFn).call(this, v); + if (__privateGet(this, _isCompound)) { + __privateGet(this, _parent)[v] = GRAPH_NODE; + __privateGet(this, _children)[v] = {}; + __privateGet(this, _children)[GRAPH_NODE][v] = true; + } + __privateGet(this, _in)[v] = {}; + __privateGet(this, _preds)[v] = {}; + __privateGet(this, _out)[v] = {}; + __privateGet(this, _sucs)[v] = {}; + ++__privateWrapper(this, _nodeCount)._; + return this; + } + node(v) { + return __privateGet(this, _nodes)[v]; + } + hasNode(v) { + return __privateGet(this, _nodes).hasOwnProperty(v); + } + removeNode(v) { + var self = this; + if (__privateGet(this, _nodes).hasOwnProperty(v)) { + var removeEdge = (e) => self.removeEdge(__privateGet(self, _edgeObjs)[e]); + delete __privateGet(this, _nodes)[v]; + if (__privateGet(this, _isCompound)) { + __privateMethod(this, _removeFromParentsChildList, removeFromParentsChildList_fn).call(this, v); + delete __privateGet(this, _parent)[v]; + this.children(v).forEach(function(child) { + self.setParent(child); + }); + delete __privateGet(this, _children)[v]; + } + Object.keys(__privateGet(this, _in)[v]).forEach(removeEdge); + delete __privateGet(this, _in)[v]; + delete __privateGet(this, _preds)[v]; + Object.keys(__privateGet(this, _out)[v]).forEach(removeEdge); + delete __privateGet(this, _out)[v]; + delete __privateGet(this, _sucs)[v]; + --__privateWrapper(this, _nodeCount)._; + } + return this; + } + setParent(v, parent) { + if (!__privateGet(this, _isCompound)) { + throw new Error("Cannot set parent in a non-compound graph"); + } + if (parent === void 0) { + parent = GRAPH_NODE; + } else { + parent += ""; + for (var ancestor = parent; ancestor !== void 0; ancestor = this.parent(ancestor)) { + if (ancestor === v) { + throw new Error("Setting " + parent + " as parent of " + v + " would create a cycle"); + } + } + this.setNode(parent); + } + this.setNode(v); + __privateMethod(this, _removeFromParentsChildList, removeFromParentsChildList_fn).call(this, v); + __privateGet(this, _parent)[v] = parent; + __privateGet(this, _children)[parent][v] = true; + return this; + } + parent(v) { + if (__privateGet(this, _isCompound)) { + var parent = __privateGet(this, _parent)[v]; + if (parent !== GRAPH_NODE) { + return parent; + } + } + } + children(v = GRAPH_NODE) { + if (__privateGet(this, _isCompound)) { + var children2 = __privateGet(this, _children)[v]; + if (children2) { + return Object.keys(children2); + } + } else if (v === GRAPH_NODE) { + return this.nodes(); + } else if (this.hasNode(v)) { + return []; + } + } + predecessors(v) { + var predsV = __privateGet(this, _preds)[v]; + if (predsV) { + return Object.keys(predsV); + } + } + successors(v) { + var sucsV = __privateGet(this, _sucs)[v]; + if (sucsV) { + return Object.keys(sucsV); + } + } + neighbors(v) { + var preds = this.predecessors(v); + if (preds) { + const union = new Set(preds); + for (var succ of this.successors(v)) { + union.add(succ); + } + return Array.from(union.values()); + } + } + isLeaf(v) { + var neighbors; + if (this.isDirected()) { + neighbors = this.successors(v); + } else { + neighbors = this.neighbors(v); + } + return neighbors.length === 0; + } + filterNodes(filter) { + var copy = new this.constructor({ + directed: __privateGet(this, _isDirected), + multigraph: __privateGet(this, _isMultigraph), + compound: __privateGet(this, _isCompound) + }); + copy.setGraph(this.graph()); + var self = this; + Object.entries(__privateGet(this, _nodes)).forEach(function([v, value]) { + if (filter(v)) { + copy.setNode(v, value); + } + }); + Object.values(__privateGet(this, _edgeObjs)).forEach(function(e) { + if (copy.hasNode(e.v) && copy.hasNode(e.w)) { + copy.setEdge(e, self.edge(e)); + } + }); + var parents = {}; + function findParent(v) { + var parent = self.parent(v); + if (parent === void 0 || copy.hasNode(parent)) { + parents[v] = parent; + return parent; + } else if (parent in parents) { + return parents[parent]; + } else { + return findParent(parent); + } + } + if (__privateGet(this, _isCompound)) { + copy.nodes().forEach((v) => copy.setParent(v, findParent(v))); + } + return copy; + } + setDefaultEdgeLabel(newDefault) { + __privateSet(this, _defaultEdgeLabelFn, newDefault); + if (typeof newDefault !== "function") { + __privateSet(this, _defaultEdgeLabelFn, () => newDefault); + } + return this; + } + edgeCount() { + return __privateGet(this, _edgeCount); + } + edges() { + return Object.values(__privateGet(this, _edgeObjs)); + } + setPath(vs, value) { + var self = this; + var args = arguments; + vs.reduce(function(v, w) { + if (args.length > 1) { + self.setEdge(v, w, value); + } else { + self.setEdge(v, w); + } + return w; + }); + return this; + } + setEdge() { + var v, w, name, value; + var valueSpecified = false; + var arg0 = arguments[0]; + if (typeof arg0 === "object" && arg0 !== null && "v" in arg0) { + v = arg0.v; + w = arg0.w; + name = arg0.name; + if (arguments.length === 2) { + value = arguments[1]; + valueSpecified = true; + } + } else { + v = arg0; + w = arguments[1]; + name = arguments[3]; + if (arguments.length > 2) { + value = arguments[2]; + valueSpecified = true; + } + } + v = "" + v; + w = "" + w; + if (name !== void 0) { + name = "" + name; + } + var e = edgeArgsToId(__privateGet(this, _isDirected), v, w, name); + if (__privateGet(this, _edgeLabels).hasOwnProperty(e)) { + if (valueSpecified) { + __privateGet(this, _edgeLabels)[e] = value; + } + return this; + } + if (name !== void 0 && !__privateGet(this, _isMultigraph)) { + throw new Error("Cannot set a named edge when isMultigraph = false"); + } + this.setNode(v); + this.setNode(w); + __privateGet(this, _edgeLabels)[e] = valueSpecified ? value : __privateGet(this, _defaultEdgeLabelFn).call(this, v, w, name); + var edgeObj = edgeArgsToObj(__privateGet(this, _isDirected), v, w, name); + v = edgeObj.v; + w = edgeObj.w; + Object.freeze(edgeObj); + __privateGet(this, _edgeObjs)[e] = edgeObj; + incrementOrInitEntry(__privateGet(this, _preds)[w], v); + incrementOrInitEntry(__privateGet(this, _sucs)[v], w); + __privateGet(this, _in)[w][e] = edgeObj; + __privateGet(this, _out)[v][e] = edgeObj; + __privateWrapper(this, _edgeCount)._++; + return this; + } + edge(v, w, name) { + var e = arguments.length === 1 ? edgeObjToId(__privateGet(this, _isDirected), arguments[0]) : edgeArgsToId(__privateGet(this, _isDirected), v, w, name); + return __privateGet(this, _edgeLabels)[e]; + } + edgeAsObj() { + const edge = this.edge(...arguments); + if (typeof edge !== "object") { + return { label: edge }; + } + return edge; + } + hasEdge(v, w, name) { + var e = arguments.length === 1 ? edgeObjToId(__privateGet(this, _isDirected), arguments[0]) : edgeArgsToId(__privateGet(this, _isDirected), v, w, name); + return __privateGet(this, _edgeLabels).hasOwnProperty(e); + } + removeEdge(v, w, name) { + var e = arguments.length === 1 ? edgeObjToId(__privateGet(this, _isDirected), arguments[0]) : edgeArgsToId(__privateGet(this, _isDirected), v, w, name); + var edge = __privateGet(this, _edgeObjs)[e]; + if (edge) { + v = edge.v; + w = edge.w; + delete __privateGet(this, _edgeLabels)[e]; + delete __privateGet(this, _edgeObjs)[e]; + decrementOrRemoveEntry(__privateGet(this, _preds)[w], v); + decrementOrRemoveEntry(__privateGet(this, _sucs)[v], w); + delete __privateGet(this, _in)[w][e]; + delete __privateGet(this, _out)[v][e]; + __privateWrapper(this, _edgeCount)._--; + } + return this; + } + inEdges(v, u) { + var inV = __privateGet(this, _in)[v]; + if (inV) { + var edges = Object.values(inV); + if (!u) { + return edges; + } + return edges.filter((edge) => edge.v === u); + } + } + outEdges(v, w) { + var outV = __privateGet(this, _out)[v]; + if (outV) { + var edges = Object.values(outV); + if (!w) { + return edges; + } + return edges.filter((edge) => edge.w === w); + } + } + nodeEdges(v, w) { + var inEdges = this.inEdges(v, w); + if (inEdges) { + return inEdges.concat(this.outEdges(v, w)); + } + } + }; + _isDirected = new WeakMap(); + _isMultigraph = new WeakMap(); + _isCompound = new WeakMap(); + _label = new WeakMap(); + _defaultNodeLabelFn = new WeakMap(); + _defaultEdgeLabelFn = new WeakMap(); + _nodes = new WeakMap(); + _in = new WeakMap(); + _preds = new WeakMap(); + _out = new WeakMap(); + _sucs = new WeakMap(); + _edgeObjs = new WeakMap(); + _edgeLabels = new WeakMap(); + _nodeCount = new WeakMap(); + _edgeCount = new WeakMap(); + _parent = new WeakMap(); + _children = new WeakMap(); + _removeFromParentsChildList = new WeakSet(); + removeFromParentsChildList_fn = function(v) { + delete __privateGet(this, _children)[__privateGet(this, _parent)[v]][v]; + }; + function incrementOrInitEntry(map, k) { + if (map[k]) { + map[k]++; + } else { + map[k] = 1; + } + } + function decrementOrRemoveEntry(map, k) { + if (!--map[k]) { + delete map[k]; + } + } + function edgeArgsToId(isDirected, v_, w_, name) { + var v = "" + v_; + var w = "" + w_; + if (!isDirected && v > w) { + var tmp = v; + v = w; + w = tmp; + } + return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (name === void 0 ? DEFAULT_EDGE_NAME : name); + } + function edgeArgsToObj(isDirected, v_, w_, name) { + var v = "" + v_; + var w = "" + w_; + if (!isDirected && v > w) { + var tmp = v; + v = w; + w = tmp; + } + var edgeObj = { v, w }; + if (name) { + edgeObj.name = name; + } + return edgeObj; + } + function edgeObjToId(isDirected, edgeObj) { + return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); + } + module2.exports = Graph; + } +}); + +// node_modules/@dagrejs/graphlib/lib/version.js +var require_version = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/version.js"(exports, module2) { + module2.exports = "2.1.13"; + } +}); + +// node_modules/@dagrejs/graphlib/lib/index.js +var require_lib = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/index.js"(exports, module2) { + module2.exports = { + Graph: require_graph(), + version: require_version() + }; + } +}); + +// node_modules/@dagrejs/graphlib/lib/json.js +var require_json = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/json.js"(exports, module2) { + var Graph = require_graph(); + module2.exports = { + write: write2, + read: read2 + }; + function write2(g) { + var json = { + options: { + directed: g.isDirected(), + multigraph: g.isMultigraph(), + compound: g.isCompound() + }, + nodes: writeNodes(g), + edges: writeEdges(g) + }; + if (g.graph() !== void 0) { + json.value = structuredClone(g.graph()); + } + return json; + } + function writeNodes(g) { + return g.nodes().map(function(v) { + var nodeValue = g.node(v); + var parent = g.parent(v); + var node = { v }; + if (nodeValue !== void 0) { + node.value = nodeValue; + } + if (parent !== void 0) { + node.parent = parent; + } + return node; + }); + } + function writeEdges(g) { + return g.edges().map(function(e) { + var edgeValue = g.edge(e); + var edge = { v: e.v, w: e.w }; + if (e.name !== void 0) { + edge.name = e.name; + } + if (edgeValue !== void 0) { + edge.value = edgeValue; + } + return edge; + }); + } + function read2(json) { + var g = new Graph(json.options).setGraph(json.value); + json.nodes.forEach(function(entry) { + g.setNode(entry.v, entry.value); + if (entry.parent) { + g.setParent(entry.v, entry.parent); + } + }); + json.edges.forEach(function(entry) { + g.setEdge({ v: entry.v, w: entry.w, name: entry.name }, entry.value); + }); + return g; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/components.js +var require_components = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/components.js"(exports, module2) { + module2.exports = components; + function components(g) { + var visited = {}; + var cmpts = []; + var cmpt; + function dfs(v) { + if (visited.hasOwnProperty(v)) + return; + visited[v] = true; + cmpt.push(v); + g.successors(v).forEach(dfs); + g.predecessors(v).forEach(dfs); + } + g.nodes().forEach(function(v) { + cmpt = []; + dfs(v); + if (cmpt.length) { + cmpts.push(cmpt); + } + }); + return cmpts; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/data/priority-queue.js +var require_priority_queue = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/data/priority-queue.js"(exports, module2) { + var _arr, _keyIndices, _heapify, heapify_fn, _decrease, decrease_fn, _swap, swap_fn; + var PriorityQueue = class { + constructor() { + __privateAdd(this, _heapify); + __privateAdd(this, _decrease); + __privateAdd(this, _swap); + __privateAdd(this, _arr, []); + __privateAdd(this, _keyIndices, {}); + } + size() { + return __privateGet(this, _arr).length; + } + keys() { + return __privateGet(this, _arr).map(function(x) { + return x.key; + }); + } + has(key) { + return __privateGet(this, _keyIndices).hasOwnProperty(key); + } + priority(key) { + var index = __privateGet(this, _keyIndices)[key]; + if (index !== void 0) { + return __privateGet(this, _arr)[index].priority; + } + } + min() { + if (this.size() === 0) { + throw new Error("Queue underflow"); + } + return __privateGet(this, _arr)[0].key; + } + add(key, priority) { + var keyIndices = __privateGet(this, _keyIndices); + key = String(key); + if (!keyIndices.hasOwnProperty(key)) { + var arr = __privateGet(this, _arr); + var index = arr.length; + keyIndices[key] = index; + arr.push({ key, priority }); + __privateMethod(this, _decrease, decrease_fn).call(this, index); + return true; + } + return false; + } + removeMin() { + __privateMethod(this, _swap, swap_fn).call(this, 0, __privateGet(this, _arr).length - 1); + var min2 = __privateGet(this, _arr).pop(); + delete __privateGet(this, _keyIndices)[min2.key]; + __privateMethod(this, _heapify, heapify_fn).call(this, 0); + return min2.key; + } + decrease(key, priority) { + var index = __privateGet(this, _keyIndices)[key]; + if (priority > __privateGet(this, _arr)[index].priority) { + throw new Error("New priority is greater than current priority. Key: " + key + " Old: " + __privateGet(this, _arr)[index].priority + " New: " + priority); + } + __privateGet(this, _arr)[index].priority = priority; + __privateMethod(this, _decrease, decrease_fn).call(this, index); + } + }; + _arr = new WeakMap(); + _keyIndices = new WeakMap(); + _heapify = new WeakSet(); + heapify_fn = function(i) { + var arr = __privateGet(this, _arr); + var l = 2 * i; + var r = l + 1; + var largest = i; + if (l < arr.length) { + largest = arr[l].priority < arr[largest].priority ? l : largest; + if (r < arr.length) { + largest = arr[r].priority < arr[largest].priority ? r : largest; + } + if (largest !== i) { + __privateMethod(this, _swap, swap_fn).call(this, i, largest); + __privateMethod(this, _heapify, heapify_fn).call(this, largest); + } + } + }; + _decrease = new WeakSet(); + decrease_fn = function(index) { + var arr = __privateGet(this, _arr); + var priority = arr[index].priority; + var parent; + while (index !== 0) { + parent = index >> 1; + if (arr[parent].priority < priority) { + break; + } + __privateMethod(this, _swap, swap_fn).call(this, index, parent); + index = parent; + } + }; + _swap = new WeakSet(); + swap_fn = function(i, j) { + var arr = __privateGet(this, _arr); + var keyIndices = __privateGet(this, _keyIndices); + var origArrI = arr[i]; + var origArrJ = arr[j]; + arr[i] = origArrJ; + arr[j] = origArrI; + keyIndices[origArrJ.key] = i; + keyIndices[origArrI.key] = j; + }; + module2.exports = PriorityQueue; + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/dijkstra.js +var require_dijkstra = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/dijkstra.js"(exports, module2) { + var PriorityQueue = require_priority_queue(); + module2.exports = dijkstra; + var DEFAULT_WEIGHT_FUNC = () => 1; + function dijkstra(g, source, weightFn, edgeFn) { + return runDijkstra(g, String(source), weightFn || DEFAULT_WEIGHT_FUNC, edgeFn || function(v) { + return g.outEdges(v); + }); + } + function runDijkstra(g, source, weightFn, edgeFn) { + var results = {}; + var pq = new PriorityQueue(); + var v, vEntry; + var updateNeighbors = function(edge) { + var w = edge.v !== v ? edge.v : edge.w; + var wEntry = results[w]; + var weight = weightFn(edge); + var distance = vEntry.distance + weight; + if (weight < 0) { + throw new Error("dijkstra does not allow negative edge weights. Bad edge: " + edge + " Weight: " + weight); + } + if (distance < wEntry.distance) { + wEntry.distance = distance; + wEntry.predecessor = v; + pq.decrease(w, distance); + } + }; + g.nodes().forEach(function(v2) { + var distance = v2 === source ? 0 : Number.POSITIVE_INFINITY; + results[v2] = { distance }; + pq.add(v2, distance); + }); + while (pq.size() > 0) { + v = pq.removeMin(); + vEntry = results[v]; + if (vEntry.distance === Number.POSITIVE_INFINITY) { + break; + } + edgeFn(v).forEach(updateNeighbors); + } + return results; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/dijkstra-all.js +var require_dijkstra_all = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/dijkstra-all.js"(exports, module2) { + var dijkstra = require_dijkstra(); + module2.exports = dijkstraAll; + function dijkstraAll(g, weightFunc, edgeFunc) { + return g.nodes().reduce(function(acc, v) { + acc[v] = dijkstra(g, v, weightFunc, edgeFunc); + return acc; + }, {}); + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/tarjan.js +var require_tarjan = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/tarjan.js"(exports, module2) { + module2.exports = tarjan; + function tarjan(g) { + var index = 0; + var stack = []; + var visited = {}; + var results = []; + function dfs(v) { + var entry = visited[v] = { + onStack: true, + lowlink: index, + index: index++ + }; + stack.push(v); + g.successors(v).forEach(function(w2) { + if (!visited.hasOwnProperty(w2)) { + dfs(w2); + entry.lowlink = Math.min(entry.lowlink, visited[w2].lowlink); + } else if (visited[w2].onStack) { + entry.lowlink = Math.min(entry.lowlink, visited[w2].index); + } + }); + if (entry.lowlink === entry.index) { + var cmpt = []; + var w; + do { + w = stack.pop(); + visited[w].onStack = false; + cmpt.push(w); + } while (v !== w); + results.push(cmpt); + } + } + g.nodes().forEach(function(v) { + if (!visited.hasOwnProperty(v)) { + dfs(v); + } + }); + return results; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/find-cycles.js +var require_find_cycles = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/find-cycles.js"(exports, module2) { + var tarjan = require_tarjan(); + module2.exports = findCycles; + function findCycles(g) { + return tarjan(g).filter(function(cmpt) { + return cmpt.length > 1 || cmpt.length === 1 && g.hasEdge(cmpt[0], cmpt[0]); + }); + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/floyd-warshall.js +var require_floyd_warshall = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/floyd-warshall.js"(exports, module2) { + module2.exports = floydWarshall; + var DEFAULT_WEIGHT_FUNC = () => 1; + function floydWarshall(g, weightFn, edgeFn) { + return runFloydWarshall(g, weightFn || DEFAULT_WEIGHT_FUNC, edgeFn || function(v) { + return g.outEdges(v); + }); + } + function runFloydWarshall(g, weightFn, edgeFn) { + var results = {}; + var nodes = g.nodes(); + nodes.forEach(function(v) { + results[v] = {}; + results[v][v] = { distance: 0 }; + nodes.forEach(function(w) { + if (v !== w) { + results[v][w] = { distance: Number.POSITIVE_INFINITY }; + } + }); + edgeFn(v).forEach(function(edge) { + var w = edge.v === v ? edge.w : edge.v; + var d = weightFn(edge); + results[v][w] = { distance: d, predecessor: v }; + }); + }); + nodes.forEach(function(k) { + var rowK = results[k]; + nodes.forEach(function(i) { + var rowI = results[i]; + nodes.forEach(function(j) { + var ik = rowI[k]; + var kj = rowK[j]; + var ij = rowI[j]; + var altDistance = ik.distance + kj.distance; + if (altDistance < ij.distance) { + ij.distance = altDistance; + ij.predecessor = kj.predecessor; + } + }); + }); + }); + return results; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/topsort.js +var require_topsort = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/topsort.js"(exports, module2) { + function topsort(g) { + var visited = {}; + var stack = {}; + var results = []; + function visit(node) { + if (stack.hasOwnProperty(node)) { + throw new CycleException(); + } + if (!visited.hasOwnProperty(node)) { + stack[node] = true; + visited[node] = true; + g.predecessors(node).forEach(visit); + delete stack[node]; + results.push(node); + } + } + g.sinks().forEach(visit); + if (Object.keys(visited).length !== g.nodeCount()) { + throw new CycleException(); + } + return results; + } + var CycleException = class extends Error { + constructor() { + super(...arguments); + } + }; + module2.exports = topsort; + topsort.CycleException = CycleException; + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/is-acyclic.js +var require_is_acyclic = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/is-acyclic.js"(exports, module2) { + var topsort = require_topsort(); + module2.exports = isAcyclic; + function isAcyclic(g) { + try { + topsort(g); + } catch (e) { + if (e instanceof topsort.CycleException) { + return false; + } + throw e; + } + return true; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/dfs.js +var require_dfs = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/dfs.js"(exports, module2) { + module2.exports = dfs; + function dfs(g, vs, order2) { + if (!Array.isArray(vs)) { + vs = [vs]; + } + var navigation = g.isDirected() ? (v) => g.successors(v) : (v) => g.neighbors(v); + var orderFunc = order2 === "post" ? postOrderDfs : preOrderDfs; + var acc = []; + var visited = {}; + vs.forEach((v) => { + if (!g.hasNode(v)) { + throw new Error("Graph does not have node: " + v); + } + orderFunc(v, navigation, visited, acc); + }); + return acc; + } + function postOrderDfs(v, navigation, visited, acc) { + var stack = [[v, false]]; + while (stack.length > 0) { + var curr = stack.pop(); + if (curr[1]) { + acc.push(curr[0]); + } else { + if (!visited.hasOwnProperty(curr[0])) { + visited[curr[0]] = true; + stack.push([curr[0], true]); + forEachRight(navigation(curr[0]), (w) => stack.push([w, false])); + } + } + } + } + function preOrderDfs(v, navigation, visited, acc) { + var stack = [v]; + while (stack.length > 0) { + var curr = stack.pop(); + if (!visited.hasOwnProperty(curr)) { + visited[curr] = true; + acc.push(curr); + forEachRight(navigation(curr), (w) => stack.push(w)); + } + } + } + function forEachRight(array, iteratee) { + var length = array.length; + while (length--) { + iteratee(array[length], length, array); + } + return array; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/postorder.js +var require_postorder = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/postorder.js"(exports, module2) { + var dfs = require_dfs(); + module2.exports = postorder; + function postorder(g, vs) { + return dfs(g, vs, "post"); + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/preorder.js +var require_preorder = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/preorder.js"(exports, module2) { + var dfs = require_dfs(); + module2.exports = preorder; + function preorder(g, vs) { + return dfs(g, vs, "pre"); + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/prim.js +var require_prim = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/prim.js"(exports, module2) { + var Graph = require_graph(); + var PriorityQueue = require_priority_queue(); + module2.exports = prim; + function prim(g, weightFunc) { + var result = new Graph(); + var parents = {}; + var pq = new PriorityQueue(); + var v; + function updateNeighbors(edge) { + var w = edge.v === v ? edge.w : edge.v; + var pri = pq.priority(w); + if (pri !== void 0) { + var edgeWeight = weightFunc(edge); + if (edgeWeight < pri) { + parents[w] = v; + pq.decrease(w, edgeWeight); + } + } + } + if (g.nodeCount() === 0) { + return result; + } + g.nodes().forEach(function(v2) { + pq.add(v2, Number.POSITIVE_INFINITY); + result.setNode(v2); + }); + pq.decrease(g.nodes()[0], 0); + var init3 = false; + while (pq.size() > 0) { + v = pq.removeMin(); + if (parents.hasOwnProperty(v)) { + result.setEdge(v, parents[v]); + } else if (init3) { + throw new Error("Input graph is not connected: " + g); + } else { + init3 = true; + } + g.nodeEdges(v).forEach(updateNeighbors); + } + return result; + } + } +}); + +// node_modules/@dagrejs/graphlib/lib/alg/index.js +var require_alg = __commonJS({ + "node_modules/@dagrejs/graphlib/lib/alg/index.js"(exports, module2) { + module2.exports = { + components: require_components(), + dijkstra: require_dijkstra(), + dijkstraAll: require_dijkstra_all(), + findCycles: require_find_cycles(), + floydWarshall: require_floyd_warshall(), + isAcyclic: require_is_acyclic(), + postorder: require_postorder(), + preorder: require_preorder(), + prim: require_prim(), + tarjan: require_tarjan(), + topsort: require_topsort() + }; + } +}); + +// node_modules/@dagrejs/graphlib/index.js +var require_graphlib = __commonJS({ + "node_modules/@dagrejs/graphlib/index.js"(exports, module2) { + var lib = require_lib(); + module2.exports = { + Graph: lib.Graph, + json: require_json(), + alg: require_alg(), + version: lib.version + }; + } +}); + +// node_modules/@dagrejs/dagre/lib/data/list.js +var require_list = __commonJS({ + "node_modules/@dagrejs/dagre/lib/data/list.js"(exports, module2) { + module2.exports = List; + function List() { + var sentinel = {}; + sentinel._next = sentinel._prev = sentinel; + this._sentinel = sentinel; + } + List.prototype.dequeue = function() { + var sentinel = this._sentinel; + var entry = sentinel._prev; + if (entry !== sentinel) { + unlink(entry); + return entry; + } + }; + List.prototype.enqueue = function(entry) { + var sentinel = this._sentinel; + if (entry._prev && entry._next) { + unlink(entry); + } + entry._next = sentinel._next; + sentinel._next._prev = entry; + sentinel._next = entry; + entry._prev = sentinel; + }; + List.prototype.toString = function() { + var strs = []; + var sentinel = this._sentinel; + var curr = sentinel._prev; + while (curr !== sentinel) { + strs.push(JSON.stringify(curr, filterOutLinks)); + curr = curr._prev; + } + return "[" + strs.join(", ") + "]"; + }; + function unlink(entry) { + entry._prev._next = entry._next; + entry._next._prev = entry._prev; + delete entry._next; + delete entry._prev; + } + function filterOutLinks(k, v) { + if (k !== "_next" && k !== "_prev") { + return v; + } + } + } +}); + +// node_modules/@dagrejs/dagre/lib/greedy-fas.js +var require_greedy_fas = __commonJS({ + "node_modules/@dagrejs/dagre/lib/greedy-fas.js"(exports, module2) { + var Graph = require_graphlib().Graph; + var List = require_list(); + module2.exports = greedyFAS; + var DEFAULT_WEIGHT_FN = () => 1; + function greedyFAS(g, weightFn) { + if (g.nodeCount() <= 1) { + return []; + } + var state = buildState(g, weightFn || DEFAULT_WEIGHT_FN); + var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx); + return results.flatMap((e) => g.outEdges(e.v, e.w)); + } + function doGreedyFAS(g, buckets, zeroIdx) { + var results = []; + var sources = buckets[buckets.length - 1]; + var sinks = buckets[0]; + var entry; + while (g.nodeCount()) { + while (entry = sinks.dequeue()) { + removeNode(g, buckets, zeroIdx, entry); + } + while (entry = sources.dequeue()) { + removeNode(g, buckets, zeroIdx, entry); + } + if (g.nodeCount()) { + for (var i = buckets.length - 2; i > 0; --i) { + entry = buckets[i].dequeue(); + if (entry) { + results = results.concat(removeNode(g, buckets, zeroIdx, entry, true)); + break; + } + } + } + } + return results; + } + function removeNode(g, buckets, zeroIdx, entry, collectPredecessors) { + var results = collectPredecessors ? [] : void 0; + g.inEdges(entry.v).forEach(function(edge) { + var weight = g.edge(edge); + var uEntry = g.node(edge.v); + if (collectPredecessors) { + results.push({ v: edge.v, w: edge.w }); + } + uEntry.out -= weight; + assignBucket(buckets, zeroIdx, uEntry); + }); + g.outEdges(entry.v).forEach(function(edge) { + var weight = g.edge(edge); + var w = edge.w; + var wEntry = g.node(w); + wEntry["in"] -= weight; + assignBucket(buckets, zeroIdx, wEntry); + }); + g.removeNode(entry.v); + return results; + } + function buildState(g, weightFn) { + var fasGraph = new Graph(); + var maxIn = 0; + var maxOut = 0; + g.nodes().forEach(function(v) { + fasGraph.setNode(v, { v, "in": 0, out: 0 }); + }); + g.edges().forEach(function(e) { + var prevWeight = fasGraph.edge(e.v, e.w) || 0; + var weight = weightFn(e); + var edgeWeight = prevWeight + weight; + fasGraph.setEdge(e.v, e.w, edgeWeight); + maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight); + maxIn = Math.max(maxIn, fasGraph.node(e.w)["in"] += weight); + }); + var buckets = range(maxOut + maxIn + 3).map(() => new List()); + var zeroIdx = maxIn + 1; + fasGraph.nodes().forEach(function(v) { + assignBucket(buckets, zeroIdx, fasGraph.node(v)); + }); + return { graph: fasGraph, buckets, zeroIdx }; + } + function assignBucket(buckets, zeroIdx, entry) { + if (!entry.out) { + buckets[0].enqueue(entry); + } else if (!entry["in"]) { + buckets[buckets.length - 1].enqueue(entry); + } else { + buckets[entry.out - entry["in"] + zeroIdx].enqueue(entry); + } + } + function range(limit) { + const range2 = []; + for (let i = 0; i < limit; i++) { + range2.push(i); + } + return range2; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/util.js +var require_util = __commonJS({ + "node_modules/@dagrejs/dagre/lib/util.js"(exports, module2) { + "use strict"; + var Graph = require_graphlib().Graph; + module2.exports = { + addBorderNode, + addDummyNode, + asNonCompoundGraph, + buildLayerMatrix, + intersectRect, + mapValues, + maxRank, + normalizeRanks, + notime, + partition, + pick, + predecessorWeights, + range, + removeEmptyRanks, + simplify, + successorWeights, + time, + uniqueId, + zipObject + }; + function addDummyNode(g, type, attrs, name) { + var v; + do { + v = uniqueId(name); + } while (g.hasNode(v)); + attrs.dummy = type; + g.setNode(v, attrs); + return v; + } + function simplify(g) { + var simplified = new Graph().setGraph(g.graph()); + g.nodes().forEach((v) => simplified.setNode(v, g.node(v))); + g.edges().forEach((e) => { + var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 }; + var label = g.edge(e); + simplified.setEdge(e.v, e.w, { + weight: simpleLabel.weight + label.weight, + minlen: Math.max(simpleLabel.minlen, label.minlen) + }); + }); + return simplified; + } + function asNonCompoundGraph(g) { + var simplified = new Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph()); + g.nodes().forEach((v) => { + if (!g.children(v).length) { + simplified.setNode(v, g.node(v)); + } + }); + g.edges().forEach((e) => { + simplified.setEdge(e, g.edge(e)); + }); + return simplified; + } + function successorWeights(g) { + var weightMap = g.nodes().map((v) => { + var sucs = {}; + g.outEdges(v).forEach((e) => { + sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight; + }); + return sucs; + }); + return zipObject(g.nodes(), weightMap); + } + function predecessorWeights(g) { + var weightMap = g.nodes().map((v) => { + var preds = {}; + g.inEdges(v).forEach((e) => { + preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight; + }); + return preds; + }); + return zipObject(g.nodes(), weightMap); + } + function intersectRect(rect, point) { + var x = rect.x; + var y = rect.y; + var dx = point.x - x; + var dy = point.y - y; + var w = rect.width / 2; + var h = rect.height / 2; + if (!dx && !dy) { + throw new Error("Not possible to find intersection inside of the rectangle"); + } + var sx, sy; + if (Math.abs(dy) * w > Math.abs(dx) * h) { + if (dy < 0) { + h = -h; + } + sx = h * dx / dy; + sy = h; + } else { + if (dx < 0) { + w = -w; + } + sx = w; + sy = w * dy / dx; + } + return { x: x + sx, y: y + sy }; + } + function buildLayerMatrix(g) { + var layering = range(maxRank(g) + 1).map(() => []); + g.nodes().forEach((v) => { + var node = g.node(v); + var rank = node.rank; + if (rank !== void 0) { + layering[rank][node.order] = v; + } + }); + return layering; + } + function normalizeRanks(g) { + var min2 = Math.min(...g.nodes().map((v) => { + var rank = g.node(v).rank; + if (rank === void 0) { + return Number.MAX_VALUE; + } + return rank; + })); + g.nodes().forEach((v) => { + var node = g.node(v); + if (node.hasOwnProperty("rank")) { + node.rank -= min2; + } + }); + } + function removeEmptyRanks(g) { + var offset2 = Math.min(...g.nodes().map((v) => g.node(v).rank)); + var layers = []; + g.nodes().forEach((v) => { + var rank = g.node(v).rank - offset2; + if (!layers[rank]) { + layers[rank] = []; + } + layers[rank].push(v); + }); + var delta = 0; + var nodeRankFactor = g.graph().nodeRankFactor; + Array.from(layers).forEach((vs, i) => { + if (vs === void 0 && i % nodeRankFactor !== 0) { + --delta; + } else if (vs !== void 0 && delta) { + vs.forEach((v) => g.node(v).rank += delta); + } + }); + } + function addBorderNode(g, prefix, rank, order2) { + var node = { + width: 0, + height: 0 + }; + if (arguments.length >= 4) { + node.rank = rank; + node.order = order2; + } + return addDummyNode(g, "border", node, prefix); + } + function maxRank(g) { + return Math.max(...g.nodes().map((v) => { + var rank = g.node(v).rank; + if (rank === void 0) { + return Number.MIN_VALUE; + } + return rank; + })); + } + function partition(collection, fn2) { + var result = { lhs: [], rhs: [] }; + collection.forEach((value) => { + if (fn2(value)) { + result.lhs.push(value); + } else { + result.rhs.push(value); + } + }); + return result; + } + function time(name, fn2) { + var start2 = Date.now(); + try { + return fn2(); + } finally { + console.log(name + " time: " + (Date.now() - start2) + "ms"); + } + } + function notime(name, fn2) { + return fn2(); + } + var idCounter = 0; + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + function range(start2, limit, step = 1) { + if (limit == null) { + limit = start2; + start2 = 0; + } + let endCon = (i) => i < limit; + if (step < 0) { + endCon = (i) => limit < i; + } + const range2 = []; + for (let i = start2; endCon(i); i += step) { + range2.push(i); + } + return range2; + } + function pick(source, keys) { + const dest = {}; + for (const key of keys) { + if (source[key] !== void 0) { + dest[key] = source[key]; + } + } + return dest; + } + function mapValues(obj, funcOrProp) { + let func = funcOrProp; + if (typeof funcOrProp === "string") { + func = (val) => val[funcOrProp]; + } + return Object.entries(obj).reduce((acc, [k, v]) => { + acc[k] = func(v, k); + return acc; + }, {}); + } + function zipObject(props, values) { + return props.reduce((acc, key, i) => { + acc[key] = values[i]; + return acc; + }, {}); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/acyclic.js +var require_acyclic = __commonJS({ + "node_modules/@dagrejs/dagre/lib/acyclic.js"(exports, module2) { + "use strict"; + var greedyFAS = require_greedy_fas(); + var uniqueId = require_util().uniqueId; + module2.exports = { + run: run2, + undo + }; + function run2(g) { + var fas = g.graph().acyclicer === "greedy" ? greedyFAS(g, weightFn(g)) : dfsFAS(g); + fas.forEach(function(e) { + var label = g.edge(e); + g.removeEdge(e); + label.forwardName = e.name; + label.reversed = true; + g.setEdge(e.w, e.v, label, uniqueId("rev")); + }); + function weightFn(g2) { + return function(e) { + return g2.edge(e).weight; + }; + } + } + function dfsFAS(g) { + var fas = []; + var stack = {}; + var visited = {}; + function dfs(v) { + if (visited.hasOwnProperty(v)) { + return; + } + visited[v] = true; + stack[v] = true; + g.outEdges(v).forEach(function(e) { + if (stack.hasOwnProperty(e.w)) { + fas.push(e); + } else { + dfs(e.w); + } + }); + delete stack[v]; + } + g.nodes().forEach(dfs); + return fas; + } + function undo(g) { + g.edges().forEach(function(e) { + var label = g.edge(e); + if (label.reversed) { + g.removeEdge(e); + var forwardName = label.forwardName; + delete label.reversed; + delete label.forwardName; + g.setEdge(e.w, e.v, label, forwardName); + } + }); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/normalize.js +var require_normalize = __commonJS({ + "node_modules/@dagrejs/dagre/lib/normalize.js"(exports, module2) { + "use strict"; + var util = require_util(); + module2.exports = { + run: run2, + undo + }; + function run2(g) { + g.graph().dummyChains = []; + g.edges().forEach((edge) => normalizeEdge(g, edge)); + } + function normalizeEdge(g, e) { + var v = e.v; + var vRank = g.node(v).rank; + var w = e.w; + var wRank = g.node(w).rank; + var name = e.name; + var edgeLabel = g.edge(e); + var labelRank = edgeLabel.labelRank; + if (wRank === vRank + 1) + return; + g.removeEdge(e); + var dummy, attrs, i; + for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) { + edgeLabel.points = []; + attrs = { + width: 0, + height: 0, + edgeLabel, + edgeObj: e, + rank: vRank + }; + dummy = util.addDummyNode(g, "edge", attrs, "_d"); + if (vRank === labelRank) { + attrs.width = edgeLabel.width; + attrs.height = edgeLabel.height; + attrs.dummy = "edge-label"; + attrs.labelpos = edgeLabel.labelpos; + } + g.setEdge(v, dummy, { weight: edgeLabel.weight }, name); + if (i === 0) { + g.graph().dummyChains.push(dummy); + } + v = dummy; + } + g.setEdge(v, w, { weight: edgeLabel.weight }, name); + } + function undo(g) { + g.graph().dummyChains.forEach(function(v) { + var node = g.node(v); + var origLabel = node.edgeLabel; + var w; + g.setEdge(node.edgeObj, origLabel); + while (node.dummy) { + w = g.successors(v)[0]; + g.removeNode(v); + origLabel.points.push({ x: node.x, y: node.y }); + if (node.dummy === "edge-label") { + origLabel.x = node.x; + origLabel.y = node.y; + origLabel.width = node.width; + origLabel.height = node.height; + } + v = w; + node = g.node(v); + } + }); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/rank/util.js +var require_util2 = __commonJS({ + "node_modules/@dagrejs/dagre/lib/rank/util.js"(exports, module2) { + "use strict"; + module2.exports = { + longestPath, + slack + }; + function longestPath(g) { + var visited = {}; + function dfs(v) { + var label = g.node(v); + if (visited.hasOwnProperty(v)) { + return label.rank; + } + visited[v] = true; + var rank = Math.min(...g.outEdges(v).map((e) => { + if (e == null) { + return Number.POSITIVE_INFINITY; + } + return dfs(e.w) - g.edge(e).minlen; + })); + if (rank === Number.POSITIVE_INFINITY) { + rank = 0; + } + return label.rank = rank; + } + g.sources().forEach(dfs); + } + function slack(g, e) { + return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/rank/feasible-tree.js +var require_feasible_tree = __commonJS({ + "node_modules/@dagrejs/dagre/lib/rank/feasible-tree.js"(exports, module2) { + "use strict"; + var Graph = require_graphlib().Graph; + var slack = require_util2().slack; + module2.exports = feasibleTree; + function feasibleTree(g) { + var t = new Graph({ directed: false }); + var start2 = g.nodes()[0]; + var size = g.nodeCount(); + t.setNode(start2, {}); + var edge, delta; + while (tightTree(t, g) < size) { + edge = findMinSlackEdge(t, g); + delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge); + shiftRanks(t, g, delta); + } + return t; + } + function tightTree(t, g) { + function dfs(v) { + g.nodeEdges(v).forEach(function(e) { + var edgeV = e.v, w = v === edgeV ? e.w : edgeV; + if (!t.hasNode(w) && !slack(g, e)) { + t.setNode(w, {}); + t.setEdge(v, w, {}); + dfs(w); + } + }); + } + t.nodes().forEach(dfs); + return t.nodeCount(); + } + function findMinSlackEdge(t, g) { + const edges = g.edges(); + return edges.reduce((acc, edge) => { + let edgeSlack = Number.POSITIVE_INFINITY; + if (t.hasNode(edge.v) !== t.hasNode(edge.w)) { + edgeSlack = slack(g, edge); + } + if (edgeSlack < acc[0]) { + return [edgeSlack, edge]; + } + return acc; + }, [Number.POSITIVE_INFINITY, null])[1]; + } + function shiftRanks(t, g, delta) { + t.nodes().forEach((v) => g.node(v).rank += delta); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/rank/network-simplex.js +var require_network_simplex = __commonJS({ + "node_modules/@dagrejs/dagre/lib/rank/network-simplex.js"(exports, module2) { + "use strict"; + var feasibleTree = require_feasible_tree(); + var slack = require_util2().slack; + var initRank = require_util2().longestPath; + var preorder = require_graphlib().alg.preorder; + var postorder = require_graphlib().alg.postorder; + var simplify = require_util().simplify; + module2.exports = networkSimplex; + networkSimplex.initLowLimValues = initLowLimValues; + networkSimplex.initCutValues = initCutValues; + networkSimplex.calcCutValue = calcCutValue; + networkSimplex.leaveEdge = leaveEdge; + networkSimplex.enterEdge = enterEdge; + networkSimplex.exchangeEdges = exchangeEdges; + function networkSimplex(g) { + g = simplify(g); + initRank(g); + var t = feasibleTree(g); + initLowLimValues(t); + initCutValues(t, g); + var e, f; + while (e = leaveEdge(t)) { + f = enterEdge(t, g, e); + exchangeEdges(t, g, e, f); + } + } + function initCutValues(t, g) { + var vs = postorder(t, t.nodes()); + vs = vs.slice(0, vs.length - 1); + vs.forEach((v) => assignCutValue(t, g, v)); + } + function assignCutValue(t, g, child) { + var childLab = t.node(child); + var parent = childLab.parent; + t.edge(child, parent).cutvalue = calcCutValue(t, g, child); + } + function calcCutValue(t, g, child) { + var childLab = t.node(child); + var parent = childLab.parent; + var childIsTail = true; + var graphEdge = g.edge(child, parent); + var cutValue = 0; + if (!graphEdge) { + childIsTail = false; + graphEdge = g.edge(parent, child); + } + cutValue = graphEdge.weight; + g.nodeEdges(child).forEach(function(e) { + var isOutEdge = e.v === child, other = isOutEdge ? e.w : e.v; + if (other !== parent) { + var pointsToHead = isOutEdge === childIsTail, otherWeight = g.edge(e).weight; + cutValue += pointsToHead ? otherWeight : -otherWeight; + if (isTreeEdge(t, child, other)) { + var otherCutValue = t.edge(child, other).cutvalue; + cutValue += pointsToHead ? -otherCutValue : otherCutValue; + } + } + }); + return cutValue; + } + function initLowLimValues(tree, root) { + if (arguments.length < 2) { + root = tree.nodes()[0]; + } + dfsAssignLowLim(tree, {}, 1, root); + } + function dfsAssignLowLim(tree, visited, nextLim, v, parent) { + var low = nextLim; + var label = tree.node(v); + visited[v] = true; + tree.neighbors(v).forEach(function(w) { + if (!visited.hasOwnProperty(w)) { + nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v); + } + }); + label.low = low; + label.lim = nextLim++; + if (parent) { + label.parent = parent; + } else { + delete label.parent; + } + return nextLim; + } + function leaveEdge(tree) { + return tree.edges().find((e) => tree.edge(e).cutvalue < 0); + } + function enterEdge(t, g, edge) { + var v = edge.v; + var w = edge.w; + if (!g.hasEdge(v, w)) { + v = edge.w; + w = edge.v; + } + var vLabel = t.node(v); + var wLabel = t.node(w); + var tailLabel = vLabel; + var flip2 = false; + if (vLabel.lim > wLabel.lim) { + tailLabel = wLabel; + flip2 = true; + } + var candidates = g.edges().filter(function(edge2) { + return flip2 === isDescendant(t, t.node(edge2.v), tailLabel) && flip2 !== isDescendant(t, t.node(edge2.w), tailLabel); + }); + return candidates.reduce((acc, edge2) => { + if (slack(g, edge2) < slack(g, acc)) { + return edge2; + } + return acc; + }); + } + function exchangeEdges(t, g, e, f) { + var v = e.v; + var w = e.w; + t.removeEdge(v, w); + t.setEdge(f.v, f.w, {}); + initLowLimValues(t); + initCutValues(t, g); + updateRanks(t, g); + } + function updateRanks(t, g) { + var root = t.nodes().find((v) => !g.node(v).parent); + var vs = preorder(t, root); + vs = vs.slice(1); + vs.forEach(function(v) { + var parent = t.node(v).parent, edge = g.edge(v, parent), flipped = false; + if (!edge) { + edge = g.edge(parent, v); + flipped = true; + } + g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen); + }); + } + function isTreeEdge(tree, u, v) { + return tree.hasEdge(u, v); + } + function isDescendant(tree, vLabel, rootLabel) { + return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/rank/index.js +var require_rank = __commonJS({ + "node_modules/@dagrejs/dagre/lib/rank/index.js"(exports, module2) { + "use strict"; + var rankUtil = require_util2(); + var longestPath = rankUtil.longestPath; + var feasibleTree = require_feasible_tree(); + var networkSimplex = require_network_simplex(); + module2.exports = rank; + function rank(g) { + switch (g.graph().ranker) { + case "network-simplex": + networkSimplexRanker(g); + break; + case "tight-tree": + tightTreeRanker(g); + break; + case "longest-path": + longestPathRanker(g); + break; + default: + networkSimplexRanker(g); + } + } + var longestPathRanker = longestPath; + function tightTreeRanker(g) { + longestPath(g); + feasibleTree(g); + } + function networkSimplexRanker(g) { + networkSimplex(g); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/parent-dummy-chains.js +var require_parent_dummy_chains = __commonJS({ + "node_modules/@dagrejs/dagre/lib/parent-dummy-chains.js"(exports, module2) { + module2.exports = parentDummyChains; + function parentDummyChains(g) { + var postorderNums = postorder(g); + g.graph().dummyChains.forEach(function(v) { + var node = g.node(v); + var edgeObj = node.edgeObj; + var pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w); + var path = pathData.path; + var lca = pathData.lca; + var pathIdx = 0; + var pathV = path[pathIdx]; + var ascending = true; + while (v !== edgeObj.w) { + node = g.node(v); + if (ascending) { + while ((pathV = path[pathIdx]) !== lca && g.node(pathV).maxRank < node.rank) { + pathIdx++; + } + if (pathV === lca) { + ascending = false; + } + } + if (!ascending) { + while (pathIdx < path.length - 1 && g.node(pathV = path[pathIdx + 1]).minRank <= node.rank) { + pathIdx++; + } + pathV = path[pathIdx]; + } + g.setParent(v, pathV); + v = g.successors(v)[0]; + } + }); + } + function findPath(g, postorderNums, v, w) { + var vPath = []; + var wPath = []; + var low = Math.min(postorderNums[v].low, postorderNums[w].low); + var lim = Math.max(postorderNums[v].lim, postorderNums[w].lim); + var parent; + var lca; + parent = v; + do { + parent = g.parent(parent); + vPath.push(parent); + } while (parent && (postorderNums[parent].low > low || lim > postorderNums[parent].lim)); + lca = parent; + parent = w; + while ((parent = g.parent(parent)) !== lca) { + wPath.push(parent); + } + return { path: vPath.concat(wPath.reverse()), lca }; + } + function postorder(g) { + var result = {}; + var lim = 0; + function dfs(v) { + var low = lim; + g.children(v).forEach(dfs); + result[v] = { low, lim: lim++ }; + } + g.children().forEach(dfs); + return result; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/nesting-graph.js +var require_nesting_graph = __commonJS({ + "node_modules/@dagrejs/dagre/lib/nesting-graph.js"(exports, module2) { + var util = require_util(); + module2.exports = { + run: run2, + cleanup + }; + function run2(g) { + var root = util.addDummyNode(g, "root", {}, "_root"); + var depths = treeDepths(g); + var height = Math.max(...Object.values(depths)) - 1; + var nodeSep = 2 * height + 1; + g.graph().nestingRoot = root; + g.edges().forEach((e) => g.edge(e).minlen *= nodeSep); + var weight = sumWeights(g) + 1; + g.children().forEach(function(child) { + dfs(g, root, nodeSep, weight, height, depths, child); + }); + g.graph().nodeRankFactor = nodeSep; + } + function dfs(g, root, nodeSep, weight, height, depths, v) { + var children2 = g.children(v); + if (!children2.length) { + if (v !== root) { + g.setEdge(root, v, { weight: 0, minlen: nodeSep }); + } + return; + } + var top2 = util.addBorderNode(g, "_bt"); + var bottom2 = util.addBorderNode(g, "_bb"); + var label = g.node(v); + g.setParent(top2, v); + label.borderTop = top2; + g.setParent(bottom2, v); + label.borderBottom = bottom2; + children2.forEach(function(child) { + dfs(g, root, nodeSep, weight, height, depths, child); + var childNode = g.node(child); + var childTop = childNode.borderTop ? childNode.borderTop : child; + var childBottom = childNode.borderBottom ? childNode.borderBottom : child; + var thisWeight = childNode.borderTop ? weight : 2 * weight; + var minlen = childTop !== childBottom ? 1 : height - depths[v] + 1; + g.setEdge(top2, childTop, { + weight: thisWeight, + minlen, + nestingEdge: true + }); + g.setEdge(childBottom, bottom2, { + weight: thisWeight, + minlen, + nestingEdge: true + }); + }); + if (!g.parent(v)) { + g.setEdge(root, top2, { weight: 0, minlen: height + depths[v] }); + } + } + function treeDepths(g) { + var depths = {}; + function dfs2(v, depth) { + var children2 = g.children(v); + if (children2 && children2.length) { + children2.forEach((child) => dfs2(child, depth + 1)); + } + depths[v] = depth; + } + g.children().forEach((v) => dfs2(v, 1)); + return depths; + } + function sumWeights(g) { + return g.edges().reduce((acc, e) => acc + g.edge(e).weight, 0); + } + function cleanup(g) { + var graphLabel = g.graph(); + g.removeNode(graphLabel.nestingRoot); + delete graphLabel.nestingRoot; + g.edges().forEach((e) => { + var edge = g.edge(e); + if (edge.nestingEdge) { + g.removeEdge(e); + } + }); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/add-border-segments.js +var require_add_border_segments = __commonJS({ + "node_modules/@dagrejs/dagre/lib/add-border-segments.js"(exports, module2) { + var util = require_util(); + module2.exports = addBorderSegments; + function addBorderSegments(g) { + function dfs(v) { + var children2 = g.children(v); + var node = g.node(v); + if (children2.length) { + children2.forEach(dfs); + } + if (node.hasOwnProperty("minRank")) { + node.borderLeft = []; + node.borderRight = []; + for (var rank = node.minRank, maxRank = node.maxRank + 1; rank < maxRank; ++rank) { + addBorderNode(g, "borderLeft", "_bl", v, node, rank); + addBorderNode(g, "borderRight", "_br", v, node, rank); + } + } + } + g.children().forEach(dfs); + } + function addBorderNode(g, prop, prefix, sg, sgNode, rank) { + var label = { width: 0, height: 0, rank, borderType: prop }; + var prev = sgNode[prop][rank - 1]; + var curr = util.addDummyNode(g, "border", label, prefix); + sgNode[prop][rank] = curr; + g.setParent(curr, sg); + if (prev) { + g.setEdge(prev, curr, { weight: 1 }); + } + } + } +}); + +// node_modules/@dagrejs/dagre/lib/coordinate-system.js +var require_coordinate_system = __commonJS({ + "node_modules/@dagrejs/dagre/lib/coordinate-system.js"(exports, module2) { + "use strict"; + module2.exports = { + adjust, + undo + }; + function adjust(g) { + var rankDir = g.graph().rankdir.toLowerCase(); + if (rankDir === "lr" || rankDir === "rl") { + swapWidthHeight(g); + } + } + function undo(g) { + var rankDir = g.graph().rankdir.toLowerCase(); + if (rankDir === "bt" || rankDir === "rl") { + reverseY(g); + } + if (rankDir === "lr" || rankDir === "rl") { + swapXY(g); + swapWidthHeight(g); + } + } + function swapWidthHeight(g) { + g.nodes().forEach((v) => swapWidthHeightOne(g.node(v))); + g.edges().forEach((e) => swapWidthHeightOne(g.edge(e))); + } + function swapWidthHeightOne(attrs) { + var w = attrs.width; + attrs.width = attrs.height; + attrs.height = w; + } + function reverseY(g) { + g.nodes().forEach((v) => reverseYOne(g.node(v))); + g.edges().forEach(function(e) { + var edge = g.edge(e); + edge.points.forEach(reverseYOne); + if (edge.hasOwnProperty("y")) { + reverseYOne(edge); + } + }); + } + function reverseYOne(attrs) { + attrs.y = -attrs.y; + } + function swapXY(g) { + g.nodes().forEach((v) => swapXYOne(g.node(v))); + g.edges().forEach(function(e) { + var edge = g.edge(e); + edge.points.forEach(swapXYOne); + if (edge.hasOwnProperty("x")) { + swapXYOne(edge); + } + }); + } + function swapXYOne(attrs) { + var x = attrs.x; + attrs.x = attrs.y; + attrs.y = x; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/init-order.js +var require_init_order = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/init-order.js"(exports, module2) { + "use strict"; + var util = require_util(); + module2.exports = initOrder; + function initOrder(g) { + var visited = {}; + var simpleNodes = g.nodes().filter((v) => !g.children(v).length); + var maxRank = Math.max(...simpleNodes.map((v) => g.node(v).rank)); + var layers = util.range(maxRank + 1).map(() => []); + function dfs(v) { + if (visited[v]) + return; + visited[v] = true; + var node = g.node(v); + layers[node.rank].push(v); + g.successors(v).forEach(dfs); + } + var orderedVs = simpleNodes.sort((a, b) => g.node(a).rank - g.node(b).rank); + orderedVs.forEach(dfs); + return layers; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/cross-count.js +var require_cross_count = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/cross-count.js"(exports, module2) { + "use strict"; + var zipObject = require_util().zipObject; + module2.exports = crossCount; + function crossCount(g, layering) { + var cc = 0; + for (var i = 1; i < layering.length; ++i) { + cc += twoLayerCrossCount(g, layering[i - 1], layering[i]); + } + return cc; + } + function twoLayerCrossCount(g, northLayer, southLayer) { + var southPos = zipObject(southLayer, southLayer.map((v, i) => i)); + var southEntries = northLayer.flatMap((v) => { + return g.outEdges(v).map((e) => { + return { pos: southPos[e.w], weight: g.edge(e).weight }; + }).sort((a, b) => a.pos - b.pos); + }); + var firstIndex = 1; + while (firstIndex < southLayer.length) + firstIndex <<= 1; + var treeSize = 2 * firstIndex - 1; + firstIndex -= 1; + var tree = new Array(treeSize).fill(0); + var cc = 0; + southEntries.forEach((entry) => { + var index = entry.pos + firstIndex; + tree[index] += entry.weight; + var weightSum = 0; + while (index > 0) { + if (index % 2) { + weightSum += tree[index + 1]; + } + index = index - 1 >> 1; + tree[index] += entry.weight; + } + cc += entry.weight * weightSum; + }); + return cc; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/barycenter.js +var require_barycenter = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/barycenter.js"(exports, module2) { + module2.exports = barycenter; + function barycenter(g, movable = []) { + return movable.map((v) => { + var inV = g.inEdges(v); + if (!inV.length) { + return { v }; + } else { + var result = inV.reduce((acc, e) => { + var edge = g.edge(e), nodeU = g.node(e.v); + return { + sum: acc.sum + edge.weight * nodeU.order, + weight: acc.weight + edge.weight + }; + }, { sum: 0, weight: 0 }); + return { + v, + barycenter: result.sum / result.weight, + weight: result.weight + }; + } + }); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/resolve-conflicts.js +var require_resolve_conflicts = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/resolve-conflicts.js"(exports, module2) { + "use strict"; + var util = require_util(); + module2.exports = resolveConflicts; + function resolveConflicts(entries, cg) { + var mappedEntries = {}; + entries.forEach((entry, i) => { + var tmp = mappedEntries[entry.v] = { + indegree: 0, + "in": [], + out: [], + vs: [entry.v], + i + }; + if (entry.barycenter !== void 0) { + tmp.barycenter = entry.barycenter; + tmp.weight = entry.weight; + } + }); + cg.edges().forEach((e) => { + var entryV = mappedEntries[e.v]; + var entryW = mappedEntries[e.w]; + if (entryV !== void 0 && entryW !== void 0) { + entryW.indegree++; + entryV.out.push(mappedEntries[e.w]); + } + }); + var sourceSet = Object.values(mappedEntries).filter((entry) => !entry.indegree); + return doResolveConflicts(sourceSet); + } + function doResolveConflicts(sourceSet) { + var entries = []; + function handleIn(vEntry) { + return function(uEntry) { + if (uEntry.merged) { + return; + } + if (uEntry.barycenter === void 0 || vEntry.barycenter === void 0 || uEntry.barycenter >= vEntry.barycenter) { + mergeEntries(vEntry, uEntry); + } + }; + } + function handleOut(vEntry) { + return function(wEntry) { + wEntry["in"].push(vEntry); + if (--wEntry.indegree === 0) { + sourceSet.push(wEntry); + } + }; + } + while (sourceSet.length) { + var entry = sourceSet.pop(); + entries.push(entry); + entry["in"].reverse().forEach(handleIn(entry)); + entry.out.forEach(handleOut(entry)); + } + return entries.filter((entry2) => !entry2.merged).map((entry2) => { + return util.pick(entry2, ["vs", "i", "barycenter", "weight"]); + }); + } + function mergeEntries(target, source) { + var sum = 0; + var weight = 0; + if (target.weight) { + sum += target.barycenter * target.weight; + weight += target.weight; + } + if (source.weight) { + sum += source.barycenter * source.weight; + weight += source.weight; + } + target.vs = source.vs.concat(target.vs); + target.barycenter = sum / weight; + target.weight = weight; + target.i = Math.min(source.i, target.i); + source.merged = true; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/sort.js +var require_sort = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/sort.js"(exports, module2) { + var util = require_util(); + module2.exports = sort; + function sort(entries, biasRight) { + var parts = util.partition(entries, function(entry) { + return entry.hasOwnProperty("barycenter"); + }); + var sortable = parts.lhs, unsortable = parts.rhs.sort((a, b) => b.i - a.i), vs = [], sum = 0, weight = 0, vsIndex = 0; + sortable.sort(compareWithBias(!!biasRight)); + vsIndex = consumeUnsortable(vs, unsortable, vsIndex); + sortable.forEach(function(entry) { + vsIndex += entry.vs.length; + vs.push(entry.vs); + sum += entry.barycenter * entry.weight; + weight += entry.weight; + vsIndex = consumeUnsortable(vs, unsortable, vsIndex); + }); + var result = { vs: vs.flat(true) }; + if (weight) { + result.barycenter = sum / weight; + result.weight = weight; + } + return result; + } + function consumeUnsortable(vs, unsortable, index) { + var last; + while (unsortable.length && (last = unsortable[unsortable.length - 1]).i <= index) { + unsortable.pop(); + vs.push(last.vs); + index++; + } + return index; + } + function compareWithBias(bias) { + return function(entryV, entryW) { + if (entryV.barycenter < entryW.barycenter) { + return -1; + } else if (entryV.barycenter > entryW.barycenter) { + return 1; + } + return !bias ? entryV.i - entryW.i : entryW.i - entryV.i; + }; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/sort-subgraph.js +var require_sort_subgraph = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/sort-subgraph.js"(exports, module2) { + var barycenter = require_barycenter(); + var resolveConflicts = require_resolve_conflicts(); + var sort = require_sort(); + module2.exports = sortSubgraph; + function sortSubgraph(g, v, cg, biasRight) { + var movable = g.children(v); + var node = g.node(v); + var bl = node ? node.borderLeft : void 0; + var br = node ? node.borderRight : void 0; + var subgraphs = {}; + if (bl) { + movable = movable.filter((w) => w !== bl && w !== br); + } + var barycenters = barycenter(g, movable); + barycenters.forEach(function(entry) { + if (g.children(entry.v).length) { + var subgraphResult = sortSubgraph(g, entry.v, cg, biasRight); + subgraphs[entry.v] = subgraphResult; + if (subgraphResult.hasOwnProperty("barycenter")) { + mergeBarycenters(entry, subgraphResult); + } + } + }); + var entries = resolveConflicts(barycenters, cg); + expandSubgraphs(entries, subgraphs); + var result = sort(entries, biasRight); + if (bl) { + result.vs = [bl, result.vs, br].flat(true); + if (g.predecessors(bl).length) { + var blPred = g.node(g.predecessors(bl)[0]), brPred = g.node(g.predecessors(br)[0]); + if (!result.hasOwnProperty("barycenter")) { + result.barycenter = 0; + result.weight = 0; + } + result.barycenter = (result.barycenter * result.weight + blPred.order + brPred.order) / (result.weight + 2); + result.weight += 2; + } + } + return result; + } + function expandSubgraphs(entries, subgraphs) { + entries.forEach(function(entry) { + entry.vs = entry.vs.flatMap(function(v) { + if (subgraphs[v]) { + return subgraphs[v].vs; + } + return v; + }); + }); + } + function mergeBarycenters(target, other) { + if (target.barycenter !== void 0) { + target.barycenter = (target.barycenter * target.weight + other.barycenter * other.weight) / (target.weight + other.weight); + target.weight += other.weight; + } else { + target.barycenter = other.barycenter; + target.weight = other.weight; + } + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/build-layer-graph.js +var require_build_layer_graph = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/build-layer-graph.js"(exports, module2) { + var Graph = require_graphlib().Graph; + var util = require_util(); + module2.exports = buildLayerGraph; + function buildLayerGraph(g, rank, relationship) { + var root = createRootNode2(g), result = new Graph({ compound: true }).setGraph({ root }).setDefaultNodeLabel(function(v) { + return g.node(v); + }); + g.nodes().forEach(function(v) { + var node = g.node(v), parent = g.parent(v); + if (node.rank === rank || node.minRank <= rank && rank <= node.maxRank) { + result.setNode(v); + result.setParent(v, parent || root); + g[relationship](v).forEach(function(e) { + var u = e.v === v ? e.w : e.v, edge = result.edge(u, v), weight = edge !== void 0 ? edge.weight : 0; + result.setEdge(u, v, { weight: g.edge(e).weight + weight }); + }); + if (node.hasOwnProperty("minRank")) { + result.setNode(v, { + borderLeft: node.borderLeft[rank], + borderRight: node.borderRight[rank] + }); + } + } + }); + return result; + } + function createRootNode2(g) { + var v; + while (g.hasNode(v = util.uniqueId("_root"))) + ; + return v; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/add-subgraph-constraints.js +var require_add_subgraph_constraints = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/add-subgraph-constraints.js"(exports, module2) { + module2.exports = addSubgraphConstraints; + function addSubgraphConstraints(g, cg, vs) { + var prev = {}, rootPrev; + vs.forEach(function(v) { + var child = g.parent(v), parent, prevChild; + while (child) { + parent = g.parent(child); + if (parent) { + prevChild = prev[parent]; + prev[parent] = child; + } else { + prevChild = rootPrev; + rootPrev = child; + } + if (prevChild && prevChild !== child) { + cg.setEdge(prevChild, child); + return; + } + child = parent; + } + }); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/order/index.js +var require_order = __commonJS({ + "node_modules/@dagrejs/dagre/lib/order/index.js"(exports, module2) { + "use strict"; + var initOrder = require_init_order(); + var crossCount = require_cross_count(); + var sortSubgraph = require_sort_subgraph(); + var buildLayerGraph = require_build_layer_graph(); + var addSubgraphConstraints = require_add_subgraph_constraints(); + var Graph = require_graphlib().Graph; + var util = require_util(); + module2.exports = order2; + function order2(g) { + var maxRank = util.maxRank(g), downLayerGraphs = buildLayerGraphs(g, util.range(1, maxRank + 1), "inEdges"), upLayerGraphs = buildLayerGraphs(g, util.range(maxRank - 1, -1, -1), "outEdges"); + var layering = initOrder(g); + assignOrder(g, layering); + var bestCC = Number.POSITIVE_INFINITY, best; + for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) { + sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2); + layering = util.buildLayerMatrix(g); + var cc = crossCount(g, layering); + if (cc < bestCC) { + lastBest = 0; + best = Object.assign({}, layering); + bestCC = cc; + } + } + assignOrder(g, best); + } + function buildLayerGraphs(g, ranks, relationship) { + return ranks.map(function(rank) { + return buildLayerGraph(g, rank, relationship); + }); + } + function sweepLayerGraphs(layerGraphs, biasRight) { + var cg = new Graph(); + layerGraphs.forEach(function(lg) { + var root = lg.graph().root; + var sorted = sortSubgraph(lg, root, cg, biasRight); + sorted.vs.forEach((v, i) => lg.node(v).order = i); + addSubgraphConstraints(lg, cg, sorted.vs); + }); + } + function assignOrder(g, layering) { + Object.values(layering).forEach((layer) => layer.forEach((v, i) => g.node(v).order = i)); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/position/bk.js +var require_bk = __commonJS({ + "node_modules/@dagrejs/dagre/lib/position/bk.js"(exports, module2) { + "use strict"; + var Graph = require_graphlib().Graph; + var util = require_util(); + module2.exports = { + positionX, + findType1Conflicts, + findType2Conflicts, + addConflict, + hasConflict, + verticalAlignment, + horizontalCompaction, + alignCoordinates, + findSmallestWidthAlignment, + balance + }; + function findType1Conflicts(g, layering) { + var conflicts = {}; + function visitLayer(prevLayer, layer) { + var k0 = 0, scanPos = 0, prevLayerLength = prevLayer.length, lastNode = layer[layer.length - 1]; + layer.forEach(function(v, i) { + var w = findOtherInnerSegmentNode(g, v), k1 = w ? g.node(w).order : prevLayerLength; + if (w || v === lastNode) { + layer.slice(scanPos, i + 1).forEach(function(scanNode) { + g.predecessors(scanNode).forEach(function(u) { + var uLabel = g.node(u), uPos = uLabel.order; + if ((uPos < k0 || k1 < uPos) && !(uLabel.dummy && g.node(scanNode).dummy)) { + addConflict(conflicts, u, scanNode); + } + }); + }); + scanPos = i + 1; + k0 = k1; + } + }); + return layer; + } + layering.reduce(visitLayer); + return conflicts; + } + function findType2Conflicts(g, layering) { + var conflicts = {}; + function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) { + var v; + util.range(southPos, southEnd).forEach(function(i) { + v = south[i]; + if (g.node(v).dummy) { + g.predecessors(v).forEach(function(u) { + var uNode = g.node(u); + if (uNode.dummy && (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) { + addConflict(conflicts, u, v); + } + }); + } + }); + } + function visitLayer(north, south) { + var prevNorthPos = -1, nextNorthPos, southPos = 0; + south.forEach(function(v, southLookahead) { + if (g.node(v).dummy === "border") { + var predecessors = g.predecessors(v); + if (predecessors.length) { + nextNorthPos = g.node(predecessors[0]).order; + scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos); + southPos = southLookahead; + prevNorthPos = nextNorthPos; + } + } + scan(south, southPos, south.length, nextNorthPos, north.length); + }); + return south; + } + layering.reduce(visitLayer); + return conflicts; + } + function findOtherInnerSegmentNode(g, v) { + if (g.node(v).dummy) { + return g.predecessors(v).find((u) => g.node(u).dummy); + } + } + function addConflict(conflicts, v, w) { + if (v > w) { + var tmp = v; + v = w; + w = tmp; + } + var conflictsV = conflicts[v]; + if (!conflictsV) { + conflicts[v] = conflictsV = {}; + } + conflictsV[w] = true; + } + function hasConflict(conflicts, v, w) { + if (v > w) { + var tmp = v; + v = w; + w = tmp; + } + return !!conflicts[v] && conflicts[v].hasOwnProperty(w); + } + function verticalAlignment(g, layering, conflicts, neighborFn) { + var root = {}, align = {}, pos = {}; + layering.forEach(function(layer) { + layer.forEach(function(v, order2) { + root[v] = v; + align[v] = v; + pos[v] = order2; + }); + }); + layering.forEach(function(layer) { + var prevIdx = -1; + layer.forEach(function(v) { + var ws = neighborFn(v); + if (ws.length) { + ws = ws.sort((a, b) => pos[a] - pos[b]); + var mp = (ws.length - 1) / 2; + for (var i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) { + var w = ws[i]; + if (align[v] === v && prevIdx < pos[w] && !hasConflict(conflicts, v, w)) { + align[w] = v; + align[v] = root[v] = root[w]; + prevIdx = pos[w]; + } + } + } + }); + }); + return { root, align }; + } + function horizontalCompaction(g, layering, root, align, reverseSep) { + var xs = {}, blockG = buildBlockGraph(g, layering, root, reverseSep), borderType = reverseSep ? "borderLeft" : "borderRight"; + function iterate(setXsFunc, nextNodesFunc) { + var stack = blockG.nodes(); + var elem = stack.pop(); + var visited = {}; + while (elem) { + if (visited[elem]) { + setXsFunc(elem); + } else { + visited[elem] = true; + stack.push(elem); + stack = stack.concat(nextNodesFunc(elem)); + } + elem = stack.pop(); + } + } + function pass1(elem) { + xs[elem] = blockG.inEdges(elem).reduce(function(acc, e) { + return Math.max(acc, xs[e.v] + blockG.edge(e)); + }, 0); + } + function pass2(elem) { + var min2 = blockG.outEdges(elem).reduce(function(acc, e) { + return Math.min(acc, xs[e.w] - blockG.edge(e)); + }, Number.POSITIVE_INFINITY); + var node = g.node(elem); + if (min2 !== Number.POSITIVE_INFINITY && node.borderType !== borderType) { + xs[elem] = Math.max(xs[elem], min2); + } + } + iterate(pass1, blockG.predecessors.bind(blockG)); + iterate(pass2, blockG.successors.bind(blockG)); + Object.keys(align).forEach((v) => xs[v] = xs[root[v]]); + return xs; + } + function buildBlockGraph(g, layering, root, reverseSep) { + var blockGraph = new Graph(), graphLabel = g.graph(), sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep); + layering.forEach(function(layer) { + var u; + layer.forEach(function(v) { + var vRoot = root[v]; + blockGraph.setNode(vRoot); + if (u) { + var uRoot = root[u], prevMax = blockGraph.edge(uRoot, vRoot); + blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0)); + } + u = v; + }); + }); + return blockGraph; + } + function findSmallestWidthAlignment(g, xss) { + return Object.values(xss).reduce((currentMinAndXs, xs) => { + var max2 = Number.NEGATIVE_INFINITY; + var min2 = Number.POSITIVE_INFINITY; + Object.entries(xs).forEach(([v, x]) => { + var halfWidth = width(g, v) / 2; + max2 = Math.max(x + halfWidth, max2); + min2 = Math.min(x - halfWidth, min2); + }); + const newMin = max2 - min2; + if (newMin < currentMinAndXs[0]) { + currentMinAndXs = [newMin, xs]; + } + return currentMinAndXs; + }, [Number.POSITIVE_INFINITY, null])[1]; + } + function alignCoordinates(xss, alignTo) { + var alignToVals = Object.values(alignTo), alignToMin = Math.min(...alignToVals), alignToMax = Math.max(...alignToVals); + ["u", "d"].forEach(function(vert) { + ["l", "r"].forEach(function(horiz) { + var alignment = vert + horiz, xs = xss[alignment]; + if (xs === alignTo) + return; + var xsVals = Object.values(xs); + let delta = alignToMin - Math.min(...xsVals); + if (horiz !== "l") { + delta = alignToMax - Math.max(...xsVals); + } + if (delta) { + xss[alignment] = util.mapValues(xs, (x) => x + delta); + } + }); + }); + } + function balance(xss, align) { + return util.mapValues(xss.ul, function(num, v) { + if (align) { + return xss[align.toLowerCase()][v]; + } else { + var xs = Object.values(xss).map((xs2) => xs2[v]).sort((a, b) => a - b); + return (xs[1] + xs[2]) / 2; + } + }); + } + function positionX(g) { + var layering = util.buildLayerMatrix(g); + var conflicts = Object.assign(findType1Conflicts(g, layering), findType2Conflicts(g, layering)); + var xss = {}; + var adjustedLayering; + ["u", "d"].forEach(function(vert) { + adjustedLayering = vert === "u" ? layering : Object.values(layering).reverse(); + ["l", "r"].forEach(function(horiz) { + if (horiz === "r") { + adjustedLayering = adjustedLayering.map((inner) => { + return Object.values(inner).reverse(); + }); + } + var neighborFn = (vert === "u" ? g.predecessors : g.successors).bind(g); + var align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn); + var xs = horizontalCompaction(g, adjustedLayering, align.root, align.align, horiz === "r"); + if (horiz === "r") { + xs = util.mapValues(xs, (x) => -x); + } + xss[vert + horiz] = xs; + }); + }); + var smallestWidth = findSmallestWidthAlignment(g, xss); + alignCoordinates(xss, smallestWidth); + return balance(xss, g.graph().align); + } + function sep(nodeSep, edgeSep, reverseSep) { + return function(g, v, w) { + var vLabel = g.node(v); + var wLabel = g.node(w); + var sum = 0; + var delta; + sum += vLabel.width / 2; + if (vLabel.hasOwnProperty("labelpos")) { + switch (vLabel.labelpos.toLowerCase()) { + case "l": + delta = -vLabel.width / 2; + break; + case "r": + delta = vLabel.width / 2; + break; + } + } + if (delta) { + sum += reverseSep ? delta : -delta; + } + delta = 0; + sum += (vLabel.dummy ? edgeSep : nodeSep) / 2; + sum += (wLabel.dummy ? edgeSep : nodeSep) / 2; + sum += wLabel.width / 2; + if (wLabel.hasOwnProperty("labelpos")) { + switch (wLabel.labelpos.toLowerCase()) { + case "l": + delta = wLabel.width / 2; + break; + case "r": + delta = -wLabel.width / 2; + break; + } + } + if (delta) { + sum += reverseSep ? delta : -delta; + } + delta = 0; + return sum; + }; + } + function width(g, v) { + return g.node(v).width; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/position/index.js +var require_position = __commonJS({ + "node_modules/@dagrejs/dagre/lib/position/index.js"(exports, module2) { + "use strict"; + var util = require_util(); + var positionX = require_bk().positionX; + module2.exports = position; + function position(g) { + g = util.asNonCompoundGraph(g); + positionY(g); + Object.entries(positionX(g)).forEach(([v, x]) => g.node(v).x = x); + } + function positionY(g) { + var layering = util.buildLayerMatrix(g); + var rankSep = g.graph().ranksep; + var prevY = 0; + layering.forEach(function(layer) { + const maxHeight = layer.reduce((acc, v) => { + const height = g.node(v).height; + if (acc > height) { + return acc; + } else { + return height; + } + }, 0); + layer.forEach((v) => g.node(v).y = prevY + maxHeight / 2); + prevY += maxHeight + rankSep; + }); + } + } +}); + +// node_modules/@dagrejs/dagre/lib/layout.js +var require_layout = __commonJS({ + "node_modules/@dagrejs/dagre/lib/layout.js"(exports, module2) { + "use strict"; + var acyclic = require_acyclic(); + var normalize = require_normalize(); + var rank = require_rank(); + var normalizeRanks = require_util().normalizeRanks; + var parentDummyChains = require_parent_dummy_chains(); + var removeEmptyRanks = require_util().removeEmptyRanks; + var nestingGraph = require_nesting_graph(); + var addBorderSegments = require_add_border_segments(); + var coordinateSystem = require_coordinate_system(); + var order2 = require_order(); + var position = require_position(); + var util = require_util(); + var Graph = require_graphlib().Graph; + module2.exports = layout; + function layout(g, opts) { + var time = opts && opts.debugTiming ? util.time : util.notime; + time("layout", function() { + var layoutGraph = time(" buildLayoutGraph", function() { + return buildLayoutGraph(g); + }); + time(" runLayout", function() { + runLayout(layoutGraph, time); + }); + time(" updateInputGraph", function() { + updateInputGraph(g, layoutGraph); + }); + }); + } + function runLayout(g, time) { + time(" makeSpaceForEdgeLabels", function() { + makeSpaceForEdgeLabels(g); + }); + time(" removeSelfEdges", function() { + removeSelfEdges(g); + }); + time(" acyclic", function() { + acyclic.run(g); + }); + time(" nestingGraph.run", function() { + nestingGraph.run(g); + }); + time(" rank", function() { + rank(util.asNonCompoundGraph(g)); + }); + time(" injectEdgeLabelProxies", function() { + injectEdgeLabelProxies(g); + }); + time(" removeEmptyRanks", function() { + removeEmptyRanks(g); + }); + time(" nestingGraph.cleanup", function() { + nestingGraph.cleanup(g); + }); + time(" normalizeRanks", function() { + normalizeRanks(g); + }); + time(" assignRankMinMax", function() { + assignRankMinMax(g); + }); + time(" removeEdgeLabelProxies", function() { + removeEdgeLabelProxies(g); + }); + time(" normalize.run", function() { + normalize.run(g); + }); + time(" parentDummyChains", function() { + parentDummyChains(g); + }); + time(" addBorderSegments", function() { + addBorderSegments(g); + }); + time(" order", function() { + order2(g); + }); + time(" insertSelfEdges", function() { + insertSelfEdges(g); + }); + time(" adjustCoordinateSystem", function() { + coordinateSystem.adjust(g); + }); + time(" position", function() { + position(g); + }); + time(" positionSelfEdges", function() { + positionSelfEdges(g); + }); + time(" removeBorderNodes", function() { + removeBorderNodes(g); + }); + time(" normalize.undo", function() { + normalize.undo(g); + }); + time(" fixupEdgeLabelCoords", function() { + fixupEdgeLabelCoords(g); + }); + time(" undoCoordinateSystem", function() { + coordinateSystem.undo(g); + }); + time(" translateGraph", function() { + translateGraph(g); + }); + time(" assignNodeIntersects", function() { + assignNodeIntersects(g); + }); + time(" reversePoints", function() { + reversePointsForReversedEdges(g); + }); + time(" acyclic.undo", function() { + acyclic.undo(g); + }); + } + function updateInputGraph(inputGraph, layoutGraph) { + inputGraph.nodes().forEach((v) => { + var inputLabel = inputGraph.node(v); + var layoutLabel = layoutGraph.node(v); + if (inputLabel) { + inputLabel.x = layoutLabel.x; + inputLabel.y = layoutLabel.y; + inputLabel.rank = layoutLabel.rank; + if (layoutGraph.children(v).length) { + inputLabel.width = layoutLabel.width; + inputLabel.height = layoutLabel.height; + } + } + }); + inputGraph.edges().forEach((e) => { + var inputLabel = inputGraph.edge(e); + var layoutLabel = layoutGraph.edge(e); + inputLabel.points = layoutLabel.points; + if (layoutLabel.hasOwnProperty("x")) { + inputLabel.x = layoutLabel.x; + inputLabel.y = layoutLabel.y; + } + }); + inputGraph.graph().width = layoutGraph.graph().width; + inputGraph.graph().height = layoutGraph.graph().height; + } + var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"]; + var graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb" }; + var graphAttrs = ["acyclicer", "ranker", "rankdir", "align"]; + var nodeNumAttrs = ["width", "height"]; + var nodeDefaults = { width: 0, height: 0 }; + var edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"]; + var edgeDefaults = { + minlen: 1, + weight: 1, + width: 0, + height: 0, + labeloffset: 10, + labelpos: "r" + }; + var edgeAttrs = ["labelpos"]; + function buildLayoutGraph(inputGraph) { + var g = new Graph({ multigraph: true, compound: true }); + var graph = canonicalize(inputGraph.graph()); + g.setGraph(Object.assign({}, graphDefaults, selectNumberAttrs(graph, graphNumAttrs), util.pick(graph, graphAttrs))); + inputGraph.nodes().forEach((v) => { + var node = canonicalize(inputGraph.node(v)); + const newNode = selectNumberAttrs(node, nodeNumAttrs); + Object.keys(nodeDefaults).forEach((k) => { + if (newNode[k] === void 0) { + newNode[k] = nodeDefaults[k]; + } + }); + g.setNode(v, newNode); + g.setParent(v, inputGraph.parent(v)); + }); + inputGraph.edges().forEach((e) => { + var edge = canonicalize(inputGraph.edge(e)); + g.setEdge(e, Object.assign({}, edgeDefaults, selectNumberAttrs(edge, edgeNumAttrs), util.pick(edge, edgeAttrs))); + }); + return g; + } + function makeSpaceForEdgeLabels(g) { + var graph = g.graph(); + graph.ranksep /= 2; + g.edges().forEach((e) => { + var edge = g.edge(e); + edge.minlen *= 2; + if (edge.labelpos.toLowerCase() !== "c") { + if (graph.rankdir === "TB" || graph.rankdir === "BT") { + edge.width += edge.labeloffset; + } else { + edge.height += edge.labeloffset; + } + } + }); + } + function injectEdgeLabelProxies(g) { + g.edges().forEach((e) => { + var edge = g.edge(e); + if (edge.width && edge.height) { + var v = g.node(e.v); + var w = g.node(e.w); + var label = { rank: (w.rank - v.rank) / 2 + v.rank, e }; + util.addDummyNode(g, "edge-proxy", label, "_ep"); + } + }); + } + function assignRankMinMax(g) { + var maxRank = 0; + g.nodes().forEach((v) => { + var node = g.node(v); + if (node.borderTop) { + node.minRank = g.node(node.borderTop).rank; + node.maxRank = g.node(node.borderBottom).rank; + maxRank = Math.max(maxRank, node.maxRank); + } + }); + g.graph().maxRank = maxRank; + } + function removeEdgeLabelProxies(g) { + g.nodes().forEach((v) => { + var node = g.node(v); + if (node.dummy === "edge-proxy") { + g.edge(node.e).labelRank = node.rank; + g.removeNode(v); + } + }); + } + function translateGraph(g) { + var minX = Number.POSITIVE_INFINITY; + var maxX = 0; + var minY = Number.POSITIVE_INFINITY; + var maxY = 0; + var graphLabel = g.graph(); + var marginX = graphLabel.marginx || 0; + var marginY = graphLabel.marginy || 0; + function getExtremes(attrs) { + var x = attrs.x; + var y = attrs.y; + var w = attrs.width; + var h = attrs.height; + minX = Math.min(minX, x - w / 2); + maxX = Math.max(maxX, x + w / 2); + minY = Math.min(minY, y - h / 2); + maxY = Math.max(maxY, y + h / 2); + } + g.nodes().forEach((v) => getExtremes(g.node(v))); + g.edges().forEach((e) => { + var edge = g.edge(e); + if (edge.hasOwnProperty("x")) { + getExtremes(edge); + } + }); + minX -= marginX; + minY -= marginY; + g.nodes().forEach((v) => { + var node = g.node(v); + node.x -= minX; + node.y -= minY; + }); + g.edges().forEach((e) => { + var edge = g.edge(e); + edge.points.forEach((p) => { + p.x -= minX; + p.y -= minY; + }); + if (edge.hasOwnProperty("x")) { + edge.x -= minX; + } + if (edge.hasOwnProperty("y")) { + edge.y -= minY; + } + }); + graphLabel.width = maxX - minX + marginX; + graphLabel.height = maxY - minY + marginY; + } + function assignNodeIntersects(g) { + g.edges().forEach((e) => { + var edge = g.edge(e); + var nodeV = g.node(e.v); + var nodeW = g.node(e.w); + var p1, p2; + if (!edge.points) { + edge.points = []; + p1 = nodeW; + p2 = nodeV; + } else { + p1 = edge.points[0]; + p2 = edge.points[edge.points.length - 1]; + } + edge.points.unshift(util.intersectRect(nodeV, p1)); + edge.points.push(util.intersectRect(nodeW, p2)); + }); + } + function fixupEdgeLabelCoords(g) { + g.edges().forEach((e) => { + var edge = g.edge(e); + if (edge.hasOwnProperty("x")) { + if (edge.labelpos === "l" || edge.labelpos === "r") { + edge.width -= edge.labeloffset; + } + switch (edge.labelpos) { + case "l": + edge.x -= edge.width / 2 + edge.labeloffset; + break; + case "r": + edge.x += edge.width / 2 + edge.labeloffset; + break; + } + } + }); + } + function reversePointsForReversedEdges(g) { + g.edges().forEach((e) => { + var edge = g.edge(e); + if (edge.reversed) { + edge.points.reverse(); + } + }); + } + function removeBorderNodes(g) { + g.nodes().forEach((v) => { + if (g.children(v).length) { + var node = g.node(v); + var t = g.node(node.borderTop); + var b = g.node(node.borderBottom); + var l = g.node(node.borderLeft[node.borderLeft.length - 1]); + var r = g.node(node.borderRight[node.borderRight.length - 1]); + node.width = Math.abs(r.x - l.x); + node.height = Math.abs(b.y - t.y); + node.x = l.x + node.width / 2; + node.y = t.y + node.height / 2; + } + }); + g.nodes().forEach((v) => { + if (g.node(v).dummy === "border") { + g.removeNode(v); + } + }); + } + function removeSelfEdges(g) { + g.edges().forEach((e) => { + if (e.v === e.w) { + var node = g.node(e.v); + if (!node.selfEdges) { + node.selfEdges = []; + } + node.selfEdges.push({ e, label: g.edge(e) }); + g.removeEdge(e); + } + }); + } + function insertSelfEdges(g) { + var layers = util.buildLayerMatrix(g); + layers.forEach((layer) => { + var orderShift = 0; + layer.forEach((v, i) => { + var node = g.node(v); + node.order = i + orderShift; + (node.selfEdges || []).forEach((selfEdge) => { + util.addDummyNode(g, "selfedge", { + width: selfEdge.label.width, + height: selfEdge.label.height, + rank: node.rank, + order: i + ++orderShift, + e: selfEdge.e, + label: selfEdge.label + }, "_se"); + }); + delete node.selfEdges; + }); + }); + } + function positionSelfEdges(g) { + g.nodes().forEach((v) => { + var node = g.node(v); + if (node.dummy === "selfedge") { + var selfNode = g.node(node.e.v); + var x = selfNode.x + selfNode.width / 2; + var y = selfNode.y; + var dx = node.x - x; + var dy = selfNode.height / 2; + g.setEdge(node.e, node.label); + g.removeNode(v); + node.label.points = [ + { x: x + 2 * dx / 3, y: y - dy }, + { x: x + 5 * dx / 6, y: y - dy }, + { x: x + dx, y }, + { x: x + 5 * dx / 6, y: y + dy }, + { x: x + 2 * dx / 3, y: y + dy } + ]; + node.label.x = node.x; + node.label.y = node.y; + } + }); + } + function selectNumberAttrs(obj, attrs) { + return util.mapValues(util.pick(obj, attrs), Number); + } + function canonicalize(attrs) { + var newAttrs = {}; + if (attrs) { + Object.entries(attrs).forEach(([k, v]) => { + if (typeof k === "string") { + k = k.toLowerCase(); + } + newAttrs[k] = v; + }); + } + return newAttrs; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/debug.js +var require_debug = __commonJS({ + "node_modules/@dagrejs/dagre/lib/debug.js"(exports, module2) { + var util = require_util(); + var Graph = require_graphlib().Graph; + module2.exports = { + debugOrdering + }; + function debugOrdering(g) { + var layerMatrix = util.buildLayerMatrix(g); + var h = new Graph({ compound: true, multigraph: true }).setGraph({}); + g.nodes().forEach(function(v) { + h.setNode(v, { label: v }); + h.setParent(v, "layer" + g.node(v).rank); + }); + g.edges().forEach(function(e) { + h.setEdge(e.v, e.w, {}, e.name); + }); + layerMatrix.forEach(function(layer, i) { + var layerV = "layer" + i; + h.setNode(layerV, { rank: "same" }); + layer.reduce(function(u, v) { + h.setEdge(u, v, { style: "invis" }); + return v; + }); + }); + return h; + } + } +}); + +// node_modules/@dagrejs/dagre/lib/version.js +var require_version2 = __commonJS({ + "node_modules/@dagrejs/dagre/lib/version.js"(exports, module2) { + module2.exports = "1.0.2"; + } +}); + +// node_modules/@dagrejs/dagre/index.js +var require_dagre = __commonJS({ + "node_modules/@dagrejs/dagre/index.js"(exports, module2) { + module2.exports = { + graphlib: require_graphlib(), + layout: require_layout(), + debug: require_debug(), + util: { + time: require_util().time, + notime: require_util().notime + }, + version: require_version2() + }; + } +}); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => ObsidianClipperPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian7 = require("obsidian"); + +// node_modules/deepmerge-ts/dist/node/index.mjs +var actions = { + defaultMerge: Symbol("deepmerge-ts: default merge"), + skip: Symbol("deepmerge-ts: skip") +}; +var actionsInto = { + defaultMerge: actions.defaultMerge +}; +function defaultMetaDataUpdater(previousMeta, metaMeta) { + return metaMeta; +} +function getObjectType(object) { + if (typeof object !== "object" || object === null) { + return 0; + } + if (Array.isArray(object)) { + return 2; + } + if (isRecord(object)) { + return 1; + } + if (object instanceof Set) { + return 3; + } + if (object instanceof Map) { + return 4; + } + return 5; +} +function getKeys(objects) { + const keys = /* @__PURE__ */ new Set(); + for (const object of objects) { + for (const key of [ + ...Object.keys(object), + ...Object.getOwnPropertySymbols(object) + ]) { + keys.add(key); + } + } + return keys; +} +function objectHasProperty(object, property) { + return typeof object === "object" && Object.prototype.propertyIsEnumerable.call(object, property); +} +function getIterableOfIterables(iterables) { + return { + *[Symbol.iterator]() { + for (const iterable of iterables) { + for (const value of iterable) { + yield value; + } + } + } + }; +} +var validRecordToStringValues = /* @__PURE__ */ new Set([ + "[object Object]", + "[object Module]" +]); +function isRecord(value) { + if (!validRecordToStringValues.has(Object.prototype.toString.call(value))) { + return false; + } + const { constructor } = value; + if (constructor === void 0) { + return true; + } + const prototype = constructor.prototype; + if (prototype === null || typeof prototype !== "object" || !validRecordToStringValues.has(Object.prototype.toString.call(prototype))) { + return false; + } + if (!prototype.hasOwnProperty("isPrototypeOf")) { + return false; + } + return true; +} +function mergeRecords$2(values, utils, meta) { + const result = {}; + for (const key of getKeys(values)) { + const propValues = []; + for (const value of values) { + if (objectHasProperty(value, key)) { + propValues.push(value[key]); + } + } + if (propValues.length === 0) { + continue; + } + const updatedMeta = utils.metaDataUpdater(meta, { + key, + parents: values + }); + const propertyResult = mergeUnknowns(propValues, utils, updatedMeta); + if (propertyResult === actions.skip) { + continue; + } + if (key === "__proto__") { + Object.defineProperty(result, key, { + value: propertyResult, + configurable: true, + enumerable: true, + writable: true + }); + } else { + result[key] = propertyResult; + } + } + return result; +} +function mergeArrays$2(values) { + return values.flat(); +} +function mergeSets$2(values) { + return new Set(getIterableOfIterables(values)); +} +function mergeMaps$2(values) { + return new Map(getIterableOfIterables(values)); +} +function mergeOthers$2(values) { + return values[values.length - 1]; +} +var defaultMergeFunctions = /* @__PURE__ */ Object.freeze({ + __proto__: null, + mergeRecords: mergeRecords$2, + mergeArrays: mergeArrays$2, + mergeSets: mergeSets$2, + mergeMaps: mergeMaps$2, + mergeOthers: mergeOthers$2 +}); +function deepmerge(...objects) { + return deepmergeCustom({})(...objects); +} +function deepmergeCustom(options, rootMetaData) { + const utils = getUtils(options, customizedDeepmerge); + function customizedDeepmerge(...objects) { + return mergeUnknowns(objects, utils, rootMetaData); + } + return customizedDeepmerge; +} +function getUtils(options, customizedDeepmerge) { + var _a, _b; + return { + defaultMergeFunctions, + mergeFunctions: { + ...defaultMergeFunctions, + ...Object.fromEntries(Object.entries(options).filter(([key, option]) => Object.prototype.hasOwnProperty.call(defaultMergeFunctions, key)).map(([key, option]) => option === false ? [key, mergeOthers$2] : [key, option])) + }, + metaDataUpdater: (_a = options.metaDataUpdater) !== null && _a !== void 0 ? _a : defaultMetaDataUpdater, + deepmerge: customizedDeepmerge, + useImplicitDefaultMerging: (_b = options.enableImplicitDefaultMerging) !== null && _b !== void 0 ? _b : false, + actions + }; +} +function mergeUnknowns(values, utils, meta) { + if (values.length === 0) { + return void 0; + } + if (values.length === 1) { + return mergeOthers$1(values, utils, meta); + } + const type = getObjectType(values[0]); + if (type !== 0 && type !== 5) { + for (let m_index = 1; m_index < values.length; m_index++) { + if (getObjectType(values[m_index]) === type) { + continue; + } + return mergeOthers$1(values, utils, meta); + } + } + switch (type) { + case 1: { + return mergeRecords$1(values, utils, meta); + } + case 2: { + return mergeArrays$1(values, utils, meta); + } + case 3: { + return mergeSets$1(values, utils, meta); + } + case 4: { + return mergeMaps$1(values, utils, meta); + } + default: { + return mergeOthers$1(values, utils, meta); + } + } +} +function mergeRecords$1(values, utils, meta) { + const result = utils.mergeFunctions.mergeRecords(values, utils, meta); + if (result === actions.defaultMerge || utils.useImplicitDefaultMerging && result === void 0 && utils.mergeFunctions.mergeRecords !== utils.defaultMergeFunctions.mergeRecords) { + return utils.defaultMergeFunctions.mergeRecords(values, utils, meta); + } + return result; +} +function mergeArrays$1(values, utils, meta) { + const result = utils.mergeFunctions.mergeArrays(values, utils, meta); + if (result === actions.defaultMerge || utils.useImplicitDefaultMerging && result === void 0 && utils.mergeFunctions.mergeArrays !== utils.defaultMergeFunctions.mergeArrays) { + return utils.defaultMergeFunctions.mergeArrays(values); + } + return result; +} +function mergeSets$1(values, utils, meta) { + const result = utils.mergeFunctions.mergeSets(values, utils, meta); + if (result === actions.defaultMerge || utils.useImplicitDefaultMerging && result === void 0 && utils.mergeFunctions.mergeSets !== utils.defaultMergeFunctions.mergeSets) { + return utils.defaultMergeFunctions.mergeSets(values); + } + return result; +} +function mergeMaps$1(values, utils, meta) { + const result = utils.mergeFunctions.mergeMaps(values, utils, meta); + if (result === actions.defaultMerge || utils.useImplicitDefaultMerging && result === void 0 && utils.mergeFunctions.mergeMaps !== utils.defaultMergeFunctions.mergeMaps) { + return utils.defaultMergeFunctions.mergeMaps(values); + } + return result; +} +function mergeOthers$1(values, utils, meta) { + const result = utils.mergeFunctions.mergeOthers(values, utils, meta); + if (result === actions.defaultMerge || utils.useImplicitDefaultMerging && result === void 0 && utils.mergeFunctions.mergeOthers !== utils.defaultMergeFunctions.mergeOthers) { + return utils.defaultMergeFunctions.mergeOthers(values); + } + return result; +} + +// src/settings/types.ts +var SectionPosition = { + PREPEND: "prepend", + APPEND: "append" +}; +var DEFAULT_SETTINGS = { + dailyNoteHeading: "", + weeklyNoteHeading: "", + tags: "", + timestampFormat: "HH:mm", + dateFormat: "MM/DD/YY", + dailyOpenOnWrite: false, + useDailyNote: true, + dailyPosition: SectionPosition.APPEND, + useWeeklyNote: false, + weeklyPosition: SectionPosition.APPEND, + weeklyOpenOnWrite: false, + dailyEntryTemplateLocation: "", + weeklyEntryTemplateLocation: "", + topicEntryTemplateLocation: "", + topicPosition: SectionPosition.APPEND, + topicOpenOnWrite: false, + markdownSettings: { + h1: "##", + h2: "##", + h3: "###", + h4: "####", + h5: "#####", + h6: "######" + }, + advanced: false, + advancedStorageFolder: "clippings", + captureComments: false, + experimentalCanvas: false, + experimentalBookmarkletComment: false +}; + +// src/utils/templateutils.ts +var import_obsidian = require("obsidian"); +async function getTemplateContents(app, templatePath) { + const { metadataCache, vault } = app; + const normalizedTemplatePath = (0, import_obsidian.normalizePath)(templatePath != null ? templatePath : ""); + if (templatePath === "/") { + return Promise.resolve(""); + } + let templateContents = ""; + try { + const templateFile = metadataCache.getFirstLinkpathDest(normalizedTemplatePath, ""); + if (templateFile) { + templateContents = await vault.cachedRead(templateFile); + } + return `${templateContents} +`; + } catch (err) { + console.error(`Failed to read the clipper entry template '${normalizedTemplatePath}'`, err); + new import_obsidian.Notice("Failed to read the Obsidian Clipper daily note entry template configured in Settings"); + throw Error("Template File Missing"); + } +} +function applyTemplateTransformations(title, url, tags, time, date, content = "", comment = "", rawTemplateContents) { + const templateContents = rawTemplateContents.replace(/{{\s*title\s*}}/gi, title).replace(/{{\s*url\s*}}/gi, url).replace(/{{\s*tags\s*}}/gi, tags).replace(/{{\s*content\s*}}/gi, content).replace(/{{\s*comment\s*}}/gi, comment).replace(/{{\s*time\s*}}/gi, time).replace(/{{\s*date\s*}}/gi, date); + return templateContents; +} + +// src/clippeddata.ts +var ClippedData = class { + constructor(title, url, settings2, app, data = "", comment = "") { + this.title = title; + this.url = url; + this.title = title; + this.url = url; + if (data !== "") { + this.data = data; + } + this.comment = comment; + const tagJoins = []; + settings2.tags.split(",").forEach((t) => { + tagJoins.push(`#${t}`); + }); + this.tags = tagJoins.join(" "); + this.settings = settings2; + this.app = app; + this.timeStamp = window.moment().format(this.settings.timestampFormat); + this.date = window.moment().format(this.settings.dateFormat); + } + async formattedEntry(template) { + let formattedData = ""; + if (template && template != "") { + const rawTemplateContents = await getTemplateContents(this.app, template); + formattedData = applyTemplateTransformations(this.title, this.url, this.tags, this.timeStamp, this.date, this.data, this.comment, rawTemplateContents); + } else { + if (!this.data) { + formattedData = `- [ ] [${this.title}](${this.url}) ${this.tags} + +---`; + } else { + if (this.settings.advanced) { + formattedData = `- [ ] ${this.title} ${this.tags} +${this.data} + +---`; + } else { + formattedData = `- [ ] [${this.title}](${this.url}) ${this.tags} +${this.data} + +---`; + } + } + } + return formattedData; + } + getUrl() { + return this.url; + } + getEntryContent() { + return this.data; + } +}; + +// src/periodicnotes/dailyperiodicnoteentry.ts +var import_obsidian_daily_notes_interface = __toESM(require_main()); + +// src/periodicnotes/periodicnoteentry.ts +var import_obsidian4 = require("obsidian"); + +// src/abstracts/noteentry.ts +var import_obsidian3 = require("obsidian"); + +// src/periodicnotes/filewriter.ts +var import_obsidian2 = require("obsidian"); + +// node_modules/parse-domain/serialized-tries/icann.js +var icann_default = "ac>com,edu,gov,net,mil,orgnomco,net,org,sch,ac,gov,milaccident-investigation,accident-prevention,aerobatic,aeroclub,aerodrome,agents,aircraft,airline,airport,air-surveillance,airtraffic,air-traffic-control,ambulance,amusement,association,author,ballooning,broker,caa,cargo,catering,certification,championship,charter,civilaviation,club,conference,consultant,consulting,control,council,crew,design,dgca,educator,emergency,engine,engineer,entertainment,equipment,exchange,express,federation,flight,fuel,gliding,government,groundhandling,group,hanggliding,homebuilt,insurance,journal,journalist,leasing,logistics,magazine,maintenance,media,microlight,modelling,navigation,parachuting,paragliding,passenger-association,pilot,press,production,recreation,repbody,res,research,rotorcraft,safety,scientist,services,show,skydiving,software,student,trader,trading,trainer,union,workinggroup,worksgov,com,org,net,educom,org,net,co,nomoff,com,net,orgcom,edu,gov,mil,net,orgco,com,commune,net,orged,gv,og,co,pb,itbet,com,coop,edu,gob,gov,int,mil,musica,mutual,net,org,senasa,ture164,in-addr,ip6,iris,uri,urngovac>sthcom,net,org,edu>act,catholic,nsw>schoolsqld,sa,tas,vic,wacomcom,net,int,gov,org,edu,info,pp,mil,name,pro,bizcom,edu,gov,mil,net,orgbiz,co,com,edu,gov,info,net,org,store,tv*acgova,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9com,edu,net,org,govco,com,edu,or,orgasso,barreau,gouvcom,edu,gov,net,orgcom,edu,gov,net,orgcom,edu,gob,int,org,net,mil,tv,web,academia,agro,arte,blog,bolivia,ciencia,cooperativa,democracia,deporte,ecologia,economia,empresa,indigena,industria,info,medicina,movimiento,musica,natural,nombre,noticias,patria,politica,profesional,plurinacional,pueblo,revista,salud,tecnologia,tksat,transporte,wiki
9guacu,abc,adm,adv,agr,aju,am,anani,aparecida,app,arq,art,ato,b,barueri,belem,bhz,bib,bio,blog,bmd,boavista,bsb,campinagrande,campinas,caxias,cim,cng,cnt,com,contagem,coop,coz,cri,cuiaba,curitiba,def,des,det,dev,ecn,eco,edu,emp,enf,eng,esp,etc,eti,far,feira,flog,floripa,fm,fnd,fortal,fot,foz,fst,g12,geo,ggf,goiania,gov>ac,al,am,ap,ba,ce,df,es,go,ma,mg,ms,mt,pa,pb,pe,pi,pr,rj,rn,ro,rr,rs,sc,se,sp,to*com,net,org,edu,govcom,edu,gov,net,orgco,orggov,mil,com,ofcom,net,org,edu,govab,bc,mb,nb,nf,nl,ns,nt,nu,on,pe,qc,sk,yk,gcgovorg,or,com,co,edu,ed,ac,net,go,asso,xn--aroport-bya,int,presse,md,gouv*,!wwwco,gob,gov,milco,com,gov,netac,com,edu,gov,net,org,mil,xn--55qx5d,xn--io0a7i,xn--od0alg,ah,bj,cq,fj,gd,gs,gz,gx,ha,hb,he,hi,hl,hn,jl,js,jx,ln,nm,nx,qh,sc,sd,sh,sn,sx,tj,xj,xz,yn,zj,hk,mo,twarts,com,edu,firm,gov,info,int,mil,net,nom,org,rec,webac,co,ed,fi,go,or,sacom,edu,org,net,gov,infcom,edu,int,nome,orgcom,edu,net,orggovac,biz,com,ekloges,gov,ltd,mil,net,org,press,pro,tmcom,net,org,edu,govart,com,edu,gob,gov,mil,net,org,sld,webart,asso,com,edu,gov,org,net,pol,soc,tmcom,info,net,fin,k12,med,pro,org,edu,gov,gob,miledu,gov,riik,lib,med,com,pri,aip,org,fiecom,edu,eun,gov,mil,name,net,org,sci*com,nom,org,gob,educom,gov,org,edu,biz,name,info,netalandac,biz,com,gov,info,mil,name,net,org,pro*com,edu,net,orgasso,com,gouv,nom,prd,tm,aeroport,avocat,avoues,cci,chambagri,chirurgiens-dentistes,experts-comptables,geometre-expert,greta,huissier-justice,medecin,notaires,pharmacien,port,veterinaireedu,govcom,edu,gov,org,mil,net,pvtco,net,orgcom,edu,gov,org,milcom,ltd,gov,mod,edu,orgco,com,edu,net,orgac,com,edu,gov,org,netcom,net,mobi,edu,org,assocom,edu,net,org,govcom,edu,gob,ind,mil,net,orgcom,edu,gov,guam,info,net,org,webco,com,edu,gov,net,orgcom,edu,gov,idv,net,org,xn--55qx5d,xn--wcvs22d,xn--lcvr32d,xn--mxtq1m,xn--gmqw5a,xn--ciqpn,xn--gmq050i,xn--zf0avx,xn--io0a7i,xn--mk0axi,xn--od0alg,xn--od0aq3b,xn--tn0ag,xn--uc0atv,xn--uc0ay4acom,edu,org,net,mil,gob
iz,from,name,comcom,shop,firm,info,adult,net,pro,org,med,art,coop,pol,asso,edu,rel,gouv,persoco,info,org,priv,sport,tm,2000,agrar,bolt,casino,city,erotica,erotika,film,forum,games,hotel,ingatlan,jogasz,konyvelo,lakas,media,news,reklam,sex,shop,suli,szex,tozsde,utazas,videoac,biz,co,desa,go,mil,my,net,or,ponpes,sch,webgovac,co,gov,idf,k12,muni,net,orgac,co>ltd,plcco,firm,net,org,gen,ind,nic,ac,edu,res,gov,mileucomgov,edu,mil,com,org,netac,co,gov,id,net,org,sch,xn--mgba3a4f16a,xn--mgba3a4franet,com,edu,gov,org,intgov,edu,abr,abruzzo,aosta-valley,aostavalley,bas,basilicata,cal,calabria,cam,campania,emilia-romagna,emiliaromagna,emr,friuli-v-giulia,friuli-ve-giulia,friuli-vegiulia,friuli-venezia-giulia,friuli-veneziagiulia,friuli-vgiulia,friuliv-giulia,friulive-giulia,friulivegiulia,friulivenezia-giulia,friuliveneziagiulia,friulivgiulia,fvg,laz,lazio,lig,liguria,lom,lombardia,lombardy,lucania,mar,marche,mol,molise,piedmont,piemonte,pmn,pug,puglia,sar,sardegna,sardinia,sic,sicilia,sicily,taa,tos,toscana,trentin-sud-tirol,xn--trentin-sd-tirol-rzb,trentin-sudtirol,xn--trentin-sdtirol-7vb,trentin-sued-tirol,trentin-suedtirol,trentino-a-adige,trentino-aadige,trentino-alto-adige,trentino-altoadige,trentino-s-tirol,trentino-stirol,trentino-sud-tirol,xn--trentino-sd-tirol-c3b,trentino-sudtirol,xn--trentino-sdtirol-szb,trentino-sued-tirol,trentino-suedtirol,trentino,trentinoa-adige,trentinoaadige,trentinoalto-adige,trentinoaltoadige,trentinos-tirol,trentinostirol,trentinosud-tirol,xn--trentinosd-tirol-rzb,trentinosudtirol,xn--trentinosdtirol-7vb,trentinosued-tirol,trentinosuedtirol,trentinsud-tirol,xn--trentinsd-tirol-6vb,trentinsudtirol,xn--trentinsdtirol-nsb,trentinsued-tirol,trentinsuedtirol,tuscany,umb,umbria,val-d-aosta,val-daosta,vald-aosta,valdaosta,valle-aosta,valle-d-aosta,valle-daosta,valleaosta,valled-aosta,valledaosta,vallee-aoste,xn--valle-aoste-ebb,vallee-d-aoste,xn--valle-d-aoste-ehb,valleeaoste,xn--valleaoste-e7a,valleedaoste,xn--valledaoste-ebb,vao,vda,ven,veneto,ag,agrigento,al,alessandria,alto-adige,altoadige,an,ancona,andria-barletta-trani,andria-trani-barletta,andriabarlettatrani,andriatranibarletta,ao,aosta,aoste,ap,aq,aquila,ar,arezzo,ascoli-piceno,ascolipiceno,asti,at,av,avellino,ba,balsan-sudtirol,xn--balsan-sdtirol-nsb,balsan-suedtirol,balsan,bari,barletta-trani-andria,barlettatraniandria,belluno,benevento,bergamo,bg,bi,biella,bl,bn,bo,bologna,bolzano-altoadige,bolzano,bozen-sudtirol,xn--bozen-sdtirol-2ob,bozen-suedtirol,bozen,br,brescia,brindisi,bs,bt,bulsan-sudtirol,xn--bulsan-sdtirol-nsb,bulsan-suedtirol,bulsan,bz,ca,cagliari,caltanissetta,campidano-medio,campidanomedio,campobasso,carbonia-iglesias,carboniaiglesias,carrara-massa,carraramassa,caserta,catania,catanzaro,cb,ce,cesena-forli,xn--cesena-forl-mcb,cesenaforli,xn--cesenaforl-i8a,ch,chieti,ci,cl,cn,co,como,cosenza,cr,cremona,crotone,cs,ct,cuneo,cz,dell-ogliastra,dellogliastra,en,enna,fc,fe,fermo,ferrara,fg,fi,firenze,florence,fm,foggia,forli-cesena,xn--forl-cesena-fcb,forlicesena,xn--forlcesena-c8a,fr,frosinone,ge,genoa,genova,go,gorizia,gr,grosseto,iglesias-carbonia,iglesiascarbonia,im,imperia,is,isernia,kr,la-spezia,laquila,laspezia,latina,lc,le,lecce,lecco,li,livorno,lo,lodi,lt,lu,lucca,macerata,mantova,massa-carrara,massacarrara,matera,mb,mc,me,medio-campidano,mediocampidano,messina,mi,milan,milano,mn,mo,modena,monza-brianza,monza-e-della-brianza,monza,monzabrianza,monzaebrianza,monzaedellabrianza,ms,mt,na,naples,napoli,no,novara,nu,nuoro,og,ogliastra,olbia-tempio,olbiatempio,or,oristano,ot,pa,padova,padua,palermo,parma,pavia,pc,pd,pe,perugia,pesaro-urbino,pesarourbino,pescara,pg,pi,piacenza,pisa,pistoia,pn,po,pordenone,potenza,pr,prato,pt,pu,pv,pz,ra,ragusa,ravenna,rc,re,reggio-calabria,reggio-emilia,reggiocalabria,reggioemilia,rg,ri,rieti,rimini,rm,rn,ro,roma,rome,rovigo,sa,salerno,sassari,savona,si,siena,siracusa,so,sondrio,sp,sr,ss,suedtirol,xn--sdtirol-n2a,sv,ta,taranto,te,tempio-olbia,tempioolbia,teramo,terni,tn,to,torino,tp,tr,trani-andria-barletta,trani-barletta-andria,traniandriabarletta,tranibarlettaandria,trapani,trento,treviso,trieste,ts,turin,tv,ud,udine,urbino-pesaro,urbinopesaro,va,varese,vb,vc,ve,venezia,venice,verbania,vercelli,verona,vi,vibo-valentia,vibovalentia,vicenza,viterbo,vr,vs,vt,vvco,net,org*com,org,net,edu,sch,gov,mil,nameac,ad,co,ed,go,gr,lg,ne,or,aichi>aisai,ama,anjo,asuke,chiryu,chita,fuso,gamagori,handa,hazu,hekinan,higashiura,ichinomiya,inazawa,inuyama,isshiki,iwakura,kanie,kariya,kasugai,kira,kiyosu,komaki,konan,kota,mihama,miyoshi,nishio,nisshin,obu,oguchi,oharu,okazaki,owariasahi,seto,shikatsu,shinshiro,shitara,tahara,takahama,tobishima,toei,togo,tokai,tokoname,toyoake,toyohashi,toyokawa,toyone,toyota,tsushima,yatomiakita,daisen,fujisato,gojome,hachirogata,happou,higashinaruse,honjo,honjyo,ikawa,kamikoani,kamioka,katagami,kazuno,kitaakita,kosaka,kyowa,misato,mitane,moriyoshi,nikaho,noshiro,odate,oga,ogata,semboku,yokote,yurihonjoaomori,gonohe,hachinohe,hashikami,hiranai,hirosaki,itayanagi,kuroishi,misawa,mutsu,nakadomari,noheji,oirase,owani,rokunohe,sannohe,shichinohe,shingo,takko,towada,tsugaru,tsurutaabiko,asahi,chonan,chosei,choshi,chuo,funabashi,futtsu,hanamigawa,ichihara,ichikawa,ichinomiya,inzai,isumi,kamagaya,kamogawa,kashiwa,katori,katsuura,kimitsu,kisarazu,kozaki,kujukuri,kyonan,matsudo,midori,mihama,minamiboso,mobara,mutsuzawa,nagara,nagareyama,narashino,narita,noda,oamishirasato,omigawa,onjuku,otaki,sakae,sakura,shimofusa,shirako,shiroi,shisui,sodegaura,sosa,tako,tateyama,togane,tohnosho,tomisato,urayasu,yachimata,yachiyo,yokaichiba,yokoshibahikari,yotsukaidoainan,honai,ikata,imabari,iyo,kamijima,kihoku,kumakogen,masaki,matsuno,matsuyama,namikata,niihama,ozu,saijo,seiyo,shikokuchuo,tobe,toon,uchiko,uwajima,yawatahamaechizen,eiheiji,fukui,ikeda,katsuyama,mihama,minamiechizen,obama,ohi,ono,sabae,sakai,takahama,tsuruga,wakasaashiya,buzen,chikugo,chikuho,chikujo,chikushino,chikuzen,chuo,dazaifu,fukuchi,hakata,higashi,hirokawa,hisayama,iizuka,inatsuki,kaho,kasuga,kasuya,kawara,keisen,koga,kurate,kurogi,kurume,minami,miyako,miyama,miyawaka,mizumaki,munakata,nakagawa,nakama,nishi,nogata,ogori,okagaki,okawa,oki,omuta,onga,onojo,oto,saigawa,sasaguri,shingu,shinyoshitomi,shonai,soeda,sue,tachiarai,tagawa,takata,toho,toyotsu,tsuiki,ukiha,umi,usui,yamada,yame,yanagawa,yukuhashiaizubange,aizumisato,aizuwakamatsu,asakawa,bandai,date,fukushima,furudono,futaba,hanawa,higashi,hirata,hirono,iitate,inawashiro,ishikawa,iwaki,izumizaki,kagamiishi,kaneyama,kawamata,kitakata,kitashiobara,koori,koriyama,kunimi,miharu,mishima,namie,nango,nishiaizu,nishigo,okuma,omotego,ono,otama,samegawa,shimogo,shirakawa,showa,soma,sukagawa,taishin,tamakawa,tanagura,tenei,yabuki,yamato,yamatsuri,yanaizu,yugawaanpachi,ena,gifu,ginan,godo,gujo,hashima,hichiso,hida,higashishirakawa,ibigawa,ikeda,kakamigahara,kani,kasahara,kasamatsu,kawaue,kitagata,mino,minokamo,mitake,mizunami,motosu,nakatsugawa,ogaki,sakahogi,seki,sekigahara,shirakawa,tajimi,takayama,tarui,toki,tomika,wanouchi,yamagata,yaotsu,yoroannaka,chiyoda,fujioka,higashiagatsuma,isesaki,itakura,kanna,kanra,katashina,kawaba,kiryu,kusatsu,maebashi,meiwa,midori,minakami,naganohara,nakanojo,nanmoku,numata,oizumi,ora,ota,shibukawa,shimonita,shinto,showa,takasaki,takayama,tamamura,tatebayashi,tomioka,tsukiyono,tsumagoi,ueno,yoshiokaasaminami,daiwa,etajima,fuchu,fukuyama,hatsukaichi,higashihiroshima,hongo,jinsekikogen,kaita,kui,kumano,kure,mihara,miyoshi,naka,onomichi,osakikamijima,otake,saka,sera,seranishi,shinichi,shobara,takeharaabashiri,abira,aibetsu,akabira,akkeshi,asahikawa,ashibetsu,ashoro,assabu,atsuma,bibai,biei,bifuka,bihoro,biratori,chippubetsu,chitose,date,ebetsu,embetsu,eniwa,erimo,esan,esashi,fukagawa,fukushima,furano,furubira,haboro,hakodate,hamatonbetsu,hidaka,higashikagura,higashikawa,hiroo,hokuryu,hokuto,honbetsu,horokanai,horonobe,ikeda,imakane,ishikari,iwamizawa,iwanai,kamifurano,kamikawa,kamishihoro,kamisunagawa,kamoenai,kayabe,kembuchi,kikonai,kimobetsu,kitahiroshima,kitami,kiyosato,koshimizu,kunneppu,kuriyama,kuromatsunai,kushiro,kutchan,kyowa,mashike,matsumae,mikasa,minamifurano,mombetsu,moseushi,mukawa,muroran,naie,nakagawa,nakasatsunai,nakatombetsu,nanae,nanporo,nayoro,nemuro,niikappu,niki,nishiokoppe,noboribetsu,numata,obihiro,obira,oketo,okoppe,otaru,otobe,otofuke,otoineppu,oumu,ozora,pippu,rankoshi,rebun,rikubetsu,rishiri,rishirifuji,saroma,sarufutsu,shakotan,shari,shibecha,shibetsu,shikabe,shikaoi,shimamaki,shimizu,shimokawa,shinshinotsu,shintoku,shiranuka,shiraoi,shiriuchi,sobetsu,sunagawa,taiki,takasu,takikawa,takinoue,teshikaga,tobetsu,tohma,tomakomai,tomari,toya,toyako,toyotomi,toyoura,tsubetsu,tsukigata,urakawa,urausu,uryu,utashinai,wakkanai,wassamu,yakumo,yoichiaioi,akashi,ako,amagasaki,aogaki,asago,ashiya,awaji,fukusaki,goshiki,harima,himeji,ichikawa,inagawa,itami,kakogawa,kamigori,kamikawa,kasai,kasuga,kawanishi,miki,minamiawaji,nishinomiya,nishiwaki,ono,sanda,sannan,sasayama,sayo,shingu,shinonsen,shiso,sumoto,taishi,taka,takarazuka,takasago,takino,tamba,tatsuno,toyooka,yabu,yashiro,yoka,yokawaami,asahi,bando,chikusei,daigo,fujishiro,hitachi,hitachinaka,hitachiomiya,hitachiota,ibaraki,ina,inashiki,itako,iwama,joso,kamisu,kasama,kashima,kasumigaura,koga,miho,mito,moriya,naka,namegata,oarai,ogawa,omitama,ryugasaki,sakai,sakuragawa,shimodate,shimotsuma,shirosato,sowa,suifu,takahagi,tamatsukuri,tokai,tomobe,tone,toride,tsuchiura,tsukuba,uchihara,ushiku,yachiyo,yamagata,yawara,yukianamizu,hakui,hakusan,kaga,kahoku,kanazawa,kawakita,komatsu,nakanoto,nanao,nomi,nonoichi,noto,shika,suzu,tsubata,tsurugi,uchinada,wajimafudai,fujisawa,hanamaki,hiraizumi,hirono,ichinohe,ichinoseki,iwaizumi,iwate,joboji,kamaishi,kanegasaki,karumai,kawai,kitakami,kuji,kunohe,kuzumaki,miyako,mizusawa,morioka,ninohe,noda,ofunato,oshu,otsuchi,rikuzentakata,shiwa,shizukuishi,sumita,tanohata,tono,yahaba,yamadaayagawa,higashikagawa,kanonji,kotohira,manno,marugame,mitoyo,naoshima,sanuki,tadotsu,takamatsu,tonosho,uchinomi,utazu,zentsujiakune,amami,hioki,isa,isen,izumi,kagoshima,kanoya,kawanabe,kinko,kouyama,makurazaki,matsumoto,minamitane,nakatane,nishinoomote,satsumasendai,soo,tarumizu,yusuiaikawa,atsugi,ayase,chigasaki,ebina,fujisawa,hadano,hakone,hiratsuka,isehara,kaisei,kamakura,kiyokawa,matsuda,minamiashigara,miura,nakai,ninomiya,odawara,oi,oiso,sagamihara,samukawa,tsukui,yamakita,yamato,yokosuka,yugawara,zama,zushiaki,geisei,hidaka,higashitsuno,ino,kagami,kami,kitagawa,kochi,mihara,motoyama,muroto,nahari,nakamura,nankoku,nishitosa,niyodogawa,ochi,okawa,otoyo,otsuki,sakawa,sukumo,susaki,tosa,tosashimizu,toyo,tsuno,umaji,yasuda,yusuharaamakusa,arao,aso,choyo,gyokuto,kamiamakusa,kikuchi,kumamoto,mashiki,mifune,minamata,minamioguni,nagasu,nishihara,oguni,ozu,sumoto,takamori,uki,uto,yamaga,yamato,yatsushiroayabe,fukuchiyama,higashiyama,ide,ine,joyo,kameoka,kamo,kita,kizu,kumiyama,kyotamba,kyotanabe,kyotango,maizuru,minami,minamiyamashiro,miyazu,muko,nagaokakyo,nakagyo,nantan,oyamazaki,sakyo,seika,tanabe,uji,ujitawara,wazuka,yamashina,yawataasahi,inabe,ise,kameyama,kawagoe,kiho,kisosaki,kiwa,komono,kumano,kuwana,matsusaka,meiwa,mihama,minamiise,misugi,miyama,nabari,shima,suzuka,tado,taiki,taki,tamaki,toba,tsu,udono,ureshino,watarai,yokkaichifurukawa,higashimatsushima,ishinomaki,iwanuma,kakuda,kami,kawasaki,marumori,matsushima,minamisanriku,misato,murata,natori,ogawara,ohira,onagawa,osaki,rifu,semine,shibata,shichikashuku,shikama,shiogama,shiroishi,tagajo,taiwa,tome,tomiya,wakuya,watari,yamamoto,zaoaya,ebino,gokase,hyuga,kadogawa,kawaminami,kijo,kitagawa,kitakata,kitaura,kobayashi,kunitomi,kushima,mimata,miyakonojo,miyazaki,morotsuka,nichinan,nishimera,nobeoka,saito,shiiba,shintomi,takaharu,takanabe,takazaki,tsunoachi,agematsu,anan,aoki,asahi,azumino,chikuhoku,chikuma,chino,fujimi,hakuba,hara,hiraya,iida,iijima,iiyama,iizuna,ikeda,ikusaka,ina,karuizawa,kawakami,kiso,kisofukushima,kitaaiki,komagane,komoro,matsukawa,matsumoto,miasa,minamiaiki,minamimaki,minamiminowa,minowa,miyada,miyota,mochizuki,nagano,nagawa,nagiso,nakagawa,nakano,nozawaonsen,obuse,ogawa,okaya,omachi,omi,ookuwa,ooshika,otaki,otari,sakae,sakaki,saku,sakuho,shimosuwa,shinanomachi,shiojiri,suwa,suzaka,takagi,takamori,takayama,tateshina,tatsuno,togakushi,togura,tomi,ueda,wada,yamagata,yamanouchi,yasaka,yasuokachijiwa,futsu,goto,hasami,hirado,iki,isahaya,kawatana,kuchinotsu,matsuura,nagasaki,obama,omura,oseto,saikai,sasebo,seihi,shimabara,shinkamigoto,togitsu,tsushima,unzenando,gose,heguri,higashiyoshino,ikaruga,ikoma,kamikitayama,kanmaki,kashiba,kashihara,katsuragi,kawai,kawakami,kawanishi,koryo,kurotaki,mitsue,miyake,nara,nosegawa,oji,ouda,oyodo,sakurai,sango,shimoichi,shimokitayama,shinjo,soni,takatori,tawaramoto,tenkawa,tenri,uda,yamatokoriyama,yamatotakada,yamazoe,yoshinoaga,agano,gosen,itoigawa,izumozaki,joetsu,kamo,kariwa,kashiwazaki,minamiuonuma,mitsuke,muika,murakami,myoko,nagaoka,niigata,ojiya,omi,sado,sanjo,seiro,seirou,sekikawa,shibata,tagami,tainai,tochio,tokamachi,tsubame,tsunan,uonuma,yahiko,yoita,yuzawabeppu,bungoono,bungotakada,hasama,hiji,himeshima,hita,kamitsue,kokonoe,kuju,kunisaki,kusu,oita,saiki,taketa,tsukumi,usa,usuki,yufuakaiwa,asakuchi,bizen,hayashima,ibara,kagamino,kasaoka,kibichuo,kumenan,kurashiki,maniwa,misaki,nagi,niimi,nishiawakura,okayama,satosho,setouchi,shinjo,shoo,soja,takahashi,tamano,tsuyama,wake,yakageaguni,ginowan,ginoza,gushikami,haebaru,higashi,hirara,iheya,ishigaki,ishikawa,itoman,izena,kadena,kin,kitadaito,kitanakagusuku,kumejima,kunigami,minamidaito,motobu,nago,naha,nakagusuku,nakijin,nanjo,nishihara,ogimi,okinawa,onna,shimoji,taketomi,tarama,tokashiki,tomigusuku,tonaki,urasoe,uruma,yaese,yomitan,yonabaru,yonaguni,zamamiabeno,chihayaakasaka,chuo,daito,fujiidera,habikino,hannan,higashiosaka,higashisumiyoshi,higashiyodogawa,hirakata,ibaraki,ikeda,izumi,izumiotsu,izumisano,kadoma,kaizuka,kanan,kashiwara,katano,kawachinagano,kishiwada,kita,kumatori,matsubara,minato,minoh,misaki,moriguchi,neyagawa,nishi,nose,osakasayama,sakai,sayama,sennan,settsu,shijonawate,shimamoto,suita,tadaoka,taishi,tajiri,takaishi,takatsuki,tondabayashi,toyonaka,toyono,yaoariake,arita,fukudomi,genkai,hamatama,hizen,imari,kamimine,kanzaki,karatsu,kashima,kitagata,kitahata,kiyama,kouhoku,kyuragi,nishiarita,ogi,omachi,ouchi,saga,shiroishi,taku,tara,tosu,yoshinogariarakawa,asaka,chichibu,fujimi,fujimino,fukaya,hanno,hanyu,hasuda,hatogaya,hatoyama,hidaka,higashichichibu,higashimatsuyama,honjo,ina,iruma,iwatsuki,kamiizumi,kamikawa,kamisato,kasukabe,kawagoe,kawaguchi,kawajima,kazo,kitamoto,koshigaya,kounosu,kuki,kumagaya,matsubushi,minano,misato,miyashiro,miyoshi,moroyama,nagatoro,namegawa,niiza,ogano,ogawa,ogose,okegawa,omiya,otaki,ranzan,ryokami,saitama,sakado,satte,sayama,shiki,shiraoka,soka,sugito,toda,tokigawa,tokorozawa,tsurugashima,urawa,warabi,yashio,yokoze,yono,yorii,yoshida,yoshikawa,yoshimiaisho,gamo,higashiomi,hikone,koka,konan,kosei,koto,kusatsu,maibara,moriyama,nagahama,nishiazai,notogawa,omihachiman,otsu,ritto,ryuoh,takashima,takatsuki,torahime,toyosato,yasuakagi,ama,gotsu,hamada,higashiizumo,hikawa,hikimi,izumo,kakinoki,masuda,matsue,misato,nishinoshima,ohda,okinoshima,okuizumo,shimane,tamayu,tsuwano,unnan,yakumo,yasugi,yatsukaarai,atami,fuji,fujieda,fujikawa,fujinomiya,fukuroi,gotemba,haibara,hamamatsu,higashiizu,ito,iwata,izu,izunokuni,kakegawa,kannami,kawanehon,kawazu,kikugawa,kosai,makinohara,matsuzaki,minamiizu,mishima,morimachi,nishiizu,numazu,omaezaki,shimada,shimizu,shimoda,shizuoka,susono,yaizu,yoshidaashikaga,bato,haga,ichikai,iwafune,kaminokawa,kanuma,karasuyama,kuroiso,mashiko,mibu,moka,motegi,nasu,nasushiobara,nikko,nishikata,nogi,ohira,ohtawara,oyama,sakura,sano,shimotsuke,shioya,takanezawa,tochigi,tsuga,ujiie,utsunomiya,yaitaaizumi,anan,ichiba,itano,kainan,komatsushima,matsushige,mima,minami,miyoshi,mugi,nakagawa,naruto,sanagochi,shishikui,tokushima,wajikiadachi,akiruno,akishima,aogashima,arakawa,bunkyo,chiyoda,chofu,chuo,edogawa,fuchu,fussa,hachijo,hachioji,hamura,higashikurume,higashimurayama,higashiyamato,hino,hinode,hinohara,inagi,itabashi,katsushika,kita,kiyose,kodaira,koganei,kokubunji,komae,koto,kouzushima,kunitachi,machida,meguro,minato,mitaka,mizuho,musashimurayama,musashino,nakano,nerima,ogasawara,okutama,ome,oshima,ota,setagaya,shibuya,shinagawa,shinjuku,suginami,sumida,tachikawa,taito,tama,toshimachizu,hino,kawahara,koge,kotoura,misasa,nanbu,nichinan,sakaiminato,tottori,wakasa,yazu,yonagoasahi,fuchu,fukumitsu,funahashi,himi,imizu,inami,johana,kamiichi,kurobe,nakaniikawa,namerikawa,nanto,nyuzen,oyabe,taira,takaoka,tateyama,toga,tonami,toyama,unazuki,uozu,yamadaarida,aridagawa,gobo,hashimoto,hidaka,hirogawa,inami,iwade,kainan,kamitonda,katsuragi,kimino,kinokawa,kitayama,koya,koza,kozagawa,kudoyama,kushimoto,mihama,misato,nachikatsuura,shingu,shirahama,taiji,tanabe,wakayama,yuasa,yuraasahi,funagata,higashine,iide,kahoku,kaminoyama,kaneyama,kawanishi,mamurogawa,mikawa,murayama,nagai,nakayama,nanyo,nishikawa,obanazawa,oe,oguni,ohkura,oishida,sagae,sakata,sakegawa,shinjo,shirataka,shonai,takahata,tendo,tozawa,tsuruoka,yamagata,yamanobe,yonezawa,yuzaabu,hagi,hikari,hofu,iwakuni,kudamatsu,mitou,nagato,oshima,shimonoseki,shunan,tabuse,tokuyama,toyota,ube,yuuchuo,doshi,fuefuki,fujikawa,fujikawaguchiko,fujiyoshida,hayakawa,hokuto,ichikawamisato,kai,kofu,koshu,kosuge,minami-alps,minobu,nakamichi,nanbu,narusawa,nirasaki,nishikatsura,oshino,otsuki,showa,tabayama,tsuru,uenohara,yamanakako,yamanashi*,!city*,!city*,!city*,!city*,!city*,!city*,!city<ac,co,go,info,me,mobi,ne,or,scorg,net,com,edu,gov,mil*edu,biz,net,org,gov,info,comorg,nom,gov,prd,tm,edu,mil,ass,com,coop,asso,presse,medecin,notaires,pharmaciens,veterinaire,gouvnet,org,edu,govcom,edu,gov,org,rep,traac,co,es,go,hs,kg,mil,ms,ne,or,pe,re,sc,busan,chungbuk,chungnam,daegu,daejeon,gangwon,gwangju,gyeongbuk,gyeonggi,gyeongnam,incheon,jeju,jeonbuk,jeonnam,seoul,ulsancom,edu,emb,gov,ind,net,orgcom,edu,net,orgorg,edu,net,gov,mil,comint,net,info,edu,gov,per,com,orgcom,edu,gov,net,orgcom,net,co,org,edu,govgov,sch,net,int,com,org,edu,ngo,soc,web,ltd,assn,grp,hotel,accom,edu,gov,org,netac,biz,co,edu,gov,info,net,org,scgovcom,edu,gov,org,mil,id,net,asn,confcom,net,gov,plc,edu,sch,med,org,idco,net,gov,org,ac,presstm,assoco,net,org,edu,ac,gov,its,privorg,nom,gov,prd,tm,edu,mil,com,cocom,org,net,edu,gov,inf,namecom,edu,gouv,gov,net,org,presse*gov,edu,orgcom,net,org,edu,govgovcom,edu,gov,net,orgcom,edu,net,orgcom,net,org,gov,ac,co,oracademy,agriculture,air,airguard,alabama,alaska,amber,ambulance,american,americana,americanantiques,americanart,amsterdam,and,annefrank,anthro,anthropology,antiques,aquarium,arboretum,archaeological,archaeology,architecture,art,artanddesign,artcenter,artdeco,arteducation,artgallery,arts,artsandcrafts,asmatart,assassination,assisi,association,astronomy,atlanta,austin,australia,automotive,aviation,axis,badajoz,baghdad,bahn,bale,baltimore,barcelona,baseball,basel,baths,bauern,beauxarts,beeldengeluid,bellevue,bergbau,berkeley,berlin,bern,bible,bilbao,bill,birdart,birthplace,bonn,boston,botanical,botanicalgarden,botanicgarden,botany,brandywinevalley,brasil,bristol,british,britishcolumbia,broadcast,brunel,brussel,brussels,bruxelles,building,burghof,bus,bushey,cadaques,california,cambridge,can,canada,capebreton,carrier,cartoonart,casadelamoneda,castle,castres,celtic,center,chattanooga,cheltenham,chesapeakebay,chicago,children,childrens,childrensgarden,chiropractic,chocolate,christiansburg,cincinnati,cinema,circus,civilisation,civilization,civilwar,clinton,clock,coal,coastaldefence,cody,coldwar,collection,colonialwilliamsburg,coloradoplateau,columbia,columbus,communication,communications,community,computer,computerhistory,xn--comunicaes-v6a2o,contemporary,contemporaryart,convent,copenhagen,corporation,xn--correios-e-telecomunicaes-ghc29a,corvette,costume,countryestate,county,crafts,cranbrook,creation,cultural,culturalcenter,culture,cyber,cymru,dali,dallas,database,ddr,decorativearts,delaware,delmenhorst,denmark,depot,design,detroit,dinosaur,discovery,dolls,donostia,durham,eastafrica,eastcoast,education,educational,egyptian,eisenbahn,elburg,elvendrell,embroidery,encyclopedic,england,entomology,environment,environmentalconservation,epilepsy,essex,estate,ethnology,exeter,exhibition,family,farm,farmequipment,farmers,farmstead,field,figueres,filatelia,film,fineart,finearts,finland,flanders,florida,force,fortmissoula,fortworth,foundation,francaise,frankfurt,franziskaner,freemasonry,freiburg,fribourg,frog,fundacio,furniture,gallery,garden,gateway,geelvinck,gemological,geology,georgia,giessen,glas,glass,gorge,grandrapids,graz,guernsey,halloffame,hamburg,handson,harvestcelebration,hawaii,health,heimatunduhren,hellas,helsinki,hembygdsforbund,heritage,histoire,historical,historicalsociety,historichouses,historisch,historisches,history,historyofscience,horology,house,humanities,illustration,imageandsound,indian,indiana,indianapolis,indianmarket,intelligence,interactive,iraq,iron,isleofman,jamison,jefferson,jerusalem,jewelry,jewish,jewishart,jfk,journalism,judaica,judygarland,juedisches,juif,karate,karikatur,kids,koebenhavn,koeln,kunst,kunstsammlung,kunstunddesign,labor,labour,lajolla,lancashire,landes,lans,xn--lns-qla,larsson,lewismiller,lincoln,linz,living,livinghistory,localhistory,london,losangeles,louvre,loyalist,lucerne,luxembourg,luzern,mad,madrid,mallorca,manchester,mansion,mansions,manx,marburg,maritime,maritimo,maryland,marylhurst,media,medical,medizinhistorisches,meeres,memorial,mesaverde,michigan,midatlantic,military,mill,miners,mining,minnesota,missile,missoula,modern,moma,money,monmouth,monticello,montreal,moscow,motorcycle,muenchen,muenster,mulhouse,muncie,museet,museumcenter,museumvereniging,music,national,nationalfirearms,nationalheritage,nativeamerican,naturalhistory,naturalhistorymuseum,naturalsciences,nature,naturhistorisches,natuurwetenschappen,naumburg,naval,nebraska,neues,newhampshire,newjersey,newmexico,newport,newspaper,newyork,niepce,norfolk,north,nrw,nyc,nyny,oceanographic,oceanographique,omaha,online,ontario,openair,oregon,oregontrail,otago,oxford,pacific,paderborn,palace,paleo,palmsprings,panama,paris,pasadena,pharmacy,philadelphia,philadelphiaarea,philately,phoenix,photography,pilots,pittsburgh,planetarium,plantation,plants,plaza,portal,portland,portlligat,posts-and-telecommunications,preservation,presidio,press,project,public,pubol,quebec,railroad,railway,research,resistance,riodejaneiro,rochester,rockart,roma,russia,saintlouis,salem,salvadordali,salzburg,sandiego,sanfrancisco,santabarbara,santacruz,santafe,saskatchewan,satx,savannahga,schlesisches,schoenbrunn,schokoladen,school,schweiz,science,scienceandhistory,scienceandindustry,sciencecenter,sciencecenters,science-fiction,sciencehistory,sciences,sciencesnaturelles,scotland,seaport,settlement,settlers,shell,sherbrooke,sibenik,silk,ski,skole,society,sologne,soundandvision,southcarolina,southwest,space,spy,square,stadt,stalbans,starnberg,state,stateofdelaware,station,steam,steiermark,stjohn,stockholm,stpetersburg,stuttgart,suisse,surgeonshall,surrey,svizzera,sweden,sydney,tank,tcm,technology,telekommunikation,television,texas,textile,theater,time,timekeeping,topology,torino,touch,town,transport,tree,trolley,trust,trustee,uhren,ulm,undersea,university,usa,usantiques,usarts,uscountryestate,usculture,usdecorativearts,usgarden,ushistory,ushuaia,uslivinghistory,utah,uvic,valley,vantaa,versailles,viking,village,virginia,virtual,virtuel,vlaanderen,volkenkunde,wales,wallonie,war,washingtondc,watchandclock,watch-and-clock,western,westfalen,whaling,wildlife,williamsburg,windmill,workshop,york,yorkshire,yosemite,youth,zoological,zoology,xn--9dbhblg6di,xn--h1aeghaero,biz,com,coop,edu,gov,info,int,mil,museum,name,net,org,proac,biz,co,com,coop,edu,gov,int,museum,net,orgcom,org,gob,edu,netbiz,com,edu,gov,mil,name,net,orgac,adv,co,edu,gov,mil,net,orginfo,pro,name,school,or,dr,us,mx,ca,in,cc,tv,ws,mobi,co,com,orgasso,nomcom,net,per,rec,web,arts,firm,info,other,storecom,edu,gov,i,mil,mobi,name,net,org,schac,biz,co,com,edu,gob,in,info,int,mil,net,nom,org,webfhs,vgs,fylkesbibl,folkebibl,museum,idrett,priv,mil,stat,dep,kommune,herad,aa>gsgsgsgsgsgsgsgsgsgsgs
    gsgsgsgsgsgsgsgsgsgsbo,xn--b-5gabo,xn--b-5ga,heroy,xn--hery-iraheroy,sandexn--hery-ira,sandenesnesos,valer,xn--vler-qoaossandevalerxn--vler-qoa<*biz,info,gov,edu,org,net,comac,co,cri,geek,gen,govt,health,iwi,kiwi,maori,mil,xn--mori-qsa,net,org,parliament,schoolco,com,edu,gov,med,museum,net,org,proac,gob,com,org,sld,edu,net,ing,abo,med,nomedu,gob,nom,mil,org,com,netcom,org,edu*com,net,org,gov,edu,ngo,mil,icom,net,edu,org,fam,biz,web,gov,gob,gok,gon,gop,gos,infocom,net,org,aid,agro,atm,auto,biz,edu,gmina,gsm,info,mail,miasta,media,mil,nieruchomosci,nom,pc,powiat,priv,realestate,rel,sex,shop,sklep,sos,szkola,targi,tm,tourism,travel,turystyka,gov>ap,ic,is,us,kmpsp,kppsp,kwpsp,psp,wskr,kwp,mw,ug,um,umig,ugim,upow,uw,starostwo,pa,po,psse,pup,rzgw,sa,so,sr,wsa,sko,uzs,wiih,winb,pinb,wios,witd,wzmiuw,piw,wiw,griw,wif,oum,sdn,zp,uppo,mup,wuoz,konsulat,oirmgov,co,org,edu,netcom,net,org,gov,edu,isla,pro,biz,info,name,est,prof,acaaa,aca,acct,avocat,bar,cpa,eng,jur,law,med,rechtedu,gov,sec,plo,com,org,netnet,gov,org,edu,int,publ,com,nomeco,ne,or,ed,go,belaucom,coop,edu,gov,mil,net,orgcom,edu,gov,mil,name,net,org,schasso,com,nomarts,com,firm,info,nom,nt,org,rec,store,tm,wwwac,co,edu,gov,in,orgac,co,coop,gov,mil,net,orgcom,net,org,gov,med,pub,edu,schcom,edu,gov,net,orgcom,gov,net,org,educom,net,org,edu,med,tv,gov,infoa,ac,b,bd,brand,c,d,e,f,fh,fhsk,fhv,g,h,i,k,komforb,kommunalforbund,komvux,l,lanbib,m,n,naturbruksgymn,o,org,p,parti,pp,press,r,s,t,tm,u,w,x,y,zcom,net,org,gov,edu,percom,net,gov,org,milcom,net,edu,gov,orgart,com,edu,gouv,org,perso,univcom,edu,gov,me,net,orgbiz,com,edu,gov,me,net,org,schco,com,consulado,edu,embaixada,mil,net,org,principe,saotome,storecom,edu,gob,org,redgovedu,gov,net,mil,com,orgco,ac,orgac,co,go,in,mi,net,orac,biz,co,com,edu,go,gov,int,mil,name,net,nic,org,test,webgovcom,co,org,net,nom,gov,mil,educom,ens,fin,gov,ind,info,intl,mincom,nat,net,org,perso,tourismcom,gov,net,org,edu,milav,bbs,bel,biz,com,dr,edu,gen,gov,info,mil,k12,kep,name,net,org,pol,tel,tsk,tv,web,nc>gov<co,com,org,net,biz,info,pro,int,coop,jobs,mobi,travel,museum,aero,name,gov,eduedu,gov,mil,com,net,org,idv,game,ebiz,club,xn--zf0ao64a,xn--uc0atv,xn--czrw28bac,co,go,hotel,info,me,mil,mobi,ne,or,sc,tvcom,edu,gov,in,net,org,cherkassy,cherkasy,chernigov,chernihiv,chernivtsi,chernovtsy,ck,cn,cr,crimea,cv,dn,dnepropetrovsk,dnipropetrovsk,donetsk,dp,if,ivano-frankivsk,kh,kharkiv,kharkov,kherson,khmelnitskiy,khmelnytskyi,kiev,kirovograd,km,kr,krym,ks,kv,kyiv,lg,lt,lugansk,lutsk,lv,lviv,mk,mykolaiv,nikolaev,od,odesa,odessa,pl,poltava,rivne,rovno,rv,sb,sebastopol,sevastopol,sm,sumy,te,ternopil,uz,uzhgorod,vinnica,vinnytsia,vn,volyn,yalta,zaporizhzhe,zaporizhzhia,zhitomir,zhytomyr,zp,ztco,or,ac,sc,go,ne,com,orgac,co,gov,ltd,me,net,nhs,org,plc,police,sch>*<dni,fed,isa,kids,nsn,ak>k12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cck12,cc,libk12,cc,libk12,cc,libcc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12>pvt,chtr,parochk12,cc,libk12,cc,libk12,cc,lib,ann-arbor,cog,dst,eaton,gen,mus,tec,washtenawk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libcc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libcc,libk12,cc,libcc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libk12,cc,libcck12,cc,lib<com,edu,gub,mil,net,orgco,com,net,orgcom,net,org,gov,mil,eduarts,bib,co,com,e12,edu,firm,gob,gov,info,int,mil,net,nom,org,rar,rec,store,tec,webco,com,k12,net,orgcom,net,org,edu,gov,int,ac,biz,info,name,pro,healthcom,edu,net,orgcom,net,org,gov,eduxn--55qx5d,xn--wcvs22d,xn--mxtq1m,xn--gmqw5a,xn--od0alg,xn--uc0atvxn--o1ac,xn--c1avg,xn--90azh,xn--d1at,xn--o1ach,xn--80auxn--12c1fe0br,xn--12co0c3b4eva,xn--h3cuzk1di,xn--o3cyx2a,xn--m3ch0j3a,xn--12cfi8ixb8lcom,edu,gov,net,mil,orgac,agric,alt,co,edu,gov,grondar,law,mil,net,ngo,nic,nis,nom,org,school,tm,webac,biz,co,com,edu,gov,info,mil,net,org,schac,co,gov,mil,org { + const labelsToCheck = labels.slice(); + const tlds = []; + let node = trie; + while (labelsToCheck.length !== 0) { + const label = labelsToCheck.pop(); + const labelLowerCase = label.toLowerCase(); + if (node.children.has(WILDCARD)) { + if (node.children.has(EXCEPTION + labelLowerCase)) { + break; + } + node = node.children.get(WILDCARD); + } else { + if (node.children.has(labelLowerCase) === false) { + break; + } + node = node.children.get(labelLowerCase); + } + tlds.unshift(label); + } + return tlds; +}; + +// node_modules/ip-regex/index.js +var word = "[a-fA-F\\d:]"; +var boundry = (options) => options && options.includeBoundaries ? `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))` : ""; +var v4 = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}"; +var v6segment = "[a-fA-F\\d]{1,4}"; +var v6 = ` +(?: +(?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8 +(?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4 +(?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4 +(?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4 +(?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4 +(?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4 +(?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4 +(?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4 +)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1 +`.replace(/\s*\/\/.*$/gm, "").replace(/\n/g, "").trim(); +var v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`); +var v4exact = new RegExp(`^${v4}$`); +var v6exact = new RegExp(`^${v6}$`); +var ipRegex = (options) => options && options.exact ? v46Exact : new RegExp(`(?:${boundry(options)}${v4}${boundry(options)})|(?:${boundry(options)}${v6}${boundry(options)})`, "g"); +ipRegex.v4 = (options) => options && options.exact ? v4exact : new RegExp(`${boundry(options)}${v4}${boundry(options)}`, "g"); +ipRegex.v6 = (options) => options && options.exact ? v6exact : new RegExp(`${boundry(options)}${v6}${boundry(options)}`, "g"); +var ip_regex_default = ipRegex; + +// node_modules/is-ip/index.js +function isIP(string) { + return ip_regex_default({ exact: true }).test(string); +} +function isIPv6(string) { + return ip_regex_default.v6({ exact: true }).test(string); +} +function ipVersion(string) { + return isIP(string) ? isIPv6(string) ? 6 : 4 : void 0; +} + +// node_modules/parse-domain/build/sanitize.js +var LABEL_SEPARATOR = "."; +var LABEL_LENGTH_MIN = 1; +var LABEL_LENGTH_MAX = 63; +var DOMAIN_LENGTH_MAX = 253; +var textEncoder = new TextEncoder(); +var Validation; +(function(Validation2) { + Validation2["Lax"] = "LAX"; + Validation2["Strict"] = "STRICT"; +})(Validation || (Validation = {})); +var ValidationErrorType; +(function(ValidationErrorType2) { + ValidationErrorType2["NoHostname"] = "NO_HOSTNAME"; + ValidationErrorType2["DomainMaxLength"] = "DOMAIN_MAX_LENGTH"; + ValidationErrorType2["LabelMinLength"] = "LABEL_MIN_LENGTH"; + ValidationErrorType2["LabelMaxLength"] = "LABEL_MAX_LENGTH"; + ValidationErrorType2["LabelInvalidCharacter"] = "LABEL_INVALID_CHARACTER"; + ValidationErrorType2["LastLabelInvalid"] = "LAST_LABEL_INVALID"; +})(ValidationErrorType || (ValidationErrorType = {})); +var SanitizationResultType; +(function(SanitizationResultType2) { + SanitizationResultType2["ValidIp"] = "VALID_IP"; + SanitizationResultType2["ValidDomain"] = "VALID_DOMAIN"; + SanitizationResultType2["Error"] = "ERROR"; +})(SanitizationResultType || (SanitizationResultType = {})); +var createNoHostnameError = (input) => { + return { + type: ValidationErrorType.NoHostname, + message: `The given input ${String(input)} does not look like a hostname.`, + column: 1 + }; +}; +var createDomainMaxLengthError = (domain, length) => { + return { + type: ValidationErrorType.DomainMaxLength, + message: `Domain "${domain}" is too long. Domain is ${length} octets long but should not be longer than ${DOMAIN_LENGTH_MAX}.`, + column: length + }; +}; +var createLabelMinLengthError = (label, column) => { + const length = label.length; + return { + type: ValidationErrorType.LabelMinLength, + message: `Label "${label}" is too short. Label is ${length} octets long but should be at least ${LABEL_LENGTH_MIN}.`, + column + }; +}; +var createLabelMaxLengthError = (label, column) => { + const length = label.length; + return { + type: ValidationErrorType.LabelMaxLength, + message: `Label "${label}" is too long. Label is ${length} octets long but should not be longer than ${LABEL_LENGTH_MAX}.`, + column + }; +}; +var createLabelInvalidCharacterError = (label, invalidCharacter, column) => { + return { + type: ValidationErrorType.LabelInvalidCharacter, + message: `Label "${label}" contains invalid character "${invalidCharacter}" at column ${column}.`, + column + }; +}; +var createLastLabelInvalidError = (label, column) => { + return { + type: ValidationErrorType.LabelInvalidCharacter, + message: `Last label "${label}" must not be all-numeric.`, + column + }; +}; +var sanitize = (input, options = {}) => { + if (typeof input !== "string") { + return { + type: SanitizationResultType.Error, + errors: [createNoHostnameError(input)] + }; + } + if (input === "") { + return { + type: SanitizationResultType.ValidDomain, + domain: input, + labels: [] + }; + } + const inputTrimmedAsIp = input.replace(/^\[|]$/g, ""); + const ipVersionOfInput = ipVersion(inputTrimmedAsIp); + if (ipVersionOfInput !== void 0) { + return { + type: SanitizationResultType.ValidIp, + ip: inputTrimmedAsIp, + ipVersion: ipVersionOfInput + }; + } + const lastChar = input.charAt(input.length - 1); + const canonicalInput = lastChar === LABEL_SEPARATOR ? input.slice(0, -1) : input; + const octets = new TextEncoder().encode(canonicalInput); + if (octets.length > DOMAIN_LENGTH_MAX) { + return { + type: SanitizationResultType.Error, + errors: [createDomainMaxLengthError(input, octets.length)] + }; + } + const labels = canonicalInput.split(LABEL_SEPARATOR); + const { validation = Validation.Strict } = options; + const labelValidationErrors = validateLabels[validation](labels); + if (labelValidationErrors.length > 0) { + return { + type: SanitizationResultType.Error, + errors: labelValidationErrors + }; + } + return { + type: SanitizationResultType.ValidDomain, + domain: input, + labels + }; +}; +var validateLabels = { + [Validation.Lax]: (labels) => { + const labelValidationErrors = []; + let column = 1; + for (const label of labels) { + const octets = textEncoder.encode(label); + if (octets.length < LABEL_LENGTH_MIN) { + labelValidationErrors.push(createLabelMinLengthError(label, column)); + } else if (octets.length > LABEL_LENGTH_MAX) { + labelValidationErrors.push(createLabelMaxLengthError(label, column)); + } + column += label.length + LABEL_SEPARATOR.length; + } + return labelValidationErrors; + }, + [Validation.Strict]: (labels) => { + const labelValidationErrors = []; + let column = 1; + let lastLabel; + for (const label of labels) { + const invalidCharacter = /[^\da-z-]/i.exec(label); + if (invalidCharacter) { + labelValidationErrors.push(createLabelInvalidCharacterError(label, invalidCharacter[0], invalidCharacter.index + 1)); + } + if (label.startsWith("-")) { + labelValidationErrors.push(createLabelInvalidCharacterError(label, "-", column)); + } else if (label.endsWith("-")) { + labelValidationErrors.push(createLabelInvalidCharacterError(label, "-", column + label.length - 1)); + } + if (label.length < LABEL_LENGTH_MIN) { + labelValidationErrors.push(createLabelMinLengthError(label, column)); + } else if (label.length > LABEL_LENGTH_MAX) { + labelValidationErrors.push(createLabelMaxLengthError(label, column)); + } + column += label.length + LABEL_SEPARATOR.length; + lastLabel = label; + } + if (lastLabel !== void 0 && /[a-z-]/iu.test(lastLabel) === false) { + labelValidationErrors.push(createLastLabelInvalidError(lastLabel, column - lastLabel.length - LABEL_SEPARATOR.length)); + } + return labelValidationErrors; + } +}; + +// node_modules/parse-domain/build/trie/nodes.js +var NODE_TYPE_ROOT = Symbol("ROOT"); +var NODE_TYPE_CHILD = Symbol("CHILD"); +var createRootNode = () => { + return { + type: NODE_TYPE_ROOT, + children: /* @__PURE__ */ new Map() + }; +}; +var createOrGetChild = (parent, label) => { + let child = parent.children.get(label); + if (child === void 0) { + child = { + type: NODE_TYPE_CHILD, + label, + children: /* @__PURE__ */ new Map(), + parent + }; + parent.children.set(label, child); + } + return child; +}; + +// node_modules/parse-domain/build/trie/parse-trie.js +var parseTrie = (serializedTrie) => { + const rootNode = createRootNode(); + let domain = ""; + let parentNode = rootNode; + let node = rootNode; + const addDomain = () => { + node = createOrGetChild(parentNode, domain); + domain = ""; + }; + for (let i = 0; i < serializedTrie.length; i++) { + const char = serializedTrie.charAt(i); + switch (char) { + case SAME: { + addDomain(); + continue; + } + case DOWN: { + addDomain(); + parentNode = node; + continue; + } + case RESET: { + addDomain(); + parentNode = rootNode; + continue; + } + case UP: { + if (parentNode.type === NODE_TYPE_ROOT) { + throw new Error(`Error in serialized trie at position ${i}: Cannot go up, current parent node is already root`); + } + addDomain(); + parentNode = parentNode.parent; + continue; + } + } + domain += char; + } + if (domain !== "") { + addDomain(); + } + return rootNode; +}; + +// node_modules/parse-domain/build/parse-domain.js +var RESERVED_TOP_LEVEL_DOMAINS = [ + "localhost", + "local", + "example", + "invalid", + "test" +]; +var ParseResultType; +(function(ParseResultType2) { + ParseResultType2["Invalid"] = "INVALID"; + ParseResultType2["Ip"] = "IP"; + ParseResultType2["Reserved"] = "RESERVED"; + ParseResultType2["NotListed"] = "NOT_LISTED"; + ParseResultType2["Listed"] = "LISTED"; +})(ParseResultType || (ParseResultType = {})); +var getAtIndex = (array, index) => { + return index >= 0 && index < array.length ? array[index] : void 0; +}; +var splitLabelsIntoDomains = (labels, index) => { + return { + subDomains: labels.slice(0, Math.max(0, index)), + domain: getAtIndex(labels, index), + topLevelDomains: labels.slice(index + 1) + }; +}; +var parsedIcannTrie; +var parsedPrivateTrie; +var parseDomain = (hostname, options) => { + const sanitizationResult = sanitize(hostname, options); + if (sanitizationResult.type === SanitizationResultType.Error) { + return { + type: ParseResultType.Invalid, + hostname, + errors: sanitizationResult.errors + }; + } + if (sanitizationResult.type === SanitizationResultType.ValidIp) { + return { + type: ParseResultType.Ip, + hostname: sanitizationResult.ip, + ipVersion: sanitizationResult.ipVersion + }; + } + const { labels, domain } = sanitizationResult; + if (hostname === "" || RESERVED_TOP_LEVEL_DOMAINS.includes(labels[labels.length - 1])) { + return { + type: ParseResultType.Reserved, + hostname: domain, + labels + }; + } + parsedIcannTrie = parsedIcannTrie !== null && parsedIcannTrie !== void 0 ? parsedIcannTrie : parseTrie(icann_default); + parsedPrivateTrie = parsedPrivateTrie !== null && parsedPrivateTrie !== void 0 ? parsedPrivateTrie : parseTrie(private_default); + const icannTlds = lookUpTldsInTrie(labels, parsedIcannTrie); + const privateTlds = lookUpTldsInTrie(labels, parsedPrivateTrie); + if (icannTlds.length === 0 && privateTlds.length === 0) { + return { + type: ParseResultType.NotListed, + hostname: domain, + labels + }; + } + const indexOfPublicSuffixDomain = labels.length - Math.max(privateTlds.length, icannTlds.length) - 1; + const indexOfIcannDomain = labels.length - icannTlds.length - 1; + return Object.assign({ type: ParseResultType.Listed, hostname: domain, labels, icann: splitLabelsIntoDomains(labels, indexOfIcannDomain) }, splitLabelsIntoDomains(labels, indexOfPublicSuffixDomain)); +}; + +// node_modules/parse-domain/build/from-url.js +var urlPattern = /^[a-z][*+.a-z-]+:\/\//i; +var invalidIpv6Pattern = /^([a-z][*+.a-z-]+:\/\/)([^[][^/?]*:[^/?]*:[^/?]*)(.*)/i; +var NO_HOSTNAME = Symbol("NO_HOSTNAME"); +var fromUrl = (urlLike) => { + if (typeof URL !== "function") { + throw new Error("Looks like the new URL() constructor is not globally available in your environment. Please make sure to use a polyfill."); + } + if (typeof urlLike !== "string") { + return NO_HOSTNAME; + } + let url = urlLike.startsWith("//") ? `http:${urlLike}` : urlLike.startsWith("/") ? urlLike : urlPattern.test(urlLike) ? urlLike : `http://${urlLike}`; + url = url.replace(invalidIpv6Pattern, "$1[$2]$3"); + try { + return new URL(url).hostname; + } catch (_a) { + return NO_HOSTNAME; + } +}; + +// src/utils/utility.ts +var Utility = class { + static assertNotNull(value) { + if (!value) { + throw new Error("Value is null"); + } + } + static parseDomainFromUrl(Url) { + return parseDomain(fromUrl(Url)).hostname.toString(); + } + static cleanHeading(heading) { + let cleanHeading = heading; + if (heading.startsWith("#") && heading[1] == " ") { + cleanHeading = heading.substring(2); + } + return cleanHeading; + } +}; + +// src/periodicnotes/filewriter.ts +var FileWriter = class { + constructor(app, openFileOnWrite) { + this.app = app; + this.openFileOnWrite = openFileOnWrite; + } + async write(file, clippedData, heading) { + const fileData = await this.app.vault.read(file); + const fileLines = fileData.split("\n"); + if (!heading) { + const startLine = this.getEndOfFrontmatter(file); + return this.writeAndOpenFile(file.path, this.positionDataWithNoHeader(fileData, clippedData, startLine)); + } else { + let insertSection = { + firstLine: 0, + lastLine: 0 + }; + try { + insertSection = this.getEndAndBeginningOfHeading(file, heading); + } catch (e) { + throw Error("Missing Expected Heading"); + } + const preSectionContent = fileLines.slice(0, insertSection.firstLine); + let targetSection = fileLines.slice(insertSection.firstLine, insertSection.lastLine); + targetSection = this.positionDataWithHeader(targetSection, clippedData); + let lines = []; + if (insertSection.lastLine !== -1) { + const postSectionContent = fileLines.slice(insertSection.lastLine); + lines = [...preSectionContent, ...targetSection, ...postSectionContent]; + } else { + lines = [...preSectionContent, ...targetSection]; + } + return this.writeAndOpenFile(file.path, lines.join("\n")); + } + } + async writeAndOpenFile(outputFileName, text2) { + const file = this.app.vault.getAbstractFileByPath(outputFileName); + if (file instanceof import_obsidian2.TFile) { + await this.app.vault.modify(file, text2); + } else { + const parts = outputFileName.split("/"); + const dir = parts.slice(0, parts.length - 1).join("/"); + if (parts.length > 1 && !(this.app.vault.getAbstractFileByPath(dir) instanceof import_obsidian2.TFolder)) { + await this.app.vault.createFolder(dir); + } + const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + if (base64regex.test(text2)) { + await this.app.vault.createBinary(outputFileName, (0, import_obsidian2.base64ToArrayBuffer)(text2)); + } else { + await this.app.vault.create(outputFileName, text2); + } + } + if (this.openFileOnWrite) { + let fileIsAlreadyOpened = false; + this.app.workspace.iterateAllLeaves((leaf) => { + var _a; + if (((_a = leaf.view.file) == null ? void 0 : _a.path) === outputFileName) { + fileIsAlreadyOpened = true; + this.app.workspace.setActiveLeaf(leaf, { focus: true }); + } + }); + if (!fileIsAlreadyOpened) + await this.app.workspace.openLinkText(outputFileName, "", false); + } + return this.app.vault.getAbstractFileByPath(outputFileName); + } + getEndAndBeginningOfHeading(file, heading) { + const cache = this.app.metadataCache.getFileCache(file); + Utility.assertNotNull(cache); + heading = Utility.cleanHeading(heading); + try { + const cachedHeadings = cache.headings; + Utility.assertNotNull(cachedHeadings); + const foundHeadingIndex = cachedHeadings.findIndex((cachedHeading) => { + return cachedHeading.heading === heading && cachedHeading.level === 1; + }); + if (foundHeadingIndex !== -1) { + const foundHeading = cachedHeadings[foundHeadingIndex]; + let nextHeading = null; + for (let i = foundHeadingIndex + 1; i < (cachedHeadings == null ? void 0 : cachedHeadings.length); i++) { + const cachedHeading = cachedHeadings[i]; + if (cachedHeading.level === 1) { + nextHeading = cachedHeading; + break; + } + } + const prependLine = foundHeading.position.start.line; + let appendLine = -1; + if (nextHeading) { + appendLine = nextHeading.position.start.line; + } + return { lastLine: appendLine, firstLine: prependLine }; + } else { + throw Error("Heading not found"); + } + } catch (e) { + new import_obsidian2.Notice("Can't find heading"); + throw Error("Heading not found"); + } + } + getEndOfFrontmatter(file) { + var _a; + let endLine = 0; + if (file) { + const cache = this.app.metadataCache; + if (cache) { + const sections = (_a = cache.getFileCache(file)) == null ? void 0 : _a.sections; + const frontmatter = sections == null ? void 0 : sections.find((item) => { + return item.type === "yaml"; + }); + if (frontmatter) { + endLine = frontmatter.position.end.line; + } + } + } + return endLine + 1; + } +}; + +// src/periodicnotes/appendwriter.ts +var AppendWriter = class extends FileWriter { + positionDataWithNoHeader(fileData, clippedData) { + return fileData + "\n" + clippedData; + } + positionDataWithHeader(targetSection, clippedData) { + targetSection.push(clippedData); + return targetSection; + } +}; + +// src/periodicnotes/prependwriter.ts +var PrependWriter = class extends FileWriter { + positionDataWithNoHeader(fileData, clippedData, startLine = 0) { + const fileLines = fileData.split("\n"); + const preSectionContent = fileLines.slice(0, startLine); + const restOfContent = fileLines.slice(startLine); + return [...preSectionContent, clippedData, ...restOfContent].join("\n"); + } + positionDataWithHeader(targetSection, clippedData) { + targetSection.splice(1, 0, clippedData); + return targetSection; + } +}; + +// src/abstracts/noteentry.ts +var NoteEntry = class { + constructor(app, openFileOnWrite, sectionPosition, template) { + this.app = app; + this.openFileOnWrite = openFileOnWrite; + this.sectionPosition = sectionPosition; + this.template = template; + } + async handleWrite(noteFilePath, data, heading) { + const file = this.app.vault.getAbstractFileByPath(noteFilePath); + if (file instanceof import_obsidian3.TFile) { + if (this.sectionPosition === SectionPosition.PREPEND) { + new PrependWriter(this.app, this.openFileOnWrite).write(file, data, heading); + } else { + new AppendWriter(this.app, this.openFileOnWrite).write(file, data, heading); + } + } else { + new import_obsidian3.Notice(`Obsidian Clipper couldn't find the note to ${this.sectionPosition} to`); + } + } +}; + +// src/periodicnotes/periodicnoteentry.ts +var PeriodicNoteEntry = class extends NoteEntry { + constructor(app, openFileOnWrite, sectionPosition, template) { + super(app, openFileOnWrite, sectionPosition, template); + this.template = template; + } + async writeToPeriodicNote(noteEntry, heading) { + if (!this.hasPeriodicNoteEnabled()) { + new import_obsidian4.Notice(this.notice); + return; + } + const note = await this.getNote(); + this.handleWrite(note.path, await noteEntry.formattedEntry(this.template), heading); + } + async getNote() { + const now2 = globalThis.moment(); + const allNotes = this.getAllNotes(); + const periodicNote = this.getPeriodicNote(now2, allNotes); + if (!periodicNote) { + return await this.waitForNoteCreation(now2); + } + return periodicNote; + } +}; + +// src/periodicnotes/dailyperiodicnoteentry.ts +var DailyPeriodicNoteEntry = class extends PeriodicNoteEntry { + constructor(app, openFileOnWrite, sectionPosition, template) { + super(app, openFileOnWrite, sectionPosition, template); + this.notice = "To use a daily note with Obsidian Clipper the daily note needs to be enabled from the periodic-notes plugin"; + } + getPeriodicNote(moment, allNotes) { + return (0, import_obsidian_daily_notes_interface.getDailyNote)(moment, allNotes); + } + hasPeriodicNoteEnabled() { + return (0, import_obsidian_daily_notes_interface.appHasDailyNotesPluginLoaded)(); + } + async waitForNoteCreation(moment) { + const dailyNote = await (0, import_obsidian_daily_notes_interface.createDailyNote)(moment); + await new Promise((r) => setTimeout(r, 50)); + return dailyNote; + } + getAllNotes() { + return (0, import_obsidian_daily_notes_interface.getAllDailyNotes)(); + } +}; + +// src/periodicnotes/weeklyperiodicnoteentry.ts +var import_obsidian_daily_notes_interface2 = __toESM(require_main()); +var WeeklyPeriodicNoteEntry = class extends PeriodicNoteEntry { + constructor(app, openFileOnWrite, sectionPosition, template) { + super(app, openFileOnWrite, sectionPosition, template); + this.notice = "To use a weekly note with Obsidian Clipper the weekly note needs to be enabled from the periodic-notes plugin"; + } + getPeriodicNote(moment, allNotes) { + return (0, import_obsidian_daily_notes_interface2.getWeeklyNote)(moment, allNotes); + } + hasPeriodicNoteEnabled() { + return (0, import_obsidian_daily_notes_interface2.appHasWeeklyNotesPluginLoaded)(); + } + async waitForNoteCreation(moment) { + const weeklyNote = await (0, import_obsidian_daily_notes_interface2.createWeeklyNote)(moment); + await new Promise((r) => setTimeout(r, 50)); + return weeklyNote; + } + getAllNotes() { + return (0, import_obsidian_daily_notes_interface2.getAllWeeklyNotes)(); + } +}; + +// node_modules/svelte/internal/index.mjs +function noop() { +} +var identity = (x) => x; +function assign(tar, src) { + for (const k in src) + tar[k] = src[k]; + return tar; +} +function run(fn2) { + return fn2(); +} +function blank_object() { + return /* @__PURE__ */ Object.create(null); +} +function run_all(fns) { + fns.forEach(run); +} +function is_function(thing) { + return typeof thing === "function"; +} +function safe_not_equal(a, b) { + return a != a ? b == b : a !== b || (a && typeof a === "object" || typeof a === "function"); +} +function is_empty(obj) { + return Object.keys(obj).length === 0; +} +function subscribe(store, ...callbacks) { + if (store == null) { + return noop; + } + const unsub = store.subscribe(...callbacks); + return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; +} +function component_subscribe(component, store, callback) { + component.$$.on_destroy.push(subscribe(store, callback)); +} +function create_slot(definition, ctx, $$scope, fn2) { + if (definition) { + const slot_ctx = get_slot_context(definition, ctx, $$scope, fn2); + return definition[0](slot_ctx); + } +} +function get_slot_context(definition, ctx, $$scope, fn2) { + return definition[1] && fn2 ? assign($$scope.ctx.slice(), definition[1](fn2(ctx))) : $$scope.ctx; +} +function get_slot_changes(definition, $$scope, dirty, fn2) { + if (definition[2] && fn2) { + const lets = definition[2](fn2(dirty)); + if ($$scope.dirty === void 0) { + return lets; + } + if (typeof lets === "object") { + const merged = []; + const len = Math.max($$scope.dirty.length, lets.length); + for (let i = 0; i < len; i += 1) { + merged[i] = $$scope.dirty[i] | lets[i]; + } + return merged; + } + return $$scope.dirty | lets; + } + return $$scope.dirty; +} +function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) { + if (slot_changes) { + const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn); + slot.p(slot_context, slot_changes); + } +} +function get_all_dirty_from_scope($$scope) { + if ($$scope.ctx.length > 32) { + const dirty = []; + const length = $$scope.ctx.length / 32; + for (let i = 0; i < length; i++) { + dirty[i] = -1; + } + return dirty; + } + return -1; +} +function null_to_empty(value) { + return value == null ? "" : value; +} +function set_store_value(store, ret, value) { + store.set(value); + return ret; +} +function action_destroyer(action_result) { + return action_result && is_function(action_result.destroy) ? action_result.destroy : noop; +} +var is_client = typeof window !== "undefined"; +var now = is_client ? () => window.performance.now() : () => Date.now(); +var raf = is_client ? (cb) => requestAnimationFrame(cb) : noop; +var tasks = /* @__PURE__ */ new Set(); +function run_tasks(now2) { + tasks.forEach((task) => { + if (!task.c(now2)) { + tasks.delete(task); + task.f(); + } + }); + if (tasks.size !== 0) + raf(run_tasks); +} +function loop(callback) { + let task; + if (tasks.size === 0) + raf(run_tasks); + return { + promise: new Promise((fulfill) => { + tasks.add(task = { c: callback, f: fulfill }); + }), + abort() { + tasks.delete(task); + } + }; +} +var is_hydrating = false; +function start_hydrating() { + is_hydrating = true; +} +function end_hydrating() { + is_hydrating = false; +} +function append(target, node) { + target.appendChild(node); +} +function append_styles(target, style_sheet_id, styles) { + const append_styles_to = get_root_for_style(target); + if (!append_styles_to.getElementById(style_sheet_id)) { + const style = element("style"); + style.id = style_sheet_id; + style.textContent = styles; + append_stylesheet(append_styles_to, style); + } +} +function get_root_for_style(node) { + if (!node) + return document; + const root = node.getRootNode ? node.getRootNode() : node.ownerDocument; + if (root && root.host) { + return root; + } + return node.ownerDocument; +} +function append_empty_stylesheet(node) { + const style_element = element("style"); + append_stylesheet(get_root_for_style(node), style_element); + return style_element.sheet; +} +function append_stylesheet(node, style) { + append(node.head || node, style); + return style.sheet; +} +function insert(target, node, anchor) { + target.insertBefore(node, anchor || null); +} +function detach(node) { + if (node.parentNode) { + node.parentNode.removeChild(node); + } +} +function destroy_each(iterations, detaching) { + for (let i = 0; i < iterations.length; i += 1) { + if (iterations[i]) + iterations[i].d(detaching); + } +} +function element(name) { + return document.createElement(name); +} +function text(data) { + return document.createTextNode(data); +} +function space() { + return text(" "); +} +function empty() { + return text(""); +} +function listen(node, event, handler, options) { + node.addEventListener(event, handler, options); + return () => node.removeEventListener(event, handler, options); +} +function attr(node, attribute, value) { + if (value == null) + node.removeAttribute(attribute); + else if (node.getAttribute(attribute) !== value) + node.setAttribute(attribute, value); +} +function children(element2) { + return Array.from(element2.childNodes); +} +function set_data(text2, data) { + data = "" + data; + if (text2.wholeText !== data) + text2.data = data; +} +function set_input_value(input, value) { + input.value = value == null ? "" : value; +} +function set_style(node, key, value, important) { + if (value === null) { + node.style.removeProperty(key); + } else { + node.style.setProperty(key, value, important ? "important" : ""); + } +} +function select_option(select, value) { + for (let i = 0; i < select.options.length; i += 1) { + const option = select.options[i]; + if (option.__value === value) { + option.selected = true; + return; + } + } + select.selectedIndex = -1; +} +function select_value(select) { + const selected_option = select.querySelector(":checked") || select.options[0]; + return selected_option && selected_option.__value; +} +function toggle_class(element2, name, toggle) { + element2.classList[toggle ? "add" : "remove"](name); +} +function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) { + const e = document.createEvent("CustomEvent"); + e.initCustomEvent(type, bubbles, cancelable, detail); + return e; +} +function construct_svelte_component(component, props) { + return new component(props); +} +var managed_styles = /* @__PURE__ */ new Map(); +var active = 0; +function hash(str) { + let hash4 = 5381; + let i = str.length; + while (i--) + hash4 = (hash4 << 5) - hash4 ^ str.charCodeAt(i); + return hash4 >>> 0; +} +function create_style_information(doc, node) { + const info = { stylesheet: append_empty_stylesheet(node), rules: {} }; + managed_styles.set(doc, info); + return info; +} +function create_rule(node, a, b, duration, delay, ease, fn2, uid = 0) { + const step = 16.666 / duration; + let keyframes = "{\n"; + for (let p = 0; p <= 1; p += step) { + const t = a + (b - a) * ease(p); + keyframes += p * 100 + `%{${fn2(t, 1 - t)}} +`; + } + const rule = keyframes + `100% {${fn2(b, 1 - b)}} +}`; + const name = `__svelte_${hash(rule)}_${uid}`; + const doc = get_root_for_style(node); + const { stylesheet, rules } = managed_styles.get(doc) || create_style_information(doc, node); + if (!rules[name]) { + rules[name] = true; + stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length); + } + const animation = node.style.animation || ""; + node.style.animation = `${animation ? `${animation}, ` : ""}${name} ${duration}ms linear ${delay}ms 1 both`; + active += 1; + return name; +} +function delete_rule(node, name) { + const previous = (node.style.animation || "").split(", "); + const next = previous.filter(name ? (anim) => anim.indexOf(name) < 0 : (anim) => anim.indexOf("__svelte") === -1); + const deleted = previous.length - next.length; + if (deleted) { + node.style.animation = next.join(", "); + active -= deleted; + if (!active) + clear_rules(); + } +} +function clear_rules() { + raf(() => { + if (active) + return; + managed_styles.forEach((info) => { + const { ownerNode } = info.stylesheet; + if (ownerNode) + detach(ownerNode); + }); + managed_styles.clear(); + }); +} +var current_component; +function set_current_component(component) { + current_component = component; +} +function get_current_component() { + if (!current_component) + throw new Error("Function called outside component initialization"); + return current_component; +} +function onDestroy(fn2) { + get_current_component().$$.on_destroy.push(fn2); +} +function bubble(component, event) { + const callbacks = component.$$.callbacks[event.type]; + if (callbacks) { + callbacks.slice().forEach((fn2) => fn2.call(this, event)); + } +} +var dirty_components = []; +var binding_callbacks = []; +var render_callbacks = []; +var flush_callbacks = []; +var resolved_promise = Promise.resolve(); +var update_scheduled = false; +function schedule_update() { + if (!update_scheduled) { + update_scheduled = true; + resolved_promise.then(flush); + } +} +function add_render_callback(fn2) { + render_callbacks.push(fn2); +} +var seen_callbacks = /* @__PURE__ */ new Set(); +var flushidx = 0; +function flush() { + if (flushidx !== 0) { + return; + } + const saved_component = current_component; + do { + try { + while (flushidx < dirty_components.length) { + const component = dirty_components[flushidx]; + flushidx++; + set_current_component(component); + update(component.$$); + } + } catch (e) { + dirty_components.length = 0; + flushidx = 0; + throw e; + } + set_current_component(null); + dirty_components.length = 0; + flushidx = 0; + while (binding_callbacks.length) + binding_callbacks.pop()(); + for (let i = 0; i < render_callbacks.length; i += 1) { + const callback = render_callbacks[i]; + if (!seen_callbacks.has(callback)) { + seen_callbacks.add(callback); + callback(); + } + } + render_callbacks.length = 0; + } while (dirty_components.length); + while (flush_callbacks.length) { + flush_callbacks.pop()(); + } + update_scheduled = false; + seen_callbacks.clear(); + set_current_component(saved_component); +} +function update($$) { + if ($$.fragment !== null) { + $$.update(); + run_all($$.before_update); + const dirty = $$.dirty; + $$.dirty = [-1]; + $$.fragment && $$.fragment.p($$.ctx, dirty); + $$.after_update.forEach(add_render_callback); + } +} +var promise; +function wait() { + if (!promise) { + promise = Promise.resolve(); + promise.then(() => { + promise = null; + }); + } + return promise; +} +function dispatch(node, direction, kind) { + node.dispatchEvent(custom_event(`${direction ? "intro" : "outro"}${kind}`)); +} +var outroing = /* @__PURE__ */ new Set(); +var outros; +function group_outros() { + outros = { + r: 0, + c: [], + p: outros + }; +} +function check_outros() { + if (!outros.r) { + run_all(outros.c); + } + outros = outros.p; +} +function transition_in(block, local) { + if (block && block.i) { + outroing.delete(block); + block.i(local); + } +} +function transition_out(block, local, detach2, callback) { + if (block && block.o) { + if (outroing.has(block)) + return; + outroing.add(block); + outros.c.push(() => { + outroing.delete(block); + if (callback) { + if (detach2) + block.d(1); + callback(); + } + }); + block.o(local); + } else if (callback) { + callback(); + } +} +var null_transition = { duration: 0 }; +function create_in_transition(node, fn2, params) { + const options = { direction: "in" }; + let config = fn2(node, params, options); + let running = false; + let animation_name; + let task; + let uid = 0; + function cleanup() { + if (animation_name) + delete_rule(node, animation_name); + } + function go() { + const { delay = 0, duration = 300, easing = identity, tick: tick2 = noop, css } = config || null_transition; + if (css) + animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++); + tick2(0, 1); + const start_time = now() + delay; + const end_time = start_time + duration; + if (task) + task.abort(); + running = true; + add_render_callback(() => dispatch(node, true, "start")); + task = loop((now2) => { + if (running) { + if (now2 >= end_time) { + tick2(1, 0); + dispatch(node, true, "end"); + cleanup(); + return running = false; + } + if (now2 >= start_time) { + const t = easing((now2 - start_time) / duration); + tick2(t, 1 - t); + } + } + return running; + }); + } + let started = false; + return { + start() { + if (started) + return; + started = true; + delete_rule(node); + if (is_function(config)) { + config = config(options); + wait().then(go); + } else { + go(); + } + }, + invalidate() { + started = false; + }, + end() { + if (running) { + cleanup(); + running = false; + } + } + }; +} +function create_out_transition(node, fn2, params) { + const options = { direction: "out" }; + let config = fn2(node, params, options); + let running = true; + let animation_name; + const group = outros; + group.r += 1; + function go() { + const { delay = 0, duration = 300, easing = identity, tick: tick2 = noop, css } = config || null_transition; + if (css) + animation_name = create_rule(node, 1, 0, duration, delay, easing, css); + const start_time = now() + delay; + const end_time = start_time + duration; + add_render_callback(() => dispatch(node, false, "start")); + loop((now2) => { + if (running) { + if (now2 >= end_time) { + tick2(0, 1); + dispatch(node, false, "end"); + if (!--group.r) { + run_all(group.c); + } + return false; + } + if (now2 >= start_time) { + const t = easing((now2 - start_time) / duration); + tick2(1 - t, t); + } + } + return running; + }); + } + if (is_function(config)) { + wait().then(() => { + config = config(options); + go(); + }); + } else { + go(); + } + return { + end(reset) { + if (reset && config.tick) { + config.tick(1, 0); + } + if (running) { + if (animation_name) + delete_rule(node, animation_name); + running = false; + } + } + }; +} +var globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : global; +function get_spread_update(levels, updates) { + const update2 = {}; + const to_null_out = {}; + const accounted_for = { $$scope: 1 }; + let i = levels.length; + while (i--) { + const o = levels[i]; + const n = updates[i]; + if (n) { + for (const key in o) { + if (!(key in n)) + to_null_out[key] = 1; + } + for (const key in n) { + if (!accounted_for[key]) { + update2[key] = n[key]; + accounted_for[key] = 1; + } + } + levels[i] = n; + } else { + for (const key in o) { + accounted_for[key] = 1; + } + } + } + for (const key in to_null_out) { + if (!(key in update2)) + update2[key] = void 0; + } + return update2; +} +function get_spread_object(spread_props) { + return typeof spread_props === "object" && spread_props !== null ? spread_props : {}; +} +function create_component(block) { + block && block.c(); +} +function mount_component(component, target, anchor, customElement) { + const { fragment, after_update } = component.$$; + fragment && fragment.m(target, anchor); + if (!customElement) { + add_render_callback(() => { + const new_on_destroy = component.$$.on_mount.map(run).filter(is_function); + if (component.$$.on_destroy) { + component.$$.on_destroy.push(...new_on_destroy); + } else { + run_all(new_on_destroy); + } + component.$$.on_mount = []; + }); + } + after_update.forEach(add_render_callback); +} +function destroy_component(component, detaching) { + const $$ = component.$$; + if ($$.fragment !== null) { + run_all($$.on_destroy); + $$.fragment && $$.fragment.d(detaching); + $$.on_destroy = $$.fragment = null; + $$.ctx = []; + } +} +function make_dirty(component, i) { + if (component.$$.dirty[0] === -1) { + dirty_components.push(component); + schedule_update(); + component.$$.dirty.fill(0); + } + component.$$.dirty[i / 31 | 0] |= 1 << i % 31; +} +function init(component, options, instance16, create_fragment16, not_equal, props, append_styles2, dirty = [-1]) { + const parent_component = current_component; + set_current_component(component); + const $$ = component.$$ = { + fragment: null, + ctx: [], + props, + update: noop, + not_equal, + bound: blank_object(), + on_mount: [], + on_destroy: [], + on_disconnect: [], + before_update: [], + after_update: [], + context: new Map(options.context || (parent_component ? parent_component.$$.context : [])), + callbacks: blank_object(), + dirty, + skip_bound: false, + root: options.target || parent_component.$$.root + }; + append_styles2 && append_styles2($$.root); + let ready = false; + $$.ctx = instance16 ? instance16(component, options.props || {}, (i, ret, ...rest) => { + const value = rest.length ? rest[0] : ret; + if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { + if (!$$.skip_bound && $$.bound[i]) + $$.bound[i](value); + if (ready) + make_dirty(component, i); + } + return ret; + }) : []; + $$.update(); + ready = true; + run_all($$.before_update); + $$.fragment = create_fragment16 ? create_fragment16($$.ctx) : false; + if (options.target) { + if (options.hydrate) { + start_hydrating(); + const nodes = children(options.target); + $$.fragment && $$.fragment.l(nodes); + nodes.forEach(detach); + } else { + $$.fragment && $$.fragment.c(); + } + if (options.intro) + transition_in(component.$$.fragment); + mount_component(component, options.target, options.anchor, options.customElement); + end_hydrating(); + flush(); + } + set_current_component(parent_component); +} +var SvelteElement; +if (typeof HTMLElement === "function") { + SvelteElement = class extends HTMLElement { + constructor() { + super(); + this.attachShadow({ mode: "open" }); + } + connectedCallback() { + const { on_mount } = this.$$; + this.$$.on_disconnect = on_mount.map(run).filter(is_function); + for (const key in this.$$.slotted) { + this.appendChild(this.$$.slotted[key]); + } + } + attributeChangedCallback(attr2, _oldValue, newValue) { + this[attr2] = newValue; + } + disconnectedCallback() { + run_all(this.$$.on_disconnect); + } + $destroy() { + destroy_component(this, 1); + this.$destroy = noop; + } + $on(type, callback) { + if (!is_function(callback)) { + return noop; + } + const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); + callbacks.push(callback); + return () => { + const index = callbacks.indexOf(callback); + if (index !== -1) + callbacks.splice(index, 1); + }; + } + $set($$props) { + if (this.$$set && !is_empty($$props)) { + this.$$.skip_bound = true; + this.$$set($$props); + this.$$.skip_bound = false; + } + } + }; +} +var SvelteComponent = class { + $destroy() { + destroy_component(this, 1); + this.$destroy = noop; + } + $on(type, callback) { + if (!is_function(callback)) { + return noop; + } + const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []); + callbacks.push(callback); + return () => { + const index = callbacks.indexOf(callback); + if (index !== -1) + callbacks.splice(index, 1); + }; + } + $set($$props) { + if (this.$$set && !is_empty($$props)) { + this.$$.skip_bound = true; + this.$$set($$props); + this.$$.skip_bound = false; + } + } +}; + +// node_modules/svelte/easing/index.mjs +function cubicOut(t) { + const f = t - 1; + return f * f * f + 1; +} + +// node_modules/svelte/transition/index.mjs +function slide(node, { delay = 0, duration = 400, easing = cubicOut } = {}) { + const style = getComputedStyle(node); + const opacity = +style.opacity; + const height = parseFloat(style.height); + const padding_top = parseFloat(style.paddingTop); + const padding_bottom = parseFloat(style.paddingBottom); + const margin_top = parseFloat(style.marginTop); + const margin_bottom = parseFloat(style.marginBottom); + const border_top_width = parseFloat(style.borderTopWidth); + const border_bottom_width = parseFloat(style.borderBottomWidth); + return { + delay, + duration, + easing, + css: (t) => `overflow: hidden;opacity: ${Math.min(t * 20, 1) * opacity};height: ${t * height}px;padding-top: ${t * padding_top}px;padding-bottom: ${t * padding_bottom}px;margin-top: ${t * margin_top}px;margin-bottom: ${t * margin_bottom}px;border-top-width: ${t * border_top_width}px;border-bottom-width: ${t * border_bottom_width}px;` + }; +} + +// node_modules/@popperjs/core/lib/enums.js +var top = "top"; +var bottom = "bottom"; +var right = "right"; +var left = "left"; +var auto = "auto"; +var basePlacements = [top, bottom, right, left]; +var start = "start"; +var end = "end"; +var clippingParents = "clippingParents"; +var viewport = "viewport"; +var popper = "popper"; +var reference = "reference"; +var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) { + return acc.concat([placement + "-" + start, placement + "-" + end]); +}, []); +var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) { + return acc.concat([placement, placement + "-" + start, placement + "-" + end]); +}, []); +var beforeRead = "beforeRead"; +var read = "read"; +var afterRead = "afterRead"; +var beforeMain = "beforeMain"; +var main = "main"; +var afterMain = "afterMain"; +var beforeWrite = "beforeWrite"; +var write = "write"; +var afterWrite = "afterWrite"; +var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; + +// node_modules/@popperjs/core/lib/dom-utils/getNodeName.js +function getNodeName(element2) { + return element2 ? (element2.nodeName || "").toLowerCase() : null; +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindow.js +function getWindow(node) { + if (node == null) { + return window; + } + if (node.toString() !== "[object Window]") { + var ownerDocument = node.ownerDocument; + return ownerDocument ? ownerDocument.defaultView || window : window; + } + return node; +} + +// node_modules/@popperjs/core/lib/dom-utils/instanceOf.js +function isElement(node) { + var OwnElement = getWindow(node).Element; + return node instanceof OwnElement || node instanceof Element; +} +function isHTMLElement(node) { + var OwnElement = getWindow(node).HTMLElement; + return node instanceof OwnElement || node instanceof HTMLElement; +} +function isShadowRoot(node) { + if (typeof ShadowRoot === "undefined") { + return false; + } + var OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; +} + +// node_modules/@popperjs/core/lib/modifiers/applyStyles.js +function applyStyles(_ref) { + var state = _ref.state; + Object.keys(state.elements).forEach(function(name) { + var style = state.styles[name] || {}; + var attributes = state.attributes[name] || {}; + var element2 = state.elements[name]; + if (!isHTMLElement(element2) || !getNodeName(element2)) { + return; + } + Object.assign(element2.style, style); + Object.keys(attributes).forEach(function(name2) { + var value = attributes[name2]; + if (value === false) { + element2.removeAttribute(name2); + } else { + element2.setAttribute(name2, value === true ? "" : value); + } + }); + }); +} +function effect(_ref2) { + var state = _ref2.state; + var initialStyles = { + popper: { + position: state.options.strategy, + left: "0", + top: "0", + margin: "0" + }, + arrow: { + position: "absolute" + }, + reference: {} + }; + Object.assign(state.elements.popper.style, initialStyles.popper); + state.styles = initialStyles; + if (state.elements.arrow) { + Object.assign(state.elements.arrow.style, initialStyles.arrow); + } + return function() { + Object.keys(state.elements).forEach(function(name) { + var element2 = state.elements[name]; + var attributes = state.attributes[name] || {}; + var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); + var style = styleProperties.reduce(function(style2, property) { + style2[property] = ""; + return style2; + }, {}); + if (!isHTMLElement(element2) || !getNodeName(element2)) { + return; + } + Object.assign(element2.style, style); + Object.keys(attributes).forEach(function(attribute) { + element2.removeAttribute(attribute); + }); + }); + }; +} +var applyStyles_default = { + name: "applyStyles", + enabled: true, + phase: "write", + fn: applyStyles, + effect, + requires: ["computeStyles"] +}; + +// node_modules/@popperjs/core/lib/utils/getBasePlacement.js +function getBasePlacement(placement) { + return placement.split("-")[0]; +} + +// node_modules/@popperjs/core/lib/utils/math.js +var max = Math.max; +var min = Math.min; +var round = Math.round; + +// node_modules/@popperjs/core/lib/utils/userAgent.js +function getUAString() { + var uaData = navigator.userAgentData; + if (uaData != null && uaData.brands) { + return uaData.brands.map(function(item) { + return item.brand + "/" + item.version; + }).join(" "); + } + return navigator.userAgent; +} + +// node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js +function isLayoutViewport() { + return !/^((?!chrome|android).)*safari/i.test(getUAString()); +} + +// node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js +function getBoundingClientRect(element2, includeScale, isFixedStrategy) { + if (includeScale === void 0) { + includeScale = false; + } + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + var clientRect = element2.getBoundingClientRect(); + var scaleX = 1; + var scaleY = 1; + if (includeScale && isHTMLElement(element2)) { + scaleX = element2.offsetWidth > 0 ? round(clientRect.width) / element2.offsetWidth || 1 : 1; + scaleY = element2.offsetHeight > 0 ? round(clientRect.height) / element2.offsetHeight || 1 : 1; + } + var _ref = isElement(element2) ? getWindow(element2) : window, visualViewport = _ref.visualViewport; + var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; + var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; + var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; + var width = clientRect.width / scaleX; + var height = clientRect.height / scaleY; + return { + width, + height, + top: y, + right: x + width, + bottom: y + height, + left: x, + x, + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js +function getLayoutRect(element2) { + var clientRect = getBoundingClientRect(element2); + var width = element2.offsetWidth; + var height = element2.offsetHeight; + if (Math.abs(clientRect.width - width) <= 1) { + width = clientRect.width; + } + if (Math.abs(clientRect.height - height) <= 1) { + height = clientRect.height; + } + return { + x: element2.offsetLeft, + y: element2.offsetTop, + width, + height + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/contains.js +function contains(parent, child) { + var rootNode = child.getRootNode && child.getRootNode(); + if (parent.contains(child)) { + return true; + } else if (rootNode && isShadowRoot(rootNode)) { + var next = child; + do { + if (next && parent.isSameNode(next)) { + return true; + } + next = next.parentNode || next.host; + } while (next); + } + return false; +} + +// node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js +function getComputedStyle2(element2) { + return getWindow(element2).getComputedStyle(element2); +} + +// node_modules/@popperjs/core/lib/dom-utils/isTableElement.js +function isTableElement(element2) { + return ["table", "td", "th"].indexOf(getNodeName(element2)) >= 0; +} + +// node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js +function getDocumentElement(element2) { + return ((isElement(element2) ? element2.ownerDocument : element2.document) || window.document).documentElement; +} + +// node_modules/@popperjs/core/lib/dom-utils/getParentNode.js +function getParentNode(element2) { + if (getNodeName(element2) === "html") { + return element2; + } + return element2.assignedSlot || element2.parentNode || (isShadowRoot(element2) ? element2.host : null) || getDocumentElement(element2); +} + +// node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js +function getTrueOffsetParent(element2) { + if (!isHTMLElement(element2) || getComputedStyle2(element2).position === "fixed") { + return null; + } + return element2.offsetParent; +} +function getContainingBlock(element2) { + var isFirefox = /firefox/i.test(getUAString()); + var isIE = /Trident/i.test(getUAString()); + if (isIE && isHTMLElement(element2)) { + var elementCss = getComputedStyle2(element2); + if (elementCss.position === "fixed") { + return null; + } + } + var currentNode = getParentNode(element2); + if (isShadowRoot(currentNode)) { + currentNode = currentNode.host; + } + while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) { + var css = getComputedStyle2(currentNode); + if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") { + return currentNode; + } else { + currentNode = currentNode.parentNode; + } + } + return null; +} +function getOffsetParent(element2) { + var window2 = getWindow(element2); + var offsetParent = getTrueOffsetParent(element2); + while (offsetParent && isTableElement(offsetParent) && getComputedStyle2(offsetParent).position === "static") { + offsetParent = getTrueOffsetParent(offsetParent); + } + if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle2(offsetParent).position === "static")) { + return window2; + } + return offsetParent || getContainingBlock(element2) || window2; +} + +// node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js +function getMainAxisFromPlacement(placement) { + return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y"; +} + +// node_modules/@popperjs/core/lib/utils/within.js +function within(min2, value, max2) { + return max(min2, min(value, max2)); +} +function withinMaxClamp(min2, value, max2) { + var v = within(min2, value, max2); + return v > max2 ? max2 : v; +} + +// node_modules/@popperjs/core/lib/utils/getFreshSideObject.js +function getFreshSideObject() { + return { + top: 0, + right: 0, + bottom: 0, + left: 0 + }; +} + +// node_modules/@popperjs/core/lib/utils/mergePaddingObject.js +function mergePaddingObject(paddingObject) { + return Object.assign({}, getFreshSideObject(), paddingObject); +} + +// node_modules/@popperjs/core/lib/utils/expandToHashMap.js +function expandToHashMap(value, keys) { + return keys.reduce(function(hashMap, key) { + hashMap[key] = value; + return hashMap; + }, {}); +} + +// node_modules/@popperjs/core/lib/modifiers/arrow.js +var toPaddingObject = function toPaddingObject2(padding, state) { + padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, { + placement: state.placement + })) : padding; + return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); +}; +function arrow(_ref) { + var _state$modifiersData$; + var state = _ref.state, name = _ref.name, options = _ref.options; + var arrowElement = state.elements.arrow; + var popperOffsets2 = state.modifiersData.popperOffsets; + var basePlacement = getBasePlacement(state.placement); + var axis = getMainAxisFromPlacement(basePlacement); + var isVertical = [left, right].indexOf(basePlacement) >= 0; + var len = isVertical ? "height" : "width"; + if (!arrowElement || !popperOffsets2) { + return; + } + var paddingObject = toPaddingObject(options.padding, state); + var arrowRect = getLayoutRect(arrowElement); + var minProp = axis === "y" ? top : left; + var maxProp = axis === "y" ? bottom : right; + var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len]; + var startDiff = popperOffsets2[axis] - state.rects.reference[axis]; + var arrowOffsetParent = getOffsetParent(arrowElement); + var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; + var centerToReference = endDiff / 2 - startDiff / 2; + var min2 = paddingObject[minProp]; + var max2 = clientSize - arrowRect[len] - paddingObject[maxProp]; + var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; + var offset2 = within(min2, center, max2); + var axisProp = axis; + state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$); +} +function effect2(_ref2) { + var state = _ref2.state, options = _ref2.options; + var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element; + if (arrowElement == null) { + return; + } + if (typeof arrowElement === "string") { + arrowElement = state.elements.popper.querySelector(arrowElement); + if (!arrowElement) { + return; + } + } + if (true) { + if (!isHTMLElement(arrowElement)) { + console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', "To use an SVG arrow, wrap it in an HTMLElement that will be used as", "the arrow."].join(" ")); + } + } + if (!contains(state.elements.popper, arrowElement)) { + if (true) { + console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', "element."].join(" ")); + } + return; + } + state.elements.arrow = arrowElement; +} +var arrow_default = { + name: "arrow", + enabled: true, + phase: "main", + fn: arrow, + effect: effect2, + requires: ["popperOffsets"], + requiresIfExists: ["preventOverflow"] +}; + +// node_modules/@popperjs/core/lib/utils/getVariation.js +function getVariation(placement) { + return placement.split("-")[1]; +} + +// node_modules/@popperjs/core/lib/modifiers/computeStyles.js +var unsetSides = { + top: "auto", + right: "auto", + bottom: "auto", + left: "auto" +}; +function roundOffsetsByDPR(_ref) { + var x = _ref.x, y = _ref.y; + var win = window; + var dpr = win.devicePixelRatio || 1; + return { + x: round(x * dpr) / dpr || 0, + y: round(y * dpr) / dpr || 0 + }; +} +function mapToStyles(_ref2) { + var _Object$assign2; + var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed; + var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y; + var _ref3 = typeof roundOffsets === "function" ? roundOffsets({ + x, + y + }) : { + x, + y + }; + x = _ref3.x; + y = _ref3.y; + var hasX = offsets.hasOwnProperty("x"); + var hasY = offsets.hasOwnProperty("y"); + var sideX = left; + var sideY = top; + var win = window; + if (adaptive) { + var offsetParent = getOffsetParent(popper2); + var heightProp = "clientHeight"; + var widthProp = "clientWidth"; + if (offsetParent === getWindow(popper2)) { + offsetParent = getDocumentElement(popper2); + if (getComputedStyle2(offsetParent).position !== "static" && position === "absolute") { + heightProp = "scrollHeight"; + widthProp = "scrollWidth"; + } + } + offsetParent = offsetParent; + if (placement === top || (placement === left || placement === right) && variation === end) { + sideY = bottom; + var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : offsetParent[heightProp]; + y -= offsetY - popperRect.height; + y *= gpuAcceleration ? 1 : -1; + } + if (placement === left || (placement === top || placement === bottom) && variation === end) { + sideX = right; + var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : offsetParent[widthProp]; + x -= offsetX - popperRect.width; + x *= gpuAcceleration ? 1 : -1; + } + } + var commonStyles = Object.assign({ + position + }, adaptive && unsetSides); + var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ + x, + y + }) : { + x, + y + }; + x = _ref4.x; + y = _ref4.y; + if (gpuAcceleration) { + var _Object$assign; + return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); + } + return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2)); +} +function computeStyles(_ref5) { + var state = _ref5.state, options = _ref5.options; + var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; + if (true) { + var transitionProperty = getComputedStyle2(state.elements.popper).transitionProperty || ""; + if (adaptive && ["transform", "top", "right", "bottom", "left"].some(function(property) { + return transitionProperty.indexOf(property) >= 0; + })) { + console.warn(["Popper: Detected CSS transitions on at least one of the following", 'CSS properties: "transform", "top", "right", "bottom", "left".', "\n\n", 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', "for smooth transitions, or remove these properties from the CSS", "transition declaration on the popper element if only transitioning", "opacity or background-color for example.", "\n\n", "We recommend using the popper element as a wrapper around an inner", "element that can have any CSS property transitioned for animations."].join(" ")); + } + } + var commonStyles = { + placement: getBasePlacement(state.placement), + variation: getVariation(state.placement), + popper: state.elements.popper, + popperRect: state.rects.popper, + gpuAcceleration, + isFixed: state.options.strategy === "fixed" + }; + if (state.modifiersData.popperOffsets != null) { + state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.popperOffsets, + position: state.options.strategy, + adaptive, + roundOffsets + }))); + } + if (state.modifiersData.arrow != null) { + state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.arrow, + position: "absolute", + adaptive: false, + roundOffsets + }))); + } + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-placement": state.placement + }); +} +var computeStyles_default = { + name: "computeStyles", + enabled: true, + phase: "beforeWrite", + fn: computeStyles, + data: {} +}; + +// node_modules/@popperjs/core/lib/modifiers/eventListeners.js +var passive = { + passive: true +}; +function effect3(_ref) { + var state = _ref.state, instance16 = _ref.instance, options = _ref.options; + var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize; + var window2 = getWindow(state.elements.popper); + var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.addEventListener("scroll", instance16.update, passive); + }); + } + if (resize) { + window2.addEventListener("resize", instance16.update, passive); + } + return function() { + if (scroll) { + scrollParents.forEach(function(scrollParent) { + scrollParent.removeEventListener("scroll", instance16.update, passive); + }); + } + if (resize) { + window2.removeEventListener("resize", instance16.update, passive); + } + }; +} +var eventListeners_default = { + name: "eventListeners", + enabled: true, + phase: "write", + fn: function fn() { + }, + effect: effect3, + data: {} +}; + +// node_modules/@popperjs/core/lib/utils/getOppositePlacement.js +var hash2 = { + left: "right", + right: "left", + bottom: "top", + top: "bottom" +}; +function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, function(matched) { + return hash2[matched]; + }); +} + +// node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js +var hash3 = { + start: "end", + end: "start" +}; +function getOppositeVariationPlacement(placement) { + return placement.replace(/start|end/g, function(matched) { + return hash3[matched]; + }); +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js +function getWindowScroll(node) { + var win = getWindow(node); + var scrollLeft = win.pageXOffset; + var scrollTop = win.pageYOffset; + return { + scrollLeft, + scrollTop + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js +function getWindowScrollBarX(element2) { + return getBoundingClientRect(getDocumentElement(element2)).left + getWindowScroll(element2).scrollLeft; +} + +// node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js +function getViewportRect(element2, strategy) { + var win = getWindow(element2); + var html = getDocumentElement(element2); + var visualViewport = win.visualViewport; + var width = html.clientWidth; + var height = html.clientHeight; + var x = 0; + var y = 0; + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + var layoutViewport = isLayoutViewport(); + if (layoutViewport || !layoutViewport && strategy === "fixed") { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + return { + width, + height, + x: x + getWindowScrollBarX(element2), + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js +function getDocumentRect(element2) { + var _element$ownerDocumen; + var html = getDocumentElement(element2); + var winScroll = getWindowScroll(element2); + var body = (_element$ownerDocumen = element2.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; + var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); + var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); + var x = -winScroll.scrollLeft + getWindowScrollBarX(element2); + var y = -winScroll.scrollTop; + if (getComputedStyle2(body || html).direction === "rtl") { + x += max(html.clientWidth, body ? body.clientWidth : 0) - width; + } + return { + width, + height, + x, + y + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js +function isScrollParent(element2) { + var _getComputedStyle = getComputedStyle2(element2), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; + return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); +} + +// node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js +function getScrollParent(node) { + if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) { + return node.ownerDocument.body; + } + if (isHTMLElement(node) && isScrollParent(node)) { + return node; + } + return getScrollParent(getParentNode(node)); +} + +// node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js +function listScrollParents(element2, list) { + var _element$ownerDocumen; + if (list === void 0) { + list = []; + } + var scrollParent = getScrollParent(element2); + var isBody = scrollParent === ((_element$ownerDocumen = element2.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); + var win = getWindow(scrollParent); + var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; + var updatedList = list.concat(target); + return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target))); +} + +// node_modules/@popperjs/core/lib/utils/rectToClientRect.js +function rectToClientRect(rect) { + return Object.assign({}, rect, { + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height + }); +} + +// node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js +function getInnerBoundingClientRect(element2, strategy) { + var rect = getBoundingClientRect(element2, false, strategy === "fixed"); + rect.top = rect.top + element2.clientTop; + rect.left = rect.left + element2.clientLeft; + rect.bottom = rect.top + element2.clientHeight; + rect.right = rect.left + element2.clientWidth; + rect.width = element2.clientWidth; + rect.height = element2.clientHeight; + rect.x = rect.left; + rect.y = rect.top; + return rect; +} +function getClientRectFromMixedType(element2, clippingParent, strategy) { + return clippingParent === viewport ? rectToClientRect(getViewportRect(element2, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element2))); +} +function getClippingParents(element2) { + var clippingParents2 = listScrollParents(getParentNode(element2)); + var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle2(element2).position) >= 0; + var clipperElement = canEscapeClipping && isHTMLElement(element2) ? getOffsetParent(element2) : element2; + if (!isElement(clipperElement)) { + return []; + } + return clippingParents2.filter(function(clippingParent) { + return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body"; + }); +} +function getClippingRect(element2, boundary, rootBoundary, strategy) { + var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element2) : [].concat(boundary); + var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]); + var firstClippingParent = clippingParents2[0]; + var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) { + var rect = getClientRectFromMixedType(element2, clippingParent, strategy); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromMixedType(element2, firstClippingParent, strategy)); + clippingRect.width = clippingRect.right - clippingRect.left; + clippingRect.height = clippingRect.bottom - clippingRect.top; + clippingRect.x = clippingRect.left; + clippingRect.y = clippingRect.top; + return clippingRect; +} + +// node_modules/@popperjs/core/lib/utils/computeOffsets.js +function computeOffsets(_ref) { + var reference2 = _ref.reference, element2 = _ref.element, placement = _ref.placement; + var basePlacement = placement ? getBasePlacement(placement) : null; + var variation = placement ? getVariation(placement) : null; + var commonX = reference2.x + reference2.width / 2 - element2.width / 2; + var commonY = reference2.y + reference2.height / 2 - element2.height / 2; + var offsets; + switch (basePlacement) { + case top: + offsets = { + x: commonX, + y: reference2.y - element2.height + }; + break; + case bottom: + offsets = { + x: commonX, + y: reference2.y + reference2.height + }; + break; + case right: + offsets = { + x: reference2.x + reference2.width, + y: commonY + }; + break; + case left: + offsets = { + x: reference2.x - element2.width, + y: commonY + }; + break; + default: + offsets = { + x: reference2.x, + y: reference2.y + }; + } + var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; + if (mainAxis != null) { + var len = mainAxis === "y" ? "height" : "width"; + switch (variation) { + case start: + offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element2[len] / 2); + break; + case end: + offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element2[len] / 2); + break; + default: + } + } + return offsets; +} + +// node_modules/@popperjs/core/lib/utils/detectOverflow.js +function detectOverflow(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding; + var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); + var altContext = elementContext === popper ? reference : popper; + var popperRect = state.rects.popper; + var element2 = state.elements[altBoundary ? altContext : elementContext]; + var clippingClientRect = getClippingRect(isElement(element2) ? element2 : element2.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); + var referenceClientRect = getBoundingClientRect(state.elements.reference); + var popperOffsets2 = computeOffsets({ + reference: referenceClientRect, + element: popperRect, + strategy: "absolute", + placement + }); + var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2)); + var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; + var overflowOffsets = { + top: clippingClientRect.top - elementClientRect.top + paddingObject.top, + bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, + left: clippingClientRect.left - elementClientRect.left + paddingObject.left, + right: elementClientRect.right - clippingClientRect.right + paddingObject.right + }; + var offsetData = state.modifiersData.offset; + if (elementContext === popper && offsetData) { + var offset2 = offsetData[placement]; + Object.keys(overflowOffsets).forEach(function(key) { + var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; + var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x"; + overflowOffsets[key] += offset2[axis] * multiply; + }); + } + return overflowOffsets; +} + +// node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js +function computeAutoPlacement(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; + var variation = getVariation(placement); + var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) { + return getVariation(placement2) === variation; + }) : basePlacements; + var allowedPlacements = placements2.filter(function(placement2) { + return allowedAutoPlacements.indexOf(placement2) >= 0; + }); + if (allowedPlacements.length === 0) { + allowedPlacements = placements2; + if (true) { + console.error(["Popper: The `allowedAutoPlacements` option did not allow any", "placements. Ensure the `placement` option matches the variation", "of the allowed placements.", 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(" ")); + } + } + var overflows = allowedPlacements.reduce(function(acc, placement2) { + acc[placement2] = detectOverflow(state, { + placement: placement2, + boundary, + rootBoundary, + padding + })[getBasePlacement(placement2)]; + return acc; + }, {}); + return Object.keys(overflows).sort(function(a, b) { + return overflows[a] - overflows[b]; + }); +} + +// node_modules/@popperjs/core/lib/modifiers/flip.js +function getExpandedFallbackPlacements(placement) { + if (getBasePlacement(placement) === auto) { + return []; + } + var oppositePlacement = getOppositePlacement(placement); + return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; +} +function flip(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + if (state.modifiersData[name]._skip) { + return; + } + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements; + var preferredPlacement = state.options.placement; + var basePlacement = getBasePlacement(preferredPlacement); + var isBasePlacement = basePlacement === preferredPlacement; + var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); + var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) { + return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, { + placement: placement2, + boundary, + rootBoundary, + padding, + flipVariations, + allowedAutoPlacements + }) : placement2); + }, []); + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var checksMap = /* @__PURE__ */ new Map(); + var makeFallbackChecks = true; + var firstFittingPlacement = placements2[0]; + for (var i = 0; i < placements2.length; i++) { + var placement = placements2[i]; + var _basePlacement = getBasePlacement(placement); + var isStartVariation = getVariation(placement) === start; + var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; + var len = isVertical ? "width" : "height"; + var overflow = detectOverflow(state, { + placement, + boundary, + rootBoundary, + altBoundary, + padding + }); + var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; + if (referenceRect[len] > popperRect[len]) { + mainVariationSide = getOppositePlacement(mainVariationSide); + } + var altVariationSide = getOppositePlacement(mainVariationSide); + var checks = []; + if (checkMainAxis) { + checks.push(overflow[_basePlacement] <= 0); + } + if (checkAltAxis) { + checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); + } + if (checks.every(function(check) { + return check; + })) { + firstFittingPlacement = placement; + makeFallbackChecks = false; + break; + } + checksMap.set(placement, checks); + } + if (makeFallbackChecks) { + var numberOfChecks = flipVariations ? 3 : 1; + var _loop = function _loop2(_i2) { + var fittingPlacement = placements2.find(function(placement2) { + var checks2 = checksMap.get(placement2); + if (checks2) { + return checks2.slice(0, _i2).every(function(check) { + return check; + }); + } + }); + if (fittingPlacement) { + firstFittingPlacement = fittingPlacement; + return "break"; + } + }; + for (var _i = numberOfChecks; _i > 0; _i--) { + var _ret = _loop(_i); + if (_ret === "break") + break; + } + } + if (state.placement !== firstFittingPlacement) { + state.modifiersData[name]._skip = true; + state.placement = firstFittingPlacement; + state.reset = true; + } +} +var flip_default = { + name: "flip", + enabled: true, + phase: "main", + fn: flip, + requiresIfExists: ["offset"], + data: { + _skip: false + } +}; + +// node_modules/@popperjs/core/lib/modifiers/hide.js +function getSideOffsets(overflow, rect, preventedOffsets) { + if (preventedOffsets === void 0) { + preventedOffsets = { + x: 0, + y: 0 + }; + } + return { + top: overflow.top - rect.height - preventedOffsets.y, + right: overflow.right - rect.width + preventedOffsets.x, + bottom: overflow.bottom - rect.height + preventedOffsets.y, + left: overflow.left - rect.width - preventedOffsets.x + }; +} +function isAnySideFullyClipped(overflow) { + return [top, right, bottom, left].some(function(side) { + return overflow[side] >= 0; + }); +} +function hide(_ref) { + var state = _ref.state, name = _ref.name; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var preventedOffsets = state.modifiersData.preventOverflow; + var referenceOverflow = detectOverflow(state, { + elementContext: "reference" + }); + var popperAltOverflow = detectOverflow(state, { + altBoundary: true + }); + var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); + var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); + var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); + var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); + state.modifiersData[name] = { + referenceClippingOffsets, + popperEscapeOffsets, + isReferenceHidden, + hasPopperEscaped + }; + state.attributes.popper = Object.assign({}, state.attributes.popper, { + "data-popper-reference-hidden": isReferenceHidden, + "data-popper-escaped": hasPopperEscaped + }); +} +var hide_default = { + name: "hide", + enabled: true, + phase: "main", + requiresIfExists: ["preventOverflow"], + fn: hide +}; + +// node_modules/@popperjs/core/lib/modifiers/offset.js +function distanceAndSkiddingToXY(placement, rects, offset2) { + var basePlacement = getBasePlacement(placement); + var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; + var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, { + placement + })) : offset2, skidding = _ref[0], distance = _ref[1]; + skidding = skidding || 0; + distance = (distance || 0) * invertDistance; + return [left, right].indexOf(basePlacement) >= 0 ? { + x: distance, + y: skidding + } : { + x: skidding, + y: distance + }; +} +function offset(_ref2) { + var state = _ref2.state, options = _ref2.options, name = _ref2.name; + var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset; + var data = placements.reduce(function(acc, placement) { + acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2); + return acc; + }, {}); + var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y; + if (state.modifiersData.popperOffsets != null) { + state.modifiersData.popperOffsets.x += x; + state.modifiersData.popperOffsets.y += y; + } + state.modifiersData[name] = data; +} +var offset_default = { + name: "offset", + enabled: true, + phase: "main", + requires: ["popperOffsets"], + fn: offset +}; + +// node_modules/@popperjs/core/lib/modifiers/popperOffsets.js +function popperOffsets(_ref) { + var state = _ref.state, name = _ref.name; + state.modifiersData[name] = computeOffsets({ + reference: state.rects.reference, + element: state.rects.popper, + strategy: "absolute", + placement: state.placement + }); +} +var popperOffsets_default = { + name: "popperOffsets", + enabled: true, + phase: "read", + fn: popperOffsets, + data: {} +}; + +// node_modules/@popperjs/core/lib/utils/getAltAxis.js +function getAltAxis(axis) { + return axis === "x" ? "y" : "x"; +} + +// node_modules/@popperjs/core/lib/modifiers/preventOverflow.js +function preventOverflow(_ref) { + var state = _ref.state, options = _ref.options, name = _ref.name; + var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; + var overflow = detectOverflow(state, { + boundary, + rootBoundary, + padding, + altBoundary + }); + var basePlacement = getBasePlacement(state.placement); + var variation = getVariation(state.placement); + var isBasePlacement = !variation; + var mainAxis = getMainAxisFromPlacement(basePlacement); + var altAxis = getAltAxis(mainAxis); + var popperOffsets2 = state.modifiersData.popperOffsets; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, { + placement: state.placement + })) : tetherOffset; + var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? { + mainAxis: tetherOffsetValue, + altAxis: tetherOffsetValue + } : Object.assign({ + mainAxis: 0, + altAxis: 0 + }, tetherOffsetValue); + var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; + var data = { + x: 0, + y: 0 + }; + if (!popperOffsets2) { + return; + } + if (checkMainAxis) { + var _offsetModifierState$; + var mainSide = mainAxis === "y" ? top : left; + var altSide = mainAxis === "y" ? bottom : right; + var len = mainAxis === "y" ? "height" : "width"; + var offset2 = popperOffsets2[mainAxis]; + var min2 = offset2 + overflow[mainSide]; + var max2 = offset2 - overflow[altSide]; + var additive = tether ? -popperRect[len] / 2 : 0; + var minLen = variation === start ? referenceRect[len] : popperRect[len]; + var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; + var arrowElement = state.elements.arrow; + var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { + width: 0, + height: 0 + }; + var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject(); + var arrowPaddingMin = arrowPaddingObject[mainSide]; + var arrowPaddingMax = arrowPaddingObject[altSide]; + var arrowLen = within(0, referenceRect[len], arrowRect[len]); + var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; + var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; + var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); + var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; + var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; + var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset; + var tetherMax = offset2 + maxOffset - offsetModifierValue; + var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2); + popperOffsets2[mainAxis] = preventedOffset; + data[mainAxis] = preventedOffset - offset2; + } + if (checkAltAxis) { + var _offsetModifierState$2; + var _mainSide = mainAxis === "x" ? top : left; + var _altSide = mainAxis === "x" ? bottom : right; + var _offset = popperOffsets2[altAxis]; + var _len = altAxis === "y" ? "height" : "width"; + var _min = _offset + overflow[_mainSide]; + var _max = _offset - overflow[_altSide]; + var isOriginSide = [top, left].indexOf(basePlacement) !== -1; + var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; + var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; + var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; + var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); + popperOffsets2[altAxis] = _preventedOffset; + data[altAxis] = _preventedOffset - _offset; + } + state.modifiersData[name] = data; +} +var preventOverflow_default = { + name: "preventOverflow", + enabled: true, + phase: "main", + fn: preventOverflow, + requiresIfExists: ["offset"] +}; + +// node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js +function getHTMLElementScroll(element2) { + return { + scrollLeft: element2.scrollLeft, + scrollTop: element2.scrollTop + }; +} + +// node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js +function getNodeScroll(node) { + if (node === getWindow(node) || !isHTMLElement(node)) { + return getWindowScroll(node); + } else { + return getHTMLElementScroll(node); + } +} + +// node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js +function isElementScaled(element2) { + var rect = element2.getBoundingClientRect(); + var scaleX = round(rect.width) / element2.offsetWidth || 1; + var scaleY = round(rect.height) / element2.offsetHeight || 1; + return scaleX !== 1 || scaleY !== 1; +} +function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { + if (isFixed === void 0) { + isFixed = false; + } + var isOffsetParentAnElement = isHTMLElement(offsetParent); + var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); + var documentElement = getDocumentElement(offsetParent); + var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); + var scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + var offsets = { + x: 0, + y: 0 + }; + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== "body" || isScrollParent(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + offsets = getBoundingClientRect(offsetParent, true); + offsets.x += offsetParent.clientLeft; + offsets.y += offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } + } + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height + }; +} + +// node_modules/@popperjs/core/lib/utils/orderModifiers.js +function order(modifiers) { + var map = /* @__PURE__ */ new Map(); + var visited = /* @__PURE__ */ new Set(); + var result = []; + modifiers.forEach(function(modifier) { + map.set(modifier.name, modifier); + }); + function sort(modifier) { + visited.add(modifier.name); + var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); + requires.forEach(function(dep) { + if (!visited.has(dep)) { + var depModifier = map.get(dep); + if (depModifier) { + sort(depModifier); + } + } + }); + result.push(modifier); + } + modifiers.forEach(function(modifier) { + if (!visited.has(modifier.name)) { + sort(modifier); + } + }); + return result; +} +function orderModifiers(modifiers) { + var orderedModifiers = order(modifiers); + return modifierPhases.reduce(function(acc, phase) { + return acc.concat(orderedModifiers.filter(function(modifier) { + return modifier.phase === phase; + })); + }, []); +} + +// node_modules/@popperjs/core/lib/utils/debounce.js +function debounce(fn2) { + var pending; + return function() { + if (!pending) { + pending = new Promise(function(resolve) { + Promise.resolve().then(function() { + pending = void 0; + resolve(fn2()); + }); + }); + } + return pending; + }; +} + +// node_modules/@popperjs/core/lib/utils/format.js +function format(str) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + return [].concat(args).reduce(function(p, c) { + return p.replace(/%s/, c); + }, str); +} + +// node_modules/@popperjs/core/lib/utils/validateModifiers.js +var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s'; +var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available'; +var VALID_PROPERTIES = ["name", "enabled", "phase", "fn", "effect", "requires", "options"]; +function validateModifiers(modifiers) { + modifiers.forEach(function(modifier) { + [].concat(Object.keys(modifier), VALID_PROPERTIES).filter(function(value, index, self) { + return self.indexOf(value) === index; + }).forEach(function(key) { + switch (key) { + case "name": + if (typeof modifier.name !== "string") { + console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', '"' + String(modifier.name) + '"')); + } + break; + case "enabled": + if (typeof modifier.enabled !== "boolean") { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', '"' + String(modifier.enabled) + '"')); + } + break; + case "phase": + if (modifierPhases.indexOf(modifier.phase) < 0) { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(", "), '"' + String(modifier.phase) + '"')); + } + break; + case "fn": + if (typeof modifier.fn !== "function") { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', '"' + String(modifier.fn) + '"')); + } + break; + case "effect": + if (modifier.effect != null && typeof modifier.effect !== "function") { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', '"' + String(modifier.fn) + '"')); + } + break; + case "requires": + if (modifier.requires != null && !Array.isArray(modifier.requires)) { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', '"' + String(modifier.requires) + '"')); + } + break; + case "requiresIfExists": + if (!Array.isArray(modifier.requiresIfExists)) { + console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', '"' + String(modifier.requiresIfExists) + '"')); + } + break; + case "options": + case "data": + break; + default: + console.error('PopperJS: an invalid property has been provided to the "' + modifier.name + '" modifier, valid properties are ' + VALID_PROPERTIES.map(function(s) { + return '"' + s + '"'; + }).join(", ") + '; but "' + key + '" was provided.'); + } + modifier.requires && modifier.requires.forEach(function(requirement) { + if (modifiers.find(function(mod) { + return mod.name === requirement; + }) == null) { + console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement)); + } + }); + }); + }); +} + +// node_modules/@popperjs/core/lib/utils/uniqueBy.js +function uniqueBy(arr, fn2) { + var identifiers = /* @__PURE__ */ new Set(); + return arr.filter(function(item) { + var identifier = fn2(item); + if (!identifiers.has(identifier)) { + identifiers.add(identifier); + return true; + } + }); +} + +// node_modules/@popperjs/core/lib/utils/mergeByName.js +function mergeByName(modifiers) { + var merged = modifiers.reduce(function(merged2, current) { + var existing = merged2[current.name]; + merged2[current.name] = existing ? Object.assign({}, existing, current, { + options: Object.assign({}, existing.options, current.options), + data: Object.assign({}, existing.data, current.data) + }) : current; + return merged2; + }, {}); + return Object.keys(merged).map(function(key) { + return merged[key]; + }); +} + +// node_modules/@popperjs/core/lib/createPopper.js +var INVALID_ELEMENT_ERROR = "Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element."; +var INFINITE_LOOP_ERROR = "Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash."; +var DEFAULT_OPTIONS = { + placement: "bottom", + modifiers: [], + strategy: "absolute" +}; +function areValidElements() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return !args.some(function(element2) { + return !(element2 && typeof element2.getBoundingClientRect === "function"); + }); +} +function popperGenerator(generatorOptions) { + if (generatorOptions === void 0) { + generatorOptions = {}; + } + var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; + return function createPopper2(reference2, popper2, options) { + if (options === void 0) { + options = defaultOptions; + } + var state = { + placement: "bottom", + orderedModifiers: [], + options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), + modifiersData: {}, + elements: { + reference: reference2, + popper: popper2 + }, + attributes: {}, + styles: {} + }; + var effectCleanupFns = []; + var isDestroyed = false; + var instance16 = { + state, + setOptions: function setOptions(setOptionsAction) { + var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction; + cleanupModifierEffects(); + state.options = Object.assign({}, defaultOptions, state.options, options2); + state.scrollParents = { + reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [], + popper: listScrollParents(popper2) + }; + var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers))); + state.orderedModifiers = orderedModifiers.filter(function(m) { + return m.enabled; + }); + if (true) { + var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function(_ref) { + var name = _ref.name; + return name; + }); + validateModifiers(modifiers); + if (getBasePlacement(state.options.placement) === auto) { + var flipModifier = state.orderedModifiers.find(function(_ref2) { + var name = _ref2.name; + return name === "flip"; + }); + if (!flipModifier) { + console.error(['Popper: "auto" placements require the "flip" modifier be', "present and enabled to work."].join(" ")); + } + } + var _getComputedStyle = getComputedStyle2(popper2), marginTop = _getComputedStyle.marginTop, marginRight = _getComputedStyle.marginRight, marginBottom = _getComputedStyle.marginBottom, marginLeft = _getComputedStyle.marginLeft; + if ([marginTop, marginRight, marginBottom, marginLeft].some(function(margin) { + return parseFloat(margin); + })) { + console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', "between the popper and its reference element or boundary.", "To replicate margin, use the `offset` modifier, as well as", "the `padding` option in the `preventOverflow` and `flip`", "modifiers."].join(" ")); + } + } + runModifierEffects(); + return instance16.update(); + }, + forceUpdate: function forceUpdate() { + if (isDestroyed) { + return; + } + var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper; + if (!areValidElements(reference3, popper3)) { + if (true) { + console.error(INVALID_ELEMENT_ERROR); + } + return; + } + state.rects = { + reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"), + popper: getLayoutRect(popper3) + }; + state.reset = false; + state.placement = state.options.placement; + state.orderedModifiers.forEach(function(modifier) { + return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); + }); + var __debug_loops__ = 0; + for (var index = 0; index < state.orderedModifiers.length; index++) { + if (true) { + __debug_loops__ += 1; + if (__debug_loops__ > 100) { + console.error(INFINITE_LOOP_ERROR); + break; + } + } + if (state.reset === true) { + state.reset = false; + index = -1; + continue; + } + var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name; + if (typeof fn2 === "function") { + state = fn2({ + state, + options: _options, + name, + instance: instance16 + }) || state; + } + } + }, + update: debounce(function() { + return new Promise(function(resolve) { + instance16.forceUpdate(); + resolve(state); + }); + }), + destroy: function destroy() { + cleanupModifierEffects(); + isDestroyed = true; + } + }; + if (!areValidElements(reference2, popper2)) { + if (true) { + console.error(INVALID_ELEMENT_ERROR); + } + return instance16; + } + instance16.setOptions(options).then(function(state2) { + if (!isDestroyed && options.onFirstUpdate) { + options.onFirstUpdate(state2); + } + }); + function runModifierEffects() { + state.orderedModifiers.forEach(function(_ref3) { + var name = _ref3.name, _ref3$options = _ref3.options, options2 = _ref3$options === void 0 ? {} : _ref3$options, effect4 = _ref3.effect; + if (typeof effect4 === "function") { + var cleanupFn = effect4({ + state, + name, + instance: instance16, + options: options2 + }); + var noopFn = function noopFn2() { + }; + effectCleanupFns.push(cleanupFn || noopFn); + } + }); + } + function cleanupModifierEffects() { + effectCleanupFns.forEach(function(fn2) { + return fn2(); + }); + effectCleanupFns = []; + } + return instance16; + }; +} + +// node_modules/@popperjs/core/lib/popper.js +var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default]; +var createPopper = /* @__PURE__ */ popperGenerator({ + defaultModifiers +}); + +// node_modules/svelte-popperjs/dist/index.es.js +function createPopperActions(initOptions) { + let popperInstance = null; + let referenceNode; + let contentNode; + let options = initOptions; + const initPopper = () => { + if (referenceNode !== void 0 && contentNode !== void 0) { + popperInstance = createPopper(referenceNode, contentNode, options); + } + }; + const deinitPopper = () => { + if (popperInstance !== null) { + popperInstance.destroy(); + popperInstance = null; + } + }; + const referenceAction = (node) => { + if ("subscribe" in node) { + setupVirtualElementObserver(node); + return {}; + } else { + referenceNode = node; + initPopper(); + return { + destroy() { + deinitPopper(); + } + }; + } + }; + const setupVirtualElementObserver = (node) => { + const unsubscribe = node.subscribe(($node) => { + if (referenceNode === void 0) { + referenceNode = $node; + initPopper(); + } else { + Object.assign(referenceNode, $node); + popperInstance == null ? void 0 : popperInstance.update(); + } + }); + onDestroy(unsubscribe); + }; + const contentAction = (node, contentOptions) => { + contentNode = node; + options = { ...initOptions, ...contentOptions }; + initPopper(); + return { + update(newContentOptions) { + options = { ...initOptions, ...newContentOptions }; + popperInstance == null ? void 0 : popperInstance.setOptions(options); + }, + destroy() { + deinitPopper(); + } + }; + }; + return [referenceAction, contentAction, () => popperInstance]; +} + +// src/settings/components/TemplateSuggest.svelte +function add_css(target) { + append_styles(target, "svelte-153zjst", ".search_input.svelte-153zjst{width:calc(100% - 20px)}.suggestion-container.svelte-153zjst{text-align:left}"); +} +function get_each_context(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[22] = list[i]; + return child_ctx; +} +function create_if_block(ctx) { + let div2; + let div1; + let div0; + let t1; + let popperContent_action; + let mounted; + let dispose; + let each_value = ctx[3]; + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i)); + } + return { + c() { + div2 = element("div"); + div1 = element("div"); + div0 = element("div"); + div0.textContent = "None"; + t1 = space(); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(div0, "class", "suggestion-item"); + attr(div1, "class", "suggestion"); + attr(div2, "class", "suggestion-container svelte-153zjst"); + }, + m(target, anchor) { + insert(target, div2, anchor); + append(div2, div1); + append(div1, div0); + append(div1, t1); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div1, null); + } + if (!mounted) { + dispose = [ + listen(div0, "keydown", ctx[16]), + listen(div0, "focus", ctx[17]), + listen(div0, "blur", ctx[18]), + listen(div0, "click", ctx[20]), + listen(div0, "mouseover", ctx[8]), + listen(div0, "mouseout", ctx[9]), + action_destroyer(popperContent_action = ctx[5].call(null, div2, ctx[6])) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & 904) { + each_value = ctx2[3]; + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + } else { + each_blocks[i] = create_each_block(child_ctx); + each_blocks[i].c(); + each_blocks[i].m(div1, null); + } + } + for (; i < each_blocks.length; i += 1) { + each_blocks[i].d(1); + } + each_blocks.length = each_value.length; + } + }, + d(detaching) { + if (detaching) + detach(div2); + destroy_each(each_blocks, detaching); + mounted = false; + run_all(dispose); + } + }; +} +function create_each_block(ctx) { + let div; + let t0_value = ctx[22] + ""; + let t0; + let t1; + let mounted; + let dispose; + function click_handler_1() { + return ctx[21](ctx[22]); + } + return { + c() { + div = element("div"); + t0 = text(t0_value); + t1 = space(); + attr(div, "class", "suggestion-item"); + }, + m(target, anchor) { + insert(target, div, anchor); + append(div, t0); + append(div, t1); + if (!mounted) { + dispose = [ + listen(div, "keydown", ctx[13]), + listen(div, "focus", ctx[14]), + listen(div, "blur", ctx[15]), + listen(div, "click", click_handler_1), + listen(div, "mouseover", ctx[8]), + listen(div, "mouseout", ctx[9]) + ]; + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (dirty & 8 && t0_value !== (t0_value = ctx[22] + "")) + set_data(t0, t0_value); + }, + d(detaching) { + if (detaching) + detach(div); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment(ctx) { + let div3; + let div2; + let div0; + let t0; + let t1; + let div1; + let t2; + let t3; + let a; + let t5; + let div6; + let div5; + let div4; + let input; + let popperRef_action; + let t6; + let mounted; + let dispose; + let if_block = ctx[3].length > 0 && create_if_block(ctx); + return { + c() { + div3 = element("div"); + div2 = element("div"); + div0 = element("div"); + t0 = text(ctx[1]); + t1 = space(); + div1 = element("div"); + t2 = text(ctx[2]); + t3 = space(); + a = element("a"); + a.textContent = "Template Example"; + t5 = space(); + div6 = element("div"); + div5 = element("div"); + div4 = element("div"); + input = element("input"); + t6 = space(); + if (if_block) + if_block.c(); + attr(div0, "class", "setting-item-name"); + attr(div1, "class", "setting-item-description"); + attr(a, "href", "https://raw.githubusercontent.com/jgchristopher/obsidian-clipper/main/docs/example-template.md"); + attr(div2, "class", "setting-item-info"); + attr(div3, "class", "setting-item align-start"); + attr(input, "type", "text"); + attr(input, "spellcheck", "false"); + attr(input, "class", "search_input svelte-153zjst"); + attr(div4, "class", "search_input svelte-153zjst"); + attr(div5, "class", "setting-item-control"); + attr(div6, "class", "setting-item"); + }, + m(target, anchor) { + insert(target, div3, anchor); + append(div3, div2); + append(div2, div0); + append(div0, t0); + append(div2, t1); + append(div2, div1); + append(div1, t2); + append(div2, t3); + append(div2, a); + insert(target, t5, anchor); + insert(target, div6, anchor); + append(div6, div5); + append(div5, div4); + append(div4, input); + set_input_value(input, ctx[0]); + append(div5, t6); + if (if_block) + if_block.m(div5, null); + if (!mounted) { + dispose = [ + action_destroyer(popperRef_action = ctx[4].call(null, input)), + listen(input, "input", ctx[19]), + listen(input, "input", ctx[10]), + listen(input, "focusin", ctx[10]) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & 2) + set_data(t0, ctx2[1]); + if (dirty & 4) + set_data(t2, ctx2[2]); + if (dirty & 1 && input.value !== ctx2[0]) { + set_input_value(input, ctx2[0]); + } + if (ctx2[3].length > 0) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block(ctx2); + if_block.c(); + if_block.m(div5, null); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) + detach(div3); + if (detaching) + detach(t5); + if (detaching) + detach(div6); + if (if_block) + if_block.d(); + mounted = false; + run_all(dispose); + } + }; +} +function instance($$self, $$props, $$invalidate) { + let { name } = $$props; + let { description } = $$props; + let { initialValue } = $$props; + let { onChange } = $$props; + let { dataProvider } = $$props; + const [popperRef, popperContent] = createPopperActions({ + placement: "bottom-start", + strategy: "fixed" + }); + const extraOpts = { + modifiers: [ + { + name: "offset", + options: { offset: [0, 5] } + }, + { + name: "sameWidth", + enabled: true, + fn: ({ state, instance: instance16 }) => { + const targetWidth = `${state.rects.reference.width}px`; + if (state.styles.popper.width === targetWidth) { + return; + } + state.styles.popper.width = targetWidth; + instance16.update(); + }, + phase: "beforeWrite", + requires: ["computeStyles"] + } + ] + }; + let templateOptions = []; + const setInputVal = (templateOption) => { + $$invalidate(3, templateOptions = []); + $$invalidate(0, initialValue = templateOption); + onChange(templateOption); + }; + const handleMouseOver = (e) => { + if (e && e.target) { + const target = e.target; + target.addClass("is-selected"); + } + }; + const handleMouseOut = (e) => { + if (e && e.target) { + const target = e.target; + target.removeClass("is-selected"); + } + }; + const filterFiles = () => { + let storageArr = []; + dataProvider().forEach((file) => { + if (initialValue) { + if (file.path.toLowerCase().startsWith(initialValue.toLowerCase())) { + storageArr = [...storageArr, file.path]; + } + } else { + storageArr = [...storageArr, file.path]; + } + }); + $$invalidate(3, templateOptions = storageArr); + }; + function keydown_handler_1(event) { + bubble.call(this, $$self, event); + } + function focus_handler_1(event) { + bubble.call(this, $$self, event); + } + function blur_handler_1(event) { + bubble.call(this, $$self, event); + } + function keydown_handler(event) { + bubble.call(this, $$self, event); + } + function focus_handler(event) { + bubble.call(this, $$self, event); + } + function blur_handler(event) { + bubble.call(this, $$self, event); + } + function input_input_handler() { + initialValue = this.value; + $$invalidate(0, initialValue); + } + const click_handler = () => setInputVal(""); + const click_handler_1 = (templateOption) => setInputVal(templateOption); + $$self.$$set = ($$props2) => { + if ("name" in $$props2) + $$invalidate(1, name = $$props2.name); + if ("description" in $$props2) + $$invalidate(2, description = $$props2.description); + if ("initialValue" in $$props2) + $$invalidate(0, initialValue = $$props2.initialValue); + if ("onChange" in $$props2) + $$invalidate(11, onChange = $$props2.onChange); + if ("dataProvider" in $$props2) + $$invalidate(12, dataProvider = $$props2.dataProvider); + }; + $$self.$$.update = () => { + if ($$self.$$.dirty & 1) { + $: + if (!initialValue) { + $$invalidate(3, templateOptions = []); + } + } + }; + return [ + initialValue, + name, + description, + templateOptions, + popperRef, + popperContent, + extraOpts, + setInputVal, + handleMouseOver, + handleMouseOut, + filterFiles, + onChange, + dataProvider, + keydown_handler_1, + focus_handler_1, + blur_handler_1, + keydown_handler, + focus_handler, + blur_handler, + input_input_handler, + click_handler, + click_handler_1 + ]; +} +var TemplateSuggest = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance, create_fragment, safe_not_equal, { + name: 1, + description: 2, + initialValue: 0, + onChange: 11, + dataProvider: 12 + }, add_css); + } +}; +var TemplateSuggest_default = TemplateSuggest; + +// node_modules/svelte/store/index.mjs +var subscriber_queue = []; +function writable(value, start2 = noop) { + let stop; + const subscribers = /* @__PURE__ */ new Set(); + function set(new_value) { + if (safe_not_equal(value, new_value)) { + value = new_value; + if (stop) { + const run_queue = !subscriber_queue.length; + for (const subscriber of subscribers) { + subscriber[1](); + subscriber_queue.push(subscriber, value); + } + if (run_queue) { + for (let i = 0; i < subscriber_queue.length; i += 2) { + subscriber_queue[i][0](subscriber_queue[i + 1]); + } + subscriber_queue.length = 0; + } + } + } + } + function update2(fn2) { + set(fn2(value)); + } + function subscribe2(run2, invalidate = noop) { + const subscriber = [run2, invalidate]; + subscribers.add(subscriber); + if (subscribers.size === 1) { + stop = start2(set) || noop; + } + run2(value); + return () => { + subscribers.delete(subscriber); + if (subscribers.size === 0) { + stop(); + stop = null; + } + }; + } + return { set, update: update2, subscribe: subscribe2 }; +} + +// src/settings/settingsstore.ts +var settings; +function init2(plugin) { + if (settings) { + return; + } + const { subscribe: subscribe2, set, update: update2 } = writable(plugin.settings); + settings = { + subscribe: subscribe2, + update: update2, + set: (value) => { + set(value); + plugin.saveSettings(); + } + }; +} + +// src/settings/DailySettingsGroup.svelte +function create_if_block2(ctx) { + let div15; + let div4; + let div2; + let t3; + let div3; + let input; + let t4; + let div9; + let div7; + let t8; + let div8; + let select0; + let option0; + let option1; + let t11; + let div14; + let div12; + let t15; + let div13; + let select1; + let option2; + let option2_value_value; + let option3; + let option3_value_value; + let t18; + let suggest; + let div15_intro; + let div15_outro; + let current; + let mounted; + let dispose; + suggest = new TemplateSuggest_default({ + props: { + name: "Clipped Entry Template - Daily", + description: "Choose the template to use as for the clipped entry in the daily \n periodic note", + initialValue: ctx[1].dailyEntryTemplateLocation, + dataProvider: ctx[7], + onChange: ctx[2] + } + }); + return { + c() { + div15 = element("div"); + div4 = element("div"); + div2 = element("div"); + div2.innerHTML = `
    Daily Note Header
    +
    What header should highlight data be prepended/appended under in the + daily note?
    `; + t3 = space(); + div3 = element("div"); + input = element("input"); + t4 = space(); + div9 = element("div"); + div7 = element("div"); + div7.innerHTML = `
    Daily Note Position
    +
    Prepend clippings to the top of the section or append them to the + bottom of the section?
    `; + t8 = space(); + div8 = element("div"); + select0 = element("select"); + option0 = element("option"); + option0.textContent = "prepend"; + option1 = element("option"); + option1.textContent = "append"; + t11 = space(); + div14 = element("div"); + div12 = element("div"); + div12.innerHTML = `
    Open Note After Adding Clipping?
    +
    Open the daily note after adding the clipping?
    `; + t15 = space(); + div13 = element("div"); + select1 = element("select"); + option2 = element("option"); + option2.textContent = "Yes"; + option3 = element("option"); + option3.textContent = "No"; + t18 = space(); + create_component(suggest.$$.fragment); + attr(div2, "class", "setting-item-info"); + attr(input, "type", "text"); + attr(input, "spellcheck", "false"); + attr(input, "placeholder", ""); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + attr(div7, "class", "setting-item-info"); + option0.__value = "prepend"; + option0.value = option0.__value; + option1.__value = "append"; + option1.value = option1.__value; + attr(select0, "class", "dropdown"); + if (ctx[1].dailyPosition === void 0) + add_render_callback(() => ctx[5].call(select0)); + attr(div8, "class", "setting-item-control"); + attr(div9, "class", "setting-item"); + attr(div12, "class", "setting-item-info"); + option2.__value = option2_value_value = true; + option2.value = option2.__value; + option3.__value = option3_value_value = false; + option3.value = option3.__value; + attr(select1, "class", "dropdown"); + if (ctx[1].dailyOpenOnWrite === void 0) + add_render_callback(() => ctx[6].call(select1)); + attr(div13, "class", "setting-item-control"); + attr(div14, "class", "setting-item"); + }, + m(target, anchor) { + insert(target, div15, anchor); + append(div15, div4); + append(div4, div2); + append(div4, t3); + append(div4, div3); + append(div3, input); + set_input_value(input, ctx[1].dailyNoteHeading); + append(div15, t4); + append(div15, div9); + append(div9, div7); + append(div9, t8); + append(div9, div8); + append(div8, select0); + append(select0, option0); + append(select0, option1); + select_option(select0, ctx[1].dailyPosition); + append(div15, t11); + append(div15, div14); + append(div14, div12); + append(div14, t15); + append(div14, div13); + append(div13, select1); + append(select1, option2); + append(select1, option3); + select_option(select1, ctx[1].dailyOpenOnWrite); + append(div15, t18); + mount_component(suggest, div15, null); + current = true; + if (!mounted) { + dispose = [ + listen(input, "input", ctx[4]), + listen(select0, "change", ctx[5]), + listen(select1, "change", ctx[6]) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & 2 && input.value !== ctx2[1].dailyNoteHeading) { + set_input_value(input, ctx2[1].dailyNoteHeading); + } + if (dirty & 2) { + select_option(select0, ctx2[1].dailyPosition); + } + if (dirty & 2) { + select_option(select1, ctx2[1].dailyOpenOnWrite); + } + const suggest_changes = {}; + if (dirty & 2) + suggest_changes.initialValue = ctx2[1].dailyEntryTemplateLocation; + if (dirty & 1) + suggest_changes.dataProvider = ctx2[7]; + suggest.$set(suggest_changes); + }, + i(local) { + if (current) + return; + transition_in(suggest.$$.fragment, local); + if (local) { + add_render_callback(() => { + if (div15_outro) + div15_outro.end(1); + div15_intro = create_in_transition(div15, slide, { duration: 300 }); + div15_intro.start(); + }); + } + current = true; + }, + o(local) { + transition_out(suggest.$$.fragment, local); + if (div15_intro) + div15_intro.invalidate(); + if (local) { + div15_outro = create_out_transition(div15, slide, { duration: 300 }); + } + current = false; + }, + d(detaching) { + if (detaching) + detach(div15); + destroy_component(suggest); + if (detaching && div15_outro) + div15_outro.end(); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment2(ctx) { + let div3; + let div2; + let div0; + let t1; + let div1; + let label; + let input; + let t2; + let current; + let mounted; + let dispose; + let if_block = ctx[1].useDailyNote && create_if_block2(ctx); + return { + c() { + div3 = element("div"); + div2 = element("div"); + div0 = element("div"); + div0.innerHTML = `

    Daily Note Entry

    `; + t1 = space(); + div1 = element("div"); + label = element("label"); + input = element("input"); + t2 = space(); + if (if_block) + if_block.c(); + attr(div0, "class", "setting-item-info"); + attr(input, "type", "checkbox"); + attr(label, "class", "checkbox-container"); + toggle_class(label, "is-enabled", ctx[1].useDailyNote); + attr(div1, "class", "setting-item-control"); + attr(div2, "class", "setting-item mod-toggle"); + attr(div3, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div3, anchor); + append(div3, div2); + append(div2, div0); + append(div2, t1); + append(div2, div1); + append(div1, label); + append(label, input); + input.checked = ctx[1].useDailyNote; + append(div3, t2); + if (if_block) + if_block.m(div3, null); + current = true; + if (!mounted) { + dispose = listen(input, "change", ctx[3]); + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & 2) { + input.checked = ctx2[1].useDailyNote; + } + if (!current || dirty & 2) { + toggle_class(label, "is-enabled", ctx2[1].useDailyNote); + } + if (ctx2[1].useDailyNote) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & 2) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block2(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(div3, null); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) + detach(div3); + if (if_block) + if_block.d(); + mounted = false; + dispose(); + } + }; +} +function instance2($$self, $$props, $$invalidate) { + let $settings; + component_subscribe($$self, settings, ($$value) => $$invalidate(1, $settings = $$value)); + let { app } = $$props; + const onChange = (entry) => { + set_store_value(settings, $settings.dailyEntryTemplateLocation = entry, $settings); + }; + function input_change_handler() { + $settings.useDailyNote = this.checked; + settings.set($settings); + } + function input_input_handler() { + $settings.dailyNoteHeading = this.value; + settings.set($settings); + } + function select0_change_handler() { + $settings.dailyPosition = select_value(this); + settings.set($settings); + } + function select1_change_handler() { + $settings.dailyOpenOnWrite = select_value(this); + settings.set($settings); + } + const func = () => app.vault.getMarkdownFiles(); + $$self.$$set = ($$props2) => { + if ("app" in $$props2) + $$invalidate(0, app = $$props2.app); + }; + return [ + app, + $settings, + onChange, + input_change_handler, + input_input_handler, + select0_change_handler, + select1_change_handler, + func + ]; +} +var DailySettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance2, create_fragment2, safe_not_equal, { app: 0 }); + } +}; +var DailySettingsGroup_default = DailySettingsGroup; + +// src/settings/WeeklySettingsGroup.svelte +function create_if_block3(ctx) { + let div15; + let div4; + let div2; + let t3; + let div3; + let input; + let t4; + let div9; + let div7; + let t8; + let div8; + let select0; + let option0; + let option1; + let t11; + let div14; + let div12; + let t15; + let div13; + let select1; + let option2; + let option2_value_value; + let option3; + let option3_value_value; + let t18; + let suggest; + let div15_intro; + let div15_outro; + let current; + let mounted; + let dispose; + suggest = new TemplateSuggest_default({ + props: { + name: "Clipped Entry Template - Weekly", + description: "Choose the template to use as for the clipped entry in the weekly\n periodic note", + initialValue: ctx[1].weeklyEntryTemplateLocation, + dataProvider: ctx[7], + onChange: ctx[2] + } + }); + return { + c() { + div15 = element("div"); + div4 = element("div"); + div2 = element("div"); + div2.innerHTML = `
    Weekly Note Header
    +
    What header should highlight data be prepended/appended under in the + weekly note?
    `; + t3 = space(); + div3 = element("div"); + input = element("input"); + t4 = space(); + div9 = element("div"); + div7 = element("div"); + div7.innerHTML = `
    Weekly Note Position
    +
    Prepend clippings to the top of the section or append them to the + bottom of the section?
    `; + t8 = space(); + div8 = element("div"); + select0 = element("select"); + option0 = element("option"); + option0.textContent = "prepend"; + option1 = element("option"); + option1.textContent = "append"; + t11 = space(); + div14 = element("div"); + div12 = element("div"); + div12.innerHTML = `
    Open Note After Adding Clipping?
    +
    Open the weekly note after adding the clipping?
    `; + t15 = space(); + div13 = element("div"); + select1 = element("select"); + option2 = element("option"); + option2.textContent = "Yes"; + option3 = element("option"); + option3.textContent = "No"; + t18 = space(); + create_component(suggest.$$.fragment); + attr(div2, "class", "setting-item-info"); + attr(input, "type", "text"); + attr(input, "spellcheck", "false"); + attr(input, "placeholder", ""); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + attr(div7, "class", "setting-item-info"); + option0.__value = "prepend"; + option0.value = option0.__value; + option1.__value = "append"; + option1.value = option1.__value; + attr(select0, "class", "dropdown"); + if (ctx[1].weeklyPosition === void 0) + add_render_callback(() => ctx[5].call(select0)); + attr(div8, "class", "setting-item-control"); + attr(div9, "class", "setting-item"); + attr(div12, "class", "setting-item-info"); + option2.__value = option2_value_value = true; + option2.value = option2.__value; + option3.__value = option3_value_value = false; + option3.value = option3.__value; + attr(select1, "class", "dropdown"); + if (ctx[1].weeklyOpenOnWrite === void 0) + add_render_callback(() => ctx[6].call(select1)); + attr(div13, "class", "setting-item-control"); + attr(div14, "class", "setting-item"); + }, + m(target, anchor) { + insert(target, div15, anchor); + append(div15, div4); + append(div4, div2); + append(div4, t3); + append(div4, div3); + append(div3, input); + set_input_value(input, ctx[1].weeklyNoteHeading); + append(div15, t4); + append(div15, div9); + append(div9, div7); + append(div9, t8); + append(div9, div8); + append(div8, select0); + append(select0, option0); + append(select0, option1); + select_option(select0, ctx[1].weeklyPosition); + append(div15, t11); + append(div15, div14); + append(div14, div12); + append(div14, t15); + append(div14, div13); + append(div13, select1); + append(select1, option2); + append(select1, option3); + select_option(select1, ctx[1].weeklyOpenOnWrite); + append(div15, t18); + mount_component(suggest, div15, null); + current = true; + if (!mounted) { + dispose = [ + listen(input, "input", ctx[4]), + listen(select0, "change", ctx[5]), + listen(select1, "change", ctx[6]) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & 2 && input.value !== ctx2[1].weeklyNoteHeading) { + set_input_value(input, ctx2[1].weeklyNoteHeading); + } + if (dirty & 2) { + select_option(select0, ctx2[1].weeklyPosition); + } + if (dirty & 2) { + select_option(select1, ctx2[1].weeklyOpenOnWrite); + } + const suggest_changes = {}; + if (dirty & 2) + suggest_changes.initialValue = ctx2[1].weeklyEntryTemplateLocation; + if (dirty & 1) + suggest_changes.dataProvider = ctx2[7]; + suggest.$set(suggest_changes); + }, + i(local) { + if (current) + return; + transition_in(suggest.$$.fragment, local); + if (local) { + add_render_callback(() => { + if (div15_outro) + div15_outro.end(1); + div15_intro = create_in_transition(div15, slide, { duration: 300 }); + div15_intro.start(); + }); + } + current = true; + }, + o(local) { + transition_out(suggest.$$.fragment, local); + if (div15_intro) + div15_intro.invalidate(); + if (local) { + div15_outro = create_out_transition(div15, slide, { duration: 300 }); + } + current = false; + }, + d(detaching) { + if (detaching) + detach(div15); + destroy_component(suggest); + if (detaching && div15_outro) + div15_outro.end(); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment3(ctx) { + let div3; + let div2; + let div0; + let t1; + let div1; + let label; + let input; + let t2; + let current; + let mounted; + let dispose; + let if_block = ctx[1].useWeeklyNote && create_if_block3(ctx); + return { + c() { + div3 = element("div"); + div2 = element("div"); + div0 = element("div"); + div0.innerHTML = `

    Weekly Note Entry

    `; + t1 = space(); + div1 = element("div"); + label = element("label"); + input = element("input"); + t2 = space(); + if (if_block) + if_block.c(); + attr(div0, "class", "setting-item-info"); + attr(input, "type", "checkbox"); + attr(label, "class", "checkbox-container"); + toggle_class(label, "is-enabled", ctx[1].useWeeklyNote); + attr(div1, "class", "setting-item-control"); + attr(div2, "class", "setting-item mod-toggle"); + attr(div3, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div3, anchor); + append(div3, div2); + append(div2, div0); + append(div2, t1); + append(div2, div1); + append(div1, label); + append(label, input); + input.checked = ctx[1].useWeeklyNote; + append(div3, t2); + if (if_block) + if_block.m(div3, null); + current = true; + if (!mounted) { + dispose = listen(input, "change", ctx[3]); + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & 2) { + input.checked = ctx2[1].useWeeklyNote; + } + if (!current || dirty & 2) { + toggle_class(label, "is-enabled", ctx2[1].useWeeklyNote); + } + if (ctx2[1].useWeeklyNote) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & 2) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block3(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(div3, null); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (detaching) + detach(div3); + if (if_block) + if_block.d(); + mounted = false; + dispose(); + } + }; +} +function instance3($$self, $$props, $$invalidate) { + let $settings; + component_subscribe($$self, settings, ($$value) => $$invalidate(1, $settings = $$value)); + let { app } = $$props; + const onChange = (entry) => set_store_value(settings, $settings.weeklyEntryTemplateLocation = entry, $settings); + function input_change_handler() { + $settings.useWeeklyNote = this.checked; + settings.set($settings); + } + function input_input_handler() { + $settings.weeklyNoteHeading = this.value; + settings.set($settings); + } + function select0_change_handler() { + $settings.weeklyPosition = select_value(this); + settings.set($settings); + } + function select1_change_handler() { + $settings.weeklyOpenOnWrite = select_value(this); + settings.set($settings); + } + const func = () => app.vault.getMarkdownFiles(); + $$self.$$set = ($$props2) => { + if ("app" in $$props2) + $$invalidate(0, app = $$props2.app); + }; + return [ + app, + $settings, + onChange, + input_change_handler, + input_input_handler, + select0_change_handler, + select1_change_handler, + func + ]; +} +var WeeklySettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance3, create_fragment3, safe_not_equal, { app: 0 }); + } +}; +var WeeklySettingsGroup_default = WeeklySettingsGroup; + +// src/settings/CommonSettingsGroup.svelte +function create_fragment4(ctx) { + let div17; + let h1; + let t1; + let div4; + let div2; + let t5; + let div3; + let input0; + let t6; + let div10; + let div8; + let t12; + let div9; + let input1; + let t13; + let div16; + let div14; + let t19; + let div15; + let input2; + let mounted; + let dispose; + return { + c() { + div17 = element("div"); + h1 = element("h1"); + h1.textContent = "Common Settings"; + t1 = space(); + div4 = element("div"); + div2 = element("div"); + div2.innerHTML = `
    Tags
    +
    Tags to add to captured highlights?
    `; + t5 = space(); + div3 = element("div"); + input0 = element("input"); + t6 = space(); + div10 = element("div"); + div8 = element("div"); + div8.innerHTML = `
    Time Format
    +
    Format to use for the {{ time }} template in + clippings. See
    + format reference
    `; + t12 = space(); + div9 = element("div"); + input1 = element("input"); + t13 = space(); + div16 = element("div"); + div14 = element("div"); + div14.innerHTML = `
    Date Format
    +
    Format to use for the {{ date }} template in + clippings. See
    + format reference
    `; + t19 = space(); + div15 = element("div"); + input2 = element("input"); + attr(div2, "class", "setting-item-info"); + attr(input0, "type", "text"); + attr(input0, "spellcheck", "false"); + attr(input0, "placeholder", "tags,seperated,by,commas"); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + attr(div8, "class", "setting-item-info"); + attr(input1, "type", "text"); + attr(input1, "spellcheck", "false"); + attr(input1, "placeholder", "HH:mm"); + attr(div9, "class", "setting-item-control"); + attr(div10, "class", "setting-item"); + attr(div14, "class", "setting-item-info"); + attr(input2, "type", "text"); + attr(input2, "spellcheck", "false"); + attr(input2, "placeholder", "MM/DD/YY"); + attr(div15, "class", "setting-item-control"); + attr(div16, "class", "setting-item"); + attr(div17, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div17, anchor); + append(div17, h1); + append(div17, t1); + append(div17, div4); + append(div4, div2); + append(div4, t5); + append(div4, div3); + append(div3, input0); + set_input_value(input0, ctx[0].tags); + append(div17, t6); + append(div17, div10); + append(div10, div8); + append(div10, t12); + append(div10, div9); + append(div9, input1); + set_input_value(input1, ctx[0].timestampFormat); + append(div17, t13); + append(div17, div16); + append(div16, div14); + append(div16, t19); + append(div16, div15); + append(div15, input2); + set_input_value(input2, ctx[0].dateFormat); + if (!mounted) { + dispose = [ + listen(input0, "input", ctx[1]), + listen(input1, "input", ctx[2]), + listen(input2, "input", ctx[3]) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & 1 && input0.value !== ctx2[0].tags) { + set_input_value(input0, ctx2[0].tags); + } + if (dirty & 1 && input1.value !== ctx2[0].timestampFormat) { + set_input_value(input1, ctx2[0].timestampFormat); + } + if (dirty & 1 && input2.value !== ctx2[0].dateFormat) { + set_input_value(input2, ctx2[0].dateFormat); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) + detach(div17); + mounted = false; + run_all(dispose); + } + }; +} +function instance4($$self, $$props, $$invalidate) { + let $settings; + component_subscribe($$self, settings, ($$value) => $$invalidate(0, $settings = $$value)); + function input0_input_handler() { + $settings.tags = this.value; + settings.set($settings); + } + function input1_input_handler() { + $settings.timestampFormat = this.value; + settings.set($settings); + } + function input2_input_handler() { + $settings.dateFormat = this.value; + settings.set($settings); + } + return [$settings, input0_input_handler, input1_input_handler, input2_input_handler]; +} +var CommonSettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance4, create_fragment4, safe_not_equal, {}); + } +}; +var CommonSettingsGroup_default = CommonSettingsGroup; + +// src/settings/BaseSettingsTab.svelte +function create_fragment5(ctx) { + let dailysettingsgroup; + let t0; + let weeklysettingsgroup; + let t1; + let commonsettingsgroup; + let current; + dailysettingsgroup = new DailySettingsGroup_default({ props: { app: ctx[0] } }); + weeklysettingsgroup = new WeeklySettingsGroup_default({ props: { app: ctx[0] } }); + commonsettingsgroup = new CommonSettingsGroup_default({}); + return { + c() { + create_component(dailysettingsgroup.$$.fragment); + t0 = space(); + create_component(weeklysettingsgroup.$$.fragment); + t1 = space(); + create_component(commonsettingsgroup.$$.fragment); + }, + m(target, anchor) { + mount_component(dailysettingsgroup, target, anchor); + insert(target, t0, anchor); + mount_component(weeklysettingsgroup, target, anchor); + insert(target, t1, anchor); + mount_component(commonsettingsgroup, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const dailysettingsgroup_changes = {}; + if (dirty & 1) + dailysettingsgroup_changes.app = ctx2[0]; + dailysettingsgroup.$set(dailysettingsgroup_changes); + const weeklysettingsgroup_changes = {}; + if (dirty & 1) + weeklysettingsgroup_changes.app = ctx2[0]; + weeklysettingsgroup.$set(weeklysettingsgroup_changes); + }, + i(local) { + if (current) + return; + transition_in(dailysettingsgroup.$$.fragment, local); + transition_in(weeklysettingsgroup.$$.fragment, local); + transition_in(commonsettingsgroup.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(dailysettingsgroup.$$.fragment, local); + transition_out(weeklysettingsgroup.$$.fragment, local); + transition_out(commonsettingsgroup.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(dailysettingsgroup, detaching); + if (detaching) + detach(t0); + destroy_component(weeklysettingsgroup, detaching); + if (detaching) + detach(t1); + destroy_component(commonsettingsgroup, detaching); + } + }; +} +function instance5($$self, $$props, $$invalidate) { + let { app } = $$props; + $$self.$$set = ($$props2) => { + if ("app" in $$props2) + $$invalidate(0, app = $$props2.app); + }; + return [app]; +} +var BaseSettingsTab = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance5, create_fragment5, safe_not_equal, { app: 0 }); + } +}; +var BaseSettingsTab_default = BaseSettingsTab; + +// src/settings/Tabs.svelte +function add_css2(target) { + append_styles(target, "svelte-126qfyk", ".obs_clp_box.svelte-126qfyk.svelte-126qfyk{margin-bottom:10px;padding:40px;border:1px solid var(--tab-divider-color);border-radius:0 0 0.5rem 0.5rem;border-top:0}ul.svelte-126qfyk.svelte-126qfyk{display:flex;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none;border-bottom:1px solid var(--tab-divider-color)}span.svelte-126qfyk.svelte-126qfyk{border:1px solid var(--tab-divider-color);border-top-left-radius:0.25rem;border-top-right-radius:0.25rem;display:block;padding:0.5rem 1rem;cursor:pointer;color:var(--tab-text-color)}span.svelte-126qfyk.svelte-126qfyk:hover{border-color:#e9ecef #e9ecef #dee2e6;background-color:var(--background-modifier-hover);color:var(--tab-text-color-active)}li.svelte-126qfyk.svelte-126qfyk:hover{background-color:var(--background-modifier-hover)}li.active.svelte-126qfyk>span.svelte-126qfyk{background-color:var(--tab-background-active);border-color:#e9ecef #e9ecef #dee2e6;color:var(--tab-text-color-active)}"); +} +function get_each_context2(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[5] = list[i]; + return child_ctx; +} +function get_each_context_1(ctx, list, i) { + const child_ctx = ctx.slice(); + child_ctx[5] = list[i]; + return child_ctx; +} +function create_each_block_1(ctx) { + let li; + let span; + let t0_value = ctx[5].label + ""; + let t0; + let t1; + let li_class_value; + let mounted; + let dispose; + function keypress_handler() { + return ctx[3](ctx[5]); + } + function click_handler() { + return ctx[4](ctx[5]); + } + return { + c() { + li = element("li"); + span = element("span"); + t0 = text(t0_value); + t1 = space(); + attr(span, "class", "svelte-126qfyk"); + attr(li, "class", li_class_value = null_to_empty(ctx[0] === ctx[5].value ? "active" : "") + " svelte-126qfyk"); + }, + m(target, anchor) { + insert(target, li, anchor); + append(li, span); + append(span, t0); + append(li, t1); + if (!mounted) { + dispose = [ + listen(span, "keypress", keypress_handler), + listen(span, "click", click_handler) + ]; + mounted = true; + } + }, + p(new_ctx, dirty) { + ctx = new_ctx; + if (dirty & 2 && t0_value !== (t0_value = ctx[5].label + "")) + set_data(t0, t0_value); + if (dirty & 3 && li_class_value !== (li_class_value = null_to_empty(ctx[0] === ctx[5].value ? "active" : "") + " svelte-126qfyk")) { + attr(li, "class", li_class_value); + } + }, + d(detaching) { + if (detaching) + detach(li); + mounted = false; + run_all(dispose); + } + }; +} +function create_if_block4(ctx) { + let div; + let switch_instance; + let t; + let current; + const switch_instance_spread_levels = [ctx[5].props]; + var switch_value = ctx[5].component; + function switch_props(ctx2) { + let switch_instance_props = {}; + for (let i = 0; i < switch_instance_spread_levels.length; i += 1) { + switch_instance_props = assign(switch_instance_props, switch_instance_spread_levels[i]); + } + return { props: switch_instance_props }; + } + if (switch_value) { + switch_instance = construct_svelte_component(switch_value, switch_props(ctx)); + } + return { + c() { + div = element("div"); + if (switch_instance) + create_component(switch_instance.$$.fragment); + t = space(); + attr(div, "class", "obs_clp_box svelte-126qfyk"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (switch_instance) + mount_component(switch_instance, div, null); + append(div, t); + current = true; + }, + p(ctx2, dirty) { + const switch_instance_changes = dirty & 2 ? get_spread_update(switch_instance_spread_levels, [get_spread_object(ctx2[5].props)]) : {}; + if (switch_value !== (switch_value = ctx2[5].component)) { + if (switch_instance) { + group_outros(); + const old_component = switch_instance; + transition_out(old_component.$$.fragment, 1, 0, () => { + destroy_component(old_component, 1); + }); + check_outros(); + } + if (switch_value) { + switch_instance = construct_svelte_component(switch_value, switch_props(ctx2)); + create_component(switch_instance.$$.fragment); + transition_in(switch_instance.$$.fragment, 1); + mount_component(switch_instance, div, t); + } else { + switch_instance = null; + } + } else if (switch_value) { + switch_instance.$set(switch_instance_changes); + } + }, + i(local) { + if (current) + return; + if (switch_instance) + transition_in(switch_instance.$$.fragment, local); + current = true; + }, + o(local) { + if (switch_instance) + transition_out(switch_instance.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) + detach(div); + if (switch_instance) + destroy_component(switch_instance); + } + }; +} +function create_each_block2(ctx) { + let if_block_anchor; + let current; + let if_block = ctx[0] == ctx[5].value && create_if_block4(ctx); + return { + c() { + if (if_block) + if_block.c(); + if_block_anchor = empty(); + }, + m(target, anchor) { + if (if_block) + if_block.m(target, anchor); + insert(target, if_block_anchor, anchor); + current = true; + }, + p(ctx2, dirty) { + if (ctx2[0] == ctx2[5].value) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & 3) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block4(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(if_block_anchor.parentNode, if_block_anchor); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + }, + i(local) { + if (current) + return; + transition_in(if_block); + current = true; + }, + o(local) { + transition_out(if_block); + current = false; + }, + d(detaching) { + if (if_block) + if_block.d(detaching); + if (detaching) + detach(if_block_anchor); + } + }; +} +function create_fragment6(ctx) { + let div1; + let div0; + let ul; + let t; + let current; + let each_value_1 = ctx[1]; + let each_blocks_1 = []; + for (let i = 0; i < each_value_1.length; i += 1) { + each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i)); + } + let each_value = ctx[1]; + let each_blocks = []; + for (let i = 0; i < each_value.length; i += 1) { + each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i)); + } + const out = (i) => transition_out(each_blocks[i], 1, 1, () => { + each_blocks[i] = null; + }); + return { + c() { + div1 = element("div"); + div0 = element("div"); + ul = element("ul"); + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].c(); + } + t = space(); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].c(); + } + attr(ul, "class", "svelte-126qfyk"); + }, + m(target, anchor) { + insert(target, div1, anchor); + append(div1, div0); + append(div0, ul); + for (let i = 0; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].m(ul, null); + } + append(div1, t); + for (let i = 0; i < each_blocks.length; i += 1) { + each_blocks[i].m(div1, null); + } + current = true; + }, + p(ctx2, [dirty]) { + if (dirty & 7) { + each_value_1 = ctx2[1]; + let i; + for (i = 0; i < each_value_1.length; i += 1) { + const child_ctx = get_each_context_1(ctx2, each_value_1, i); + if (each_blocks_1[i]) { + each_blocks_1[i].p(child_ctx, dirty); + } else { + each_blocks_1[i] = create_each_block_1(child_ctx); + each_blocks_1[i].c(); + each_blocks_1[i].m(ul, null); + } + } + for (; i < each_blocks_1.length; i += 1) { + each_blocks_1[i].d(1); + } + each_blocks_1.length = each_value_1.length; + } + if (dirty & 3) { + each_value = ctx2[1]; + let i; + for (i = 0; i < each_value.length; i += 1) { + const child_ctx = get_each_context2(ctx2, each_value, i); + if (each_blocks[i]) { + each_blocks[i].p(child_ctx, dirty); + transition_in(each_blocks[i], 1); + } else { + each_blocks[i] = create_each_block2(child_ctx); + each_blocks[i].c(); + transition_in(each_blocks[i], 1); + each_blocks[i].m(div1, null); + } + } + group_outros(); + for (i = each_value.length; i < each_blocks.length; i += 1) { + out(i); + } + check_outros(); + } + }, + i(local) { + if (current) + return; + for (let i = 0; i < each_value.length; i += 1) { + transition_in(each_blocks[i]); + } + current = true; + }, + o(local) { + each_blocks = each_blocks.filter(Boolean); + for (let i = 0; i < each_blocks.length; i += 1) { + transition_out(each_blocks[i]); + } + current = false; + }, + d(detaching) { + if (detaching) + detach(div1); + destroy_each(each_blocks_1, detaching); + destroy_each(each_blocks, detaching); + } + }; +} +function instance6($$self, $$props, $$invalidate) { + let { tabs } = $$props; + let { activeTabValue = 1 } = $$props; + const handleClick = (tabValue) => $$invalidate(0, activeTabValue = tabValue); + const keypress_handler = (tab) => handleClick(tab.value); + const click_handler = (tab) => handleClick(tab.value); + $$self.$$set = ($$props2) => { + if ("tabs" in $$props2) + $$invalidate(1, tabs = $$props2.tabs); + if ("activeTabValue" in $$props2) + $$invalidate(0, activeTabValue = $$props2.activeTabValue); + }; + return [activeTabValue, tabs, handleClick, keypress_handler, click_handler]; +} +var Tabs = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance6, create_fragment6, safe_not_equal, { tabs: 1, activeTabValue: 0 }, add_css2); + } +}; +var Tabs_default = Tabs; + +// src/settings/Notice.svelte +var get_calloutLink_slot_changes = (dirty) => ({}); +var get_calloutLink_slot_context = (ctx) => ({}); +var get_noticeText_slot_changes = (dirty) => ({}); +var get_noticeText_slot_context = (ctx) => ({}); +function fallback_block(ctx) { + let span; + return { + c() { + span = element("span"); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + p: noop, + d(detaching) { + if (detaching) + detach(span); + } + }; +} +function create_fragment7(ctx) { + let div3; + let div2; + let div0; + let t0; + let div1; + let p0; + let t1; + let p1; + let current; + const noticeText_slot_template = ctx[1].noticeText; + const noticeText_slot = create_slot(noticeText_slot_template, ctx, ctx[0], get_noticeText_slot_context); + const noticeText_slot_or_fallback = noticeText_slot || fallback_block(ctx); + const calloutLink_slot_template = ctx[1].calloutLink; + const calloutLink_slot = create_slot(calloutLink_slot_template, ctx, ctx[0], get_calloutLink_slot_context); + return { + c() { + div3 = element("div"); + div2 = element("div"); + div0 = element("div"); + div0.innerHTML = ``; + t0 = space(); + div1 = element("div"); + p0 = element("p"); + if (noticeText_slot_or_fallback) + noticeText_slot_or_fallback.c(); + t1 = space(); + p1 = element("p"); + if (calloutLink_slot) + calloutLink_slot.c(); + attr(div0, "class", "flex-shrink-0"); + attr(p0, "class", "text-sm text-blue-700"); + attr(p1, "class", "mt-3 text-sm md:mt-0 md:ml-6"); + attr(div1, "class", "ml-3 flex-1 md:flex md:justify-between"); + attr(div2, "class", "flex"); + attr(div3, "class", "rounded-md bg-blue-50 p-4"); + }, + m(target, anchor) { + insert(target, div3, anchor); + append(div3, div2); + append(div2, div0); + append(div2, t0); + append(div2, div1); + append(div1, p0); + if (noticeText_slot_or_fallback) { + noticeText_slot_or_fallback.m(p0, null); + } + append(div1, t1); + append(div1, p1); + if (calloutLink_slot) { + calloutLink_slot.m(p1, null); + } + current = true; + }, + p(ctx2, [dirty]) { + if (noticeText_slot) { + if (noticeText_slot.p && (!current || dirty & 1)) { + update_slot_base(noticeText_slot, noticeText_slot_template, ctx2, ctx2[0], !current ? get_all_dirty_from_scope(ctx2[0]) : get_slot_changes(noticeText_slot_template, ctx2[0], dirty, get_noticeText_slot_changes), get_noticeText_slot_context); + } + } + if (calloutLink_slot) { + if (calloutLink_slot.p && (!current || dirty & 1)) { + update_slot_base(calloutLink_slot, calloutLink_slot_template, ctx2, ctx2[0], !current ? get_all_dirty_from_scope(ctx2[0]) : get_slot_changes(calloutLink_slot_template, ctx2[0], dirty, get_calloutLink_slot_changes), get_calloutLink_slot_context); + } + } + }, + i(local) { + if (current) + return; + transition_in(noticeText_slot_or_fallback, local); + transition_in(calloutLink_slot, local); + current = true; + }, + o(local) { + transition_out(noticeText_slot_or_fallback, local); + transition_out(calloutLink_slot, local); + current = false; + }, + d(detaching) { + if (detaching) + detach(div3); + if (noticeText_slot_or_fallback) + noticeText_slot_or_fallback.d(detaching); + if (calloutLink_slot) + calloutLink_slot.d(detaching); + } + }; +} +function instance7($$self, $$props, $$invalidate) { + let { $$slots: slots = {}, $$scope } = $$props; + $$self.$$set = ($$props2) => { + if ("$$scope" in $$props2) + $$invalidate(0, $$scope = $$props2.$$scope); + }; + return [$$scope, slots]; +} +var Notice5 = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance7, create_fragment7, safe_not_equal, {}); + } +}; +var Notice_default = Notice5; + +// src/settings/TopicSettingsGroup.svelte +function create_fragment8(ctx) { + let div10; + let div4; + let div2; + let t3; + let div3; + let select0; + let option0; + let option1; + let t6; + let div9; + let div7; + let t10; + let div8; + let select1; + let option2; + let option2_value_value; + let option3; + let option3_value_value; + let t13; + let suggest; + let current; + let mounted; + let dispose; + suggest = new TemplateSuggest_default({ + props: { + name: "Clipped Entry Template", + description: "Choose the template to use for the clipped entry in a topic note", + initialValue: ctx[1].topicEntryTemplateLocation, + dataProvider: ctx[5], + onChange: ctx[2] + } + }); + return { + c() { + div10 = element("div"); + div4 = element("div"); + div2 = element("div"); + div2.innerHTML = `
    Topic Note Position
    +
    Prepend clippings or append them to the bottom?
    `; + t3 = space(); + div3 = element("div"); + select0 = element("select"); + option0 = element("option"); + option0.textContent = "prepend"; + option1 = element("option"); + option1.textContent = "append"; + t6 = space(); + div9 = element("div"); + div7 = element("div"); + div7.innerHTML = `
    Open Note After Adding Clipping?
    +
    Open the note after adding the clipping?
    `; + t10 = space(); + div8 = element("div"); + select1 = element("select"); + option2 = element("option"); + option2.textContent = "Yes"; + option3 = element("option"); + option3.textContent = "No"; + t13 = space(); + create_component(suggest.$$.fragment); + attr(div2, "class", "setting-item-info"); + option0.__value = "prepend"; + option0.value = option0.__value; + option1.__value = "append"; + option1.value = option1.__value; + attr(select0, "class", "dropdown"); + if (ctx[1].topicPosition === void 0) + add_render_callback(() => ctx[3].call(select0)); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + attr(div7, "class", "setting-item-info"); + option2.__value = option2_value_value = true; + option2.value = option2.__value; + option3.__value = option3_value_value = false; + option3.value = option3.__value; + attr(select1, "class", "dropdown"); + if (ctx[1].topicOpenOnWrite === void 0) + add_render_callback(() => ctx[4].call(select1)); + attr(div8, "class", "setting-item-control"); + attr(div9, "class", "setting-item"); + attr(div10, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div10, anchor); + append(div10, div4); + append(div4, div2); + append(div4, t3); + append(div4, div3); + append(div3, select0); + append(select0, option0); + append(select0, option1); + select_option(select0, ctx[1].topicPosition); + append(div10, t6); + append(div10, div9); + append(div9, div7); + append(div9, t10); + append(div9, div8); + append(div8, select1); + append(select1, option2); + append(select1, option3); + select_option(select1, ctx[1].topicOpenOnWrite); + append(div10, t13); + mount_component(suggest, div10, null); + current = true; + if (!mounted) { + dispose = [ + listen(select0, "change", ctx[3]), + listen(select1, "change", ctx[4]) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & 2) { + select_option(select0, ctx2[1].topicPosition); + } + if (dirty & 2) { + select_option(select1, ctx2[1].topicOpenOnWrite); + } + const suggest_changes = {}; + if (dirty & 2) + suggest_changes.initialValue = ctx2[1].topicEntryTemplateLocation; + if (dirty & 1) + suggest_changes.dataProvider = ctx2[5]; + suggest.$set(suggest_changes); + }, + i(local) { + if (current) + return; + transition_in(suggest.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(suggest.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) + detach(div10); + destroy_component(suggest); + mounted = false; + run_all(dispose); + } + }; +} +function instance8($$self, $$props, $$invalidate) { + let $settings; + component_subscribe($$self, settings, ($$value) => $$invalidate(1, $settings = $$value)); + let { app } = $$props; + const onChange = (entry) => { + set_store_value(settings, $settings.topicEntryTemplateLocation = entry, $settings); + }; + function select0_change_handler() { + $settings.topicPosition = select_value(this); + settings.set($settings); + } + function select1_change_handler() { + $settings.topicOpenOnWrite = select_value(this); + settings.set($settings); + } + const func = () => app.vault.getMarkdownFiles(); + $$self.$$set = ($$props2) => { + if ("app" in $$props2) + $$invalidate(0, app = $$props2.app); + }; + return [app, $settings, onChange, select0_change_handler, select1_change_handler, func]; +} +var TopicSettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance8, create_fragment8, safe_not_equal, { app: 0 }); + } +}; +var TopicSettingsGroup_default = TopicSettingsGroup; + +// src/settings/TopicSettingsTab.svelte +function create_fragment9(ctx) { + let topicsettingsgroup; + let current; + topicsettingsgroup = new TopicSettingsGroup_default({ props: { app: ctx[0] } }); + return { + c() { + create_component(topicsettingsgroup.$$.fragment); + }, + m(target, anchor) { + mount_component(topicsettingsgroup, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const topicsettingsgroup_changes = {}; + if (dirty & 1) + topicsettingsgroup_changes.app = ctx2[0]; + topicsettingsgroup.$set(topicsettingsgroup_changes); + }, + i(local) { + if (current) + return; + transition_in(topicsettingsgroup.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(topicsettingsgroup.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(topicsettingsgroup, detaching); + } + }; +} +function instance9($$self, $$props, $$invalidate) { + let { app } = $$props; + $$self.$$set = ($$props2) => { + if ("app" in $$props2) + $$invalidate(0, app = $$props2.app); + }; + return [app]; +} +var TopicSettingsTab = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance9, create_fragment9, safe_not_equal, { app: 0 }); + } +}; +var TopicSettingsTab_default = TopicSettingsTab; + +// src/utils/fileutils.ts +function getFileName(filePath) { + const lastSlashIndex = filePath.lastIndexOf("/"); + let fileName = filePath; + if (lastSlashIndex !== -1) { + fileName = filePath.substring(lastSlashIndex + 1); + } + return fileName; +} + +// src/bookmarkletlink/bookmarkletgenerator.ts +var BookmarketlGenerator = class { + constructor(vaultName, notePath = "", markdownSettings, captureComments) { + this.vaultName = vaultName; + this.notePath = notePath; + this.markdownSettings = markdownSettings; + this.captureComments = captureComments; + } + generateBookmarklet() { + return `javascript:(function()%7B(()%3D%3E%7B%22use%20strict%22%3Bvar%20e%2Cn%2Ct%3D%7B36%3A(e%2Cn%2Ct)%3D%3E%7Bfunction%20r(e%2Cn)%7Breturn%20Array(n%2B1).join(e)%7Dt.r(n)%2Ct.d(n%2C%7Bdefault%3A()%3D%3EL%7D)%3Bvar%20i%3D%5B%22ADDRESS%22%2C%22ARTICLE%22%2C%22ASIDE%22%2C%22AUDIO%22%2C%22BLOCKQUOTE%22%2C%22BODY%22%2C%22CANVAS%22%2C%22CENTER%22%2C%22DD%22%2C%22DIR%22%2C%22DIV%22%2C%22DL%22%2C%22DT%22%2C%22FIELDSET%22%2C%22FIGCAPTION%22%2C%22FIGURE%22%2C%22FOOTER%22%2C%22FORM%22%2C%22FRAMESET%22%2C%22H1%22%2C%22H2%22%2C%22H3%22%2C%22H4%22%2C%22H5%22%2C%22H6%22%2C%22HEADER%22%2C%22HGROUP%22%2C%22HR%22%2C%22HTML%22%2C%22ISINDEX%22%2C%22LI%22%2C%22MAIN%22%2C%22MENU%22%2C%22NAV%22%2C%22NOFRAMES%22%2C%22NOSCRIPT%22%2C%22OL%22%2C%22OUTPUT%22%2C%22P%22%2C%22PRE%22%2C%22SECTION%22%2C%22TABLE%22%2C%22TBODY%22%2C%22TD%22%2C%22TFOOT%22%2C%22TH%22%2C%22THEAD%22%2C%22TR%22%2C%22UL%22%5D%3Bfunction%20o(e)%7Breturn%20c(e%2Ci)%7Dvar%20a%3D%5B%22AREA%22%2C%22BASE%22%2C%22BR%22%2C%22COL%22%2C%22COMMAND%22%2C%22EMBED%22%2C%22HR%22%2C%22IMG%22%2C%22INPUT%22%2C%22KEYGEN%22%2C%22LINK%22%2C%22META%22%2C%22PARAM%22%2C%22SOURCE%22%2C%22TRACK%22%2C%22WBR%22%5D%3Bfunction%20l(e)%7Breturn%20c(e%2Ca)%7Dvar%20d%3D%5B%22A%22%2C%22TABLE%22%2C%22THEAD%22%2C%22TBODY%22%2C%22TFOOT%22%2C%22TH%22%2C%22TD%22%2C%22IFRAME%22%2C%22SCRIPT%22%2C%22AUDIO%22%2C%22VIDEO%22%5D%3Bfunction%20c(e%2Cn)%7Breturn%20n.indexOf(e.nodeName)%3E%3D0%7Dfunction%20u(e%2Cn)%7Breturn%20e.getElementsByTagName%26%26n.some((function(n)%7Breturn%20e.getElementsByTagName(n).length%7D))%7Dvar%20s%3D%7B%7D%3Bfunction%20p(e)%7Breturn%20e%3Fe.replace(%2F(%5Cn%2B%5Cs*)%2B%2Fg%2C%22%5Cn%22)%3A%22%22%7Dfunction%20f(e)%7Bfor(var%20n%20in%20this.options%3De%2Cthis._keep%3D%5B%5D%2Cthis._remove%3D%5B%5D%2Cthis.blankRule%3D%7Breplacement%3Ae.blankReplacement%7D%2Cthis.keepReplacement%3De.keepReplacement%2Cthis.defaultRule%3D%7Breplacement%3Ae.defaultReplacement%7D%2Cthis.array%3D%5B%5D%2Ce.rules)this.array.push(e.rules%5Bn%5D)%7Dfunction%20m(e%2Cn%2Ct)%7Bfor(var%20r%3D0%3Br%3Ce.length%3Br%2B%2B)%7Bvar%20i%3De%5Br%5D%3Bif(h(i%2Cn%2Ct))return%20i%7D%7Dfunction%20h(e%2Cn%2Ct)%7Bvar%20r%3De.filter%3Bif(%22string%22%3D%3Dtypeof%20r)%7Bif(r%3D%3D%3Dn.nodeName.toLowerCase())return!0%7Delse%20if(Array.isArray(r))%7Bif(r.indexOf(n.nodeName.toLowerCase())%3E-1)return!0%7Delse%7Bif(%22function%22!%3Dtypeof%20r)throw%20new%20TypeError(%22%60filter%60%20needs%20to%20be%20a%20string%2C%20array%2C%20or%20function%22)%3Bif(r.call(e%2Cn%2Ct))return!0%7D%7Dfunction%20g(e)%7Bvar%20n%3De.nextSibling%7C%7Ce.parentNode%3Breturn%20e.parentNode.removeChild(e)%2Cn%7Dfunction%20b(e%2Cn%2Ct)%7Breturn%20e%26%26e.parentNode%3D%3D%3Dn%7C%7Ct(n)%3Fn.nextSibling%7C%7Cn.parentNode%3An.firstChild%7C%7Cn.nextSibling%7C%7Cn.parentNode%7Ds.paragraph%3D%7Bfilter%3A%22p%22%2Creplacement%3Afunction(e)%7Breturn%22%5Cn%5Cn%22%2Be%2B%22%5Cn%5Cn%22%7D%7D%2Cs.lineBreak%3D%7Bfilter%3A%22br%22%2Creplacement%3Afunction(e%2Cn%2Ct)%7Breturn%20t.br%2B%22%5Cn%22%7D%7D%2Cs.heading%3D%7Bfilter%3A%5B%22h1%22%2C%22h2%22%2C%22h3%22%2C%22h4%22%2C%22h5%22%2C%22h6%22%5D%2Creplacement%3Afunction(e%2Cn%2Ct)%7Bvar%20i%3DNumber(n.nodeName.charAt(1))%3Breturn%22setext%22%3D%3D%3Dt.headingStyle%26%26i%3C3%3F%22%5Cn%5Cn%22%2Be%2B%22%5Cn%22%2Br(1%3D%3D%3Di%3F%22%3D%22%3A%22-%22%2Ce.length)%2B%22%5Cn%5Cn%22%3A%22%5Cn%5Cn%22%2Br(%22%23%22%2Ci)%2B%22%20%22%2Be%2B%22%5Cn%5Cn%22%7D%7D%2Cs.blockquote%3D%7Bfilter%3A%22blockquote%22%2Creplacement%3Afunction(e)%7Breturn%22%5Cn%5Cn%22%2B(e%3D(e%3De.replace(%2F%5E%5Cn%2B%7C%5Cn%2B%24%2Fg%2C%22%22)).replace(%2F%5E%2Fgm%2C%22%3E%20%22))%2B%22%5Cn%5Cn%22%7D%7D%2Cs.list%3D%7Bfilter%3A%5B%22ul%22%2C%22ol%22%5D%2Creplacement%3Afunction(e%2Cn)%7Bvar%20t%3Dn.parentNode%3Breturn%22LI%22%3D%3D%3Dt.nodeName%26%26t.lastElementChild%3D%3D%3Dn%3F%22%5Cn%22%2Be%3A%22%5Cn%5Cn%22%2Be%2B%22%5Cn%5Cn%22%7D%7D%2Cs.listItem%3D%7Bfilter%3A%22li%22%2Creplacement%3Afunction(e%2Cn%2Ct)%7Be%3De.replace(%2F%5E%5Cn%2B%2F%2C%22%22).replace(%2F%5Cn%2B%24%2F%2C%22%5Cn%22).replace(%2F%5Cn%2Fgm%2C%22%5Cn%20%20%20%20%22)%3Bvar%20r%3Dt.bulletListMarker%2B%22%20%20%20%22%2Ci%3Dn.parentNode%3Bif(%22OL%22%3D%3D%3Di.nodeName)%7Bvar%20o%3Di.getAttribute(%22start%22)%2Ca%3DArray.prototype.indexOf.call(i.children%2Cn)%3Br%3D(o%3FNumber(o)%2Ba%3Aa%2B1)%2B%22.%20%20%22%7Dreturn%20r%2Be%2B(n.nextSibling%26%26!%2F%5Cn%24%2F.test(e)%3F%22%5Cn%22%3A%22%22)%7D%7D%2Cs.indentedCodeBlock%3D%7Bfilter%3Afunction(e%2Cn)%7Breturn%22indented%22%3D%3D%3Dn.codeBlockStyle%26%26%22PRE%22%3D%3D%3De.nodeName%26%26e.firstChild%26%26%22CODE%22%3D%3D%3De.firstChild.nodeName%7D%2Creplacement%3Afunction(e%2Cn%2Ct)%7Breturn%22%5Cn%5Cn%20%20%20%20%22%2Bn.firstChild.textContent.replace(%2F%5Cn%2Fg%2C%22%5Cn%20%20%20%20%22)%2B%22%5Cn%5Cn%22%7D%7D%2Cs.fencedCodeBlock%3D%7Bfilter%3Afunction(e%2Cn)%7Breturn%22fenced%22%3D%3D%3Dn.codeBlockStyle%26%26%22PRE%22%3D%3D%3De.nodeName%26%26e.firstChild%26%26%22CODE%22%3D%3D%3De.firstChild.nodeName%7D%2Creplacement%3Afunction(e%2Cn%2Ct)%7Bfor(var%20i%2Co%3D((n.firstChild.getAttribute(%22class%22)%7C%7C%22%22).match(%2Flanguage-(%5CS%2B)%2F)%7C%7C%5Bnull%2C%22%22%5D)%5B1%5D%2Ca%3Dn.firstChild.textContent%2Cl%3Dt.fence.charAt(0)%2Cd%3D3%2Cc%3Dnew%20RegExp(%22%5E%22%2Bl%2B%22%7B3%2C%7D%22%2C%22gm%22)%3Bi%3Dc.exec(a)%3B)i%5B0%5D.length%3E%3Dd%26%26(d%3Di%5B0%5D.length%2B1)%3Bvar%20u%3Dr(l%2Cd)%3Breturn%22%5Cn%5Cn%22%2Bu%2Bo%2B%22%5Cn%22%2Ba.replace(%2F%5Cn%24%2F%2C%22%22)%2B%22%5Cn%22%2Bu%2B%22%5Cn%5Cn%22%7D%7D%2Cs.horizontalRule%3D%7Bfilter%3A%22hr%22%2Creplacement%3Afunction(e%2Cn%2Ct)%7Breturn%22%5Cn%5Cn%22%2Bt.hr%2B%22%5Cn%5Cn%22%7D%7D%2Cs.inlineLink%3D%7Bfilter%3Afunction(e%2Cn)%7Breturn%22inlined%22%3D%3D%3Dn.linkStyle%26%26%22A%22%3D%3D%3De.nodeName%26%26e.getAttribute(%22href%22)%7D%2Creplacement%3Afunction(e%2Cn)%7Bvar%20t%3Dn.getAttribute(%22href%22)%2Cr%3Dp(n.getAttribute(%22title%22))%3Breturn%20r%26%26(r%3D'%20%22'%2Br%2B'%22')%2C%22%5B%22%2Be%2B%22%5D(%22%2Bt%2Br%2B%22)%22%7D%7D%2Cs.referenceLink%3D%7Bfilter%3Afunction(e%2Cn)%7Breturn%22referenced%22%3D%3D%3Dn.linkStyle%26%26%22A%22%3D%3D%3De.nodeName%26%26e.getAttribute(%22href%22)%7D%2Creplacement%3Afunction(e%2Cn%2Ct)%7Bvar%20r%2Ci%2Co%3Dn.getAttribute(%22href%22)%2Ca%3Dp(n.getAttribute(%22title%22))%3Bswitch(a%26%26(a%3D'%20%22'%2Ba%2B'%22')%2Ct.linkReferenceStyle)%7Bcase%22collapsed%22%3Ar%3D%22%5B%22%2Be%2B%22%5D%5B%5D%22%2Ci%3D%22%5B%22%2Be%2B%22%5D%3A%20%22%2Bo%2Ba%3Bbreak%3Bcase%22shortcut%22%3Ar%3D%22%5B%22%2Be%2B%22%5D%22%2Ci%3D%22%5B%22%2Be%2B%22%5D%3A%20%22%2Bo%2Ba%3Bbreak%3Bdefault%3Avar%20l%3Dthis.references.length%2B1%3Br%3D%22%5B%22%2Be%2B%22%5D%5B%22%2Bl%2B%22%5D%22%2Ci%3D%22%5B%22%2Bl%2B%22%5D%3A%20%22%2Bo%2Ba%7Dreturn%20this.references.push(i)%2Cr%7D%2Creferences%3A%5B%5D%2Cappend%3Afunction(e)%7Bvar%20n%3D%22%22%3Breturn%20this.references.length%26%26(n%3D%22%5Cn%5Cn%22%2Bthis.references.join(%22%5Cn%22)%2B%22%5Cn%5Cn%22%2Cthis.references%3D%5B%5D)%2Cn%7D%7D%2Cs.emphasis%3D%7Bfilter%3A%5B%22em%22%2C%22i%22%5D%2Creplacement%3Afunction(e%2Cn%2Ct)%7Breturn%20e.trim()%3Ft.emDelimiter%2Be%2Bt.emDelimiter%3A%22%22%7D%7D%2Cs.strong%3D%7Bfilter%3A%5B%22strong%22%2C%22b%22%5D%2Creplacement%3Afunction(e%2Cn%2Ct)%7Breturn%20e.trim()%3Ft.strongDelimiter%2Be%2Bt.strongDelimiter%3A%22%22%7D%7D%2Cs.code%3D%7Bfilter%3Afunction(e)%7Bvar%20n%3De.previousSibling%7C%7Ce.nextSibling%2Ct%3D%22PRE%22%3D%3D%3De.parentNode.nodeName%26%26!n%3Breturn%22CODE%22%3D%3D%3De.nodeName%26%26!t%7D%2Creplacement%3Afunction(e)%7Bif(!e)return%22%22%3Be%3De.replace(%2F%5Cr%3F%5Cn%7C%5Cr%2Fg%2C%22%20%22)%3Bfor(var%20n%3D%2F%5E%60%7C%5E%20.*%3F%5B%5E%20%5D.*%20%24%7C%60%24%2F.test(e)%3F%22%20%22%3A%22%22%2Ct%3D%22%60%22%2Cr%3De.match(%2F%60%2B%2Fgm)%7C%7C%5B%5D%3B-1!%3D%3Dr.indexOf(t)%3B)t%2B%3D%22%60%22%3Breturn%20t%2Bn%2Be%2Bn%2Bt%7D%7D%2Cs.image%3D%7Bfilter%3A%22img%22%2Creplacement%3Afunction(e%2Cn)%7Bvar%20t%3Dp(n.getAttribute(%22alt%22))%2Cr%3Dn.getAttribute(%22src%22)%7C%7C%22%22%2Ci%3Dp(n.getAttribute(%22title%22))%3Breturn%20r%3F%22!%5B%22%2Bt%2B%22%5D(%22%2Br%2B(i%3F'%20%22'%2Bi%2B'%22'%3A%22%22)%2B%22)%22%3A%22%22%7D%7D%2Cf.prototype%3D%7Badd%3Afunction(e%2Cn)%7Bthis.array.unshift(n)%7D%2Ckeep%3Afunction(e)%7Bthis._keep.unshift(%7Bfilter%3Ae%2Creplacement%3Athis.keepReplacement%7D)%7D%2Cremove%3Afunction(e)%7Bthis._remove.unshift(%7Bfilter%3Ae%2Creplacement%3Afunction()%7Breturn%22%22%7D%7D)%7D%2CforNode%3Afunction(e)%7Breturn%20e.isBlank%3Fthis.blankRule%3A(n%3Dm(this.array%2Ce%2Cthis.options))%7C%7C(n%3Dm(this._keep%2Ce%2Cthis.options))%7C%7C(n%3Dm(this._remove%2Ce%2Cthis.options))%3Fn%3Athis.defaultRule%3Bvar%20n%7D%2CforEach%3Afunction(e)%7Bfor(var%20n%3D0%3Bn%3Cthis.array.length%3Bn%2B%2B)e(this.array%5Bn%5D%2Cn)%7D%7D%3Bvar%20v%2Cy%2CC%3D%22undefined%22!%3Dtypeof%20window%3Fwindow%3A%7B%7D%2CN%3Dfunction()%7Bvar%20e%3DC.DOMParser%2Cn%3D!1%3Btry%7B(new%20e).parseFromString(%22%22%2C%22text%2Fhtml%22)%26%26(n%3D!0)%7Dcatch(e)%7B%7Dreturn%20n%7D()%3FC.DOMParser%3A(v%3Dfunction()%7B%7D%2Cfunction()%7Bvar%20e%3D!1%3Btry%7Bdocument.implementation.createHTMLDocument(%22%22).open()%7Dcatch(n)%7Bwindow.ActiveXObject%26%26(e%3D!0)%7Dreturn%20e%7D()%3Fv.prototype.parseFromString%3Dfunction(e)%7Bvar%20n%3Dnew%20window.ActiveXObject(%22htmlfile%22)%3Breturn%20n.designMode%3D%22on%22%2Cn.open()%2Cn.write(e)%2Cn.close()%2Cn%7D%3Av.prototype.parseFromString%3Dfunction(e)%7Bvar%20n%3Ddocument.implementation.createHTMLDocument(%22%22)%3Breturn%20n.open()%2Cn.write(e)%2Cn.close()%2Cn%7D%2Cv)%3Bfunction%20T(e%2Cn)%7Bvar%20t%3Breturn%20function(e)%7Bvar%20n%3De.element%2Ct%3De.isBlock%2Cr%3De.isVoid%2Ci%3De.isPre%7C%7Cfunction(e)%7Breturn%22PRE%22%3D%3D%3De.nodeName%7D%3Bif(n.firstChild%26%26!i(n))%7Bfor(var%20o%3Dnull%2Ca%3D!1%2Cl%3Dnull%2Cd%3Db(l%2Cn%2Ci)%3Bd!%3D%3Dn%3B)%7Bif(3%3D%3D%3Dd.nodeType%7C%7C4%3D%3D%3Dd.nodeType)%7Bvar%20c%3Dd.data.replace(%2F%5B%20%5Cr%5Cn%5Ct%5D%2B%2Fg%2C%22%20%22)%3Bif(o%26%26!%2F%20%24%2F.test(o.data)%7C%7Ca%7C%7C%22%20%22!%3D%3Dc%5B0%5D%7C%7C(c%3Dc.substr(1))%2C!c)%7Bd%3Dg(d)%3Bcontinue%7Dd.data%3Dc%2Co%3Dd%7Delse%7Bif(1!%3D%3Dd.nodeType)%7Bd%3Dg(d)%3Bcontinue%7Dt(d)%7C%7C%22BR%22%3D%3D%3Dd.nodeName%3F(o%26%26(o.data%3Do.data.replace(%2F%20%24%2F%2C%22%22))%2Co%3Dnull%2Ca%3D!1)%3Ar(d)%7C%7Ci(d)%3F(o%3Dnull%2Ca%3D!0)%3Ao%26%26(a%3D!1)%7Dvar%20u%3Db(l%2Cd%2Ci)%3Bl%3Dd%2Cd%3Du%7Do%26%26(o.data%3Do.data.replace(%2F%20%24%2F%2C%22%22)%2Co.data%7C%7Cg(o))%7D%7D(%7Belement%3At%3D%22string%22%3D%3Dtypeof%20e%3F(y%3Dy%7C%7Cnew%20N).parseFromString('%3Cx-turndown%20id%3D%22turndown-root%22%3E'%2Be%2B%22%3C%2Fx-turndown%3E%22%2C%22text%2Fhtml%22).getElementById(%22turndown-root%22)%3Ae.cloneNode(!0)%2CisBlock%3Ao%2CisVoid%3Al%2CisPre%3An.preformattedCode%3FA%3Anull%7D)%2Ct%7Dfunction%20A(e)%7Breturn%22PRE%22%3D%3D%3De.nodeName%7C%7C%22CODE%22%3D%3D%3De.nodeName%7Dfunction%20w(e%2Cn)%7Breturn%20e.isBlock%3Do(e)%2Ce.isCode%3D%22CODE%22%3D%3D%3De.nodeName%7C%7Ce.parentNode.isCode%2Ce.isBlank%3Dfunction(e)%7Breturn!l(e)%26%26!function(e)%7Breturn%20c(e%2Cd)%7D(e)%26%26%2F%5E%5Cs*%24%2Fi.test(e.textContent)%26%26!function(e)%7Breturn%20u(e%2Ca)%7D(e)%26%26!function(e)%7Breturn%20u(e%2Cd)%7D(e)%7D(e)%2Ce.flankingWhitespace%3Dfunction(e%2Cn)%7Bif(e.isBlock%7C%7Cn.preformattedCode%26%26e.isCode)return%7Bleading%3A%22%22%2Ctrailing%3A%22%22%7D%3Bvar%20t%2Cr%3D%7Bleading%3A(t%3De.textContent.match(%2F%5E((%5B%20%5Ct%5Cr%5Cn%5D*)(%5Cs*))%5B%5Cs%5CS%5D*%3F((%5Cs*%3F)(%5B%20%5Ct%5Cr%5Cn%5D*))%24%2F))%5B1%5D%2CleadingAscii%3At%5B2%5D%2CleadingNonAscii%3At%5B3%5D%2Ctrailing%3At%5B4%5D%2CtrailingNonAscii%3At%5B5%5D%2CtrailingAscii%3At%5B6%5D%7D%3Breturn%20r.leadingAscii%26%26E(%22left%22%2Ce%2Cn)%26%26(r.leading%3Dr.leadingNonAscii)%2Cr.trailingAscii%26%26E(%22right%22%2Ce%2Cn)%26%26(r.trailing%3Dr.trailingNonAscii)%2C%7Bleading%3Ar.leading%2Ctrailing%3Ar.trailing%7D%7D(e%2Cn)%2Ce%7Dfunction%20E(e%2Cn%2Ct)%7Bvar%20r%2Ci%2Ca%3Breturn%22left%22%3D%3D%3De%3F(r%3Dn.previousSibling%2Ci%3D%2F%20%24%2F)%3A(r%3Dn.nextSibling%2Ci%3D%2F%5E%20%2F)%2Cr%26%26(3%3D%3D%3Dr.nodeType%3Fa%3Di.test(r.nodeValue)%3At.preformattedCode%26%26%22CODE%22%3D%3D%3Dr.nodeName%3Fa%3D!1%3A1!%3D%3Dr.nodeType%7C%7Co(r)%7C%7C(a%3Di.test(r.textContent)))%2Ca%7Dvar%20R%3DArray.prototype.reduce%2CS%3D%5B%5B%2F%5C%5C%2Fg%2C%22%5C%5C%5C%5C%22%5D%2C%5B%2F%5C*%2Fg%2C%22%5C%5C*%22%5D%2C%5B%2F%5E-%2Fg%2C%22%5C%5C-%22%5D%2C%5B%2F%5E%5C%2B%20%2Fg%2C%22%5C%5C%2B%20%22%5D%2C%5B%2F%5E(%3D%2B)%2Fg%2C%22%5C%5C%241%22%5D%2C%5B%2F%5E(%23%7B1%2C6%7D)%20%2Fg%2C%22%5C%5C%241%20%22%5D%2C%5B%2F%60%2Fg%2C%22%5C%5C%60%22%5D%2C%5B%2F%5E~~~%2Fg%2C%22%5C%5C~~~%22%5D%2C%5B%2F%5C%5B%2Fg%2C%22%5C%5C%5B%22%5D%2C%5B%2F%5C%5D%2Fg%2C%22%5C%5C%5D%22%5D%2C%5B%2F%5E%3E%2Fg%2C%22%5C%5C%3E%22%5D%2C%5B%2F_%2Fg%2C%22%5C%5C_%22%5D%2C%5B%2F%5E(%5Cd%2B)%5C.%20%2Fg%2C%22%241%5C%5C.%20%22%5D%5D%3Bfunction%20k(e)%7Bif(!(this%20instanceof%20k))return%20new%20k(e)%3Bvar%20n%3D%7Brules%3As%2CheadingStyle%3A%22setext%22%2Chr%3A%22*%20*%20*%22%2CbulletListMarker%3A%22*%22%2CcodeBlockStyle%3A%22indented%22%2Cfence%3A%22%60%60%60%22%2CemDelimiter%3A%22_%22%2CstrongDelimiter%3A%22**%22%2ClinkStyle%3A%22inlined%22%2ClinkReferenceStyle%3A%22full%22%2Cbr%3A%22%20%20%22%2CpreformattedCode%3A!1%2CblankReplacement%3Afunction(e%2Cn)%7Breturn%20n.isBlock%3F%22%5Cn%5Cn%22%3A%22%22%7D%2CkeepReplacement%3Afunction(e%2Cn)%7Breturn%20n.isBlock%3F%22%5Cn%5Cn%22%2Bn.outerHTML%2B%22%5Cn%5Cn%22%3An.outerHTML%7D%2CdefaultReplacement%3Afunction(e%2Cn)%7Breturn%20n.isBlock%3F%22%5Cn%5Cn%22%2Be%2B%22%5Cn%5Cn%22%3Ae%7D%7D%3Bthis.options%3Dfunction(e)%7Bfor(var%20n%3D1%3Bn%3Carguments.length%3Bn%2B%2B)%7Bvar%20t%3Darguments%5Bn%5D%3Bfor(var%20r%20in%20t)t.hasOwnProperty(r)%26%26(e%5Br%5D%3Dt%5Br%5D)%7Dreturn%20e%7D(%7B%7D%2Cn%2Ce)%2Cthis.rules%3Dnew%20f(this.options)%7Dfunction%20x(e)%7Bvar%20n%3Dthis%3Breturn%20R.call(e.childNodes%2C(function(e%2Ct)%7Bvar%20r%3D%22%22%3Breturn%203%3D%3D%3D(t%3Dnew%20w(t%2Cn.options)).nodeType%3Fr%3Dt.isCode%3Ft.nodeValue%3An.escape(t.nodeValue)%3A1%3D%3D%3Dt.nodeType%26%26(r%3DB.call(n%2Ct))%2CD(e%2Cr)%7D)%2C%22%22)%7Dfunction%20O(e)%7Bvar%20n%3Dthis%3Breturn%20this.rules.forEach((function(t)%7B%22function%22%3D%3Dtypeof%20t.append%26%26(e%3DD(e%2Ct.append(n.options)))%7D))%2Ce.replace(%2F%5E%5B%5Ct%5Cr%5Cn%5D%2B%2F%2C%22%22).replace(%2F%5B%5Ct%5Cr%5Cn%5Cs%5D%2B%24%2F%2C%22%22)%7Dfunction%20B(e)%7Bvar%20n%3Dthis.rules.forNode(e)%2Ct%3Dx.call(this%2Ce)%2Cr%3De.flankingWhitespace%3Breturn(r.leading%7C%7Cr.trailing)%26%26(t%3Dt.trim())%2Cr.leading%2Bn.replacement(t%2Ce%2Cthis.options)%2Br.trailing%7Dfunction%20D(e%2Cn)%7Bvar%20t%3Dfunction(e)%7Bfor(var%20n%3De.length%3Bn%3E0%26%26%22%5Cn%22%3D%3D%3De%5Bn-1%5D%3B)n--%3Breturn%20e.substring(0%2Cn)%7D(e)%2Cr%3Dn.replace(%2F%5E%5Cn*%2F%2C%22%22)%2Ci%3DMath.max(e.length-t.length%2Cn.length-r.length)%3Breturn%20t%2B%22%5Cn%5Cn%22.substring(0%2Ci)%2Br%7Dk.prototype%3D%7Bturndown%3Afunction(e)%7Bif(!function(e)%7Breturn%20null!%3De%26%26(%22string%22%3D%3Dtypeof%20e%7C%7Ce.nodeType%26%26(1%3D%3D%3De.nodeType%7C%7C9%3D%3D%3De.nodeType%7C%7C11%3D%3D%3De.nodeType))%7D(e))throw%20new%20TypeError(e%2B%22%20is%20not%20a%20string%2C%20or%20an%20element%2Fdocument%2Ffragment%20node.%22)%3Bif(%22%22%3D%3D%3De)return%22%22%3Bvar%20n%3Dx.call(this%2Cnew%20T(e%2Cthis.options))%3Breturn%20O.call(this%2Cn)%7D%2Cuse%3Afunction(e)%7Bif(Array.isArray(e))for(var%20n%3D0%3Bn%3Ce.length%3Bn%2B%2B)this.use(e%5Bn%5D)%3Belse%7Bif(%22function%22!%3Dtypeof%20e)throw%20new%20TypeError(%22plugin%20must%20be%20a%20Function%20or%20an%20Array%20of%20Functions%22)%3Be(this)%7Dreturn%20this%7D%2CaddRule%3Afunction(e%2Cn)%7Breturn%20this.rules.add(e%2Cn)%2Cthis%7D%2Ckeep%3Afunction(e)%7Breturn%20this.rules.keep(e)%2Cthis%7D%2Cremove%3Afunction(e)%7Breturn%20this.rules.remove(e)%2Cthis%7D%2Cescape%3Afunction(e)%7Breturn%20S.reduce((function(e%2Cn)%7Breturn%20e.replace(n%5B0%5D%2Cn%5B1%5D)%7D)%2Ce)%7D%7D%3Bconst%20L%3Dk%7D%2C402%3A(e%2Cn)%3D%3E%7Bn.__esModule%3D!0%2Cn.MarkdownTables%3Dvoid%200%3Bvar%20t%3Dfunction()%7Bfunction%20e()%7B%7Dreturn%20e.tableShouldBeSkipped%3Dfunction(n)%7Breturn!n%7C%7C!n.rows%7C%7C1%3D%3D%3Dn.rows.length%26%26n.rows%5B0%5D.childNodes.length%3C%3D1%7C%7C!!e.nodeContainsTable(n)%7D%2Ce.isHeadingRow%3Dfunction(n)%7Bvar%20t%3Dn.parentNode%2Cr%3D!1%3Breturn%20t%26%26(%22THEAD%22%3D%3D%3Dt.nodeName%3Fr%3D!0%3At.firstChild!%3D%3Dn%3Fr%3D!1%3A(%22TABLE%22%3D%3D%3Dt.nodeName%7C%7Ce.isFirstTbody(t))%26%26(r%3DArray.prototype.every.call(n.childNodes%2C(function(e)%7Breturn%22TH%22%3D%3D%3De.nodeName%7D))))%2Cr%7D%2Ce.isFirstTbody%3Dfunction(e)%7Bvar%20n%3De.previousSibling%2Ct%3D!1%3Breturn%20n%26%26(t%3D!(%22TBODY%22!%3D%3De.nodeName%7C%7Cn%26%26(%22THEAD%22!%3D%3Dn.nodeName%7C%7C!n.textContent%7C%7C!%2F%5E%5Cs*%24%2Fi.test(n.textContent))))%2Ct%7D%2Ce.cell%3Dfunction(n%2Ct%2Cr)%7Bvoid%200%3D%3D%3Dt%26%26(t%3Dnull)%2Cvoid%200%3D%3D%3Dr%26%26(r%3Dnull)%2Cnull%3D%3D%3Dr%26%26null!%3Dt%26%26t.parentNode%26%26(r%3DArray.prototype.indexOf.call(t.parentNode.childNodes%2Ct))%3Bvar%20i%3D%22%20%22%3B0%3D%3D%3Dr%26%26(i%3D%22%7C%20%22)%3Bvar%20o%3Dn.trim().replace(%2F%5Cn%5Cr%2Fg%2C%22%3Cbr%3E%22).replace(%2F%5Cn%2Fg%2C%22%3Cbr%3E%22)%3Bfor(o%3Do.replace(%2F%5C%7C%2B%2Fg%2C%22%5C%5C%7C%22)%3Bo.length%3C3%3B)o%2B%3D%22%20%22%3Breturn%20t%26%26(o%3De.handleColSpan(o%2Ct%2C%22%20%22))%2Ci%2Bo%2B%22%20%7C%22%7D%2Ce.nodeContainsTable%3Dfunction(n)%7Bif(!n.childNodes)return!1%3Bfor(var%20t%3D0%3Bt%3Cn.childNodes.length%3Bt%2B%2B)%7Bvar%20r%3Dn.childNodes%5Bt%5D%3Bif(%22TABLE%22%3D%3D%3Dr.nodeName)return!0%3Bif(e.nodeContainsTable(r))return!0%7Dreturn!1%7D%2Ce.nodeParentTable%3Dfunction(e)%7Bvar%20n%3De.parentNode%3Bif(n)for(%3Bn%26%26%22TABLE%22!%3D%3Dn.nodeName%3B)n%3Dn.parentNode%3Breturn%20n%7D%2Ce.handleColSpan%3Dfunction(e%2Cn%2Ct)%7Bfor(var%20r%3Dn.getAttribute(%22colspan%22)%7C%7C%221%22%2Ci%3D1%3Bi%3CparseInt(r%2C10)%3Bi%2B%2B)e%2B%3D%22%20%7C%20%22%2Bt.repeat(3)%3Breturn%20e%7D%2Ce.tableColCount%3Dfunction(e)%7Bvar%20n%3D0%3Bif(e%26%26e.rows)for(var%20t%3D0%3Bt%3Ce.rows.length%3Bt%2B%2B)%7Bvar%20r%3De.rows%5Bt%5D.childNodes.length%3Br%3En%26%26(n%3Dr)%7Dreturn%20n%7D%2Ce%7D()%2Cr%3Dfunction()%7Bfunction%20e()%7B%7Dreturn%20e.prototype.tables%3Dfunction(e)%7Be.keep((function(e)%7Bvar%20n%3D!1%3Breturn%20e.nodeName%26%26(n%3D%22TABLE%22%3D%3D%3De.nodeName)%2Cn%7D))%3Bvar%20n%2Cr%3D%7BtableCell%3A%7Bfilter%3A%5B%22th%22%2C%22td%22%5D%2Creplacement%3Afunction(e%2Cn)%7Breturn%20t.tableShouldBeSkipped(t.nodeParentTable(n))%3Fe%3At.cell(e%2Cn)%7D%7D%2CtableRow%3A%7Bfilter%3A%22tr%22%2Creplacement%3Afunction(e%2Cn)%7Bvar%20r%3Dt.nodeParentTable(n)%3Bif(t.tableShouldBeSkipped(r))return%20e%3Bvar%20i%3D%22%22%2Co%3D%7Bleft%3A%22%3A--%22%2Cright%3A%22--%3A%22%2Ccenter%3A%22%3A-%3A%22%7D%3Bif(t.isHeadingRow(n))for(var%20a%3Dt.tableColCount(r)%2Cl%3D0%3Bl%3Ca%3Bl%2B%2B)%7Bvar%20d%3Da%3E%3Dn.childNodes.length%3Fnull%3An.childNodes%5Bl%5D%2Cc%3D%22---%22%2Cu%3Dd%3F(d.getAttribute(%22align%22)%7C%7C%22%22).toLowerCase()%3A%22%22%3Bu%26%26(c%3Do%5Bu%5D%7C%7Cc)%2Ci%2B%3Dd%3Ft.cell(c%2Cn.childNodes%5Bl%5D)%3At.cell(c%2Cnull%2Cl)%7Dreturn%22%5Cn%22%2Be%2B(i%3F%22%5Cn%22%2Bi%3A%22%22)%7D%7D%2Ctable%3A%7Bfilter%3Afunction(e)%7Breturn%22TABLE%22%3D%3D%3De.nodeName%7D%2Creplacement%3Afunction(e%2Cn)%7Bif(t.tableShouldBeSkipped(n))return%20e%3Bvar%20r%3D(e%3De.replace(%2F%5Cn%2B%2Fg%2C%22%5Cn%22)).trim().split(%22%5Cn%22)%3Br.length%3E%3D2%26%26(r%3Dr%5B1%5D)%3Bvar%20i%3D0%3D%3D%3Dr.indexOf(%22%7C%20---%22)%2Co%3Dt.tableColCount(n)%2Ca%3D%22%22%3Breturn%20o%26%26!i%26%26(a%3D%22%7C%22%2B%22%20%20%20%20%20%7C%22.repeat(o)%2B%22%5Cn%7C%22%2B%22%20---%20%7C%22.repeat(o))%2C%22%5Cn%5Cn%22%2Ba%2Be%2B%22%5Cn%5Cn%22%7D%7D%2CtableSection%3A%7Bfilter%3A%5B%22thead%22%2C%22tbody%22%2C%22tfoot%22%5D%2Creplacement%3Afunction(e)%7Breturn%20e%7D%7D%7D%3Bfor(n%20in%20r)e.addRule(n%2Cr%5Bn%5D)%7D%2Ce%7D()%3Bn.MarkdownTables%3Dr%7D%7D%2Cr%3D%7B%7D%3Bfunction%20i(e)%7Bvar%20n%3Dr%5Be%5D%3Bif(void%200!%3D%3Dn)return%20n.exports%3Bvar%20o%3Dr%5Be%5D%3D%7Bexports%3A%7B%7D%7D%3Breturn%20t%5Be%5D(o%2Co.exports%2Ci)%2Co.exports%7Di.d%3D(e%2Cn)%3D%3E%7Bfor(var%20t%20in%20n)i.o(n%2Ct)%26%26!i.o(e%2Ct)%26%26Object.defineProperty(e%2Ct%2C%7Benumerable%3A!0%2Cget%3An%5Bt%5D%7D)%7D%2Ci.o%3D(e%2Cn)%3D%3EObject.prototype.hasOwnProperty.call(e%2Cn)%2Ci.r%3De%3D%3E%7B%22undefined%22!%3Dtypeof%20Symbol%26%26Symbol.toStringTag%26%26Object.defineProperty(e%2CSymbol.toStringTag%2C%7Bvalue%3A%22Module%22%7D)%2CObject.defineProperty(e%2C%22__esModule%22%2C%7Bvalue%3A!0%7D)%7D%2Ce%3Di(36)%2Cn%3Di(402)%2Cfunction(t%2Cr%2Ci%2Co)%7Bvar%20a%3DencodeURIComponent(%22${this.vaultName}%22)%2Cl%3DencodeURIComponent(%22${this.notePath}%22)%2Cd%3DencodeURIComponent(%22${this.captureComments}%22)%2Cc%3D%22%22%2Cu%3Dnew%20e.default(%7BheadingStyle%3A%22atx%22%2Chr%3A%22---%22%2CbulletListMarker%3A%22-%22%2CcodeBlockStyle%3A%22fenced%22%2CemDelimiter%3A%22*%22%7D)%2Cs%3Dnew%20n.MarkdownTables%3Bu.use(s.tables)%2Cu.addRule(%22heading_1_update%22%2C%7Bfilter%3A%5B%22h1%22%5D%2Creplacement%3Afunction(e)%7Breturn%22%22.concat(i.h1%2C%22%20%22).concat(e)%7D%7D)%2Cu.addRule(%22heading_2_update%22%2C%7Bfilter%3A%5B%22h2%22%5D%2Creplacement%3Afunction(e)%7Breturn%22%22.concat(i.h2%2C%22%20%22).concat(e)%7D%7D)%2Cu.addRule(%22heading_3_update%22%2C%7Bfilter%3A%5B%22h3%22%5D%2Creplacement%3Afunction(e)%7Breturn%22%22.concat(i.h3%2C%22%20%22).concat(e)%7D%7D)%2Cu.addRule(%22heading_4_update%22%2C%7Bfilter%3A%5B%22h4%22%5D%2Creplacement%3Afunction(e)%7Breturn%22%22.concat(i.h4%2C%22%20%22).concat(e)%7D%7D)%2Cu.addRule(%22heading_5_update%22%2C%7Bfilter%3A%5B%22h5%22%5D%2Creplacement%3Afunction(e)%7Breturn%22%22.concat(i.h5%2C%22%20%22).concat(e)%7D%7D)%2Cu.addRule(%22heading_6_update%22%2C%7Bfilter%3A%5B%22h6%22%5D%2Creplacement%3Afunction(e)%7Breturn%22%22.concat(i.h6%2C%22%20%22).concat(e)%7D%7D)%2Cu.addRule(%22fix_relative_links%22%2C%7Bfilter%3A%5B%22a%22%5D%2Creplacement%3Afunction(e%2Cn)%7Bvar%20t%3Dn.href%3Breturn%20t.includes(%22%3A%2F%2F%22)%7C%7C(t%3Dwindow.location.protocol%2B%22%2F%2F%22%2Bwindow.location.host%2Bt)%2C%22%5B%22.concat(e%2C%22%5D(%22).concat(t%2C%22)%22)%7D%7D)%3Bvar%20p%3Du.turndown(function()%7Bvar%20e%3D%22%22%3Bif(void%200!%3D%3Dwindow.getSelection)%7Bvar%20n%3Dwindow.getSelection()%3Bif(n%26%26n.rangeCount)%7Bfor(var%20t%3Ddocument.createElement(%22div%22)%2Cr%3D0%2Ci%3Dn.rangeCount%3Br%3Ci%3B%2B%2Br)t.appendChild(n.getRangeAt(r).cloneContents())%3Be%3Dt.innerHTML%7D%7Dreturn%20e%7D())%3Bfunction%20f()%7Bvar%20e%3Ddocument.getElementsByClassName(%22obsidian-clipper-modal-overlay%22)%5B0%5D%3Bif(e)%7Bvar%20n%3Ddocument.getElementById(%22obsidian-clipper-comment%22)%3Bc%3Dn.value%2Cn.value%3D%22%22%2Ce.style.display%3D%22none%22%7Dvar%20t%3Ddocument.URL%2Cr%3Ddocument.title%2Ci%3D%22obsidian%3A%2F%2Fobsidian-clipper%3Fvault%3D%22.concat(a%2C%22%26notePath%3D%22).concat(l%2C%22%26url%3D%22).concat(encodeURIComponent(t)%2C%22%26format%3Dmd%26title%3D%22).concat(encodeURIComponent(r)%2C%22%26highlightdata%3D%22).concat(encodeURIComponent(p)%2C%22%26comments%3D%22).concat(encodeURIComponent(c))%3B-1!%3D%3Dnavigator.userAgent.indexOf(%22Chrome%22)%26%26-1!%3D%3Dnavigator.userAgent.indexOf(%22Windows%22)%26%26i.length%3E%3D2e3%26%26alert(%22Chrome%20on%20Windows%20doesn't%20allow%20a%20highlight%20this%20large.%20%22.concat(i.length%2C%22%20characters%20have%20been%20selected%20and%20it%20must%20be%20less%20than%202000%22))%2Cfunction(e)%7Breturn-1!%3D%3Dnavigator.userAgent.indexOf(%22Chrome%22)%26%26-1!%3D%3Dnavigator.userAgent.indexOf(%22Windows%22)%26%26e.length%3E%3D2e3%26%26(alert(%22Chrome%20on%20Windows%20doesn't%20allow%20a%20highlight%20this%20large.%5Cn%20%22.concat(e.length%2C%22%20characters%20have%20been%20selected%20and%20it%20must%20be%20less%20than%202000.%20%5Cn%5Cn%20Firefox%20on%20Windows%20doesn't%20seem%20to%20have%20this%20same%20problem.%22))%2C!0)%7D(i)%7C%7C(document.location.href%3Di)%7D%22true%22%3D%3D%3Dd%3Ffunction()%7Bvar%20e%2Cn%3Ddocument.getElementsByClassName(%22obsidian-clipper-modal-overlay%22)%5B0%5D%3Bif(n)n.style.display%3D%22block%22%3Belse%7Bvar%20t%3Ddocument.createElement(%22style%22)%2Cr%3Ddocument.createTextNode(%22%5Cn.obsidian-clipper-modal%20%7B%5Cn%5Ctz-index%3A%2010000%3B%5Cn%5Ctposition%3A%20fixed%3B%5Cn%5Cttop%3A%2050%25%3B%5Cn%5Ctleft%3A%2050%25%3B%5Cn%5Cttransform%3A%20translate(-50%25%2C%20-50%25)%3B%5Cn%5Ctdisplay%3A%20flex%3B%5Cn%20%20flex-direction%3A%20column%3B%5Cn%20%20gap%3A%200.4rem%3B%5Cn%20%20width%3A%20450px%3B%5Cn%20%20padding%3A%201.3rem%3B%5Cn%20%20background-color%3A%20white%3B%5Cn%20%20border%3A%201px%20solid%20%23ddd%3B%5Cn%20%20border-radius%3A%2015px%3B%5Cn%7D%5Cn.obsidian-clipper-modal%20.flex%20%7B%5Cn%20%20display%3A%20flex%3B%5Cn%20%20align-items%3A%20center%3B%5Cn%20%20justify-content%3A%20space-between%3B%5Cn%7D%5Cn%5Cn.obsidian-clipper-modal%20input%20%7B%5Cn%20%20padding%3A%200.7rem%201rem%3B%5Cn%20%20border%3A%201px%20solid%20%23ddd%3B%5Cn%20%20border-radius%3A%205px%3B%5Cn%20%20font-size%3A%200.9em%3B%5Cn%7D%5Cn%5Cn.obsidian-clipper-modal%20p%20%7B%5Cn%20%20font-size%3A%200.9rem%3B%5Cn%20%20color%3A%20%23777%3B%5Cn%20%20margin%3A%200.4rem%200%200.2rem%3B%5Cn%7D%5Cn%5Cn.obsidian-clipper-modal%20label%20%7B%5Cndisplay%3A%20block%3B%20%5Cnmargin-bottom%3A%200.5rem%3B%20%5Cncolor%3A%20%23111827%3B%20%5Cnfont-size%3A%200.875rem%3B%5Cnline-height%3A%201.25rem%3B%20%5Cnfont-weight%3A%20500%3B%5Cn%7D%5Cn%5Cn.obsidian-clipper-modal%20textarea%20%7B%5Cn%5Ctdisplay%3A%20block%3B%20!important%3B%20%5Cn%5Ctpadding%3A%200.625rem%20!important%3B%20%5Cn%5Ctbackground-color%3A%20%23F9FAFB%20!important%3B%20%5Cn%5Ctcolor%3A%20%23111827%20!important%3B%20%5Cn%5Ctfont-size%3A%200.875rem%20!important%3B%20%5Cn%5Ctline-height%3A%201.25rem%20!important%3B%20%5Cn%20%5Ctwidth%3A%20100%25%20!important%3B%20%5Cn%5Ctborder-radius%3A%200.5rem%20!important%3B%20%5Cn%5Ctborder-width%3A%201px%20!important%3B%20%5Cn%5Ctborder-color%3A%20%23D1D5DB%20!important%3B%20%5Cn%7D%5Cn%5Cn.obsidian-clipper-modal%20button%20%7B%5Cn%5Ctpadding-top%3A%200.625rem%20!important%3B%5Cnpadding-bottom%3A%200.625rem%20!important%3B%5Cnpadding-left%3A%201.25rem%20!important%3B%5Cnpadding-right%3A%201.25rem%20!important%3B%5Cnmargin-right%3A%200.5rem%20!important%3B%5Cnmargin-bottom%3A%200.5rem%20!important%3B%5Cnbackground-color%3A%20%231F2937%20!important%3B%5Cncolor%3A%20%23ffffff%20!important%3B%5Cnfont-size%3A%200.875rem%20!important%3B%5Cnline-height%3A%201.25rem%20!important%3B%5Cnfont-weight%3A%20500%20!important%3B%5Cnborder-radius%3A%200.5rem%20!important%3B%5Cn%7D%5Cn%5Cn.obsidian-clipper-modal-overlay%20%7B%5Cn%20%20background%3A%20rgba(0%2C%200%2C%200%2C%200.6)%3B%5Cn%20%20position%3A%20fixed%3B%5Cn%20%20top%3A%200%3B%5Cn%20%20left%3A%200%3B%5Cn%20%20right%3A%200%3B%5Cn%20%20bottom%3A%200%3B%5Cn%20%20z-index%3A%209999%3B%5Cn%7D%5Cn%5Cn%22)%3Bt.appendChild(r)%2Cdocument.getElementsByTagName(%22head%22)%5B0%5D.appendChild(t)%3Bvar%20i%3Ddocument.createElement(%22div%22)%2Co%3Ddocument.createElement(%22div%22)%3Bo.innerHTML%3D'%5Cn%5Ct%5Ct%3Cdiv%3E%5Cn%5Ct%5Ct%5Ct%3Clabel%3EObsidian%20Clipper%3C%2Flabel%3E%5Cn%5Ct%5Ct%5Ct%3Ctextarea%20id%3D%22obsidian-clipper-comment%22%20rows%3D%226%22%5Ctplaceholder%3D%22Add%20your%20thoughts...%22%3E%3C%2Ftextarea%3E%5Cn%5Ct%5Ct%3C%2Fdiv%3E'%3Bvar%20a%3Ddocument.createElement(%22button%22)%3Ba.appendChild(document.createTextNode(%22Submit%22))%2Ca.addEventListener(%22click%22%2Cf%2C!1)%2Co.appendChild(a)%2Co.classList.add(%22obsidian-clipper-modal%22)%2Ci.classList.add(%22obsidian-clipper-modal-overlay%22)%2Ci.appendChild(o)%2Cdocument.body.appendChild(i)%2Cnull%3D%3D%3D(e%3Ddocument.getElementById(%22obsidian-clipper-comment%22))%7C%7Cvoid%200%3D%3D%3De%7C%7Ce.focus()%7D%7D()%3Af()%7D(0%2C0%2C%7Bh1%3A%22${this.markdownSettings.h1}%22%2Ch2%3A%22${this.markdownSettings.h2}%22%2Ch3%3A%22${this.markdownSettings.h3}%22%2Ch4%3A%22${this.markdownSettings.h4}%22%2Ch5%3A%22${this.markdownSettings.h5}%22%2Ch6%3A%22${this.markdownSettings.h6}%22%7D)%7D)()%3B%7D)()`; + } +}; + +// src/settings/BookmarkletSettingsGroup.svelte +function create_fragment10(ctx) { + let div3; + let div2; + let div1; + let div0; + let t1; + let a; + let t2; + let t3; + let t4; + return { + c() { + div3 = element("div"); + div2 = element("div"); + div1 = element("div"); + div0 = element("div"); + div0.textContent = "You can drag or copy the link below to your browser bookmark bar. This\n bookmarklet will allow you to highlight information on the web and send\n it to obsidian"; + t1 = space(); + a = element("a"); + t2 = text("Obsidian Clipper ("); + t3 = text(ctx[1]); + t4 = text(")"); + attr(a, "href", ctx[0]); + attr(div1, "class", "flex-1 basis-0"); + attr(div2, "class", "flex flex-row"); + attr(div3, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div3, anchor); + append(div3, div2); + append(div2, div1); + append(div1, div0); + append(div1, t1); + append(div1, a); + append(a, t2); + append(a, t3); + append(a, t4); + }, + p(ctx2, [dirty]) { + if (dirty & 2) + set_data(t3, ctx2[1]); + if (dirty & 1) { + attr(a, "href", ctx2[0]); + } + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) + detach(div3); + } + }; +} +function instance10($$self, $$props, $$invalidate) { + let { clipperHref } = $$props; + let { noteOrVault } = $$props; + $$self.$$set = ($$props2) => { + if ("clipperHref" in $$props2) + $$invalidate(0, clipperHref = $$props2.clipperHref); + if ("noteOrVault" in $$props2) + $$invalidate(1, noteOrVault = $$props2.noteOrVault); + }; + return [clipperHref, noteOrVault]; +} +var BookmarkletSettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance10, create_fragment10, safe_not_equal, { clipperHref: 0, noteOrVault: 1 }); + } +}; +var BookmarkletSettingsGroup_default = BookmarkletSettingsGroup; + +// src/settings/ExtensionSettingsGroup.svelte +var import_obsidian5 = require("obsidian"); +function create_fragment11(ctx) { + let div3; + let div2; + let div0; + let t0; + let span; + let t1; + let t2; + let t3; + let div1; + let button; + let t4; + let t5; + let t6; + let mounted; + let dispose; + return { + c() { + div3 = element("div"); + div2 = element("div"); + div0 = element("div"); + t0 = text("Click the button below to generate a personalized Chrome-based extension\n for the "); + span = element("span"); + t1 = text(ctx[0]); + t2 = text(". After clicking\n the button, use the link to download the .zip file."); + t3 = space(); + div1 = element("div"); + button = element("button"); + t4 = text("Chrome Extension ("); + t5 = text(ctx[0]); + t6 = text(")"); + attr(span, "class", "font-extrabold"); + attr(div1, "class", "my-4"); + attr(div3, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div3, anchor); + append(div3, div2); + append(div2, div0); + append(div0, t0); + append(div0, span); + append(span, t1); + append(div0, t2); + append(div2, t3); + append(div2, div1); + append(div1, button); + append(button, t4); + append(button, t5); + append(button, t6); + ctx[4](div1); + if (!mounted) { + dispose = listen(button, "click", ctx[2]); + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & 1) + set_data(t1, ctx2[0]); + if (dirty & 1) + set_data(t5, ctx2[0]); + }, + i: noop, + o: noop, + d(detaching) { + if (detaching) + detach(div3); + ctx[4](null); + mounted = false; + dispose(); + } + }; +} +function instance11($$self, $$props, $$invalidate) { + let { clipperHref } = $$props; + let { noteOrVault } = $$props; + let s3LinkContainer; + const getExtension = async () => { + const response = await (0, import_obsidian5.requestUrl)({ + url: "https://obsidianclipper.com/api/extension", + contentType: "application/json", + method: "POST", + body: JSON.stringify({ + name: noteOrVault, + bookmarklet_code: clipperHref + }) + }); + const s3Link = window.document.createElement("a"); + s3Link.href = response.json.data.link; + s3Link.textContent = "Download Chrome Extension"; + s3LinkContainer.replaceChildren(s3Link); + }; + function div1_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + s3LinkContainer = $$value; + $$invalidate(1, s3LinkContainer); + }); + } + $$self.$$set = ($$props2) => { + if ("clipperHref" in $$props2) + $$invalidate(3, clipperHref = $$props2.clipperHref); + if ("noteOrVault" in $$props2) + $$invalidate(0, noteOrVault = $$props2.noteOrVault); + }; + return [noteOrVault, s3LinkContainer, getExtension, clipperHref, div1_binding]; +} +var ExtensionSettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance11, create_fragment11, safe_not_equal, { clipperHref: 3, noteOrVault: 0 }); + } +}; +var ExtensionSettingsGroup_default = ExtensionSettingsGroup; + +// src/settings/LinksSettingsGroup.svelte +function create_if_block5(ctx) { + let div4; + let div2; + let t3; + let div3; + let input; + let mounted; + let dispose; + return { + c() { + div4 = element("div"); + div2 = element("div"); + div2.innerHTML = `
    Capture Comment in Browser
    +
    Display a modal in the browser to capture any comments before sending + to Obsidian?
    `; + t3 = space(); + div3 = element("div"); + input = element("input"); + attr(div2, "class", "setting-item-info"); + attr(input, "type", "checkbox"); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + }, + m(target, anchor) { + insert(target, div4, anchor); + append(div4, div2); + append(div4, t3); + append(div4, div3); + append(div3, input); + input.checked = ctx[1].captureComments; + if (!mounted) { + dispose = [ + listen(input, "change", ctx[6]), + listen(input, "change", ctx[3]) + ]; + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & 2) { + input.checked = ctx2[1].captureComments; + } + }, + d(detaching) { + if (detaching) + detach(div4); + mounted = false; + run_all(dispose); + } + }; +} +function create_fragment12(ctx) { + let div0; + let bookmarkletsettingsgroup; + let t0; + let extensionsettingsgroup; + let t1; + let div28; + let h10; + let t3; + let t4; + let div2; + let t6; + let div7; + let div5; + let t10; + let div6; + let input0; + let t11; + let div12; + let div10; + let t15; + let div11; + let input1; + let t16; + let div17; + let div15; + let t20; + let div16; + let input2; + let t21; + let div22; + let div20; + let t25; + let div21; + let input3; + let t26; + let div27; + let div25; + let t30; + let div26; + let input4; + let current; + let mounted; + let dispose; + bookmarkletsettingsgroup = new BookmarkletSettingsGroup_default({ + props: { + clipperHref: ctx[0], + noteOrVault: ctx[2] + } + }); + extensionsettingsgroup = new ExtensionSettingsGroup_default({ + props: { + clipperHref: ctx[0], + noteOrVault: ctx[2] + } + }); + let if_block = ctx[1].experimentalBookmarkletComment && create_if_block5(ctx); + return { + c() { + div0 = element("div"); + create_component(bookmarkletsettingsgroup.$$.fragment); + t0 = space(); + create_component(extensionsettingsgroup.$$.fragment); + t1 = space(); + div28 = element("div"); + h10 = element("h1"); + h10.textContent = "Bookmarklet Settings"; + t3 = space(); + if (if_block) + if_block.c(); + t4 = space(); + div2 = element("div"); + div2.innerHTML = `

    Markdown Headings

    `; + t6 = space(); + div7 = element("div"); + div5 = element("div"); + div5.innerHTML = `
    H2
    +
    What should replace H2 elements found in the highlight data?
    `; + t10 = space(); + div6 = element("div"); + input0 = element("input"); + t11 = space(); + div12 = element("div"); + div10 = element("div"); + div10.innerHTML = `
    H3
    +
    What should replace H3 elements found in the highlight data?
    `; + t15 = space(); + div11 = element("div"); + input1 = element("input"); + t16 = space(); + div17 = element("div"); + div15 = element("div"); + div15.innerHTML = `
    H4
    +
    What should replace H4 elements found in the highlight data?
    `; + t20 = space(); + div16 = element("div"); + input2 = element("input"); + t21 = space(); + div22 = element("div"); + div20 = element("div"); + div20.innerHTML = `
    H5
    +
    What should replace H5 elements found in the highlight data?
    `; + t25 = space(); + div21 = element("div"); + input3 = element("input"); + t26 = space(); + div27 = element("div"); + div25 = element("div"); + div25.innerHTML = `
    H6
    +
    What should replace H6 elements found in the highlight data?
    `; + t30 = space(); + div26 = element("div"); + input4 = element("input"); + attr(div0, "class", "clp_section_margin"); + attr(div2, "class", "setting-item"); + attr(div5, "class", "setting-item-info"); + attr(input0, "type", "text"); + attr(input0, "spellcheck", "false"); + attr(input0, "placeholder", ""); + attr(div6, "class", "setting-item-control"); + attr(div7, "class", "setting-item"); + attr(div10, "class", "setting-item-info"); + attr(input1, "type", "text"); + attr(input1, "spellcheck", "false"); + attr(input1, "placeholder", ""); + attr(div11, "class", "setting-item-control"); + attr(div12, "class", "setting-item"); + attr(div15, "class", "setting-item-info"); + attr(input2, "type", "text"); + attr(input2, "spellcheck", "false"); + attr(input2, "placeholder", ""); + attr(div16, "class", "setting-item-control"); + attr(div17, "class", "setting-item"); + attr(div20, "class", "setting-item-info"); + attr(input3, "type", "text"); + attr(input3, "spellcheck", "false"); + attr(input3, "placeholder", ""); + attr(div21, "class", "setting-item-control"); + attr(div22, "class", "setting-item"); + attr(div25, "class", "setting-item-info"); + attr(input4, "type", "text"); + attr(input4, "spellcheck", "false"); + attr(input4, "placeholder", ""); + attr(div26, "class", "setting-item-control"); + attr(div27, "class", "setting-item"); + attr(div28, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div0, anchor); + mount_component(bookmarkletsettingsgroup, div0, null); + append(div0, t0); + mount_component(extensionsettingsgroup, div0, null); + insert(target, t1, anchor); + insert(target, div28, anchor); + append(div28, h10); + append(div28, t3); + if (if_block) + if_block.m(div28, null); + append(div28, t4); + append(div28, div2); + append(div28, t6); + append(div28, div7); + append(div7, div5); + append(div7, t10); + append(div7, div6); + append(div6, input0); + set_input_value(input0, ctx[1].markdownSettings.h2); + append(div28, t11); + append(div28, div12); + append(div12, div10); + append(div12, t15); + append(div12, div11); + append(div11, input1); + set_input_value(input1, ctx[1].markdownSettings.h3); + append(div28, t16); + append(div28, div17); + append(div17, div15); + append(div17, t20); + append(div17, div16); + append(div16, input2); + set_input_value(input2, ctx[1].markdownSettings.h4); + append(div28, t21); + append(div28, div22); + append(div22, div20); + append(div22, t25); + append(div22, div21); + append(div21, input3); + set_input_value(input3, ctx[1].markdownSettings.h5); + append(div28, t26); + append(div28, div27); + append(div27, div25); + append(div27, t30); + append(div27, div26); + append(div26, input4); + set_input_value(input4, ctx[1].markdownSettings.h6); + current = true; + if (!mounted) { + dispose = [ + listen(input0, "input", ctx[7]), + listen(input1, "input", ctx[8]), + listen(input2, "input", ctx[9]), + listen(input3, "input", ctx[10]), + listen(input4, "input", ctx[11]) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + const bookmarkletsettingsgroup_changes = {}; + if (dirty & 1) + bookmarkletsettingsgroup_changes.clipperHref = ctx2[0]; + bookmarkletsettingsgroup.$set(bookmarkletsettingsgroup_changes); + const extensionsettingsgroup_changes = {}; + if (dirty & 1) + extensionsettingsgroup_changes.clipperHref = ctx2[0]; + extensionsettingsgroup.$set(extensionsettingsgroup_changes); + if (ctx2[1].experimentalBookmarkletComment) { + if (if_block) { + if_block.p(ctx2, dirty); + } else { + if_block = create_if_block5(ctx2); + if_block.c(); + if_block.m(div28, t4); + } + } else if (if_block) { + if_block.d(1); + if_block = null; + } + if (dirty & 2 && input0.value !== ctx2[1].markdownSettings.h2) { + set_input_value(input0, ctx2[1].markdownSettings.h2); + } + if (dirty & 2 && input1.value !== ctx2[1].markdownSettings.h3) { + set_input_value(input1, ctx2[1].markdownSettings.h3); + } + if (dirty & 2 && input2.value !== ctx2[1].markdownSettings.h4) { + set_input_value(input2, ctx2[1].markdownSettings.h4); + } + if (dirty & 2 && input3.value !== ctx2[1].markdownSettings.h5) { + set_input_value(input3, ctx2[1].markdownSettings.h5); + } + if (dirty & 2 && input4.value !== ctx2[1].markdownSettings.h6) { + set_input_value(input4, ctx2[1].markdownSettings.h6); + } + }, + i(local) { + if (current) + return; + transition_in(bookmarkletsettingsgroup.$$.fragment, local); + transition_in(extensionsettingsgroup.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(bookmarkletsettingsgroup.$$.fragment, local); + transition_out(extensionsettingsgroup.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) + detach(div0); + destroy_component(bookmarkletsettingsgroup); + destroy_component(extensionsettingsgroup); + if (detaching) + detach(t1); + if (detaching) + detach(div28); + if (if_block) + if_block.d(); + mounted = false; + run_all(dispose); + } + }; +} +function instance12($$self, $$props, $$invalidate) { + let $settings; + component_subscribe($$self, settings, ($$value) => $$invalidate(1, $settings = $$value)); + let { vaultName = "" } = $$props; + let { filePath = "" } = $$props; + let fileName = ""; + if (filePath !== "") { + fileName = getFileName(filePath); + } + let noteOrVault = fileName !== "" ? `${fileName} file` : `${vaultName} vault`; + let clipperHref = new BookmarketlGenerator(vaultName, filePath, $settings.markdownSettings, ($settings.experimentalBookmarkletComment && $settings.captureComments).toString()).generateBookmarklet(); + let updateClipperHref = () => { + $$invalidate(0, clipperHref = new BookmarketlGenerator(vaultName, filePath, $settings.markdownSettings, ($settings.experimentalBookmarkletComment && $settings.captureComments).toString()).generateBookmarklet()); + }; + function input_change_handler() { + $settings.captureComments = this.checked; + settings.set($settings); + } + function input0_input_handler() { + $settings.markdownSettings.h2 = this.value; + settings.set($settings); + } + function input1_input_handler() { + $settings.markdownSettings.h3 = this.value; + settings.set($settings); + } + function input2_input_handler() { + $settings.markdownSettings.h4 = this.value; + settings.set($settings); + } + function input3_input_handler() { + $settings.markdownSettings.h5 = this.value; + settings.set($settings); + } + function input4_input_handler() { + $settings.markdownSettings.h6 = this.value; + settings.set($settings); + } + $$self.$$set = ($$props2) => { + if ("vaultName" in $$props2) + $$invalidate(4, vaultName = $$props2.vaultName); + if ("filePath" in $$props2) + $$invalidate(5, filePath = $$props2.filePath); + }; + return [ + clipperHref, + $settings, + noteOrVault, + updateClipperHref, + vaultName, + filePath, + input_change_handler, + input0_input_handler, + input1_input_handler, + input2_input_handler, + input3_input_handler, + input4_input_handler + ]; +} +var LinksSettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance12, create_fragment12, safe_not_equal, { vaultName: 4, filePath: 5 }); + } +}; +var LinksSettingsGroup_default = LinksSettingsGroup; + +// src/settings/AdvancedSettingsGroup.svelte +function create_if_block6(ctx) { + let div5; + let div4; + let div2; + let t3; + let div3; + let input; + let div5_intro; + let div5_outro; + let current; + let mounted; + let dispose; + return { + c() { + div5 = element("div"); + div4 = element("div"); + div2 = element("div"); + div2.innerHTML = `
    Clipped Entry Storage Location
    +
    Choose the folder to store all of your clippings. A note per domain + clipped from. Default is a \`clippings\`
    `; + t3 = space(); + div3 = element("div"); + input = element("input"); + attr(div2, "class", "setting-item-info"); + attr(input, "type", "text"); + attr(input, "spellcheck", "false"); + attr(input, "placeholder", ""); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + }, + m(target, anchor) { + insert(target, div5, anchor); + append(div5, div4); + append(div4, div2); + append(div4, t3); + append(div4, div3); + append(div3, input); + set_input_value(input, ctx[0].advancedStorageFolder); + current = true; + if (!mounted) { + dispose = listen(input, "input", ctx[2]); + mounted = true; + } + }, + p(ctx2, dirty) { + if (dirty & 1 && input.value !== ctx2[0].advancedStorageFolder) { + set_input_value(input, ctx2[0].advancedStorageFolder); + } + }, + i(local) { + if (current) + return; + if (local) { + add_render_callback(() => { + if (div5_outro) + div5_outro.end(1); + div5_intro = create_in_transition(div5, slide, { duration: 300 }); + div5_intro.start(); + }); + } + current = true; + }, + o(local) { + if (div5_intro) + div5_intro.invalidate(); + if (local) { + div5_outro = create_out_transition(div5, slide, { duration: 300 }); + } + current = false; + }, + d(detaching) { + if (detaching) + detach(div5); + if (detaching && div5_outro) + div5_outro.end(); + mounted = false; + dispose(); + } + }; +} +function create_fragment13(ctx) { + let div5; + let h10; + let t1; + let div4; + let div2; + let t5; + let div3; + let label0; + let input0; + let t6; + let t7; + let div13; + let h11; + let t9; + let div8; + let div6; + let t11; + let div7; + let label1; + let input1; + let t12; + let div12; + let div10; + let t16; + let div11; + let label2; + let input2; + let mounted; + let dispose; + let if_block = ctx[0].advanced && create_if_block6(ctx); + return { + c() { + div5 = element("div"); + h10 = element("h1"); + h10.textContent = "Advanced Settings"; + t1 = space(); + div4 = element("div"); + div2 = element("div"); + div2.innerHTML = `
    Store Clippings Per Domain
    +
    Creates a note per top-level domain and stores all clippings from that + domain within it. It will add an embedded document link in your Daily + Note.
    `; + t5 = space(); + div3 = element("div"); + label0 = element("label"); + input0 = element("input"); + t6 = space(); + if (if_block) + if_block.c(); + t7 = space(); + div13 = element("div"); + h11 = element("h1"); + h11.textContent = "Experimental Settings"; + t9 = space(); + div8 = element("div"); + div6 = element("div"); + div6.innerHTML = `

    Support Canvas

    `; + t11 = space(); + div7 = element("div"); + label1 = element("label"); + input1 = element("input"); + t12 = space(); + div12 = element("div"); + div10 = element("div"); + div10.innerHTML = `

    Comment Support in Browser

    +
    After enabling this option, you must go to the 'Browser' tab, update + your settings to turn on the 'Capture Comment in Browser' setting and + reinstall the bookmarklet.
    `; + t16 = space(); + div11 = element("div"); + label2 = element("label"); + input2 = element("input"); + attr(div2, "class", "setting-item-info"); + attr(input0, "type", "checkbox"); + attr(label0, "class", "checkbox-container"); + toggle_class(label0, "is-enabled", ctx[0].advanced); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item mod-toggle"); + attr(div5, "class", "clp_section_margin"); + attr(div6, "class", "setting-item-info"); + attr(input1, "type", "checkbox"); + attr(label1, "class", "checkbox-container"); + toggle_class(label1, "is-enabled", ctx[0].experimentalCanvas); + attr(div7, "class", "setting-item-control"); + attr(div8, "class", "setting-item mod-toggle"); + attr(div10, "class", "setting-item-info"); + attr(input2, "type", "checkbox"); + attr(label2, "class", "checkbox-container"); + toggle_class(label2, "is-enabled", ctx[0].experimentalBookmarkletComment); + attr(div11, "class", "setting-item-control"); + attr(div12, "class", "setting-item mod-toggle"); + set_style(div12, "border-top", "none", 1); + attr(div13, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div5, anchor); + append(div5, h10); + append(div5, t1); + append(div5, div4); + append(div4, div2); + append(div4, t5); + append(div4, div3); + append(div3, label0); + append(label0, input0); + input0.checked = ctx[0].advanced; + append(div5, t6); + if (if_block) + if_block.m(div5, null); + insert(target, t7, anchor); + insert(target, div13, anchor); + append(div13, h11); + append(div13, t9); + append(div13, div8); + append(div8, div6); + append(div8, t11); + append(div8, div7); + append(div7, label1); + append(label1, input1); + input1.checked = ctx[0].experimentalCanvas; + append(div13, t12); + append(div13, div12); + append(div12, div10); + append(div12, t16); + append(div12, div11); + append(div11, label2); + append(label2, input2); + input2.checked = ctx[0].experimentalBookmarkletComment; + if (!mounted) { + dispose = [ + listen(input0, "change", ctx[1]), + listen(input1, "change", ctx[3]), + listen(input2, "change", ctx[4]) + ]; + mounted = true; + } + }, + p(ctx2, [dirty]) { + if (dirty & 1) { + input0.checked = ctx2[0].advanced; + } + if (dirty & 1) { + toggle_class(label0, "is-enabled", ctx2[0].advanced); + } + if (ctx2[0].advanced) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & 1) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block6(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(div5, null); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + if (dirty & 1) { + input1.checked = ctx2[0].experimentalCanvas; + } + if (dirty & 1) { + toggle_class(label1, "is-enabled", ctx2[0].experimentalCanvas); + } + if (dirty & 1) { + input2.checked = ctx2[0].experimentalBookmarkletComment; + } + if (dirty & 1) { + toggle_class(label2, "is-enabled", ctx2[0].experimentalBookmarkletComment); + } + }, + i(local) { + transition_in(if_block); + }, + o(local) { + transition_out(if_block); + }, + d(detaching) { + if (detaching) + detach(div5); + if (if_block) + if_block.d(); + if (detaching) + detach(t7); + if (detaching) + detach(div13); + mounted = false; + run_all(dispose); + } + }; +} +function instance13($$self, $$props, $$invalidate) { + let $settings; + component_subscribe($$self, settings, ($$value) => $$invalidate(0, $settings = $$value)); + function input0_change_handler() { + $settings.advanced = this.checked; + settings.set($settings); + } + function input_input_handler() { + $settings.advancedStorageFolder = this.value; + settings.set($settings); + } + function input1_change_handler() { + $settings.experimentalCanvas = this.checked; + settings.set($settings); + } + function input2_change_handler() { + $settings.experimentalBookmarkletComment = this.checked; + settings.set($settings); + } + return [ + $settings, + input0_change_handler, + input_input_handler, + input1_change_handler, + input2_change_handler + ]; +} +var AdvancedSettingsGroup = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance13, create_fragment13, safe_not_equal, {}); + } +}; +var AdvancedSettingsGroup_default = AdvancedSettingsGroup; + +// src/settings/SettingsComponent.svelte +function create_noticeText_slot(ctx) { + let span; + return { + c() { + span = element("span"); + span.textContent = `${noticeText}`; + attr(span, "slot", "noticeText"); + }, + m(target, anchor) { + insert(target, span, anchor); + }, + p: noop, + d(detaching) { + if (detaching) + detach(span); + } + }; +} +function create_calloutLink_slot(ctx) { + let span1; + return { + c() { + span1 = element("span"); + span1.innerHTML = `Details + `; + attr(span1, "slot", "calloutLink"); + }, + m(target, anchor) { + insert(target, span1, anchor); + }, + p: noop, + d(detaching) { + if (detaching) + detach(span1); + } + }; +} +function create_fragment14(ctx) { + let notice; + let t0; + let br; + let t1; + let tabs_1; + let current; + notice = new Notice_default({ + props: { + $$slots: { + calloutLink: [create_calloutLink_slot], + noticeText: [create_noticeText_slot] + }, + $$scope: { ctx } + } + }); + tabs_1 = new Tabs_default({ props: { tabs: ctx[0] } }); + return { + c() { + create_component(notice.$$.fragment); + t0 = space(); + br = element("br"); + t1 = space(); + create_component(tabs_1.$$.fragment); + }, + m(target, anchor) { + mount_component(notice, target, anchor); + insert(target, t0, anchor); + insert(target, br, anchor); + insert(target, t1, anchor); + mount_component(tabs_1, target, anchor); + current = true; + }, + p(ctx2, [dirty]) { + const notice_changes = {}; + if (dirty & 8) { + notice_changes.$$scope = { dirty, ctx: ctx2 }; + } + notice.$set(notice_changes); + }, + i(local) { + if (current) + return; + transition_in(notice.$$.fragment, local); + transition_in(tabs_1.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(notice.$$.fragment, local); + transition_out(tabs_1.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(notice, detaching); + if (detaching) + detach(t0); + if (detaching) + detach(br); + if (detaching) + detach(t1); + destroy_component(tabs_1, detaching); + } + }; +} +var noticeText = "Lost on how to get started? Check out the new documentation website"; +function instance14($$self, $$props, $$invalidate) { + let { app } = $$props; + const vaultName = app.vault.getName(); + let tabs = [ + { + label: "Base", + value: 1, + component: BaseSettingsTab_default, + props: { app } + }, + { + label: "Topic Note", + value: 2, + component: TopicSettingsTab_default, + props: { app } + }, + { + label: "Browser", + value: 3, + component: LinksSettingsGroup_default, + props: { vaultName } + }, + { + label: "Advanced", + value: 4, + component: AdvancedSettingsGroup_default, + props: { app } + } + ]; + $$self.$$set = ($$props2) => { + if ("app" in $$props2) + $$invalidate(1, app = $$props2.app); + }; + return [tabs, app]; +} +var SettingsComponent = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance14, create_fragment14, safe_not_equal, { app: 1 }); + } +}; +var SettingsComponent_default = SettingsComponent; + +// src/modals/BookmarkletModalComponent.svelte +function create_if_block7(ctx) { + let notice; + let current; + notice = new Notice_default({ + props: { + $$slots: { noticeText: [create_noticeText_slot2] }, + $$scope: { ctx } + } + }); + return { + c() { + create_component(notice.$$.fragment); + }, + m(target, anchor) { + mount_component(notice, target, anchor); + current = true; + }, + p(ctx2, dirty) { + const notice_changes = {}; + if (dirty & 9) { + notice_changes.$$scope = { dirty, ctx: ctx2 }; + } + notice.$set(notice_changes); + }, + i(local) { + if (current) + return; + transition_in(notice.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(notice.$$.fragment, local); + current = false; + }, + d(detaching) { + destroy_component(notice, detaching); + } + }; +} +function create_noticeText_slot2(ctx) { + let span; + let t; + return { + c() { + span = element("span"); + t = text(ctx[0]); + attr(span, "slot", "noticeText"); + }, + m(target, anchor) { + insert(target, span, anchor); + append(span, t); + }, + p(ctx2, dirty) { + if (dirty & 1) + set_data(t, ctx2[0]); + }, + d(detaching) { + if (detaching) + detach(span); + } + }; +} +function create_fragment15(ctx) { + let div; + let t; + let linkssettingsgroup; + let current; + let if_block = ctx[0] && create_if_block7(ctx); + linkssettingsgroup = new LinksSettingsGroup_default({ + props: { + vaultName: ctx[1], + filePath: ctx[2] + } + }); + return { + c() { + div = element("div"); + if (if_block) + if_block.c(); + t = space(); + create_component(linkssettingsgroup.$$.fragment); + attr(div, "class", "clp_section_margin"); + }, + m(target, anchor) { + insert(target, div, anchor); + if (if_block) + if_block.m(div, null); + append(div, t); + mount_component(linkssettingsgroup, div, null); + current = true; + }, + p(ctx2, [dirty]) { + if (ctx2[0]) { + if (if_block) { + if_block.p(ctx2, dirty); + if (dirty & 1) { + transition_in(if_block, 1); + } + } else { + if_block = create_if_block7(ctx2); + if_block.c(); + transition_in(if_block, 1); + if_block.m(div, t); + } + } else if (if_block) { + group_outros(); + transition_out(if_block, 1, 1, () => { + if_block = null; + }); + check_outros(); + } + const linkssettingsgroup_changes = {}; + if (dirty & 2) + linkssettingsgroup_changes.vaultName = ctx2[1]; + if (dirty & 4) + linkssettingsgroup_changes.filePath = ctx2[2]; + linkssettingsgroup.$set(linkssettingsgroup_changes); + }, + i(local) { + if (current) + return; + transition_in(if_block); + transition_in(linkssettingsgroup.$$.fragment, local); + current = true; + }, + o(local) { + transition_out(if_block); + transition_out(linkssettingsgroup.$$.fragment, local); + current = false; + }, + d(detaching) { + if (detaching) + detach(div); + if (if_block) + if_block.d(); + destroy_component(linkssettingsgroup); + } + }; +} +function instance15($$self, $$props, $$invalidate) { + let { noticeText: noticeText2 } = $$props; + let { vaultName } = $$props; + let { filePath = "" } = $$props; + $$self.$$set = ($$props2) => { + if ("noticeText" in $$props2) + $$invalidate(0, noticeText2 = $$props2.noticeText); + if ("vaultName" in $$props2) + $$invalidate(1, vaultName = $$props2.vaultName); + if ("filePath" in $$props2) + $$invalidate(2, filePath = $$props2.filePath); + }; + return [noticeText2, vaultName, filePath]; +} +var BookmarkletModalComponent = class extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance15, create_fragment15, safe_not_equal, { noticeText: 0, vaultName: 1, filePath: 2 }); + } +}; +var BookmarkletModalComponent_default = BookmarkletModalComponent; + +// src/topicnoteentry.ts +var TopicNoteEntry = class extends NoteEntry { + async writeToNote(file, noteEntry) { + Utility.assertNotNull(file); + this.handleWrite(file.path, await noteEntry.formattedEntry(this.template)); + } +}; + +// src/advancednotes/advancednoteentry.ts +var import_obsidian6 = require("obsidian"); +var AdvancedNoteEntry = class extends NoteEntry { + constructor(app, storageFolder) { + super(app, false, SectionPosition.APPEND, ""); + this.storageFolder = storageFolder; + } + async writeToAdvancedNoteStorage(hostName, data, url) { + const noteFilePath = `${this.storageFolder}/${hostName}.md`; + const folder = this.app.vault.getAbstractFileByPath(this.storageFolder); + let file = this.app.vault.getAbstractFileByPath(noteFilePath); + const sectionHeader = window.moment().toISOString().replaceAll(":", "-"); + const entry = ` +# ${sectionHeader} + ${data} +[^1] + + [^1]: ${url} +`; + if (!(file instanceof import_obsidian6.TFile)) { + if (!(folder instanceof import_obsidian6.TFolder)) { + this.app.vault.createFolder(this.storageFolder); + await new Promise((r) => setTimeout(r, 50)); + } + file = await this.app.vault.create(noteFilePath, entry); + } else { + new AppendWriter(this.app, this.openFileOnWrite).write(file, entry); + } + await new Promise((r) => setTimeout(r, 50)); + if (!file) { + const errorMessage = `Unable to create clipper storage file. Most likely ${this.storageFolder} doesn't exist and we were unable to create it.`; + console.error(errorMessage); + new import_obsidian6.Notice(errorMessage); + throw Error(errorMessage); + } + return `![[${this.storageFolder}/${hostName}#${sectionHeader}|clipped]]`; + } +}; + +// src/canvasentry.ts +var import_crypto = require("crypto"); +var import_dagre = __toESM(require_dagre()); +var CanvasEntry = class { + constructor(app) { + this.app = app; + } + async writeToCanvas(file, noteEntry) { + const content = noteEntry.getEntryContent(); + Utility.assertNotNull(content); + const fileData = await this.app.vault.read(file); + const canvasData = JSON.parse(fileData); + const newNode = this.createTextNode(canvasData.nodes, `${content} +[^1] + +[^1](${noteEntry.getUrl()})`, { + width: 600, + height: 400 + }); + const domainNode = this.findDomainNodeOrCreate(canvasData, Utility.parseDomainFromUrl(noteEntry.getUrl())); + canvasData.nodes.push(newNode); + this.linkNewNodeToDomainNode(canvasData, domainNode, newNode); + const layout = this.processWithDagre(canvasData); + const nodesWithLayout = []; + layout.nodes().forEach((element2) => { + const nodeData = layout.node(element2); + console.log(nodeData); + const label = nodeData.label; + Utility.assertNotNull(label); + nodesWithLayout.push({ + id: element2, + type: "text", + text: label, + width: nodeData.width, + height: nodeData.height, + x: nodeData.x, + y: nodeData.y + }); + }); + canvasData.nodes = nodesWithLayout; + await this.app.vault.modify(file, JSON.stringify(canvasData)); + await new Promise((r) => setTimeout(r, 50)); + } + findDomainNodeOrCreate(canvasData, domain) { + if (!canvasData.nodes) { + canvasData.nodes = []; + } + let domainNode = canvasData.nodes.find((node) => node.text === domain); + if (!domainNode) { + domainNode = this.createTextNode(canvasData.nodes, domain); + canvasData.nodes.push(domainNode); + } + return domainNode; + } + createTextNode(nodes, content, options = { width: 240, height: 50 }) { + const { x, y } = this.getPositionCoordinatesForNewNode(nodes); + return { + id: (0, import_crypto.randomUUID)(), + type: "text", + text: content, + x, + y, + width: options.width, + height: options.height, + createdBy: "obsidian-clipper" + }; + } + getPositionCoordinatesForNewNode(nodes) { + return { x: -1300, y: -800 }; + } + linkNewNodeToDomainNode(canvasData, domainNode, newNode) { + const edge = { + id: (0, import_crypto.randomUUID)(), + fromNode: newNode.id, + fromSide: "top", + toNode: domainNode.id, + toSide: "bottom" + }; + if (!canvasData.edges) { + canvasData.edges = []; + } + canvasData.edges.push(edge); + } + processWithDagre(canvasData) { + const g = new import_dagre.default.graphlib.Graph({ directed: true, multigraph: true }); + g.setGraph({}); + g.setDefaultEdgeLabel(function() { + return {}; + }); + canvasData.nodes.forEach((node) => { + g.setNode(node.id, { + label: node.text, + width: node.width, + height: node.height, + createdBy: node.createdBy, + type: node.type, + x: node.x, + y: node.y + }); + }); + canvasData.edges.forEach((edge) => { + g.setEdge(edge.toNode, edge.fromNode); + }); + import_dagre.default.layout(g, { rankdir: "lr", align: "dr", ranker: "tight-tree" }); + return g; + } +}; + +// src/main.ts +var ObsidianClipperPlugin = class extends import_obsidian7.Plugin { + async onload() { + await this.loadSettings(); + this.addSettingTab(new SettingTab(this.app, this)); + this.addCommand({ + id: "copy-bookmarklet-address-clipboard", + name: "Vault Bookmarklet to Clipboard", + callback: () => this.handleCopyBookmarkletToClipboard() + }); + this.addCommand({ + id: "copy-bookmarklet-address", + name: "Vault Bookmarklet", + callback: () => this.handleCopyBookmarkletCommand() + }); + this.addCommand({ + id: "copy-note-bookmarklet-address-clipboard", + name: "Topic Bookmarklet to Clipboard", + editorCallback: (_editor, ctx) => { + var _a; + this.handleCopyBookmarkletToClipboard((_a = ctx.file) == null ? void 0 : _a.path); + } + }); + this.addCommand({ + id: "copy-note-bookmarklet-address", + name: "Topic Bookmarklet", + editorCallback: (_editor, ctx) => { + var _a; + this.handleCopyBookmarkletCommand(false, (_a = ctx.file) == null ? void 0 : _a.path); + } + }); + this.addCommand({ + id: "copy-note-bookmarklet-address-canvas", + name: "Canvas Bookmarklet", + checkCallback: (checking) => { + var _a; + if (checking) { + return this.settings.experimentalCanvas && ((_a = this.app.workspace.getActiveViewOfType(import_obsidian7.View)) == null ? void 0 : _a.file.extension) === "canvas"; + } else { + const ctx = this.app.workspace.getActiveViewOfType(import_obsidian7.View); + if (ctx) { + this.handleCopyBookmarkletCommand(false, ctx.file.path); + } + } + } + }); + this.registerObsidianProtocolHandler("obsidian-clipper", async (e) => { + const parameters = e; + const url = parameters.url; + const title = parameters.title; + const notePath = parameters.notePath; + const highlightData = parameters.highlightdata; + const comments = parameters.comments; + if (parameters.format === "html") { + if (notePath !== "") { + this.handleCopyBookmarkletCommand(true, notePath); + } else { + this.handleCopyBookmarkletCommand(true); + } + return; + } + let entryReference = highlightData; + if (this.settings.advanced && highlightData) { + const domain = Utility.parseDomainFromUrl(url); + entryReference = await new AdvancedNoteEntry(this.app, this.settings.advancedStorageFolder).writeToAdvancedNoteStorage(domain, highlightData, url); + } + const noteEntry = new ClippedData(title, url, this.settings, this.app, entryReference, comments); + if (notePath && notePath !== "") { + const file = this.app.vault.getAbstractFileByPath(notePath); + if (file.extension === "canvas") { + new CanvasEntry(this.app).writeToCanvas(file, noteEntry); + } else { + new TopicNoteEntry(this.app, this.settings.topicOpenOnWrite, this.settings.topicPosition, this.settings.topicEntryTemplateLocation).writeToNote(file, noteEntry); + } + } else { + if (this.settings.useDailyNote) { + new DailyPeriodicNoteEntry(this.app, this.settings.dailyOpenOnWrite, this.settings.dailyPosition, this.settings.dailyEntryTemplateLocation).writeToPeriodicNote(noteEntry, this.settings.dailyNoteHeading); + } + if (this.settings.useWeeklyNote) { + new WeeklyPeriodicNoteEntry(this.app, this.settings.weeklyOpenOnWrite, this.settings.weeklyPosition, this.settings.weeklyEntryTemplateLocation).writeToPeriodicNote(noteEntry, this.settings.weeklyNoteHeading); + } + } + }); + } + async loadSettings() { + let mergedSettings = DEFAULT_SETTINGS; + const settingsData = await this.loadData(); + if (settingsData !== null) { + mergedSettings = deepmerge(DEFAULT_SETTINGS, settingsData); + } + this.settings = mergedSettings; + } + async saveSettings() { + await this.saveData(this.settings); + } + handleCopyBookmarkletToClipboard(notePath = "") { + navigator.clipboard.writeText(new BookmarketlGenerator(this.app.vault.getName(), notePath, this.settings.markdownSettings, (this.settings.experimentalBookmarkletComment && this.settings.captureComments).toString()).generateBookmarklet()); + new import_obsidian7.Notice("Obsidian Clipper Bookmarklet copied to clipboard."); + } + handleCopyBookmarkletCommand(updateRequired = false, filePath = "") { + let noticeText2 = ""; + if (updateRequired) { + noticeText2 = `Notice: Your Bookmarklet is out of date and needs to be updated. + Please Drag the link below to replace your current bookmarklet`; + } + const bookmarkletLinkModal = new import_obsidian7.Modal(this.app); + bookmarkletLinkModal.titleEl.createEl("h2", { + text: "Copy Your Bookmarklet" + }); + new BookmarkletModalComponent_default({ + target: bookmarkletLinkModal.contentEl, + props: { + noticeText: noticeText2, + vaultName: this.app.vault.getName(), + filePath + } + }); + bookmarkletLinkModal.open(); + } +}; +var SettingTab = class extends import_obsidian7.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + init2(this.plugin); + } + display() { + const { containerEl } = this; + containerEl.empty(); + this.view = new SettingsComponent_default({ + target: containerEl, + props: { + app: this.app + } + }); + } + async hide() { + super.hide(); + this.view.$destroy(); + } +}; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-clipper/manifest.json b/.obsidian/plugins/obsidian-clipper/manifest.json new file mode 100644 index 00000000..2471a685 --- /dev/null +++ b/.obsidian/plugins/obsidian-clipper/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "obsidian-clipper", + "name": "Clipper", + "version": "0.2.9", + "minAppVersion": "0.15.0", + "description": "This plugin helps you capture highlights from the web.", + "author": "John Christopher", + "authorUrl": "https://github.com/jgchristopher/", + "fundingUrl": "https://www.buymeacoffee.com/jgchristopher", + "isDesktopOnly": false +} diff --git a/.obsidian/plugins/obsidian-clipper/styles.css b/.obsidian/plugins/obsidian-clipper/styles.css new file mode 100644 index 00000000..ac2a55e5 --- /dev/null +++ b/.obsidian/plugins/obsidian-clipper/styles.css @@ -0,0 +1,127 @@ +.my-4 { + margin-top: 1rem; + margin-bottom: 1rem; +} + +.ml-3 { + margin-left: 0.75rem; +} + +.mt-3 { + margin-top: 0.75rem; +} + +.block { + display: block; +} + +.flex { + display: flex; +} + +.h-5 { + height: 1.25rem; +} + +.w-5 { + width: 1.25rem; +} + +.flex-1 { + flex: 1 1 0%; +} + +.flex-shrink-0 { + flex-shrink: 0; +} + +.basis-0 { + flex-basis: 0px; +} + +.flex-row { + flex-direction: row; +} + +.flex-wrap { + flex-wrap: wrap; +} + +.whitespace-nowrap { + white-space: nowrap; +} + +.rounded-md { + border-radius: 0.375rem; +} + +.border { + border-width: 1px; +} + +.bg-blue-50 { + --tw-bg-opacity: 1; + background-color: rgb(239 246 255 / var(--tw-bg-opacity)); +} + +.p-4 { + padding: 1rem; +} + +.text-sm { + font-size: 0.875rem; + line-height: 1.25rem; +} + +.font-extrabold { + font-weight: 800; +} + +.font-medium { + font-weight: 500; +} + +.text-blue-400 { + --tw-text-opacity: 1; + color: rgb(96 165 250 / var(--tw-text-opacity)); +} + +.text-blue-700 { + --tw-text-opacity: 1; + color: rgb(29 78 216 / var(--tw-text-opacity)); +} + +a { + color: var(--link-color); +} + +div.clp_section_margin { + margin: 0 0 20px 0 !important; +} + +.internal-embed[alt="clipped"] h1 { + display: none; +} + +.hover\:text-blue-600:hover { + --tw-text-opacity: 1; + color: rgb(37 99 235 / var(--tw-text-opacity)); +} + +@media (min-width: 768px) { + .md\:ml-6 { + margin-left: 1.5rem; + } + + .md\:mt-0 { + margin-top: 0px; + } + + .md\:flex { + display: flex; + } + + .md\:justify-between { + justify-content: space-between; + } +} diff --git a/.obsidian/plugins/obsidian-readwise/main.js b/.obsidian/plugins/obsidian-readwise/main.js new file mode 100644 index 00000000..9a793f0d --- /dev/null +++ b/.obsidian/plugins/obsidian-readwise/main.js @@ -0,0 +1,9668 @@ +'use strict'; + +var obsidian = require('obsidian'); + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +class ObsidianReadwiseSettingsGenerator { + static withData(data) { + return Object.assign({}, ObsidianReadwiseSettingsGenerator.defaultSettings(), data); + } + static defaultSettings() { + return { + syncOnBoot: false, + autoSyncInterval: 0, + disableNotifications: false, + headerTemplatePath: "", + highlightTemplatePath: "", + highlightStoragePath: "", + authorsMappingFilename: "authors.json", + lastUpdate: Date.now() + }; + } +} + +class ObsidianReadwiseSettingsTab extends obsidian.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + this.tokenManager = plugin.tokenManager; + } + display() { + let { containerEl } = this; + containerEl.empty(); + containerEl.createEl('h2', { text: 'Readwise Community Settings' }); + this.apiTokenSetting(); + this.syncOnBoot(); + this.syncOnInterval(); + this.highlightStoragePath(); + this.headerTemplatePath(); + this.highlightTemplatePath(); + this.notificationSettings(); + } + apiTokenSetting() { + const desc = document.createDocumentFragment(); + desc.createEl("span", null, (span) => { + span.innerText = + "Specify API Token to download highlights from Readwise. You can find the token "; + span.createEl("a", null, (link) => { + link.href = "https://readwise.io/access_token"; + link.innerText = "here!"; + }); + }); + new obsidian.Setting(this.containerEl) + .setName('Readwise API Token') + .setDesc(desc) + .addText(text => { + const token = this.tokenManager.get(); + if (token !== null) { + text.setValue(token); + } + text + .setPlaceholder('') + .onChange(token => { + this.tokenManager.upsert(token); + }); + }); + } + syncOnBoot() { + new obsidian.Setting(this.containerEl) + .setName('Sync on Startup') + .setDesc('Automatically sync updated highlights when Obsidian starts') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.syncOnBoot) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.syncOnBoot = value; + yield this.plugin.saveSettings(); + }))); + } + highlightStoragePath() { + new obsidian.Setting(this.containerEl) + .setName('Highlights Storage Path') + .setDesc('Path to the directory used to store the notes') + .addText(text => text + .setValue(this.plugin.settings.highlightStoragePath) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.highlightStoragePath = value; + yield this.plugin.saveSettings(); + }))); + } + syncOnInterval() { + new obsidian.Setting(this.containerEl) + .setName('Sync on Interval') + .setDesc('Sync updated highlights on interval (hours). To disable automatic sync specify a negative value or zero (default)') + .addText(text => text + .setValue(String(this.plugin.settings.autoSyncInterval)) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + if (!isNaN(Number(value))) { + this.plugin.settings.autoSyncInterval = Number(value); + yield this.plugin.saveSettings(); + if (this.plugin.settings.autoSyncInterval > 0) { + this.plugin.clearAutoSync(); + this.plugin.startAutoSync(this.plugin.settings.autoSyncInterval); + new obsidian.Notice(`Automatic sync enabled! Every ${this.plugin.settings.autoSyncInterval} hours.`); + } + else if (this.plugin.settings.autoSyncInterval <= 0 && this.plugin.timeoutIdSync) { + this.plugin.clearAutoSync(); + new obsidian.Notice("Automatic sync disabled!"); + } + } + else { + new obsidian.Notice("Please specify a valid number."); + } + }))); + } + headerTemplatePath() { + new obsidian.Setting(this.containerEl) + .setName('Custom Header Template Path') + .setDesc('Path to template note that overrides how the note header is written') + .addText(text => text + .setValue(this.plugin.settings.headerTemplatePath) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.headerTemplatePath = value; + yield this.plugin.saveSettings(); + }))); + } + highlightTemplatePath() { + new obsidian.Setting(this.containerEl) + .setName('Custom Highlight Template Path') + .setDesc('Path to template note that overrides how the highlights are written') + .addText(text => text + .setValue(this.plugin.settings.highlightTemplatePath) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.highlightTemplatePath = value; + yield this.plugin.saveSettings(); + }))); + } + notificationSettings() { + new obsidian.Setting(this.containerEl) + .setName('Disable Notifications') + .setDesc('Disable notifications for plugin operations to minimize distraction (refer to status bar for updates)') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.disableNotifications) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.disableNotifications = value; + yield this.plugin.saveSettings(); + }))); + } +} + +var PluginState; +(function (PluginState) { + PluginState[PluginState["idle"] = 0] = "idle"; + PluginState[PluginState["syncing"] = 1] = "syncing"; + PluginState[PluginState["checking"] = 2] = "checking"; + PluginState[PluginState["done"] = 3] = "done"; +})(PluginState || (PluginState = {})); +class StatusBar { + constructor(statusBarEl, plugin, factory) { + this.messages = []; + this.statusBarEl = statusBarEl; + this.plugin = plugin; + this.dateFactory = factory; + } + displayMessage(message, timeout) { + this.messages.push({ + message: `readwise: ${message.slice(0, 100)}`, + timeout: timeout, + }); + this.display(); + } + display() { + if (this.messages.length > 0 && !this.currentMessage) { + this.currentMessage = this.messages.shift(); + this.statusBarEl.setText(this.currentMessage.message); + this.lastMessageTimestamp = Date.now(); + } + else if (this.currentMessage) { + let messageAge = Date.now() - this.lastMessageTimestamp; + if (messageAge >= this.currentMessage.timeout) { + this.currentMessage = null; + this.lastMessageTimestamp = null; + } + } + else { + this.displayState(); + } + } + displayState() { + let state = this.plugin.getState(); + switch (state) { + case PluginState.idle: + this.displayFromNow(this.plugin.settings.lastUpdate); + break; + case PluginState.checking: + this.statusBarEl.setText("readwise: checking if there are new highlights to sync"); + break; + case PluginState.syncing: + this.statusBarEl.setText("readwise: syncing new highlights"); + break; + case PluginState.done: + this.statusBarEl.setText("readwise: sync finished"); + break; + } + } + displayFromNow(timestamp) { + if (timestamp) { + let fromNow = this.dateFactory.createHandler(timestamp).fromNow(); + this.statusBarEl.setText(`readwise: last update ${fromNow}..`); + } + else { + this.statusBarEl.setText(`readwise: ready`); + } + } +} + +class Result { + static Capture(closure) { + try { + return Result.Ok(closure()); + } + catch (e) { + return Result.Err(e); + } + } + static Ok(value) { + let result = new Result(); + result.ok = value; + return result; + } + static Err(err) { + let result = new Result(); + result.error = err; + return result; + } + static All(...results) { + results.forEach(result => { + if (result.isErr()) { + return result.intoErr(); + } + }); + let merged = results.flatMap(result => result.unwrap()); + return Result.Ok(merged); + } + isOk() { + return this.ok != null; + } + isErr() { + return this.error != null; + } + unwrap() { + if (!this.isOk()) { + throw new Error("Called 'unwrap' on a Result with an error."); + } + return this.ok; + } + unwrapErr() { + if (!this.isErr()) { + throw new Error("Called 'unwrapErr' on a Result with a value."); + } + return this.error; + } + map(func) { + if (this.isOk()) { + return Result.Ok(func(this.ok)); + } + else { + return this.intoErr(); + } + } + unwrapOr(val) { + return this.isOk() ? this.ok : val; + } + intoErr() { + return Result.Err(this.error); + } +} + +class Log { + static debug(log) { + if (isComplexLog(log)) { + printComplexLog("debug", log); + } + else { + print("debug", log); + } + } + static error(log) { + if (isComplexLog(log)) { + printComplexLog("error", log); + } + else { + print("error", log); + } + } +} +function isComplexLog(log) { + return log.message !== undefined; +} +function printComplexLog(prefix, log) { + print(prefix, log.message); + print(prefix, log.context); +} +function print(prefix, message) { + console.log(`obsidian-readwise|${prefix}: ${message}`); +} + +class Document { + constructor(raw, factory) { + this.id = raw.id; + this.title = raw.title; + this.author = raw.author; + this.num_highlights = raw.num_highlights; + this.updated = factory.createHandler(raw.updated).format("YYYY-MM-DD"); + this.highlights_url = raw.highlights_url; + this.source_url = raw.source_url; + this.category = raw.category; + } + static Parse(idocs, factory) { + return Array.from(idocs).map((idoc) => new Document(idoc, factory)); + } +} +class Highlight { + constructor(raw) { + this.id = raw.id; + this.book_id = raw.book_id; + this.note = raw.note; + this.text = raw.text; + this.url = raw.url; + this.location = raw.location; + this.updated = raw.updated; + } + static Parse(ihighs) { + return Array.from(ihighs).map((ihigh) => new Highlight(ihigh)); + } +} + +class ReadwiseApi { + constructor(token, factory) { + this.token = token; + this.dateFactory = factory; + } + getDocumentsWithHighlights(since, to) { + return __awaiter(this, void 0, void 0, function* () { + const documentsResult = yield this.getUpdatedDocuments(since, to); + if (documentsResult.isErr()) { + return documentsResult.intoErr(); + } + const documents = documentsResult.unwrap(); + const highlightsResult = yield this.getNewHighlightsInDocuments(since, to); + if (highlightsResult.isErr()) { + return highlightsResult.intoErr(); + } + const highlights = highlightsResult.unwrap(); + documents.forEach((doc) => { + doc.highlights = highlights.filter((high) => high.book_id == doc.id); + doc.highlights.sort((a, b) => a.location - b.location); + }); + return Result.Ok(documents); + }); + } + getUpdatedDocuments(since, to) { + return __awaiter(this, void 0, void 0, function* () { + let url = `https://readwise.io/api/v2/books/`; + const params = { + page_size: "1000", + }; + if (this.isValidTimestamp(since)) { + Object.assign(params, { + updated__gt: this.dateFactory + .createHandler(since) + .utc() + .format(), + }); + } + if (this.isValidTimestamp(to)) { + Object.assign(params, { + updated__lt: this.dateFactory.createHandler(to).utc().format(), + }); + } + url += "?" + new URLSearchParams(params); + try { + const response = yield fetch(url, { + headers: new Headers({ + "Content-Type": "application/json", + Authorization: `Token ${this.token}`, + }), + }); + if (response.ok) { + const content = yield response.json(); + const documents = Document.Parse(content.results, this.dateFactory); + if (documents.length > 0) { + Log.debug(`Found ${documents.length} docs with new highlights`); + } + else { + Log.debug("No updated documents"); + } + return Result.Ok(documents); + } + else { + Log.debug(`The documents API call at ${url} failed`); + } + return Result.Err(new Error(yield response.text())); + } + catch (e) { + return Result.Err(e); + } + }); + } + getNewHighlightsInDocuments(since, to) { + return __awaiter(this, void 0, void 0, function* () { + let url = "https://readwise.io/api/v2/highlights/"; + const params = { + page_size: "1000", + }; + if (this.isValidTimestamp(since)) { + Object.assign(params, { + updated__gt: this.dateFactory + .createHandler(since) + .utc() + .format(), + }); + } + if (this.isValidTimestamp(to)) { + Object.assign(params, { + updated__lt: this.dateFactory.createHandler(to).utc().format(), + }); + } + url += "?" + new URLSearchParams(params); + Log.debug(`Requesting ${url}`); + try { + const response = yield fetch(url, { + headers: new Headers({ + "Content-Type": "application/json", + Authorization: `Token ${this.token}`, + }), + }); + if (response.ok) { + const content = yield response.json(); + const highlights = Highlight.Parse(content.results); + if (highlights.length > 0) { + Log.debug(`Found ${highlights.length} new highlights`); + } + else { + Log.debug("No new highlights found"); + } + return Result.Ok(highlights); + } + else { + Log.debug(`The highlights API call at ${url} failed`); + } + return Result.Err(new Error(yield response.text())); + } + catch (e) { + return Result.Err(e); + } + }); + } + isValidTimestamp(timestamp) { + return timestamp !== undefined && timestamp > 0; + } +} + +function noop() { } +function run(fn) { + return fn(); +} +function blank_object() { + return Object.create(null); +} +function run_all(fns) { + fns.forEach(run); +} +function is_function(thing) { + return typeof thing === 'function'; +} +function safe_not_equal(a, b) { + return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); +} +function is_empty(obj) { + return Object.keys(obj).length === 0; +} + +function append(target, node) { + target.appendChild(node); +} +function insert(target, node, anchor) { + target.insertBefore(node, anchor || null); +} +function detach(node) { + node.parentNode.removeChild(node); +} +function element(name) { + return document.createElement(name); +} +function text(data) { + return document.createTextNode(data); +} +function space() { + return text(' '); +} +function listen(node, event, handler, options) { + node.addEventListener(event, handler, options); + return () => node.removeEventListener(event, handler, options); +} +function attr(node, attribute, value) { + if (value == null) + node.removeAttribute(attribute); + else if (node.getAttribute(attribute) !== value) + node.setAttribute(attribute, value); +} +function children(element) { + return Array.from(element.childNodes); +} +function set_style(node, key, value, important) { + node.style.setProperty(key, value, important ? 'important' : ''); +} + +let current_component; +function set_current_component(component) { + current_component = component; +} + +const dirty_components = []; +const binding_callbacks = []; +const render_callbacks = []; +const flush_callbacks = []; +const resolved_promise = Promise.resolve(); +let update_scheduled = false; +function schedule_update() { + if (!update_scheduled) { + update_scheduled = true; + resolved_promise.then(flush); + } +} +function add_render_callback(fn) { + render_callbacks.push(fn); +} +let flushing = false; +const seen_callbacks = new Set(); +function flush() { + if (flushing) + return; + flushing = true; + do { + // first, call beforeUpdate functions + // and update components + for (let i = 0; i < dirty_components.length; i += 1) { + const component = dirty_components[i]; + set_current_component(component); + update(component.$$); + } + set_current_component(null); + dirty_components.length = 0; + while (binding_callbacks.length) + binding_callbacks.pop()(); + // then, once components are updated, call + // afterUpdate functions. This may cause + // subsequent updates... + for (let i = 0; i < render_callbacks.length; i += 1) { + const callback = render_callbacks[i]; + if (!seen_callbacks.has(callback)) { + // ...so guard against infinite loops + seen_callbacks.add(callback); + callback(); + } + } + render_callbacks.length = 0; + } while (dirty_components.length); + while (flush_callbacks.length) { + flush_callbacks.pop()(); + } + update_scheduled = false; + flushing = false; + seen_callbacks.clear(); +} +function update($$) { + if ($$.fragment !== null) { + $$.update(); + run_all($$.before_update); + const dirty = $$.dirty; + $$.dirty = [-1]; + $$.fragment && $$.fragment.p($$.ctx, dirty); + $$.after_update.forEach(add_render_callback); + } +} +const outroing = new Set(); +function transition_in(block, local) { + if (block && block.i) { + outroing.delete(block); + block.i(local); + } +} +function mount_component(component, target, anchor) { + const { fragment, on_mount, on_destroy, after_update } = component.$$; + fragment && fragment.m(target, anchor); + // onMount happens before the initial afterUpdate + add_render_callback(() => { + const new_on_destroy = on_mount.map(run).filter(is_function); + if (on_destroy) { + on_destroy.push(...new_on_destroy); + } + else { + // Edge case - component was destroyed immediately, + // most likely as a result of a binding initialising + run_all(new_on_destroy); + } + component.$$.on_mount = []; + }); + after_update.forEach(add_render_callback); +} +function destroy_component(component, detaching) { + const $$ = component.$$; + if ($$.fragment !== null) { + run_all($$.on_destroy); + $$.fragment && $$.fragment.d(detaching); + // TODO null out other refs, including component.$$ (but need to + // preserve final state?) + $$.on_destroy = $$.fragment = null; + $$.ctx = []; + } +} +function make_dirty(component, i) { + if (component.$$.dirty[0] === -1) { + dirty_components.push(component); + schedule_update(); + component.$$.dirty.fill(0); + } + component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31)); +} +function init(component, options, instance, create_fragment, not_equal, props, dirty = [-1]) { + const parent_component = current_component; + set_current_component(component); + const $$ = component.$$ = { + fragment: null, + ctx: null, + // state + props, + update: noop, + not_equal, + bound: blank_object(), + // lifecycle + on_mount: [], + on_destroy: [], + before_update: [], + after_update: [], + context: new Map(parent_component ? parent_component.$$.context : []), + // everything else + callbacks: blank_object(), + dirty, + skip_bound: false + }; + let ready = false; + $$.ctx = instance + ? instance(component, options.props || {}, (i, ret, ...rest) => { + const value = rest.length ? rest[0] : ret; + if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { + if (!$$.skip_bound && $$.bound[i]) + $$.bound[i](value); + if (ready) + make_dirty(component, i); + } + return ret; + }) + : []; + $$.update(); + ready = true; + run_all($$.before_update); + // `false` as a special case of no DOM component + $$.fragment = create_fragment ? create_fragment($$.ctx) : false; + if (options.target) { + if (options.hydrate) { + const nodes = children(options.target); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.l(nodes); + nodes.forEach(detach); + } + else { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + $$.fragment && $$.fragment.c(); + } + if (options.intro) + transition_in(component.$$.fragment); + mount_component(component, options.target, options.anchor); + flush(); + } + set_current_component(parent_component); +} +/** + * Base class for Svelte components. Used when dev=false. + */ +class SvelteComponent { + $destroy() { + destroy_component(this, 1); + this.$destroy = noop; + } + $on(type, callback) { + const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); + callbacks.push(callback); + return () => { + const index = callbacks.indexOf(callback); + if (index !== -1) + callbacks.splice(index, 1); + }; + } + $set($$props) { + if (this.$$set && !is_empty($$props)) { + this.$$.skip_bound = true; + this.$$set($$props); + this.$$.skip_bound = false; + } + } +} + +/* src/modals/enterApiToken/enterApiTokenModalContent.svelte generated by Svelte v3.32.2 */ + +function create_fragment(ctx) { + let div4; + let div2; + let t4; + let div3; + let input; + let t5; + let button; + let mounted; + let dispose; + + return { + c() { + div4 = element("div"); + div2 = element("div"); + + div2.innerHTML = `
    Readwise Token
    +
    You can find the token + here!
    `; + + t4 = space(); + div3 = element("div"); + input = element("input"); + t5 = space(); + button = element("button"); + button.textContent = "Submit"; + attr(div2, "class", "setting-item-info"); + attr(input, "type", "text"); + attr(input, "placeholder", "API token"); + attr(div3, "class", "setting-item-control"); + attr(div4, "class", "setting-item"); + attr(button, "class", "mod-cta"); + set_style(button, "float", "right"); + }, + m(target, anchor) { + insert(target, div4, anchor); + append(div4, div2); + append(div4, t4); + append(div4, div3); + append(div3, input); + /*input_binding*/ ctx[2](input); + insert(target, t5, anchor); + insert(target, button, anchor); + + if (!mounted) { + dispose = listen(button, "click", /*click_handler*/ ctx[3]); + mounted = true; + } + }, + p: noop, + i: noop, + o: noop, + d(detaching) { + if (detaching) detach(div4); + /*input_binding*/ ctx[2](null); + if (detaching) detach(t5); + if (detaching) detach(button); + mounted = false; + dispose(); + } + }; +} + +function instance($$self, $$props, $$invalidate) { + let { onSubmit } = $$props; + let tokenInput; + + function input_binding($$value) { + binding_callbacks[$$value ? "unshift" : "push"](() => { + tokenInput = $$value; + $$invalidate(1, tokenInput); + }); + } + + const click_handler = () => onSubmit(tokenInput.value); + + $$self.$$set = $$props => { + if ("onSubmit" in $$props) $$invalidate(0, onSubmit = $$props.onSubmit); + }; + + return [onSubmit, tokenInput, input_binding, click_handler]; +} + +class EnterApiTokenModalContent extends SvelteComponent { + constructor(options) { + super(); + init(this, options, instance, create_fragment, safe_not_equal, { onSubmit: 0 }); + } +} + +class ReadwiseApiTokenModal extends obsidian.Modal { + constructor(app, tokenManager) { + super(app); + this.tokenManager = tokenManager; + this.waitForClose = new Promise((resolve) => (this.resolvePromise = resolve)); + this.titleEl.innerText = "Setup Readwise API token"; + this.modalContent = new EnterApiTokenModalContent({ + target: this.contentEl, + props: { + onSubmit: (value) => { + this.tokenManager.upsert(value); + this.close(); + }, + }, + }); + this.open(); + } + onClose() { + super.onClose(); + this.modalContent.$destroy(); + this.resolvePromise(); + } +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} + +function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); +} + +var nunjucks = createCommonjsModule(function (module, exports) { +/*! Browser bundle of nunjucks 3.2.3 */ +(function webpackUniversalModuleDefinition(root, factory) { + module.exports = factory(); +})(typeof self !== 'undefined' ? self : commonjsGlobal, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 11); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + +var ArrayProto = Array.prototype; +var ObjProto = Object.prototype; +var escapeMap = { + '&': '&', + '"': '"', + '\'': ''', + '<': '<', + '>': '>' +}; +var escapeRegex = /[&"'<>]/g; +var exports = module.exports = {}; + +function hasOwnProp(obj, k) { + return ObjProto.hasOwnProperty.call(obj, k); +} + +exports.hasOwnProp = hasOwnProp; + +function lookupEscape(ch) { + return escapeMap[ch]; +} + +function _prettifyError(path, withInternals, err) { + if (!err.Update) { + // not one of ours, cast it + err = new exports.TemplateError(err); + } + + err.Update(path); // Unless they marked the dev flag, show them a trace from here + + if (!withInternals) { + var old = err; + err = new Error(old.message); + err.name = old.name; + } + + return err; +} + +exports._prettifyError = _prettifyError; + +function TemplateError(message, lineno, colno) { + var err; + var cause; + + if (message instanceof Error) { + cause = message; + message = cause.name + ": " + cause.message; + } + + if (Object.setPrototypeOf) { + err = new Error(message); + Object.setPrototypeOf(err, TemplateError.prototype); + } else { + err = this; + Object.defineProperty(err, 'message', { + enumerable: false, + writable: true, + value: message + }); + } + + Object.defineProperty(err, 'name', { + value: 'Template render error' + }); + + if (Error.captureStackTrace) { + Error.captureStackTrace(err, this.constructor); + } + + var getStack; + + if (cause) { + var stackDescriptor = Object.getOwnPropertyDescriptor(cause, 'stack'); + + getStack = stackDescriptor && (stackDescriptor.get || function () { + return stackDescriptor.value; + }); + + if (!getStack) { + getStack = function getStack() { + return cause.stack; + }; + } + } else { + var stack = new Error(message).stack; + + getStack = function getStack() { + return stack; + }; + } + + Object.defineProperty(err, 'stack', { + get: function get() { + return getStack.call(err); + } + }); + Object.defineProperty(err, 'cause', { + value: cause + }); + err.lineno = lineno; + err.colno = colno; + err.firstUpdate = true; + + err.Update = function Update(path) { + var msg = '(' + (path || 'unknown path') + ')'; // only show lineno + colno next to path of template + // where error occurred + + if (this.firstUpdate) { + if (this.lineno && this.colno) { + msg += " [Line " + this.lineno + ", Column " + this.colno + "]"; + } else if (this.lineno) { + msg += " [Line " + this.lineno + "]"; + } + } + + msg += '\n '; + + if (this.firstUpdate) { + msg += ' '; + } + + this.message = msg + (this.message || ''); + this.firstUpdate = false; + return this; + }; + + return err; +} + +if (Object.setPrototypeOf) { + Object.setPrototypeOf(TemplateError.prototype, Error.prototype); +} else { + TemplateError.prototype = Object.create(Error.prototype, { + constructor: { + value: TemplateError + } + }); +} + +exports.TemplateError = TemplateError; + +function escape(val) { + return val.replace(escapeRegex, lookupEscape); +} + +exports.escape = escape; + +function isFunction(obj) { + return ObjProto.toString.call(obj) === '[object Function]'; +} + +exports.isFunction = isFunction; + +function isArray(obj) { + return ObjProto.toString.call(obj) === '[object Array]'; +} + +exports.isArray = isArray; + +function isString(obj) { + return ObjProto.toString.call(obj) === '[object String]'; +} + +exports.isString = isString; + +function isObject(obj) { + return ObjProto.toString.call(obj) === '[object Object]'; +} + +exports.isObject = isObject; +/** + * @param {string|number} attr + * @returns {(string|number)[]} + * @private + */ + +function _prepareAttributeParts(attr) { + if (!attr) { + return []; + } + + if (typeof attr === 'string') { + return attr.split('.'); + } + + return [attr]; +} +/** + * @param {string} attribute Attribute value. Dots allowed. + * @returns {function(Object): *} + */ + + +function getAttrGetter(attribute) { + var parts = _prepareAttributeParts(attribute); + + return function attrGetter(item) { + var _item = item; + + for (var i = 0; i < parts.length; i++) { + var part = parts[i]; // If item is not an object, and we still got parts to handle, it means + // that something goes wrong. Just roll out to undefined in that case. + + if (hasOwnProp(_item, part)) { + _item = _item[part]; + } else { + return undefined; + } + } + + return _item; + }; +} + +exports.getAttrGetter = getAttrGetter; + +function groupBy(obj, val, throwOnUndefined) { + var result = {}; + var iterator = isFunction(val) ? val : getAttrGetter(val); + + for (var i = 0; i < obj.length; i++) { + var value = obj[i]; + var key = iterator(value, i); + + if (key === undefined && throwOnUndefined === true) { + throw new TypeError("groupby: attribute \"" + val + "\" resolved to undefined"); + } + + (result[key] || (result[key] = [])).push(value); + } + + return result; +} + +exports.groupBy = groupBy; + +function toArray(obj) { + return Array.prototype.slice.call(obj); +} + +exports.toArray = toArray; + +function without(array) { + var result = []; + + if (!array) { + return result; + } + + var length = array.length; + var contains = toArray(arguments).slice(1); + var index = -1; + + while (++index < length) { + if (indexOf(contains, array[index]) === -1) { + result.push(array[index]); + } + } + + return result; +} + +exports.without = without; + +function repeat(char_, n) { + var str = ''; + + for (var i = 0; i < n; i++) { + str += char_; + } + + return str; +} + +exports.repeat = repeat; + +function each(obj, func, context) { + if (obj == null) { + return; + } + + if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) { + obj.forEach(func, context); + } else if (obj.length === +obj.length) { + for (var i = 0, l = obj.length; i < l; i++) { + func.call(context, obj[i], i, obj); + } + } +} + +exports.each = each; + +function map(obj, func) { + var results = []; + + if (obj == null) { + return results; + } + + if (ArrayProto.map && obj.map === ArrayProto.map) { + return obj.map(func); + } + + for (var i = 0; i < obj.length; i++) { + results[results.length] = func(obj[i], i); + } + + if (obj.length === +obj.length) { + results.length = obj.length; + } + + return results; +} + +exports.map = map; + +function asyncIter(arr, iter, cb) { + var i = -1; + + function next() { + i++; + + if (i < arr.length) { + iter(arr[i], i, next, cb); + } else { + cb(); + } + } + + next(); +} + +exports.asyncIter = asyncIter; + +function asyncFor(obj, iter, cb) { + var keys = keys_(obj || {}); + var len = keys.length; + var i = -1; + + function next() { + i++; + var k = keys[i]; + + if (i < len) { + iter(k, obj[k], i, len, next); + } else { + cb(); + } + } + + next(); +} + +exports.asyncFor = asyncFor; + +function indexOf(arr, searchElement, fromIndex) { + return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex); +} + +exports.indexOf = indexOf; + +function keys_(obj) { + /* eslint-disable no-restricted-syntax */ + var arr = []; + + for (var k in obj) { + if (hasOwnProp(obj, k)) { + arr.push(k); + } + } + + return arr; +} + +exports.keys = keys_; + +function _entries(obj) { + return keys_(obj).map(function (k) { + return [k, obj[k]]; + }); +} + +exports._entries = _entries; + +function _values(obj) { + return keys_(obj).map(function (k) { + return obj[k]; + }); +} + +exports._values = _values; + +function extend(obj1, obj2) { + obj1 = obj1 || {}; + keys_(obj2).forEach(function (k) { + obj1[k] = obj2[k]; + }); + return obj1; +} + +exports._assign = exports.extend = extend; + +function inOperator(key, val) { + if (isArray(val) || isString(val)) { + return val.indexOf(key) !== -1; + } else if (isObject(val)) { + return key in val; + } + + throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.'); +} + +exports.inOperator = inOperator; + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + // A simple class system, more documentation to come + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var EventEmitter = __webpack_require__(16); + +var lib = __webpack_require__(0); + +function parentWrap(parent, prop) { + if (typeof parent !== 'function' || typeof prop !== 'function') { + return prop; + } + + return function wrap() { + // Save the current parent method + var tmp = this.parent; // Set parent to the previous method, call, and restore + + this.parent = parent; + var res = prop.apply(this, arguments); + this.parent = tmp; + return res; + }; +} + +function extendClass(cls, name, props) { + props = props || {}; + lib.keys(props).forEach(function (k) { + props[k] = parentWrap(cls.prototype[k], props[k]); + }); + + var subclass = /*#__PURE__*/function (_cls) { + _inheritsLoose(subclass, _cls); + + function subclass() { + return _cls.apply(this, arguments) || this; + } + + _createClass(subclass, [{ + key: "typename", + get: function get() { + return name; + } + }]); + + return subclass; + }(cls); + + lib._assign(subclass.prototype, props); + + return subclass; +} + +var Obj = /*#__PURE__*/function () { + function Obj() { + // Unfortunately necessary for backwards compatibility + this.init.apply(this, arguments); + } + + var _proto = Obj.prototype; + + _proto.init = function init() {}; + + Obj.extend = function extend(name, props) { + if (typeof name === 'object') { + props = name; + name = 'anonymous'; + } + + return extendClass(this, name, props); + }; + + _createClass(Obj, [{ + key: "typename", + get: function get() { + return this.constructor.name; + } + }]); + + return Obj; +}(); + +var EmitterObj = /*#__PURE__*/function (_EventEmitter) { + _inheritsLoose(EmitterObj, _EventEmitter); + + function EmitterObj() { + var _this2; + + var _this; + + _this = _EventEmitter.call(this) || this; // Unfortunately necessary for backwards compatibility + + (_this2 = _this).init.apply(_this2, arguments); + + return _this; + } + + var _proto2 = EmitterObj.prototype; + + _proto2.init = function init() {}; + + EmitterObj.extend = function extend(name, props) { + if (typeof name === 'object') { + props = name; + name = 'anonymous'; + } + + return extendClass(this, name, props); + }; + + _createClass(EmitterObj, [{ + key: "typename", + get: function get() { + return this.constructor.name; + } + }]); + + return EmitterObj; +}(EventEmitter); + +module.exports = { + Obj: Obj, + EmitterObj: EmitterObj +}; + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + +var lib = __webpack_require__(0); + +var arrayFrom = Array.from; +var supportsIterators = typeof Symbol === 'function' && Symbol.iterator && typeof arrayFrom === 'function'; // Frames keep track of scoping both at compile-time and run-time so +// we know how to access variables. Block tags can introduce special +// variables, for example. + +var Frame = /*#__PURE__*/function () { + function Frame(parent, isolateWrites) { + this.variables = Object.create(null); + this.parent = parent; + this.topLevel = false; // if this is true, writes (set) should never propagate upwards past + // this frame to its parent (though reads may). + + this.isolateWrites = isolateWrites; + } + + var _proto = Frame.prototype; + + _proto.set = function set(name, val, resolveUp) { + // Allow variables with dots by automatically creating the + // nested structure + var parts = name.split('.'); + var obj = this.variables; + var frame = this; + + if (resolveUp) { + if (frame = this.resolve(parts[0], true)) { + frame.set(name, val); + return; + } + } + + for (var i = 0; i < parts.length - 1; i++) { + var id = parts[i]; + + if (!obj[id]) { + obj[id] = {}; + } + + obj = obj[id]; + } + + obj[parts[parts.length - 1]] = val; + }; + + _proto.get = function get(name) { + var val = this.variables[name]; + + if (val !== undefined) { + return val; + } + + return null; + }; + + _proto.lookup = function lookup(name) { + var p = this.parent; + var val = this.variables[name]; + + if (val !== undefined) { + return val; + } + + return p && p.lookup(name); + }; + + _proto.resolve = function resolve(name, forWrite) { + var p = forWrite && this.isolateWrites ? undefined : this.parent; + var val = this.variables[name]; + + if (val !== undefined) { + return this; + } + + return p && p.resolve(name); + }; + + _proto.push = function push(isolateWrites) { + return new Frame(this, isolateWrites); + }; + + _proto.pop = function pop() { + return this.parent; + }; + + return Frame; +}(); + +function makeMacro(argNames, kwargNames, func) { + return function macro() { + for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0; _key < _len; _key++) { + macroArgs[_key] = arguments[_key]; + } + + var argCount = numArgs(macroArgs); + var args; + var kwargs = getKeywordArgs(macroArgs); + + if (argCount > argNames.length) { + args = macroArgs.slice(0, argNames.length); // Positional arguments that should be passed in as + // keyword arguments (essentially default values) + + macroArgs.slice(args.length, argCount).forEach(function (val, i) { + if (i < kwargNames.length) { + kwargs[kwargNames[i]] = val; + } + }); + args.push(kwargs); + } else if (argCount < argNames.length) { + args = macroArgs.slice(0, argCount); + + for (var i = argCount; i < argNames.length; i++) { + var arg = argNames[i]; // Keyword arguments that should be passed as + // positional arguments, i.e. the caller explicitly + // used the name of a positional arg + + args.push(kwargs[arg]); + delete kwargs[arg]; + } + + args.push(kwargs); + } else { + args = macroArgs; + } + + return func.apply(this, args); + }; +} + +function makeKeywordArgs(obj) { + obj.__keywords = true; + return obj; +} + +function isKeywordArgs(obj) { + return obj && Object.prototype.hasOwnProperty.call(obj, '__keywords'); +} + +function getKeywordArgs(args) { + var len = args.length; + + if (len) { + var lastArg = args[len - 1]; + + if (isKeywordArgs(lastArg)) { + return lastArg; + } + } + + return {}; +} + +function numArgs(args) { + var len = args.length; + + if (len === 0) { + return 0; + } + + var lastArg = args[len - 1]; + + if (isKeywordArgs(lastArg)) { + return len - 1; + } else { + return len; + } +} // A SafeString object indicates that the string should not be +// autoescaped. This happens magically because autoescaping only +// occurs on primitive string objects. + + +function SafeString(val) { + if (typeof val !== 'string') { + return val; + } + + this.val = val; + this.length = val.length; +} + +SafeString.prototype = Object.create(String.prototype, { + length: { + writable: true, + configurable: true, + value: 0 + } +}); + +SafeString.prototype.valueOf = function valueOf() { + return this.val; +}; + +SafeString.prototype.toString = function toString() { + return this.val; +}; + +function copySafeness(dest, target) { + if (dest instanceof SafeString) { + return new SafeString(target); + } + + return target.toString(); +} + +function markSafe(val) { + var type = typeof val; + + if (type === 'string') { + return new SafeString(val); + } else if (type !== 'function') { + return val; + } else { + return function wrapSafe(args) { + var ret = val.apply(this, arguments); + + if (typeof ret === 'string') { + return new SafeString(ret); + } + + return ret; + }; + } +} + +function suppressValue(val, autoescape) { + val = val !== undefined && val !== null ? val : ''; + + if (autoescape && !(val instanceof SafeString)) { + val = lib.escape(val.toString()); + } + + return val; +} + +function ensureDefined(val, lineno, colno) { + if (val === null || val === undefined) { + throw new lib.TemplateError('attempted to output null or undefined value', lineno + 1, colno + 1); + } + + return val; +} + +function memberLookup(obj, val) { + if (obj === undefined || obj === null) { + return undefined; + } + + if (typeof obj[val] === 'function') { + return function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return obj[val].apply(obj, args); + }; + } + + return obj[val]; +} + +function callWrap(obj, name, context, args) { + if (!obj) { + throw new Error('Unable to call `' + name + '`, which is undefined or falsey'); + } else if (typeof obj !== 'function') { + throw new Error('Unable to call `' + name + '`, which is not a function'); + } + + return obj.apply(context, args); +} + +function contextOrFrameLookup(context, frame, name) { + var val = frame.lookup(name); + return val !== undefined ? val : context.lookup(name); +} + +function handleError(error, lineno, colno) { + if (error.lineno) { + return error; + } else { + return new lib.TemplateError(error, lineno, colno); + } +} + +function asyncEach(arr, dimen, iter, cb) { + if (lib.isArray(arr)) { + var len = arr.length; + lib.asyncIter(arr, function iterCallback(item, i, next) { + switch (dimen) { + case 1: + iter(item, i, len, next); + break; + + case 2: + iter(item[0], item[1], i, len, next); + break; + + case 3: + iter(item[0], item[1], item[2], i, len, next); + break; + + default: + item.push(i, len, next); + iter.apply(this, item); + } + }, cb); + } else { + lib.asyncFor(arr, function iterCallback(key, val, i, len, next) { + iter(key, val, i, len, next); + }, cb); + } +} + +function asyncAll(arr, dimen, func, cb) { + var finished = 0; + var len; + var outputArr; + + function done(i, output) { + finished++; + outputArr[i] = output; + + if (finished === len) { + cb(null, outputArr.join('')); + } + } + + if (lib.isArray(arr)) { + len = arr.length; + outputArr = new Array(len); + + if (len === 0) { + cb(null, ''); + } else { + for (var i = 0; i < arr.length; i++) { + var item = arr[i]; + + switch (dimen) { + case 1: + func(item, i, len, done); + break; + + case 2: + func(item[0], item[1], i, len, done); + break; + + case 3: + func(item[0], item[1], item[2], i, len, done); + break; + + default: + item.push(i, len, done); + func.apply(this, item); + } + } + } + } else { + var keys = lib.keys(arr || {}); + len = keys.length; + outputArr = new Array(len); + + if (len === 0) { + cb(null, ''); + } else { + for (var _i = 0; _i < keys.length; _i++) { + var k = keys[_i]; + func(k, arr[k], _i, len, done); + } + } + } +} + +function fromIterator(arr) { + if (typeof arr !== 'object' || arr === null || lib.isArray(arr)) { + return arr; + } else if (supportsIterators && Symbol.iterator in arr) { + return arrayFrom(arr); + } else { + return arr; + } +} + +module.exports = { + Frame: Frame, + makeMacro: makeMacro, + makeKeywordArgs: makeKeywordArgs, + numArgs: numArgs, + suppressValue: suppressValue, + ensureDefined: ensureDefined, + memberLookup: memberLookup, + contextOrFrameLookup: contextOrFrameLookup, + callWrap: callWrap, + handleError: handleError, + isArray: lib.isArray, + keys: lib.keys, + SafeString: SafeString, + copySafeness: copySafeness, + markSafe: markSafe, + asyncEach: asyncEach, + asyncAll: asyncAll, + inOperator: lib.inOperator, + fromIterator: fromIterator +}; + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var _require = __webpack_require__(1), + Obj = _require.Obj; + +function traverseAndCheck(obj, type, results) { + if (obj instanceof type) { + results.push(obj); + } + + if (obj instanceof Node) { + obj.findAll(type, results); + } +} + +var Node = /*#__PURE__*/function (_Obj) { + _inheritsLoose(Node, _Obj); + + function Node() { + return _Obj.apply(this, arguments) || this; + } + + var _proto = Node.prototype; + + _proto.init = function init(lineno, colno) { + var _arguments = arguments, + _this = this; + + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + + this.lineno = lineno; + this.colno = colno; + this.fields.forEach(function (field, i) { + // The first two args are line/col numbers, so offset by 2 + var val = _arguments[i + 2]; // Fields should never be undefined, but null. It makes + // testing easier to normalize values. + + if (val === undefined) { + val = null; + } + + _this[field] = val; + }); + }; + + _proto.findAll = function findAll(type, results) { + var _this2 = this; + + results = results || []; + + if (this instanceof NodeList) { + this.children.forEach(function (child) { + return traverseAndCheck(child, type, results); + }); + } else { + this.fields.forEach(function (field) { + return traverseAndCheck(_this2[field], type, results); + }); + } + + return results; + }; + + _proto.iterFields = function iterFields(func) { + var _this3 = this; + + this.fields.forEach(function (field) { + func(_this3[field], field); + }); + }; + + return Node; +}(Obj); // Abstract nodes + + +var Value = /*#__PURE__*/function (_Node) { + _inheritsLoose(Value, _Node); + + function Value() { + return _Node.apply(this, arguments) || this; + } + + _createClass(Value, [{ + key: "typename", + get: function get() { + return 'Value'; + } + }, { + key: "fields", + get: function get() { + return ['value']; + } + }]); + + return Value; +}(Node); // Concrete nodes + + +var NodeList = /*#__PURE__*/function (_Node2) { + _inheritsLoose(NodeList, _Node2); + + function NodeList() { + return _Node2.apply(this, arguments) || this; + } + + var _proto2 = NodeList.prototype; + + _proto2.init = function init(lineno, colno, nodes) { + _Node2.prototype.init.call(this, lineno, colno, nodes || []); + }; + + _proto2.addChild = function addChild(node) { + this.children.push(node); + }; + + _createClass(NodeList, [{ + key: "typename", + get: function get() { + return 'NodeList'; + } + }, { + key: "fields", + get: function get() { + return ['children']; + } + }]); + + return NodeList; +}(Node); + +var Root = NodeList.extend('Root'); +var Literal = Value.extend('Literal'); +var Symbol = Value.extend('Symbol'); +var Group = NodeList.extend('Group'); +var ArrayNode = NodeList.extend('Array'); +var Pair = Node.extend('Pair', { + fields: ['key', 'value'] +}); +var Dict = NodeList.extend('Dict'); +var LookupVal = Node.extend('LookupVal', { + fields: ['target', 'val'] +}); +var If = Node.extend('If', { + fields: ['cond', 'body', 'else_'] +}); +var IfAsync = If.extend('IfAsync'); +var InlineIf = Node.extend('InlineIf', { + fields: ['cond', 'body', 'else_'] +}); +var For = Node.extend('For', { + fields: ['arr', 'name', 'body', 'else_'] +}); +var AsyncEach = For.extend('AsyncEach'); +var AsyncAll = For.extend('AsyncAll'); +var Macro = Node.extend('Macro', { + fields: ['name', 'args', 'body'] +}); +var Caller = Macro.extend('Caller'); +var Import = Node.extend('Import', { + fields: ['template', 'target', 'withContext'] +}); + +var FromImport = /*#__PURE__*/function (_Node3) { + _inheritsLoose(FromImport, _Node3); + + function FromImport() { + return _Node3.apply(this, arguments) || this; + } + + var _proto3 = FromImport.prototype; + + _proto3.init = function init(lineno, colno, template, names, withContext) { + _Node3.prototype.init.call(this, lineno, colno, template, names || new NodeList(), withContext); + }; + + _createClass(FromImport, [{ + key: "typename", + get: function get() { + return 'FromImport'; + } + }, { + key: "fields", + get: function get() { + return ['template', 'names', 'withContext']; + } + }]); + + return FromImport; +}(Node); + +var FunCall = Node.extend('FunCall', { + fields: ['name', 'args'] +}); +var Filter = FunCall.extend('Filter'); +var FilterAsync = Filter.extend('FilterAsync', { + fields: ['name', 'args', 'symbol'] +}); +var KeywordArgs = Dict.extend('KeywordArgs'); +var Block = Node.extend('Block', { + fields: ['name', 'body'] +}); +var Super = Node.extend('Super', { + fields: ['blockName', 'symbol'] +}); +var TemplateRef = Node.extend('TemplateRef', { + fields: ['template'] +}); +var Extends = TemplateRef.extend('Extends'); +var Include = Node.extend('Include', { + fields: ['template', 'ignoreMissing'] +}); +var Set = Node.extend('Set', { + fields: ['targets', 'value'] +}); +var Switch = Node.extend('Switch', { + fields: ['expr', 'cases', 'default'] +}); +var Case = Node.extend('Case', { + fields: ['cond', 'body'] +}); +var Output = NodeList.extend('Output'); +var Capture = Node.extend('Capture', { + fields: ['body'] +}); +var TemplateData = Literal.extend('TemplateData'); +var UnaryOp = Node.extend('UnaryOp', { + fields: ['target'] +}); +var BinOp = Node.extend('BinOp', { + fields: ['left', 'right'] +}); +var In = BinOp.extend('In'); +var Is = BinOp.extend('Is'); +var Or = BinOp.extend('Or'); +var And = BinOp.extend('And'); +var Not = UnaryOp.extend('Not'); +var Add = BinOp.extend('Add'); +var Concat = BinOp.extend('Concat'); +var Sub = BinOp.extend('Sub'); +var Mul = BinOp.extend('Mul'); +var Div = BinOp.extend('Div'); +var FloorDiv = BinOp.extend('FloorDiv'); +var Mod = BinOp.extend('Mod'); +var Pow = BinOp.extend('Pow'); +var Neg = UnaryOp.extend('Neg'); +var Pos = UnaryOp.extend('Pos'); +var Compare = Node.extend('Compare', { + fields: ['expr', 'ops'] +}); +var CompareOperand = Node.extend('CompareOperand', { + fields: ['expr', 'type'] +}); +var CallExtension = Node.extend('CallExtension', { + init: function init(ext, prop, args, contentArgs) { + this.parent(); + this.extName = ext.__name || ext; + this.prop = prop; + this.args = args || new NodeList(); + this.contentArgs = contentArgs || []; + this.autoescape = ext.autoescape; + }, + fields: ['extName', 'prop', 'args', 'contentArgs'] +}); +var CallExtensionAsync = CallExtension.extend('CallExtensionAsync'); // This is hacky, but this is just a debugging function anyway + +function print(str, indent, inline) { + var lines = str.split('\n'); + lines.forEach(function (line, i) { + if (line && (inline && i > 0 || !inline)) { + process.stdout.write(' '.repeat(indent)); + } + + var nl = i === lines.length - 1 ? '' : '\n'; + process.stdout.write("" + line + nl); + }); +} // Print the AST in a nicely formatted tree format for debuggin + + +function printNodes(node, indent) { + indent = indent || 0; + print(node.typename + ': ', indent); + + if (node instanceof NodeList) { + print('\n'); + node.children.forEach(function (n) { + printNodes(n, indent + 2); + }); + } else if (node instanceof CallExtension) { + print(node.extName + "." + node.prop + "\n"); + + if (node.args) { + printNodes(node.args, indent + 2); + } + + if (node.contentArgs) { + node.contentArgs.forEach(function (n) { + printNodes(n, indent + 2); + }); + } + } else { + var nodes = []; + var props = null; + node.iterFields(function (val, fieldName) { + if (val instanceof Node) { + nodes.push([fieldName, val]); + } else { + props = props || {}; + props[fieldName] = val; + } + }); + + if (props) { + print(JSON.stringify(props, null, 2) + '\n', null, true); + } else { + print('\n'); + } + + nodes.forEach(function (_ref) { + var fieldName = _ref[0], + n = _ref[1]; + print("[" + fieldName + "] =>", indent + 2); + printNodes(n, indent + 4); + }); + } +} + +module.exports = { + Node: Node, + Root: Root, + NodeList: NodeList, + Value: Value, + Literal: Literal, + Symbol: Symbol, + Group: Group, + Array: ArrayNode, + Pair: Pair, + Dict: Dict, + Output: Output, + Capture: Capture, + TemplateData: TemplateData, + If: If, + IfAsync: IfAsync, + InlineIf: InlineIf, + For: For, + AsyncEach: AsyncEach, + AsyncAll: AsyncAll, + Macro: Macro, + Caller: Caller, + Import: Import, + FromImport: FromImport, + FunCall: FunCall, + Filter: Filter, + FilterAsync: FilterAsync, + KeywordArgs: KeywordArgs, + Block: Block, + Super: Super, + Extends: Extends, + Include: Include, + Set: Set, + Switch: Switch, + Case: Case, + LookupVal: LookupVal, + BinOp: BinOp, + In: In, + Is: Is, + Or: Or, + And: And, + Not: Not, + Add: Add, + Concat: Concat, + Sub: Sub, + Mul: Mul, + Div: Div, + FloorDiv: FloorDiv, + Mod: Mod, + Pow: Pow, + Neg: Neg, + Pos: Pos, + Compare: Compare, + CompareOperand: CompareOperand, + CallExtension: CallExtension, + CallExtensionAsync: CallExtensionAsync, + printNodes: printNodes +}; + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var parser = __webpack_require__(8); + +var transformer = __webpack_require__(17); + +var nodes = __webpack_require__(3); + +var _require = __webpack_require__(0), + TemplateError = _require.TemplateError; + +var _require2 = __webpack_require__(2), + Frame = _require2.Frame; + +var _require3 = __webpack_require__(1), + Obj = _require3.Obj; // These are all the same for now, but shouldn't be passed straight +// through + + +var compareOps = { + '==': '==', + '===': '===', + '!=': '!=', + '!==': '!==', + '<': '<', + '>': '>', + '<=': '<=', + '>=': '>=' +}; + +var Compiler = /*#__PURE__*/function (_Obj) { + _inheritsLoose(Compiler, _Obj); + + function Compiler() { + return _Obj.apply(this, arguments) || this; + } + + var _proto = Compiler.prototype; + + _proto.init = function init(templateName, throwOnUndefined) { + this.templateName = templateName; + this.codebuf = []; + this.lastId = 0; + this.buffer = null; + this.bufferStack = []; + this._scopeClosers = ''; + this.inBlock = false; + this.throwOnUndefined = throwOnUndefined; + }; + + _proto.fail = function fail(msg, lineno, colno) { + if (lineno !== undefined) { + lineno += 1; + } + + if (colno !== undefined) { + colno += 1; + } + + throw new TemplateError(msg, lineno, colno); + }; + + _proto._pushBuffer = function _pushBuffer() { + var id = this._tmpid(); + + this.bufferStack.push(this.buffer); + this.buffer = id; + + this._emit("var " + this.buffer + " = \"\";"); + + return id; + }; + + _proto._popBuffer = function _popBuffer() { + this.buffer = this.bufferStack.pop(); + }; + + _proto._emit = function _emit(code) { + this.codebuf.push(code); + }; + + _proto._emitLine = function _emitLine(code) { + this._emit(code + '\n'); + }; + + _proto._emitLines = function _emitLines() { + var _this = this; + + for (var _len = arguments.length, lines = new Array(_len), _key = 0; _key < _len; _key++) { + lines[_key] = arguments[_key]; + } + + lines.forEach(function (line) { + return _this._emitLine(line); + }); + }; + + _proto._emitFuncBegin = function _emitFuncBegin(node, name) { + this.buffer = 'output'; + this._scopeClosers = ''; + + this._emitLine("function " + name + "(env, context, frame, runtime, cb) {"); + + this._emitLine("var lineno = " + node.lineno + ";"); + + this._emitLine("var colno = " + node.colno + ";"); + + this._emitLine("var " + this.buffer + " = \"\";"); + + this._emitLine('try {'); + }; + + _proto._emitFuncEnd = function _emitFuncEnd(noReturn) { + if (!noReturn) { + this._emitLine('cb(null, ' + this.buffer + ');'); + } + + this._closeScopeLevels(); + + this._emitLine('} catch (e) {'); + + this._emitLine(' cb(runtime.handleError(e, lineno, colno));'); + + this._emitLine('}'); + + this._emitLine('}'); + + this.buffer = null; + }; + + _proto._addScopeLevel = function _addScopeLevel() { + this._scopeClosers += '})'; + }; + + _proto._closeScopeLevels = function _closeScopeLevels() { + this._emitLine(this._scopeClosers + ';'); + + this._scopeClosers = ''; + }; + + _proto._withScopedSyntax = function _withScopedSyntax(func) { + var _scopeClosers = this._scopeClosers; + this._scopeClosers = ''; + func.call(this); + + this._closeScopeLevels(); + + this._scopeClosers = _scopeClosers; + }; + + _proto._makeCallback = function _makeCallback(res) { + var err = this._tmpid(); + + return 'function(' + err + (res ? ',' + res : '') + ') {\n' + 'if(' + err + ') { cb(' + err + '); return; }'; + }; + + _proto._tmpid = function _tmpid() { + this.lastId++; + return 't_' + this.lastId; + }; + + _proto._templateName = function _templateName() { + return this.templateName == null ? 'undefined' : JSON.stringify(this.templateName); + }; + + _proto._compileChildren = function _compileChildren(node, frame) { + var _this2 = this; + + node.children.forEach(function (child) { + _this2.compile(child, frame); + }); + }; + + _proto._compileAggregate = function _compileAggregate(node, frame, startChar, endChar) { + var _this3 = this; + + if (startChar) { + this._emit(startChar); + } + + node.children.forEach(function (child, i) { + if (i > 0) { + _this3._emit(','); + } + + _this3.compile(child, frame); + }); + + if (endChar) { + this._emit(endChar); + } + }; + + _proto._compileExpression = function _compileExpression(node, frame) { + // TODO: I'm not really sure if this type check is worth it or + // not. + this.assertType(node, nodes.Literal, nodes.Symbol, nodes.Group, nodes.Array, nodes.Dict, nodes.FunCall, nodes.Caller, nodes.Filter, nodes.LookupVal, nodes.Compare, nodes.InlineIf, nodes.In, nodes.Is, nodes.And, nodes.Or, nodes.Not, nodes.Add, nodes.Concat, nodes.Sub, nodes.Mul, nodes.Div, nodes.FloorDiv, nodes.Mod, nodes.Pow, nodes.Neg, nodes.Pos, nodes.Compare, nodes.NodeList); + this.compile(node, frame); + }; + + _proto.assertType = function assertType(node) { + for (var _len2 = arguments.length, types = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + types[_key2 - 1] = arguments[_key2]; + } + + if (!types.some(function (t) { + return node instanceof t; + })) { + this.fail("assertType: invalid type: " + node.typename, node.lineno, node.colno); + } + }; + + _proto.compileCallExtension = function compileCallExtension(node, frame, async) { + var _this4 = this; + + var args = node.args; + var contentArgs = node.contentArgs; + var autoescape = typeof node.autoescape === 'boolean' ? node.autoescape : true; + + if (!async) { + this._emit(this.buffer + " += runtime.suppressValue("); + } + + this._emit("env.getExtension(\"" + node.extName + "\")[\"" + node.prop + "\"]("); + + this._emit('context'); + + if (args || contentArgs) { + this._emit(','); + } + + if (args) { + if (!(args instanceof nodes.NodeList)) { + this.fail('compileCallExtension: arguments must be a NodeList, ' + 'use `parser.parseSignature`'); + } + + args.children.forEach(function (arg, i) { + // Tag arguments are passed normally to the call. Note + // that keyword arguments are turned into a single js + // object as the last argument, if they exist. + _this4._compileExpression(arg, frame); + + if (i !== args.children.length - 1 || contentArgs.length) { + _this4._emit(','); + } + }); + } + + if (contentArgs.length) { + contentArgs.forEach(function (arg, i) { + if (i > 0) { + _this4._emit(','); + } + + if (arg) { + _this4._emitLine('function(cb) {'); + + _this4._emitLine('if(!cb) { cb = function(err) { if(err) { throw err; }}}'); + + var id = _this4._pushBuffer(); + + _this4._withScopedSyntax(function () { + _this4.compile(arg, frame); + + _this4._emitLine("cb(null, " + id + ");"); + }); + + _this4._popBuffer(); + + _this4._emitLine("return " + id + ";"); + + _this4._emitLine('}'); + } else { + _this4._emit('null'); + } + }); + } + + if (async) { + var res = this._tmpid(); + + this._emitLine(', ' + this._makeCallback(res)); + + this._emitLine(this.buffer + " += runtime.suppressValue(" + res + ", " + autoescape + " && env.opts.autoescape);"); + + this._addScopeLevel(); + } else { + this._emit(')'); + + this._emit(", " + autoescape + " && env.opts.autoescape);\n"); + } + }; + + _proto.compileCallExtensionAsync = function compileCallExtensionAsync(node, frame) { + this.compileCallExtension(node, frame, true); + }; + + _proto.compileNodeList = function compileNodeList(node, frame) { + this._compileChildren(node, frame); + }; + + _proto.compileLiteral = function compileLiteral(node) { + if (typeof node.value === 'string') { + var val = node.value.replace(/\\/g, '\\\\'); + val = val.replace(/"/g, '\\"'); + val = val.replace(/\n/g, '\\n'); + val = val.replace(/\r/g, '\\r'); + val = val.replace(/\t/g, '\\t'); + val = val.replace(/\u2028/g, "\\u2028"); + + this._emit("\"" + val + "\""); + } else if (node.value === null) { + this._emit('null'); + } else { + this._emit(node.value.toString()); + } + }; + + _proto.compileSymbol = function compileSymbol(node, frame) { + var name = node.value; + var v = frame.lookup(name); + + if (v) { + this._emit(v); + } else { + this._emit('runtime.contextOrFrameLookup(' + 'context, frame, "' + name + '")'); + } + }; + + _proto.compileGroup = function compileGroup(node, frame) { + this._compileAggregate(node, frame, '(', ')'); + }; + + _proto.compileArray = function compileArray(node, frame) { + this._compileAggregate(node, frame, '[', ']'); + }; + + _proto.compileDict = function compileDict(node, frame) { + this._compileAggregate(node, frame, '{', '}'); + }; + + _proto.compilePair = function compilePair(node, frame) { + var key = node.key; + var val = node.value; + + if (key instanceof nodes.Symbol) { + key = new nodes.Literal(key.lineno, key.colno, key.value); + } else if (!(key instanceof nodes.Literal && typeof key.value === 'string')) { + this.fail('compilePair: Dict keys must be strings or names', key.lineno, key.colno); + } + + this.compile(key, frame); + + this._emit(': '); + + this._compileExpression(val, frame); + }; + + _proto.compileInlineIf = function compileInlineIf(node, frame) { + this._emit('('); + + this.compile(node.cond, frame); + + this._emit('?'); + + this.compile(node.body, frame); + + this._emit(':'); + + if (node.else_ !== null) { + this.compile(node.else_, frame); + } else { + this._emit('""'); + } + + this._emit(')'); + }; + + _proto.compileIn = function compileIn(node, frame) { + this._emit('runtime.inOperator('); + + this.compile(node.left, frame); + + this._emit(','); + + this.compile(node.right, frame); + + this._emit(')'); + }; + + _proto.compileIs = function compileIs(node, frame) { + // first, we need to try to get the name of the test function, if it's a + // callable (i.e., has args) and not a symbol. + var right = node.right.name ? node.right.name.value // otherwise go with the symbol value + : node.right.value; + + this._emit('env.getTest("' + right + '").call(context, '); + + this.compile(node.left, frame); // compile the arguments for the callable if they exist + + if (node.right.args) { + this._emit(','); + + this.compile(node.right.args, frame); + } + + this._emit(') === true'); + }; + + _proto._binOpEmitter = function _binOpEmitter(node, frame, str) { + this.compile(node.left, frame); + + this._emit(str); + + this.compile(node.right, frame); + } // ensure concatenation instead of addition + // by adding empty string in between + ; + + _proto.compileOr = function compileOr(node, frame) { + return this._binOpEmitter(node, frame, ' || '); + }; + + _proto.compileAnd = function compileAnd(node, frame) { + return this._binOpEmitter(node, frame, ' && '); + }; + + _proto.compileAdd = function compileAdd(node, frame) { + return this._binOpEmitter(node, frame, ' + '); + }; + + _proto.compileConcat = function compileConcat(node, frame) { + return this._binOpEmitter(node, frame, ' + "" + '); + }; + + _proto.compileSub = function compileSub(node, frame) { + return this._binOpEmitter(node, frame, ' - '); + }; + + _proto.compileMul = function compileMul(node, frame) { + return this._binOpEmitter(node, frame, ' * '); + }; + + _proto.compileDiv = function compileDiv(node, frame) { + return this._binOpEmitter(node, frame, ' / '); + }; + + _proto.compileMod = function compileMod(node, frame) { + return this._binOpEmitter(node, frame, ' % '); + }; + + _proto.compileNot = function compileNot(node, frame) { + this._emit('!'); + + this.compile(node.target, frame); + }; + + _proto.compileFloorDiv = function compileFloorDiv(node, frame) { + this._emit('Math.floor('); + + this.compile(node.left, frame); + + this._emit(' / '); + + this.compile(node.right, frame); + + this._emit(')'); + }; + + _proto.compilePow = function compilePow(node, frame) { + this._emit('Math.pow('); + + this.compile(node.left, frame); + + this._emit(', '); + + this.compile(node.right, frame); + + this._emit(')'); + }; + + _proto.compileNeg = function compileNeg(node, frame) { + this._emit('-'); + + this.compile(node.target, frame); + }; + + _proto.compilePos = function compilePos(node, frame) { + this._emit('+'); + + this.compile(node.target, frame); + }; + + _proto.compileCompare = function compileCompare(node, frame) { + var _this5 = this; + + this.compile(node.expr, frame); + node.ops.forEach(function (op) { + _this5._emit(" " + compareOps[op.type] + " "); + + _this5.compile(op.expr, frame); + }); + }; + + _proto.compileLookupVal = function compileLookupVal(node, frame) { + this._emit('runtime.memberLookup(('); + + this._compileExpression(node.target, frame); + + this._emit('),'); + + this._compileExpression(node.val, frame); + + this._emit(')'); + }; + + _proto._getNodeName = function _getNodeName(node) { + switch (node.typename) { + case 'Symbol': + return node.value; + + case 'FunCall': + return 'the return value of (' + this._getNodeName(node.name) + ')'; + + case 'LookupVal': + return this._getNodeName(node.target) + '["' + this._getNodeName(node.val) + '"]'; + + case 'Literal': + return node.value.toString(); + + default: + return '--expression--'; + } + }; + + _proto.compileFunCall = function compileFunCall(node, frame) { + // Keep track of line/col info at runtime by settings + // variables within an expression. An expression in javascript + // like (x, y, z) returns the last value, and x and y can be + // anything + this._emit('(lineno = ' + node.lineno + ', colno = ' + node.colno + ', '); + + this._emit('runtime.callWrap('); // Compile it as normal. + + + this._compileExpression(node.name, frame); // Output the name of what we're calling so we can get friendly errors + // if the lookup fails. + + + this._emit(', "' + this._getNodeName(node.name).replace(/"/g, '\\"') + '", context, '); + + this._compileAggregate(node.args, frame, '[', '])'); + + this._emit(')'); + }; + + _proto.compileFilter = function compileFilter(node, frame) { + var name = node.name; + this.assertType(name, nodes.Symbol); + + this._emit('env.getFilter("' + name.value + '").call(context, '); + + this._compileAggregate(node.args, frame); + + this._emit(')'); + }; + + _proto.compileFilterAsync = function compileFilterAsync(node, frame) { + var name = node.name; + var symbol = node.symbol.value; + this.assertType(name, nodes.Symbol); + frame.set(symbol, symbol); + + this._emit('env.getFilter("' + name.value + '").call(context, '); + + this._compileAggregate(node.args, frame); + + this._emitLine(', ' + this._makeCallback(symbol)); + + this._addScopeLevel(); + }; + + _proto.compileKeywordArgs = function compileKeywordArgs(node, frame) { + this._emit('runtime.makeKeywordArgs('); + + this.compileDict(node, frame); + + this._emit(')'); + }; + + _proto.compileSet = function compileSet(node, frame) { + var _this6 = this; + + var ids = []; // Lookup the variable names for each identifier and create + // new ones if necessary + + node.targets.forEach(function (target) { + var name = target.value; + var id = frame.lookup(name); + + if (id === null || id === undefined) { + id = _this6._tmpid(); // Note: This relies on js allowing scope across + // blocks, in case this is created inside an `if` + + _this6._emitLine('var ' + id + ';'); + } + + ids.push(id); + }); + + if (node.value) { + this._emit(ids.join(' = ') + ' = '); + + this._compileExpression(node.value, frame); + + this._emitLine(';'); + } else { + this._emit(ids.join(' = ') + ' = '); + + this.compile(node.body, frame); + + this._emitLine(';'); + } + + node.targets.forEach(function (target, i) { + var id = ids[i]; + var name = target.value; // We are running this for every var, but it's very + // uncommon to assign to multiple vars anyway + + _this6._emitLine("frame.set(\"" + name + "\", " + id + ", true);"); + + _this6._emitLine('if(frame.topLevel) {'); + + _this6._emitLine("context.setVariable(\"" + name + "\", " + id + ");"); + + _this6._emitLine('}'); + + if (name.charAt(0) !== '_') { + _this6._emitLine('if(frame.topLevel) {'); + + _this6._emitLine("context.addExport(\"" + name + "\", " + id + ");"); + + _this6._emitLine('}'); + } + }); + }; + + _proto.compileSwitch = function compileSwitch(node, frame) { + var _this7 = this; + + this._emit('switch ('); + + this.compile(node.expr, frame); + + this._emit(') {'); + + node.cases.forEach(function (c, i) { + _this7._emit('case '); + + _this7.compile(c.cond, frame); + + _this7._emit(': '); + + _this7.compile(c.body, frame); // preserve fall-throughs + + + if (c.body.children.length) { + _this7._emitLine('break;'); + } + }); + + if (node.default) { + this._emit('default:'); + + this.compile(node.default, frame); + } + + this._emit('}'); + }; + + _proto.compileIf = function compileIf(node, frame, async) { + var _this8 = this; + + this._emit('if('); + + this._compileExpression(node.cond, frame); + + this._emitLine(') {'); + + this._withScopedSyntax(function () { + _this8.compile(node.body, frame); + + if (async) { + _this8._emit('cb()'); + } + }); + + if (node.else_) { + this._emitLine('}\nelse {'); + + this._withScopedSyntax(function () { + _this8.compile(node.else_, frame); + + if (async) { + _this8._emit('cb()'); + } + }); + } else if (async) { + this._emitLine('}\nelse {'); + + this._emit('cb()'); + } + + this._emitLine('}'); + }; + + _proto.compileIfAsync = function compileIfAsync(node, frame) { + this._emit('(function(cb) {'); + + this.compileIf(node, frame, true); + + this._emit('})(' + this._makeCallback()); + + this._addScopeLevel(); + }; + + _proto._emitLoopBindings = function _emitLoopBindings(node, arr, i, len) { + var _this9 = this; + + var bindings = [{ + name: 'index', + val: i + " + 1" + }, { + name: 'index0', + val: i + }, { + name: 'revindex', + val: len + " - " + i + }, { + name: 'revindex0', + val: len + " - " + i + " - 1" + }, { + name: 'first', + val: i + " === 0" + }, { + name: 'last', + val: i + " === " + len + " - 1" + }, { + name: 'length', + val: len + }]; + bindings.forEach(function (b) { + _this9._emitLine("frame.set(\"loop." + b.name + "\", " + b.val + ");"); + }); + }; + + _proto.compileFor = function compileFor(node, frame) { + var _this10 = this; + + // Some of this code is ugly, but it keeps the generated code + // as fast as possible. ForAsync also shares some of this, but + // not much. + var i = this._tmpid(); + + var len = this._tmpid(); + + var arr = this._tmpid(); + + frame = frame.push(); + + this._emitLine('frame = frame.push();'); + + this._emit("var " + arr + " = "); + + this._compileExpression(node.arr, frame); + + this._emitLine(';'); + + this._emit("if(" + arr + ") {"); + + this._emitLine(arr + ' = runtime.fromIterator(' + arr + ');'); // If multiple names are passed, we need to bind them + // appropriately + + + if (node.name instanceof nodes.Array) { + this._emitLine("var " + i + ";"); // The object could be an arroy or object. Note that the + // body of the loop is duplicated for each condition, but + // we are optimizing for speed over size. + + + this._emitLine("if(runtime.isArray(" + arr + ")) {"); + + this._emitLine("var " + len + " = " + arr + ".length;"); + + this._emitLine("for(" + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); // Bind each declared var + + + node.name.children.forEach(function (child, u) { + var tid = _this10._tmpid(); + + _this10._emitLine("var " + tid + " = " + arr + "[" + i + "][" + u + "];"); + + _this10._emitLine("frame.set(\"" + child + "\", " + arr + "[" + i + "][" + u + "]);"); + + frame.set(node.name.children[u].value, tid); + }); + + this._emitLoopBindings(node, arr, i, len); + + this._withScopedSyntax(function () { + _this10.compile(node.body, frame); + }); + + this._emitLine('}'); + + this._emitLine('} else {'); // Iterate over the key/values of an object + + + var _node$name$children = node.name.children, + key = _node$name$children[0], + val = _node$name$children[1]; + + var k = this._tmpid(); + + var v = this._tmpid(); + + frame.set(key.value, k); + frame.set(val.value, v); + + this._emitLine(i + " = -1;"); + + this._emitLine("var " + len + " = runtime.keys(" + arr + ").length;"); + + this._emitLine("for(var " + k + " in " + arr + ") {"); + + this._emitLine(i + "++;"); + + this._emitLine("var " + v + " = " + arr + "[" + k + "];"); + + this._emitLine("frame.set(\"" + key.value + "\", " + k + ");"); + + this._emitLine("frame.set(\"" + val.value + "\", " + v + ");"); + + this._emitLoopBindings(node, arr, i, len); + + this._withScopedSyntax(function () { + _this10.compile(node.body, frame); + }); + + this._emitLine('}'); + + this._emitLine('}'); + } else { + // Generate a typical array iteration + var _v = this._tmpid(); + + frame.set(node.name.value, _v); + + this._emitLine("var " + len + " = " + arr + ".length;"); + + this._emitLine("for(var " + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); + + this._emitLine("var " + _v + " = " + arr + "[" + i + "];"); + + this._emitLine("frame.set(\"" + node.name.value + "\", " + _v + ");"); + + this._emitLoopBindings(node, arr, i, len); + + this._withScopedSyntax(function () { + _this10.compile(node.body, frame); + }); + + this._emitLine('}'); + } + + this._emitLine('}'); + + if (node.else_) { + this._emitLine('if (!' + len + ') {'); + + this.compile(node.else_, frame); + + this._emitLine('}'); + } + + this._emitLine('frame = frame.pop();'); + }; + + _proto._compileAsyncLoop = function _compileAsyncLoop(node, frame, parallel) { + var _this11 = this; + + // This shares some code with the For tag, but not enough to + // worry about. This iterates across an object asynchronously, + // but not in parallel. + var i = this._tmpid(); + + var len = this._tmpid(); + + var arr = this._tmpid(); + + var asyncMethod = parallel ? 'asyncAll' : 'asyncEach'; + frame = frame.push(); + + this._emitLine('frame = frame.push();'); + + this._emit('var ' + arr + ' = runtime.fromIterator('); + + this._compileExpression(node.arr, frame); + + this._emitLine(');'); + + if (node.name instanceof nodes.Array) { + var arrayLen = node.name.children.length; + + this._emit("runtime." + asyncMethod + "(" + arr + ", " + arrayLen + ", function("); + + node.name.children.forEach(function (name) { + _this11._emit(name.value + ","); + }); + + this._emit(i + ',' + len + ',next) {'); + + node.name.children.forEach(function (name) { + var id = name.value; + frame.set(id, id); + + _this11._emitLine("frame.set(\"" + id + "\", " + id + ");"); + }); + } else { + var id = node.name.value; + + this._emitLine("runtime." + asyncMethod + "(" + arr + ", 1, function(" + id + ", " + i + ", " + len + ",next) {"); + + this._emitLine('frame.set("' + id + '", ' + id + ');'); + + frame.set(id, id); + } + + this._emitLoopBindings(node, arr, i, len); + + this._withScopedSyntax(function () { + var buf; + + if (parallel) { + buf = _this11._pushBuffer(); + } + + _this11.compile(node.body, frame); + + _this11._emitLine('next(' + i + (buf ? ',' + buf : '') + ');'); + + if (parallel) { + _this11._popBuffer(); + } + }); + + var output = this._tmpid(); + + this._emitLine('}, ' + this._makeCallback(output)); + + this._addScopeLevel(); + + if (parallel) { + this._emitLine(this.buffer + ' += ' + output + ';'); + } + + if (node.else_) { + this._emitLine('if (!' + arr + '.length) {'); + + this.compile(node.else_, frame); + + this._emitLine('}'); + } + + this._emitLine('frame = frame.pop();'); + }; + + _proto.compileAsyncEach = function compileAsyncEach(node, frame) { + this._compileAsyncLoop(node, frame); + }; + + _proto.compileAsyncAll = function compileAsyncAll(node, frame) { + this._compileAsyncLoop(node, frame, true); + }; + + _proto._compileMacro = function _compileMacro(node, frame) { + var _this12 = this; + + var args = []; + var kwargs = null; + + var funcId = 'macro_' + this._tmpid(); + + var keepFrame = frame !== undefined; // Type check the definition of the args + + node.args.children.forEach(function (arg, i) { + if (i === node.args.children.length - 1 && arg instanceof nodes.Dict) { + kwargs = arg; + } else { + _this12.assertType(arg, nodes.Symbol); + + args.push(arg); + } + }); + var realNames = [].concat(args.map(function (n) { + return "l_" + n.value; + }), ['kwargs']); // Quoted argument names + + var argNames = args.map(function (n) { + return "\"" + n.value + "\""; + }); + var kwargNames = (kwargs && kwargs.children || []).map(function (n) { + return "\"" + n.key.value + "\""; + }); // We pass a function to makeMacro which destructures the + // arguments so support setting positional args with keywords + // args and passing keyword args as positional args + // (essentially default values). See runtime.js. + + var currFrame; + + if (keepFrame) { + currFrame = frame.push(true); + } else { + currFrame = new Frame(); + } + + this._emitLines("var " + funcId + " = runtime.makeMacro(", "[" + argNames.join(', ') + "], ", "[" + kwargNames.join(', ') + "], ", "function (" + realNames.join(', ') + ") {", 'var callerFrame = frame;', 'frame = ' + (keepFrame ? 'frame.push(true);' : 'new runtime.Frame();'), 'kwargs = kwargs || {};', 'if (Object.prototype.hasOwnProperty.call(kwargs, "caller")) {', 'frame.set("caller", kwargs.caller); }'); // Expose the arguments to the template. Don't need to use + // random names because the function + // will create a new run-time scope for us + + + args.forEach(function (arg) { + _this12._emitLine("frame.set(\"" + arg.value + "\", l_" + arg.value + ");"); + + currFrame.set(arg.value, "l_" + arg.value); + }); // Expose the keyword arguments + + if (kwargs) { + kwargs.children.forEach(function (pair) { + var name = pair.key.value; + + _this12._emit("frame.set(\"" + name + "\", "); + + _this12._emit("Object.prototype.hasOwnProperty.call(kwargs, \"" + name + "\")"); + + _this12._emit(" ? kwargs[\"" + name + "\"] : "); + + _this12._compileExpression(pair.value, currFrame); + + _this12._emit(');'); + }); + } + + var bufferId = this._pushBuffer(); + + this._withScopedSyntax(function () { + _this12.compile(node.body, currFrame); + }); + + this._emitLine('frame = ' + (keepFrame ? 'frame.pop();' : 'callerFrame;')); + + this._emitLine("return new runtime.SafeString(" + bufferId + ");"); + + this._emitLine('});'); + + this._popBuffer(); + + return funcId; + }; + + _proto.compileMacro = function compileMacro(node, frame) { + var funcId = this._compileMacro(node); // Expose the macro to the templates + + + var name = node.name.value; + frame.set(name, funcId); + + if (frame.parent) { + this._emitLine("frame.set(\"" + name + "\", " + funcId + ");"); + } else { + if (node.name.value.charAt(0) !== '_') { + this._emitLine("context.addExport(\"" + name + "\");"); + } + + this._emitLine("context.setVariable(\"" + name + "\", " + funcId + ");"); + } + }; + + _proto.compileCaller = function compileCaller(node, frame) { + // basically an anonymous "macro expression" + this._emit('(function (){'); + + var funcId = this._compileMacro(node, frame); + + this._emit("return " + funcId + ";})()"); + }; + + _proto._compileGetTemplate = function _compileGetTemplate(node, frame, eagerCompile, ignoreMissing) { + var parentTemplateId = this._tmpid(); + + var parentName = this._templateName(); + + var cb = this._makeCallback(parentTemplateId); + + var eagerCompileArg = eagerCompile ? 'true' : 'false'; + var ignoreMissingArg = ignoreMissing ? 'true' : 'false'; + + this._emit('env.getTemplate('); + + this._compileExpression(node.template, frame); + + this._emitLine(", " + eagerCompileArg + ", " + parentName + ", " + ignoreMissingArg + ", " + cb); + + return parentTemplateId; + }; + + _proto.compileImport = function compileImport(node, frame) { + var target = node.target.value; + + var id = this._compileGetTemplate(node, frame, false, false); + + this._addScopeLevel(); + + this._emitLine(id + '.getExported(' + (node.withContext ? 'context.getVariables(), frame, ' : '') + this._makeCallback(id)); + + this._addScopeLevel(); + + frame.set(target, id); + + if (frame.parent) { + this._emitLine("frame.set(\"" + target + "\", " + id + ");"); + } else { + this._emitLine("context.setVariable(\"" + target + "\", " + id + ");"); + } + }; + + _proto.compileFromImport = function compileFromImport(node, frame) { + var _this13 = this; + + var importedId = this._compileGetTemplate(node, frame, false, false); + + this._addScopeLevel(); + + this._emitLine(importedId + '.getExported(' + (node.withContext ? 'context.getVariables(), frame, ' : '') + this._makeCallback(importedId)); + + this._addScopeLevel(); + + node.names.children.forEach(function (nameNode) { + var name; + var alias; + + var id = _this13._tmpid(); + + if (nameNode instanceof nodes.Pair) { + name = nameNode.key.value; + alias = nameNode.value.value; + } else { + name = nameNode.value; + alias = name; + } + + _this13._emitLine("if(Object.prototype.hasOwnProperty.call(" + importedId + ", \"" + name + "\")) {"); + + _this13._emitLine("var " + id + " = " + importedId + "." + name + ";"); + + _this13._emitLine('} else {'); + + _this13._emitLine("cb(new Error(\"cannot import '" + name + "'\")); return;"); + + _this13._emitLine('}'); + + frame.set(alias, id); + + if (frame.parent) { + _this13._emitLine("frame.set(\"" + alias + "\", " + id + ");"); + } else { + _this13._emitLine("context.setVariable(\"" + alias + "\", " + id + ");"); + } + }); + }; + + _proto.compileBlock = function compileBlock(node) { + var id = this._tmpid(); // If we are executing outside a block (creating a top-level + // block), we really don't want to execute its code because it + // will execute twice: once when the child template runs and + // again when the parent template runs. Note that blocks + // within blocks will *always* execute immediately *and* + // wherever else they are invoked (like used in a parent + // template). This may have behavioral differences from jinja + // because blocks can have side effects, but it seems like a + // waste of performance to always execute huge top-level + // blocks twice + + + if (!this.inBlock) { + this._emit('(parentTemplate ? function(e, c, f, r, cb) { cb(""); } : '); + } + + this._emit("context.getBlock(\"" + node.name.value + "\")"); + + if (!this.inBlock) { + this._emit(')'); + } + + this._emitLine('(env, context, frame, runtime, ' + this._makeCallback(id)); + + this._emitLine(this.buffer + " += " + id + ";"); + + this._addScopeLevel(); + }; + + _proto.compileSuper = function compileSuper(node, frame) { + var name = node.blockName.value; + var id = node.symbol.value; + + var cb = this._makeCallback(id); + + this._emitLine("context.getSuper(env, \"" + name + "\", b_" + name + ", frame, runtime, " + cb); + + this._emitLine(id + " = runtime.markSafe(" + id + ");"); + + this._addScopeLevel(); + + frame.set(id, id); + }; + + _proto.compileExtends = function compileExtends(node, frame) { + var k = this._tmpid(); + + var parentTemplateId = this._compileGetTemplate(node, frame, true, false); // extends is a dynamic tag and can occur within a block like + // `if`, so if this happens we need to capture the parent + // template in the top-level scope + + + this._emitLine("parentTemplate = " + parentTemplateId); + + this._emitLine("for(var " + k + " in parentTemplate.blocks) {"); + + this._emitLine("context.addBlock(" + k + ", parentTemplate.blocks[" + k + "]);"); + + this._emitLine('}'); + + this._addScopeLevel(); + }; + + _proto.compileInclude = function compileInclude(node, frame) { + this._emitLine('var tasks = [];'); + + this._emitLine('tasks.push('); + + this._emitLine('function(callback) {'); + + var id = this._compileGetTemplate(node, frame, false, node.ignoreMissing); + + this._emitLine("callback(null," + id + ");});"); + + this._emitLine('});'); + + var id2 = this._tmpid(); + + this._emitLine('tasks.push('); + + this._emitLine('function(template, callback){'); + + this._emitLine('template.render(context.getVariables(), frame, ' + this._makeCallback(id2)); + + this._emitLine('callback(null,' + id2 + ');});'); + + this._emitLine('});'); + + this._emitLine('tasks.push('); + + this._emitLine('function(result, callback){'); + + this._emitLine(this.buffer + " += result;"); + + this._emitLine('callback(null);'); + + this._emitLine('});'); + + this._emitLine('env.waterfall(tasks, function(){'); + + this._addScopeLevel(); + }; + + _proto.compileTemplateData = function compileTemplateData(node, frame) { + this.compileLiteral(node, frame); + }; + + _proto.compileCapture = function compileCapture(node, frame) { + var _this14 = this; + + // we need to temporarily override the current buffer id as 'output' + // so the set block writes to the capture output instead of the buffer + var buffer = this.buffer; + this.buffer = 'output'; + + this._emitLine('(function() {'); + + this._emitLine('var output = "";'); + + this._withScopedSyntax(function () { + _this14.compile(node.body, frame); + }); + + this._emitLine('return output;'); + + this._emitLine('})()'); // and of course, revert back to the old buffer id + + + this.buffer = buffer; + }; + + _proto.compileOutput = function compileOutput(node, frame) { + var _this15 = this; + + var children = node.children; + children.forEach(function (child) { + // TemplateData is a special case because it is never + // autoescaped, so simply output it for optimization + if (child instanceof nodes.TemplateData) { + if (child.value) { + _this15._emit(_this15.buffer + " += "); + + _this15.compileLiteral(child, frame); + + _this15._emitLine(';'); + } + } else { + _this15._emit(_this15.buffer + " += runtime.suppressValue("); + + if (_this15.throwOnUndefined) { + _this15._emit('runtime.ensureDefined('); + } + + _this15.compile(child, frame); + + if (_this15.throwOnUndefined) { + _this15._emit("," + node.lineno + "," + node.colno + ")"); + } + + _this15._emit(', env.opts.autoescape);\n'); + } + }); + }; + + _proto.compileRoot = function compileRoot(node, frame) { + var _this16 = this; + + if (frame) { + this.fail('compileRoot: root node can\'t have frame'); + } + + frame = new Frame(); + + this._emitFuncBegin(node, 'root'); + + this._emitLine('var parentTemplate = null;'); + + this._compileChildren(node, frame); + + this._emitLine('if(parentTemplate) {'); + + this._emitLine('parentTemplate.rootRenderFunc(env, context, frame, runtime, cb);'); + + this._emitLine('} else {'); + + this._emitLine("cb(null, " + this.buffer + ");"); + + this._emitLine('}'); + + this._emitFuncEnd(true); + + this.inBlock = true; + var blockNames = []; + var blocks = node.findAll(nodes.Block); + blocks.forEach(function (block, i) { + var name = block.name.value; + + if (blockNames.indexOf(name) !== -1) { + throw new Error("Block \"" + name + "\" defined more than once."); + } + + blockNames.push(name); + + _this16._emitFuncBegin(block, "b_" + name); + + var tmpFrame = new Frame(); + + _this16._emitLine('var frame = frame.push(true);'); + + _this16.compile(block.body, tmpFrame); + + _this16._emitFuncEnd(); + }); + + this._emitLine('return {'); + + blocks.forEach(function (block, i) { + var blockName = "b_" + block.name.value; + + _this16._emitLine(blockName + ": " + blockName + ","); + }); + + this._emitLine('root: root\n};'); + }; + + _proto.compile = function compile(node, frame) { + var _compile = this['compile' + node.typename]; + + if (_compile) { + _compile.call(this, node, frame); + } else { + this.fail("compile: Cannot compile node: " + node.typename, node.lineno, node.colno); + } + }; + + _proto.getCode = function getCode() { + return this.codebuf.join(''); + }; + + return Compiler; +}(Obj); + +module.exports = { + compile: function compile(src, asyncFilters, extensions, name, opts) { + if (opts === void 0) { + opts = {}; + } + + var c = new Compiler(name, opts.throwOnUndefined); // Run the extension preprocessors against the source. + + var preprocessors = (extensions || []).map(function (ext) { + return ext.preprocess; + }).filter(function (f) { + return !!f; + }); + var processedSrc = preprocessors.reduce(function (s, processor) { + return processor(s); + }, src); + c.compile(transformer.transform(parser.parse(processedSrc, extensions, opts), asyncFilters, name)); + return c.getCode(); + }, + Compiler: Compiler +}; + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var path = __webpack_require__(4); + +var _require = __webpack_require__(1), + EmitterObj = _require.EmitterObj; + +module.exports = /*#__PURE__*/function (_EmitterObj) { + _inheritsLoose(Loader, _EmitterObj); + + function Loader() { + return _EmitterObj.apply(this, arguments) || this; + } + + var _proto = Loader.prototype; + + _proto.resolve = function resolve(from, to) { + return path.resolve(path.dirname(from), to); + }; + + _proto.isRelative = function isRelative(filename) { + return filename.indexOf('./') === 0 || filename.indexOf('../') === 0; + }; + + return Loader; +}(EmitterObj); + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var asap = __webpack_require__(12); + +var _waterfall = __webpack_require__(15); + +var lib = __webpack_require__(0); + +var compiler = __webpack_require__(5); + +var filters = __webpack_require__(18); + +var _require = __webpack_require__(10), + FileSystemLoader = _require.FileSystemLoader, + WebLoader = _require.WebLoader, + PrecompiledLoader = _require.PrecompiledLoader; + +var tests = __webpack_require__(20); + +var globals = __webpack_require__(21); + +var _require2 = __webpack_require__(1), + Obj = _require2.Obj, + EmitterObj = _require2.EmitterObj; + +var globalRuntime = __webpack_require__(2); + +var handleError = globalRuntime.handleError, + Frame = globalRuntime.Frame; + +var expressApp = __webpack_require__(22); // If the user is using the async API, *always* call it +// asynchronously even if the template was synchronous. + + +function callbackAsap(cb, err, res) { + asap(function () { + cb(err, res); + }); +} +/** + * A no-op template, for use with {% include ignore missing %} + */ + + +var noopTmplSrc = { + type: 'code', + obj: { + root: function root(env, context, frame, runtime, cb) { + try { + cb(null, ''); + } catch (e) { + cb(handleError(e, null, null)); + } + } + } +}; + +var Environment = /*#__PURE__*/function (_EmitterObj) { + _inheritsLoose(Environment, _EmitterObj); + + function Environment() { + return _EmitterObj.apply(this, arguments) || this; + } + + var _proto = Environment.prototype; + + _proto.init = function init(loaders, opts) { + var _this = this; + + // The dev flag determines the trace that'll be shown on errors. + // If set to true, returns the full trace from the error point, + // otherwise will return trace starting from Template.render + // (the full trace from within nunjucks may confuse developers using + // the library) + // defaults to false + opts = this.opts = opts || {}; + this.opts.dev = !!opts.dev; // The autoescape flag sets global autoescaping. If true, + // every string variable will be escaped by default. + // If false, strings can be manually escaped using the `escape` filter. + // defaults to true + + this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true; // If true, this will make the system throw errors if trying + // to output a null or undefined value + + this.opts.throwOnUndefined = !!opts.throwOnUndefined; + this.opts.trimBlocks = !!opts.trimBlocks; + this.opts.lstripBlocks = !!opts.lstripBlocks; + this.loaders = []; + + if (!loaders) { + // The filesystem loader is only available server-side + if (FileSystemLoader) { + this.loaders = [new FileSystemLoader('views')]; + } else if (WebLoader) { + this.loaders = [new WebLoader('/views')]; + } + } else { + this.loaders = lib.isArray(loaders) ? loaders : [loaders]; + } // It's easy to use precompiled templates: just include them + // before you configure nunjucks and this will automatically + // pick it up and use it + + + if (typeof window !== 'undefined' && window.nunjucksPrecompiled) { + this.loaders.unshift(new PrecompiledLoader(window.nunjucksPrecompiled)); + } + + this._initLoaders(); + + this.globals = globals(); + this.filters = {}; + this.tests = {}; + this.asyncFilters = []; + this.extensions = {}; + this.extensionsList = []; + + lib._entries(filters).forEach(function (_ref) { + var name = _ref[0], + filter = _ref[1]; + return _this.addFilter(name, filter); + }); + + lib._entries(tests).forEach(function (_ref2) { + var name = _ref2[0], + test = _ref2[1]; + return _this.addTest(name, test); + }); + }; + + _proto._initLoaders = function _initLoaders() { + var _this2 = this; + + this.loaders.forEach(function (loader) { + // Caching and cache busting + loader.cache = {}; + + if (typeof loader.on === 'function') { + loader.on('update', function (name, fullname) { + loader.cache[name] = null; + + _this2.emit('update', name, fullname, loader); + }); + loader.on('load', function (name, source) { + _this2.emit('load', name, source, loader); + }); + } + }); + }; + + _proto.invalidateCache = function invalidateCache() { + this.loaders.forEach(function (loader) { + loader.cache = {}; + }); + }; + + _proto.addExtension = function addExtension(name, extension) { + extension.__name = name; + this.extensions[name] = extension; + this.extensionsList.push(extension); + return this; + }; + + _proto.removeExtension = function removeExtension(name) { + var extension = this.getExtension(name); + + if (!extension) { + return; + } + + this.extensionsList = lib.without(this.extensionsList, extension); + delete this.extensions[name]; + }; + + _proto.getExtension = function getExtension(name) { + return this.extensions[name]; + }; + + _proto.hasExtension = function hasExtension(name) { + return !!this.extensions[name]; + }; + + _proto.addGlobal = function addGlobal(name, value) { + this.globals[name] = value; + return this; + }; + + _proto.getGlobal = function getGlobal(name) { + if (typeof this.globals[name] === 'undefined') { + throw new Error('global not found: ' + name); + } + + return this.globals[name]; + }; + + _proto.addFilter = function addFilter(name, func, async) { + var wrapped = func; + + if (async) { + this.asyncFilters.push(name); + } + + this.filters[name] = wrapped; + return this; + }; + + _proto.getFilter = function getFilter(name) { + if (!this.filters[name]) { + throw new Error('filter not found: ' + name); + } + + return this.filters[name]; + }; + + _proto.addTest = function addTest(name, func) { + this.tests[name] = func; + return this; + }; + + _proto.getTest = function getTest(name) { + if (!this.tests[name]) { + throw new Error('test not found: ' + name); + } + + return this.tests[name]; + }; + + _proto.resolveTemplate = function resolveTemplate(loader, parentName, filename) { + var isRelative = loader.isRelative && parentName ? loader.isRelative(filename) : false; + return isRelative && loader.resolve ? loader.resolve(parentName, filename) : filename; + }; + + _proto.getTemplate = function getTemplate(name, eagerCompile, parentName, ignoreMissing, cb) { + var _this3 = this; + + var that = this; + var tmpl = null; + + if (name && name.raw) { + // this fixes autoescape for templates referenced in symbols + name = name.raw; + } + + if (lib.isFunction(parentName)) { + cb = parentName; + parentName = null; + eagerCompile = eagerCompile || false; + } + + if (lib.isFunction(eagerCompile)) { + cb = eagerCompile; + eagerCompile = false; + } + + if (name instanceof Template) { + tmpl = name; + } else if (typeof name !== 'string') { + throw new Error('template names must be a string: ' + name); + } else { + for (var i = 0; i < this.loaders.length; i++) { + var loader = this.loaders[i]; + tmpl = loader.cache[this.resolveTemplate(loader, parentName, name)]; + + if (tmpl) { + break; + } + } + } + + if (tmpl) { + if (eagerCompile) { + tmpl.compile(); + } + + if (cb) { + cb(null, tmpl); + return undefined; + } else { + return tmpl; + } + } + + var syncResult; + + var createTemplate = function createTemplate(err, info) { + if (!info && !err && !ignoreMissing) { + err = new Error('template not found: ' + name); + } + + if (err) { + if (cb) { + cb(err); + return; + } else { + throw err; + } + } + + var newTmpl; + + if (!info) { + newTmpl = new Template(noopTmplSrc, _this3, '', eagerCompile); + } else { + newTmpl = new Template(info.src, _this3, info.path, eagerCompile); + + if (!info.noCache) { + info.loader.cache[name] = newTmpl; + } + } + + if (cb) { + cb(null, newTmpl); + } else { + syncResult = newTmpl; + } + }; + + lib.asyncIter(this.loaders, function (loader, i, next, done) { + function handle(err, src) { + if (err) { + done(err); + } else if (src) { + src.loader = loader; + done(null, src); + } else { + next(); + } + } // Resolve name relative to parentName + + + name = that.resolveTemplate(loader, parentName, name); + + if (loader.async) { + loader.getSource(name, handle); + } else { + handle(null, loader.getSource(name)); + } + }, createTemplate); + return syncResult; + }; + + _proto.express = function express(app) { + return expressApp(this, app); + }; + + _proto.render = function render(name, ctx, cb) { + if (lib.isFunction(ctx)) { + cb = ctx; + ctx = null; + } // We support a synchronous API to make it easier to migrate + // existing code to async. This works because if you don't do + // anything async work, the whole thing is actually run + // synchronously. + + + var syncResult = null; + this.getTemplate(name, function (err, tmpl) { + if (err && cb) { + callbackAsap(cb, err); + } else if (err) { + throw err; + } else { + syncResult = tmpl.render(ctx, cb); + } + }); + return syncResult; + }; + + _proto.renderString = function renderString(src, ctx, opts, cb) { + if (lib.isFunction(opts)) { + cb = opts; + opts = {}; + } + + opts = opts || {}; + var tmpl = new Template(src, this, opts.path); + return tmpl.render(ctx, cb); + }; + + _proto.waterfall = function waterfall(tasks, callback, forceAsync) { + return _waterfall(tasks, callback, forceAsync); + }; + + return Environment; +}(EmitterObj); + +var Context = /*#__PURE__*/function (_Obj) { + _inheritsLoose(Context, _Obj); + + function Context() { + return _Obj.apply(this, arguments) || this; + } + + var _proto2 = Context.prototype; + + _proto2.init = function init(ctx, blocks, env) { + var _this4 = this; + + // Has to be tied to an environment so we can tap into its globals. + this.env = env || new Environment(); // Make a duplicate of ctx + + this.ctx = lib.extend({}, ctx); + this.blocks = {}; + this.exported = []; + lib.keys(blocks).forEach(function (name) { + _this4.addBlock(name, blocks[name]); + }); + }; + + _proto2.lookup = function lookup(name) { + // This is one of the most called functions, so optimize for + // the typical case where the name isn't in the globals + if (name in this.env.globals && !(name in this.ctx)) { + return this.env.globals[name]; + } else { + return this.ctx[name]; + } + }; + + _proto2.setVariable = function setVariable(name, val) { + this.ctx[name] = val; + }; + + _proto2.getVariables = function getVariables() { + return this.ctx; + }; + + _proto2.addBlock = function addBlock(name, block) { + this.blocks[name] = this.blocks[name] || []; + this.blocks[name].push(block); + return this; + }; + + _proto2.getBlock = function getBlock(name) { + if (!this.blocks[name]) { + throw new Error('unknown block "' + name + '"'); + } + + return this.blocks[name][0]; + }; + + _proto2.getSuper = function getSuper(env, name, block, frame, runtime, cb) { + var idx = lib.indexOf(this.blocks[name] || [], block); + var blk = this.blocks[name][idx + 1]; + var context = this; + + if (idx === -1 || !blk) { + throw new Error('no super block available for "' + name + '"'); + } + + blk(env, context, frame, runtime, cb); + }; + + _proto2.addExport = function addExport(name) { + this.exported.push(name); + }; + + _proto2.getExported = function getExported() { + var _this5 = this; + + var exported = {}; + this.exported.forEach(function (name) { + exported[name] = _this5.ctx[name]; + }); + return exported; + }; + + return Context; +}(Obj); + +var Template = /*#__PURE__*/function (_Obj2) { + _inheritsLoose(Template, _Obj2); + + function Template() { + return _Obj2.apply(this, arguments) || this; + } + + var _proto3 = Template.prototype; + + _proto3.init = function init(src, env, path, eagerCompile) { + this.env = env || new Environment(); + + if (lib.isObject(src)) { + switch (src.type) { + case 'code': + this.tmplProps = src.obj; + break; + + case 'string': + this.tmplStr = src.obj; + break; + + default: + throw new Error("Unexpected template object type " + src.type + "; expected 'code', or 'string'"); + } + } else if (lib.isString(src)) { + this.tmplStr = src; + } else { + throw new Error('src must be a string or an object describing the source'); + } + + this.path = path; + + if (eagerCompile) { + try { + this._compile(); + } catch (err) { + throw lib._prettifyError(this.path, this.env.opts.dev, err); + } + } else { + this.compiled = false; + } + }; + + _proto3.render = function render(ctx, parentFrame, cb) { + var _this6 = this; + + if (typeof ctx === 'function') { + cb = ctx; + ctx = {}; + } else if (typeof parentFrame === 'function') { + cb = parentFrame; + parentFrame = null; + } // If there is a parent frame, we are being called from internal + // code of another template, and the internal system + // depends on the sync/async nature of the parent template + // to be inherited, so force an async callback + + + var forceAsync = !parentFrame; // Catch compile errors for async rendering + + try { + this.compile(); + } catch (e) { + var err = lib._prettifyError(this.path, this.env.opts.dev, e); + + if (cb) { + return callbackAsap(cb, err); + } else { + throw err; + } + } + + var context = new Context(ctx || {}, this.blocks, this.env); + var frame = parentFrame ? parentFrame.push(true) : new Frame(); + frame.topLevel = true; + var syncResult = null; + var didError = false; + this.rootRenderFunc(this.env, context, frame, globalRuntime, function (err, res) { + // TODO: this is actually a bug in the compiled template (because waterfall + // tasks are both not passing errors up the chain of callbacks AND are not + // causing a return from the top-most render function). But fixing that + // will require a more substantial change to the compiler. + if (didError && cb && typeof res !== 'undefined') { + // prevent multiple calls to cb + return; + } + + if (err) { + err = lib._prettifyError(_this6.path, _this6.env.opts.dev, err); + didError = true; + } + + if (cb) { + if (forceAsync) { + callbackAsap(cb, err, res); + } else { + cb(err, res); + } + } else { + if (err) { + throw err; + } + + syncResult = res; + } + }); + return syncResult; + }; + + _proto3.getExported = function getExported(ctx, parentFrame, cb) { + // eslint-disable-line consistent-return + if (typeof ctx === 'function') { + cb = ctx; + ctx = {}; + } + + if (typeof parentFrame === 'function') { + cb = parentFrame; + parentFrame = null; + } // Catch compile errors for async rendering + + + try { + this.compile(); + } catch (e) { + if (cb) { + return cb(e); + } else { + throw e; + } + } + + var frame = parentFrame ? parentFrame.push() : new Frame(); + frame.topLevel = true; // Run the rootRenderFunc to populate the context with exported vars + + var context = new Context(ctx || {}, this.blocks, this.env); + this.rootRenderFunc(this.env, context, frame, globalRuntime, function (err) { + if (err) { + cb(err, null); + } else { + cb(null, context.getExported()); + } + }); + }; + + _proto3.compile = function compile() { + if (!this.compiled) { + this._compile(); + } + }; + + _proto3._compile = function _compile() { + var props; + + if (this.tmplProps) { + props = this.tmplProps; + } else { + var source = compiler.compile(this.tmplStr, this.env.asyncFilters, this.env.extensionsList, this.path, this.env.opts); + var func = new Function(source); // eslint-disable-line no-new-func + + props = func(); + } + + this.blocks = this._getBlocks(props); + this.rootRenderFunc = props.root; + this.compiled = true; + }; + + _proto3._getBlocks = function _getBlocks(props) { + var blocks = {}; + lib.keys(props).forEach(function (k) { + if (k.slice(0, 2) === 'b_') { + blocks[k.slice(2)] = props[k]; + } + }); + return blocks; + }; + + return Template; +}(Obj); + +module.exports = { + Environment: Environment, + Template: Template +}; + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var lexer = __webpack_require__(9); + +var nodes = __webpack_require__(3); + +var Obj = __webpack_require__(1).Obj; + +var lib = __webpack_require__(0); + +var Parser = /*#__PURE__*/function (_Obj) { + _inheritsLoose(Parser, _Obj); + + function Parser() { + return _Obj.apply(this, arguments) || this; + } + + var _proto = Parser.prototype; + + _proto.init = function init(tokens) { + this.tokens = tokens; + this.peeked = null; + this.breakOnBlocks = null; + this.dropLeadingWhitespace = false; + this.extensions = []; + }; + + _proto.nextToken = function nextToken(withWhitespace) { + var tok; + + if (this.peeked) { + if (!withWhitespace && this.peeked.type === lexer.TOKEN_WHITESPACE) { + this.peeked = null; + } else { + tok = this.peeked; + this.peeked = null; + return tok; + } + } + + tok = this.tokens.nextToken(); + + if (!withWhitespace) { + while (tok && tok.type === lexer.TOKEN_WHITESPACE) { + tok = this.tokens.nextToken(); + } + } + + return tok; + }; + + _proto.peekToken = function peekToken() { + this.peeked = this.peeked || this.nextToken(); + return this.peeked; + }; + + _proto.pushToken = function pushToken(tok) { + if (this.peeked) { + throw new Error('pushToken: can only push one token on between reads'); + } + + this.peeked = tok; + }; + + _proto.error = function error(msg, lineno, colno) { + if (lineno === undefined || colno === undefined) { + var tok = this.peekToken() || {}; + lineno = tok.lineno; + colno = tok.colno; + } + + if (lineno !== undefined) { + lineno += 1; + } + + if (colno !== undefined) { + colno += 1; + } + + return new lib.TemplateError(msg, lineno, colno); + }; + + _proto.fail = function fail(msg, lineno, colno) { + throw this.error(msg, lineno, colno); + }; + + _proto.skip = function skip(type) { + var tok = this.nextToken(); + + if (!tok || tok.type !== type) { + this.pushToken(tok); + return false; + } + + return true; + }; + + _proto.expect = function expect(type) { + var tok = this.nextToken(); + + if (tok.type !== type) { + this.fail('expected ' + type + ', got ' + tok.type, tok.lineno, tok.colno); + } + + return tok; + }; + + _proto.skipValue = function skipValue(type, val) { + var tok = this.nextToken(); + + if (!tok || tok.type !== type || tok.value !== val) { + this.pushToken(tok); + return false; + } + + return true; + }; + + _proto.skipSymbol = function skipSymbol(val) { + return this.skipValue(lexer.TOKEN_SYMBOL, val); + }; + + _proto.advanceAfterBlockEnd = function advanceAfterBlockEnd(name) { + var tok; + + if (!name) { + tok = this.peekToken(); + + if (!tok) { + this.fail('unexpected end of file'); + } + + if (tok.type !== lexer.TOKEN_SYMBOL) { + this.fail('advanceAfterBlockEnd: expected symbol token or ' + 'explicit name to be passed'); + } + + name = this.nextToken().value; + } + + tok = this.nextToken(); + + if (tok && tok.type === lexer.TOKEN_BLOCK_END) { + if (tok.value.charAt(0) === '-') { + this.dropLeadingWhitespace = true; + } + } else { + this.fail('expected block end in ' + name + ' statement'); + } + + return tok; + }; + + _proto.advanceAfterVariableEnd = function advanceAfterVariableEnd() { + var tok = this.nextToken(); + + if (tok && tok.type === lexer.TOKEN_VARIABLE_END) { + this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.VARIABLE_END.length - 1) === '-'; + } else { + this.pushToken(tok); + this.fail('expected variable end'); + } + }; + + _proto.parseFor = function parseFor() { + var forTok = this.peekToken(); + var node; + var endBlock; + + if (this.skipSymbol('for')) { + node = new nodes.For(forTok.lineno, forTok.colno); + endBlock = 'endfor'; + } else if (this.skipSymbol('asyncEach')) { + node = new nodes.AsyncEach(forTok.lineno, forTok.colno); + endBlock = 'endeach'; + } else if (this.skipSymbol('asyncAll')) { + node = new nodes.AsyncAll(forTok.lineno, forTok.colno); + endBlock = 'endall'; + } else { + this.fail('parseFor: expected for{Async}', forTok.lineno, forTok.colno); + } + + node.name = this.parsePrimary(); + + if (!(node.name instanceof nodes.Symbol)) { + this.fail('parseFor: variable name expected for loop'); + } + + var type = this.peekToken().type; + + if (type === lexer.TOKEN_COMMA) { + // key/value iteration + var key = node.name; + node.name = new nodes.Array(key.lineno, key.colno); + node.name.addChild(key); + + while (this.skip(lexer.TOKEN_COMMA)) { + var prim = this.parsePrimary(); + node.name.addChild(prim); + } + } + + if (!this.skipSymbol('in')) { + this.fail('parseFor: expected "in" keyword for loop', forTok.lineno, forTok.colno); + } + + node.arr = this.parseExpression(); + this.advanceAfterBlockEnd(forTok.value); + node.body = this.parseUntilBlocks(endBlock, 'else'); + + if (this.skipSymbol('else')) { + this.advanceAfterBlockEnd('else'); + node.else_ = this.parseUntilBlocks(endBlock); + } + + this.advanceAfterBlockEnd(); + return node; + }; + + _proto.parseMacro = function parseMacro() { + var macroTok = this.peekToken(); + + if (!this.skipSymbol('macro')) { + this.fail('expected macro'); + } + + var name = this.parsePrimary(true); + var args = this.parseSignature(); + var node = new nodes.Macro(macroTok.lineno, macroTok.colno, name, args); + this.advanceAfterBlockEnd(macroTok.value); + node.body = this.parseUntilBlocks('endmacro'); + this.advanceAfterBlockEnd(); + return node; + }; + + _proto.parseCall = function parseCall() { + // a call block is parsed as a normal FunCall, but with an added + // 'caller' kwarg which is a Caller node. + var callTok = this.peekToken(); + + if (!this.skipSymbol('call')) { + this.fail('expected call'); + } + + var callerArgs = this.parseSignature(true) || new nodes.NodeList(); + var macroCall = this.parsePrimary(); + this.advanceAfterBlockEnd(callTok.value); + var body = this.parseUntilBlocks('endcall'); + this.advanceAfterBlockEnd(); + var callerName = new nodes.Symbol(callTok.lineno, callTok.colno, 'caller'); + var callerNode = new nodes.Caller(callTok.lineno, callTok.colno, callerName, callerArgs, body); // add the additional caller kwarg, adding kwargs if necessary + + var args = macroCall.args.children; + + if (!(args[args.length - 1] instanceof nodes.KeywordArgs)) { + args.push(new nodes.KeywordArgs()); + } + + var kwargs = args[args.length - 1]; + kwargs.addChild(new nodes.Pair(callTok.lineno, callTok.colno, callerName, callerNode)); + return new nodes.Output(callTok.lineno, callTok.colno, [macroCall]); + }; + + _proto.parseWithContext = function parseWithContext() { + var tok = this.peekToken(); + var withContext = null; + + if (this.skipSymbol('with')) { + withContext = true; + } else if (this.skipSymbol('without')) { + withContext = false; + } + + if (withContext !== null) { + if (!this.skipSymbol('context')) { + this.fail('parseFrom: expected context after with/without', tok.lineno, tok.colno); + } + } + + return withContext; + }; + + _proto.parseImport = function parseImport() { + var importTok = this.peekToken(); + + if (!this.skipSymbol('import')) { + this.fail('parseImport: expected import', importTok.lineno, importTok.colno); + } + + var template = this.parseExpression(); + + if (!this.skipSymbol('as')) { + this.fail('parseImport: expected "as" keyword', importTok.lineno, importTok.colno); + } + + var target = this.parseExpression(); + var withContext = this.parseWithContext(); + var node = new nodes.Import(importTok.lineno, importTok.colno, template, target, withContext); + this.advanceAfterBlockEnd(importTok.value); + return node; + }; + + _proto.parseFrom = function parseFrom() { + var fromTok = this.peekToken(); + + if (!this.skipSymbol('from')) { + this.fail('parseFrom: expected from'); + } + + var template = this.parseExpression(); + + if (!this.skipSymbol('import')) { + this.fail('parseFrom: expected import', fromTok.lineno, fromTok.colno); + } + + var names = new nodes.NodeList(); + var withContext; + + while (1) { + // eslint-disable-line no-constant-condition + var nextTok = this.peekToken(); + + if (nextTok.type === lexer.TOKEN_BLOCK_END) { + if (!names.children.length) { + this.fail('parseFrom: Expected at least one import name', fromTok.lineno, fromTok.colno); + } // Since we are manually advancing past the block end, + // need to keep track of whitespace control (normally + // this is done in `advanceAfterBlockEnd` + + + if (nextTok.value.charAt(0) === '-') { + this.dropLeadingWhitespace = true; + } + + this.nextToken(); + break; + } + + if (names.children.length > 0 && !this.skip(lexer.TOKEN_COMMA)) { + this.fail('parseFrom: expected comma', fromTok.lineno, fromTok.colno); + } + + var name = this.parsePrimary(); + + if (name.value.charAt(0) === '_') { + this.fail('parseFrom: names starting with an underscore cannot be imported', name.lineno, name.colno); + } + + if (this.skipSymbol('as')) { + var alias = this.parsePrimary(); + names.addChild(new nodes.Pair(name.lineno, name.colno, name, alias)); + } else { + names.addChild(name); + } + + withContext = this.parseWithContext(); + } + + return new nodes.FromImport(fromTok.lineno, fromTok.colno, template, names, withContext); + }; + + _proto.parseBlock = function parseBlock() { + var tag = this.peekToken(); + + if (!this.skipSymbol('block')) { + this.fail('parseBlock: expected block', tag.lineno, tag.colno); + } + + var node = new nodes.Block(tag.lineno, tag.colno); + node.name = this.parsePrimary(); + + if (!(node.name instanceof nodes.Symbol)) { + this.fail('parseBlock: variable name expected', tag.lineno, tag.colno); + } + + this.advanceAfterBlockEnd(tag.value); + node.body = this.parseUntilBlocks('endblock'); + this.skipSymbol('endblock'); + this.skipSymbol(node.name.value); + var tok = this.peekToken(); + + if (!tok) { + this.fail('parseBlock: expected endblock, got end of file'); + } + + this.advanceAfterBlockEnd(tok.value); + return node; + }; + + _proto.parseExtends = function parseExtends() { + var tagName = 'extends'; + var tag = this.peekToken(); + + if (!this.skipSymbol(tagName)) { + this.fail('parseTemplateRef: expected ' + tagName); + } + + var node = new nodes.Extends(tag.lineno, tag.colno); + node.template = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + return node; + }; + + _proto.parseInclude = function parseInclude() { + var tagName = 'include'; + var tag = this.peekToken(); + + if (!this.skipSymbol(tagName)) { + this.fail('parseInclude: expected ' + tagName); + } + + var node = new nodes.Include(tag.lineno, tag.colno); + node.template = this.parseExpression(); + + if (this.skipSymbol('ignore') && this.skipSymbol('missing')) { + node.ignoreMissing = true; + } + + this.advanceAfterBlockEnd(tag.value); + return node; + }; + + _proto.parseIf = function parseIf() { + var tag = this.peekToken(); + var node; + + if (this.skipSymbol('if') || this.skipSymbol('elif') || this.skipSymbol('elseif')) { + node = new nodes.If(tag.lineno, tag.colno); + } else if (this.skipSymbol('ifAsync')) { + node = new nodes.IfAsync(tag.lineno, tag.colno); + } else { + this.fail('parseIf: expected if, elif, or elseif', tag.lineno, tag.colno); + } + + node.cond = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + node.body = this.parseUntilBlocks('elif', 'elseif', 'else', 'endif'); + var tok = this.peekToken(); + + switch (tok && tok.value) { + case 'elseif': + case 'elif': + node.else_ = this.parseIf(); + break; + + case 'else': + this.advanceAfterBlockEnd(); + node.else_ = this.parseUntilBlocks('endif'); + this.advanceAfterBlockEnd(); + break; + + case 'endif': + node.else_ = null; + this.advanceAfterBlockEnd(); + break; + + default: + this.fail('parseIf: expected elif, else, or endif, got end of file'); + } + + return node; + }; + + _proto.parseSet = function parseSet() { + var tag = this.peekToken(); + + if (!this.skipSymbol('set')) { + this.fail('parseSet: expected set', tag.lineno, tag.colno); + } + + var node = new nodes.Set(tag.lineno, tag.colno, []); + var target; + + while (target = this.parsePrimary()) { + node.targets.push(target); + + if (!this.skip(lexer.TOKEN_COMMA)) { + break; + } + } + + if (!this.skipValue(lexer.TOKEN_OPERATOR, '=')) { + if (!this.skip(lexer.TOKEN_BLOCK_END)) { + this.fail('parseSet: expected = or block end in set tag', tag.lineno, tag.colno); + } else { + node.body = new nodes.Capture(tag.lineno, tag.colno, this.parseUntilBlocks('endset')); + node.value = null; + this.advanceAfterBlockEnd(); + } + } else { + node.value = this.parseExpression(); + this.advanceAfterBlockEnd(tag.value); + } + + return node; + }; + + _proto.parseSwitch = function parseSwitch() { + /* + * Store the tag names in variables in case someone ever wants to + * customize this. + */ + var switchStart = 'switch'; + var switchEnd = 'endswitch'; + var caseStart = 'case'; + var caseDefault = 'default'; // Get the switch tag. + + var tag = this.peekToken(); // fail early if we get some unexpected tag. + + if (!this.skipSymbol(switchStart) && !this.skipSymbol(caseStart) && !this.skipSymbol(caseDefault)) { + this.fail('parseSwitch: expected "switch," "case" or "default"', tag.lineno, tag.colno); + } // parse the switch expression + + + var expr = this.parseExpression(); // advance until a start of a case, a default case or an endswitch. + + this.advanceAfterBlockEnd(switchStart); + this.parseUntilBlocks(caseStart, caseDefault, switchEnd); // this is the first case. it could also be an endswitch, we'll check. + + var tok = this.peekToken(); // create new variables for our cases and default case. + + var cases = []; + var defaultCase; // while we're dealing with new cases nodes... + + do { + // skip the start symbol and get the case expression + this.skipSymbol(caseStart); + var cond = this.parseExpression(); + this.advanceAfterBlockEnd(switchStart); // get the body of the case node and add it to the array of cases. + + var body = this.parseUntilBlocks(caseStart, caseDefault, switchEnd); + cases.push(new nodes.Case(tok.line, tok.col, cond, body)); // get our next case + + tok = this.peekToken(); + } while (tok && tok.value === caseStart); // we either have a default case or a switch end. + + + switch (tok.value) { + case caseDefault: + this.advanceAfterBlockEnd(); + defaultCase = this.parseUntilBlocks(switchEnd); + this.advanceAfterBlockEnd(); + break; + + case switchEnd: + this.advanceAfterBlockEnd(); + break; + + default: + // otherwise bail because EOF + this.fail('parseSwitch: expected "case," "default" or "endswitch," got EOF.'); + } // and return the switch node. + + + return new nodes.Switch(tag.lineno, tag.colno, expr, cases, defaultCase); + }; + + _proto.parseStatement = function parseStatement() { + var tok = this.peekToken(); + var node; + + if (tok.type !== lexer.TOKEN_SYMBOL) { + this.fail('tag name expected', tok.lineno, tok.colno); + } + + if (this.breakOnBlocks && lib.indexOf(this.breakOnBlocks, tok.value) !== -1) { + return null; + } + + switch (tok.value) { + case 'raw': + return this.parseRaw(); + + case 'verbatim': + return this.parseRaw('verbatim'); + + case 'if': + case 'ifAsync': + return this.parseIf(); + + case 'for': + case 'asyncEach': + case 'asyncAll': + return this.parseFor(); + + case 'block': + return this.parseBlock(); + + case 'extends': + return this.parseExtends(); + + case 'include': + return this.parseInclude(); + + case 'set': + return this.parseSet(); + + case 'macro': + return this.parseMacro(); + + case 'call': + return this.parseCall(); + + case 'import': + return this.parseImport(); + + case 'from': + return this.parseFrom(); + + case 'filter': + return this.parseFilterStatement(); + + case 'switch': + return this.parseSwitch(); + + default: + if (this.extensions.length) { + for (var i = 0; i < this.extensions.length; i++) { + var ext = this.extensions[i]; + + if (lib.indexOf(ext.tags || [], tok.value) !== -1) { + return ext.parse(this, nodes, lexer); + } + } + } + + this.fail('unknown block tag: ' + tok.value, tok.lineno, tok.colno); + } + + return node; + }; + + _proto.parseRaw = function parseRaw(tagName) { + tagName = tagName || 'raw'; + var endTagName = 'end' + tagName; // Look for upcoming raw blocks (ignore all other kinds of blocks) + + var rawBlockRegex = new RegExp('([\\s\\S]*?){%\\s*(' + tagName + '|' + endTagName + ')\\s*(?=%})%}'); + var rawLevel = 1; + var str = ''; + var matches = null; // Skip opening raw token + // Keep this token to track line and column numbers + + var begun = this.advanceAfterBlockEnd(); // Exit when there's nothing to match + // or when we've found the matching "endraw" block + + while ((matches = this.tokens._extractRegex(rawBlockRegex)) && rawLevel > 0) { + var all = matches[0]; + var pre = matches[1]; + var blockName = matches[2]; // Adjust rawlevel + + if (blockName === tagName) { + rawLevel += 1; + } else if (blockName === endTagName) { + rawLevel -= 1; + } // Add to str + + + if (rawLevel === 0) { + // We want to exclude the last "endraw" + str += pre; // Move tokenizer to beginning of endraw block + + this.tokens.backN(all.length - pre.length); + } else { + str += all; + } + } + + return new nodes.Output(begun.lineno, begun.colno, [new nodes.TemplateData(begun.lineno, begun.colno, str)]); + }; + + _proto.parsePostfix = function parsePostfix(node) { + var lookup; + var tok = this.peekToken(); + + while (tok) { + if (tok.type === lexer.TOKEN_LEFT_PAREN) { + // Function call + node = new nodes.FunCall(tok.lineno, tok.colno, node, this.parseSignature()); + } else if (tok.type === lexer.TOKEN_LEFT_BRACKET) { + // Reference + lookup = this.parseAggregate(); + + if (lookup.children.length > 1) { + this.fail('invalid index'); + } + + node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup.children[0]); + } else if (tok.type === lexer.TOKEN_OPERATOR && tok.value === '.') { + // Reference + this.nextToken(); + var val = this.nextToken(); + + if (val.type !== lexer.TOKEN_SYMBOL) { + this.fail('expected name as lookup value, got ' + val.value, val.lineno, val.colno); + } // Make a literal string because it's not a variable + // reference + + + lookup = new nodes.Literal(val.lineno, val.colno, val.value); + node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup); + } else { + break; + } + + tok = this.peekToken(); + } + + return node; + }; + + _proto.parseExpression = function parseExpression() { + var node = this.parseInlineIf(); + return node; + }; + + _proto.parseInlineIf = function parseInlineIf() { + var node = this.parseOr(); + + if (this.skipSymbol('if')) { + var condNode = this.parseOr(); + var bodyNode = node; + node = new nodes.InlineIf(node.lineno, node.colno); + node.body = bodyNode; + node.cond = condNode; + + if (this.skipSymbol('else')) { + node.else_ = this.parseOr(); + } else { + node.else_ = null; + } + } + + return node; + }; + + _proto.parseOr = function parseOr() { + var node = this.parseAnd(); + + while (this.skipSymbol('or')) { + var node2 = this.parseAnd(); + node = new nodes.Or(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseAnd = function parseAnd() { + var node = this.parseNot(); + + while (this.skipSymbol('and')) { + var node2 = this.parseNot(); + node = new nodes.And(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseNot = function parseNot() { + var tok = this.peekToken(); + + if (this.skipSymbol('not')) { + return new nodes.Not(tok.lineno, tok.colno, this.parseNot()); + } + + return this.parseIn(); + }; + + _proto.parseIn = function parseIn() { + var node = this.parseIs(); + + while (1) { + // eslint-disable-line no-constant-condition + // check if the next token is 'not' + var tok = this.nextToken(); + + if (!tok) { + break; + } + + var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === 'not'; // if it wasn't 'not', put it back + + if (!invert) { + this.pushToken(tok); + } + + if (this.skipSymbol('in')) { + var node2 = this.parseIs(); + node = new nodes.In(node.lineno, node.colno, node, node2); + + if (invert) { + node = new nodes.Not(node.lineno, node.colno, node); + } + } else { + // if we'd found a 'not' but this wasn't an 'in', put back the 'not' + if (invert) { + this.pushToken(tok); + } + + break; + } + } + + return node; + } // I put this right after "in" in the operator precedence stack. That can + // obviously be changed to be closer to Jinja. + ; + + _proto.parseIs = function parseIs() { + var node = this.parseCompare(); // look for an is + + if (this.skipSymbol('is')) { + // look for a not + var not = this.skipSymbol('not'); // get the next node + + var node2 = this.parseCompare(); // create an Is node using the next node and the info from our Is node. + + node = new nodes.Is(node.lineno, node.colno, node, node2); // if we have a Not, create a Not node from our Is node. + + if (not) { + node = new nodes.Not(node.lineno, node.colno, node); + } + } // return the node. + + + return node; + }; + + _proto.parseCompare = function parseCompare() { + var compareOps = ['==', '===', '!=', '!==', '<', '>', '<=', '>=']; + var expr = this.parseConcat(); + var ops = []; + + while (1) { + // eslint-disable-line no-constant-condition + var tok = this.nextToken(); + + if (!tok) { + break; + } else if (compareOps.indexOf(tok.value) !== -1) { + ops.push(new nodes.CompareOperand(tok.lineno, tok.colno, this.parseConcat(), tok.value)); + } else { + this.pushToken(tok); + break; + } + } + + if (ops.length) { + return new nodes.Compare(ops[0].lineno, ops[0].colno, expr, ops); + } else { + return expr; + } + } // finds the '~' for string concatenation + ; + + _proto.parseConcat = function parseConcat() { + var node = this.parseAdd(); + + while (this.skipValue(lexer.TOKEN_TILDE, '~')) { + var node2 = this.parseAdd(); + node = new nodes.Concat(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseAdd = function parseAdd() { + var node = this.parseSub(); + + while (this.skipValue(lexer.TOKEN_OPERATOR, '+')) { + var node2 = this.parseSub(); + node = new nodes.Add(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseSub = function parseSub() { + var node = this.parseMul(); + + while (this.skipValue(lexer.TOKEN_OPERATOR, '-')) { + var node2 = this.parseMul(); + node = new nodes.Sub(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseMul = function parseMul() { + var node = this.parseDiv(); + + while (this.skipValue(lexer.TOKEN_OPERATOR, '*')) { + var node2 = this.parseDiv(); + node = new nodes.Mul(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseDiv = function parseDiv() { + var node = this.parseFloorDiv(); + + while (this.skipValue(lexer.TOKEN_OPERATOR, '/')) { + var node2 = this.parseFloorDiv(); + node = new nodes.Div(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseFloorDiv = function parseFloorDiv() { + var node = this.parseMod(); + + while (this.skipValue(lexer.TOKEN_OPERATOR, '//')) { + var node2 = this.parseMod(); + node = new nodes.FloorDiv(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseMod = function parseMod() { + var node = this.parsePow(); + + while (this.skipValue(lexer.TOKEN_OPERATOR, '%')) { + var node2 = this.parsePow(); + node = new nodes.Mod(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parsePow = function parsePow() { + var node = this.parseUnary(); + + while (this.skipValue(lexer.TOKEN_OPERATOR, '**')) { + var node2 = this.parseUnary(); + node = new nodes.Pow(node.lineno, node.colno, node, node2); + } + + return node; + }; + + _proto.parseUnary = function parseUnary(noFilters) { + var tok = this.peekToken(); + var node; + + if (this.skipValue(lexer.TOKEN_OPERATOR, '-')) { + node = new nodes.Neg(tok.lineno, tok.colno, this.parseUnary(true)); + } else if (this.skipValue(lexer.TOKEN_OPERATOR, '+')) { + node = new nodes.Pos(tok.lineno, tok.colno, this.parseUnary(true)); + } else { + node = this.parsePrimary(); + } + + if (!noFilters) { + node = this.parseFilter(node); + } + + return node; + }; + + _proto.parsePrimary = function parsePrimary(noPostfix) { + var tok = this.nextToken(); + var val; + var node = null; + + if (!tok) { + this.fail('expected expression, got end of file'); + } else if (tok.type === lexer.TOKEN_STRING) { + val = tok.value; + } else if (tok.type === lexer.TOKEN_INT) { + val = parseInt(tok.value, 10); + } else if (tok.type === lexer.TOKEN_FLOAT) { + val = parseFloat(tok.value); + } else if (tok.type === lexer.TOKEN_BOOLEAN) { + if (tok.value === 'true') { + val = true; + } else if (tok.value === 'false') { + val = false; + } else { + this.fail('invalid boolean: ' + tok.value, tok.lineno, tok.colno); + } + } else if (tok.type === lexer.TOKEN_NONE) { + val = null; + } else if (tok.type === lexer.TOKEN_REGEX) { + val = new RegExp(tok.value.body, tok.value.flags); + } + + if (val !== undefined) { + node = new nodes.Literal(tok.lineno, tok.colno, val); + } else if (tok.type === lexer.TOKEN_SYMBOL) { + node = new nodes.Symbol(tok.lineno, tok.colno, tok.value); + } else { + // See if it's an aggregate type, we need to push the + // current delimiter token back on + this.pushToken(tok); + node = this.parseAggregate(); + } + + if (!noPostfix) { + node = this.parsePostfix(node); + } + + if (node) { + return node; + } else { + throw this.error("unexpected token: " + tok.value, tok.lineno, tok.colno); + } + }; + + _proto.parseFilterName = function parseFilterName() { + var tok = this.expect(lexer.TOKEN_SYMBOL); + var name = tok.value; + + while (this.skipValue(lexer.TOKEN_OPERATOR, '.')) { + name += '.' + this.expect(lexer.TOKEN_SYMBOL).value; + } + + return new nodes.Symbol(tok.lineno, tok.colno, name); + }; + + _proto.parseFilterArgs = function parseFilterArgs(node) { + if (this.peekToken().type === lexer.TOKEN_LEFT_PAREN) { + // Get a FunCall node and add the parameters to the + // filter + var call = this.parsePostfix(node); + return call.args.children; + } + + return []; + }; + + _proto.parseFilter = function parseFilter(node) { + while (this.skip(lexer.TOKEN_PIPE)) { + var name = this.parseFilterName(); + node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [node].concat(this.parseFilterArgs(node)))); + } + + return node; + }; + + _proto.parseFilterStatement = function parseFilterStatement() { + var filterTok = this.peekToken(); + + if (!this.skipSymbol('filter')) { + this.fail('parseFilterStatement: expected filter'); + } + + var name = this.parseFilterName(); + var args = this.parseFilterArgs(name); + this.advanceAfterBlockEnd(filterTok.value); + var body = new nodes.Capture(name.lineno, name.colno, this.parseUntilBlocks('endfilter')); + this.advanceAfterBlockEnd(); + var node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [body].concat(args))); + return new nodes.Output(name.lineno, name.colno, [node]); + }; + + _proto.parseAggregate = function parseAggregate() { + var tok = this.nextToken(); + var node; + + switch (tok.type) { + case lexer.TOKEN_LEFT_PAREN: + node = new nodes.Group(tok.lineno, tok.colno); + break; + + case lexer.TOKEN_LEFT_BRACKET: + node = new nodes.Array(tok.lineno, tok.colno); + break; + + case lexer.TOKEN_LEFT_CURLY: + node = new nodes.Dict(tok.lineno, tok.colno); + break; + + default: + return null; + } + + while (1) { + // eslint-disable-line no-constant-condition + var type = this.peekToken().type; + + if (type === lexer.TOKEN_RIGHT_PAREN || type === lexer.TOKEN_RIGHT_BRACKET || type === lexer.TOKEN_RIGHT_CURLY) { + this.nextToken(); + break; + } + + if (node.children.length > 0) { + if (!this.skip(lexer.TOKEN_COMMA)) { + this.fail('parseAggregate: expected comma after expression', tok.lineno, tok.colno); + } + } + + if (node instanceof nodes.Dict) { + // TODO: check for errors + var key = this.parsePrimary(); // We expect a key/value pair for dicts, separated by a + // colon + + if (!this.skip(lexer.TOKEN_COLON)) { + this.fail('parseAggregate: expected colon after dict key', tok.lineno, tok.colno); + } // TODO: check for errors + + + var value = this.parseExpression(); + node.addChild(new nodes.Pair(key.lineno, key.colno, key, value)); + } else { + // TODO: check for errors + var expr = this.parseExpression(); + node.addChild(expr); + } + } + + return node; + }; + + _proto.parseSignature = function parseSignature(tolerant, noParens) { + var tok = this.peekToken(); + + if (!noParens && tok.type !== lexer.TOKEN_LEFT_PAREN) { + if (tolerant) { + return null; + } else { + this.fail('expected arguments', tok.lineno, tok.colno); + } + } + + if (tok.type === lexer.TOKEN_LEFT_PAREN) { + tok = this.nextToken(); + } + + var args = new nodes.NodeList(tok.lineno, tok.colno); + var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno); + var checkComma = false; + + while (1) { + // eslint-disable-line no-constant-condition + tok = this.peekToken(); + + if (!noParens && tok.type === lexer.TOKEN_RIGHT_PAREN) { + this.nextToken(); + break; + } else if (noParens && tok.type === lexer.TOKEN_BLOCK_END) { + break; + } + + if (checkComma && !this.skip(lexer.TOKEN_COMMA)) { + this.fail('parseSignature: expected comma after expression', tok.lineno, tok.colno); + } else { + var arg = this.parseExpression(); + + if (this.skipValue(lexer.TOKEN_OPERATOR, '=')) { + kwargs.addChild(new nodes.Pair(arg.lineno, arg.colno, arg, this.parseExpression())); + } else { + args.addChild(arg); + } + } + + checkComma = true; + } + + if (kwargs.children.length) { + args.addChild(kwargs); + } + + return args; + }; + + _proto.parseUntilBlocks = function parseUntilBlocks() { + var prev = this.breakOnBlocks; + + for (var _len = arguments.length, blockNames = new Array(_len), _key = 0; _key < _len; _key++) { + blockNames[_key] = arguments[_key]; + } + + this.breakOnBlocks = blockNames; + var ret = this.parse(); + this.breakOnBlocks = prev; + return ret; + }; + + _proto.parseNodes = function parseNodes() { + var tok; + var buf = []; + + while (tok = this.nextToken()) { + if (tok.type === lexer.TOKEN_DATA) { + var data = tok.value; + var nextToken = this.peekToken(); + var nextVal = nextToken && nextToken.value; // If the last token has "-" we need to trim the + // leading whitespace of the data. This is marked with + // the `dropLeadingWhitespace` variable. + + if (this.dropLeadingWhitespace) { + // TODO: this could be optimized (don't use regex) + data = data.replace(/^\s*/, ''); + this.dropLeadingWhitespace = false; + } // Same for the succeeding block start token + + + if (nextToken && (nextToken.type === lexer.TOKEN_BLOCK_START && nextVal.charAt(nextVal.length - 1) === '-' || nextToken.type === lexer.TOKEN_VARIABLE_START && nextVal.charAt(this.tokens.tags.VARIABLE_START.length) === '-' || nextToken.type === lexer.TOKEN_COMMENT && nextVal.charAt(this.tokens.tags.COMMENT_START.length) === '-')) { + // TODO: this could be optimized (don't use regex) + data = data.replace(/\s*$/, ''); + } + + buf.push(new nodes.Output(tok.lineno, tok.colno, [new nodes.TemplateData(tok.lineno, tok.colno, data)])); + } else if (tok.type === lexer.TOKEN_BLOCK_START) { + this.dropLeadingWhitespace = false; + var n = this.parseStatement(); + + if (!n) { + break; + } + + buf.push(n); + } else if (tok.type === lexer.TOKEN_VARIABLE_START) { + var e = this.parseExpression(); + this.dropLeadingWhitespace = false; + this.advanceAfterVariableEnd(); + buf.push(new nodes.Output(tok.lineno, tok.colno, [e])); + } else if (tok.type === lexer.TOKEN_COMMENT) { + this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.COMMENT_END.length - 1) === '-'; + } else { + // Ignore comments, otherwise this should be an error + this.fail('Unexpected token at top-level: ' + tok.type, tok.lineno, tok.colno); + } + } + + return buf; + }; + + _proto.parse = function parse() { + return new nodes.NodeList(0, 0, this.parseNodes()); + }; + + _proto.parseAsRoot = function parseAsRoot() { + return new nodes.Root(0, 0, this.parseNodes()); + }; + + return Parser; +}(Obj); // var util = require('util'); +// var l = lexer.lex('{%- if x -%}\n hello {% endif %}'); +// var t; +// while((t = l.nextToken())) { +// console.log(util.inspect(t)); +// } +// var p = new Parser(lexer.lex('hello {% filter title %}' + +// 'Hello madam how are you' + +// '{% endfilter %}')); +// var n = p.parseAsRoot(); +// nodes.printNodes(n); + + +module.exports = { + parse: function parse(src, extensions, opts) { + var p = new Parser(lexer.lex(src, opts)); + + if (extensions !== undefined) { + p.extensions = extensions; + } + + return p.parseAsRoot(); + }, + Parser: Parser +}; + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + + +var lib = __webpack_require__(0); + +var whitespaceChars = " \n\t\r\xA0"; +var delimChars = '()[]{}%*-+~/#,:|.<>=!'; +var intChars = '0123456789'; +var BLOCK_START = '{%'; +var BLOCK_END = '%}'; +var VARIABLE_START = '{{'; +var VARIABLE_END = '}}'; +var COMMENT_START = '{#'; +var COMMENT_END = '#}'; +var TOKEN_STRING = 'string'; +var TOKEN_WHITESPACE = 'whitespace'; +var TOKEN_DATA = 'data'; +var TOKEN_BLOCK_START = 'block-start'; +var TOKEN_BLOCK_END = 'block-end'; +var TOKEN_VARIABLE_START = 'variable-start'; +var TOKEN_VARIABLE_END = 'variable-end'; +var TOKEN_COMMENT = 'comment'; +var TOKEN_LEFT_PAREN = 'left-paren'; +var TOKEN_RIGHT_PAREN = 'right-paren'; +var TOKEN_LEFT_BRACKET = 'left-bracket'; +var TOKEN_RIGHT_BRACKET = 'right-bracket'; +var TOKEN_LEFT_CURLY = 'left-curly'; +var TOKEN_RIGHT_CURLY = 'right-curly'; +var TOKEN_OPERATOR = 'operator'; +var TOKEN_COMMA = 'comma'; +var TOKEN_COLON = 'colon'; +var TOKEN_TILDE = 'tilde'; +var TOKEN_PIPE = 'pipe'; +var TOKEN_INT = 'int'; +var TOKEN_FLOAT = 'float'; +var TOKEN_BOOLEAN = 'boolean'; +var TOKEN_NONE = 'none'; +var TOKEN_SYMBOL = 'symbol'; +var TOKEN_SPECIAL = 'special'; +var TOKEN_REGEX = 'regex'; + +function token(type, value, lineno, colno) { + return { + type: type, + value: value, + lineno: lineno, + colno: colno + }; +} + +var Tokenizer = /*#__PURE__*/function () { + function Tokenizer(str, opts) { + this.str = str; + this.index = 0; + this.len = str.length; + this.lineno = 0; + this.colno = 0; + this.in_code = false; + opts = opts || {}; + var tags = opts.tags || {}; + this.tags = { + BLOCK_START: tags.blockStart || BLOCK_START, + BLOCK_END: tags.blockEnd || BLOCK_END, + VARIABLE_START: tags.variableStart || VARIABLE_START, + VARIABLE_END: tags.variableEnd || VARIABLE_END, + COMMENT_START: tags.commentStart || COMMENT_START, + COMMENT_END: tags.commentEnd || COMMENT_END + }; + this.trimBlocks = !!opts.trimBlocks; + this.lstripBlocks = !!opts.lstripBlocks; + } + + var _proto = Tokenizer.prototype; + + _proto.nextToken = function nextToken() { + var lineno = this.lineno; + var colno = this.colno; + var tok; + + if (this.in_code) { + // Otherwise, if we are in a block parse it as code + var cur = this.current(); + + if (this.isFinished()) { + // We have nothing else to parse + return null; + } else if (cur === '"' || cur === '\'') { + // We've hit a string + return token(TOKEN_STRING, this._parseString(cur), lineno, colno); + } else if (tok = this._extract(whitespaceChars)) { + // We hit some whitespace + return token(TOKEN_WHITESPACE, tok, lineno, colno); + } else if ((tok = this._extractString(this.tags.BLOCK_END)) || (tok = this._extractString('-' + this.tags.BLOCK_END))) { + // Special check for the block end tag + // + // It is a requirement that start and end tags are composed of + // delimiter characters (%{}[] etc), and our code always + // breaks on delimiters so we can assume the token parsing + // doesn't consume these elsewhere + this.in_code = false; + + if (this.trimBlocks) { + cur = this.current(); + + if (cur === '\n') { + // Skip newline + this.forward(); + } else if (cur === '\r') { + // Skip CRLF newline + this.forward(); + cur = this.current(); + + if (cur === '\n') { + this.forward(); + } else { + // Was not a CRLF, so go back + this.back(); + } + } + } + + return token(TOKEN_BLOCK_END, tok, lineno, colno); + } else if ((tok = this._extractString(this.tags.VARIABLE_END)) || (tok = this._extractString('-' + this.tags.VARIABLE_END))) { + // Special check for variable end tag (see above) + this.in_code = false; + return token(TOKEN_VARIABLE_END, tok, lineno, colno); + } else if (cur === 'r' && this.str.charAt(this.index + 1) === '/') { + // Skip past 'r/'. + this.forwardN(2); // Extract until the end of the regex -- / ends it, \/ does not. + + var regexBody = ''; + + while (!this.isFinished()) { + if (this.current() === '/' && this.previous() !== '\\') { + this.forward(); + break; + } else { + regexBody += this.current(); + this.forward(); + } + } // Check for flags. + // The possible flags are according to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) + + + var POSSIBLE_FLAGS = ['g', 'i', 'm', 'y']; + var regexFlags = ''; + + while (!this.isFinished()) { + var isCurrentAFlag = POSSIBLE_FLAGS.indexOf(this.current()) !== -1; + + if (isCurrentAFlag) { + regexFlags += this.current(); + this.forward(); + } else { + break; + } + } + + return token(TOKEN_REGEX, { + body: regexBody, + flags: regexFlags + }, lineno, colno); + } else if (delimChars.indexOf(cur) !== -1) { + // We've hit a delimiter (a special char like a bracket) + this.forward(); + var complexOps = ['==', '===', '!=', '!==', '<=', '>=', '//', '**']; + var curComplex = cur + this.current(); + var type; + + if (lib.indexOf(complexOps, curComplex) !== -1) { + this.forward(); + cur = curComplex; // See if this is a strict equality/inequality comparator + + if (lib.indexOf(complexOps, curComplex + this.current()) !== -1) { + cur = curComplex + this.current(); + this.forward(); + } + } + + switch (cur) { + case '(': + type = TOKEN_LEFT_PAREN; + break; + + case ')': + type = TOKEN_RIGHT_PAREN; + break; + + case '[': + type = TOKEN_LEFT_BRACKET; + break; + + case ']': + type = TOKEN_RIGHT_BRACKET; + break; + + case '{': + type = TOKEN_LEFT_CURLY; + break; + + case '}': + type = TOKEN_RIGHT_CURLY; + break; + + case ',': + type = TOKEN_COMMA; + break; + + case ':': + type = TOKEN_COLON; + break; + + case '~': + type = TOKEN_TILDE; + break; + + case '|': + type = TOKEN_PIPE; + break; + + default: + type = TOKEN_OPERATOR; + } + + return token(type, cur, lineno, colno); + } else { + // We are not at whitespace or a delimiter, so extract the + // text and parse it + tok = this._extractUntil(whitespaceChars + delimChars); + + if (tok.match(/^[-+]?[0-9]+$/)) { + if (this.current() === '.') { + this.forward(); + + var dec = this._extract(intChars); + + return token(TOKEN_FLOAT, tok + '.' + dec, lineno, colno); + } else { + return token(TOKEN_INT, tok, lineno, colno); + } + } else if (tok.match(/^(true|false)$/)) { + return token(TOKEN_BOOLEAN, tok, lineno, colno); + } else if (tok === 'none') { + return token(TOKEN_NONE, tok, lineno, colno); + /* + * Added to make the test `null is null` evaluate truthily. + * Otherwise, Nunjucks will look up null in the context and + * return `undefined`, which is not what we want. This *may* have + * consequences is someone is using null in their templates as a + * variable. + */ + } else if (tok === 'null') { + return token(TOKEN_NONE, tok, lineno, colno); + } else if (tok) { + return token(TOKEN_SYMBOL, tok, lineno, colno); + } else { + throw new Error('Unexpected value while parsing: ' + tok); + } + } + } else { + // Parse out the template text, breaking on tag + // delimiters because we need to look for block/variable start + // tags (don't use the full delimChars for optimization) + var beginChars = this.tags.BLOCK_START.charAt(0) + this.tags.VARIABLE_START.charAt(0) + this.tags.COMMENT_START.charAt(0) + this.tags.COMMENT_END.charAt(0); + + if (this.isFinished()) { + return null; + } else if ((tok = this._extractString(this.tags.BLOCK_START + '-')) || (tok = this._extractString(this.tags.BLOCK_START))) { + this.in_code = true; + return token(TOKEN_BLOCK_START, tok, lineno, colno); + } else if ((tok = this._extractString(this.tags.VARIABLE_START + '-')) || (tok = this._extractString(this.tags.VARIABLE_START))) { + this.in_code = true; + return token(TOKEN_VARIABLE_START, tok, lineno, colno); + } else { + tok = ''; + var data; + var inComment = false; + + if (this._matches(this.tags.COMMENT_START)) { + inComment = true; + tok = this._extractString(this.tags.COMMENT_START); + } // Continually consume text, breaking on the tag delimiter + // characters and checking to see if it's a start tag. + // + // We could hit the end of the template in the middle of + // our looping, so check for the null return value from + // _extractUntil + + + while ((data = this._extractUntil(beginChars)) !== null) { + tok += data; + + if ((this._matches(this.tags.BLOCK_START) || this._matches(this.tags.VARIABLE_START) || this._matches(this.tags.COMMENT_START)) && !inComment) { + if (this.lstripBlocks && this._matches(this.tags.BLOCK_START) && this.colno > 0 && this.colno <= tok.length) { + var lastLine = tok.slice(-this.colno); + + if (/^\s+$/.test(lastLine)) { + // Remove block leading whitespace from beginning of the string + tok = tok.slice(0, -this.colno); + + if (!tok.length) { + // All data removed, collapse to avoid unnecessary nodes + // by returning next token (block start) + return this.nextToken(); + } + } + } // If it is a start tag, stop looping + + + break; + } else if (this._matches(this.tags.COMMENT_END)) { + if (!inComment) { + throw new Error('unexpected end of comment'); + } + + tok += this._extractString(this.tags.COMMENT_END); + break; + } else { + // It does not match any tag, so add the character and + // carry on + tok += this.current(); + this.forward(); + } + } + + if (data === null && inComment) { + throw new Error('expected end of comment, got end of file'); + } + + return token(inComment ? TOKEN_COMMENT : TOKEN_DATA, tok, lineno, colno); + } + } + }; + + _proto._parseString = function _parseString(delimiter) { + this.forward(); + var str = ''; + + while (!this.isFinished() && this.current() !== delimiter) { + var cur = this.current(); + + if (cur === '\\') { + this.forward(); + + switch (this.current()) { + case 'n': + str += '\n'; + break; + + case 't': + str += '\t'; + break; + + case 'r': + str += '\r'; + break; + + default: + str += this.current(); + } + + this.forward(); + } else { + str += cur; + this.forward(); + } + } + + this.forward(); + return str; + }; + + _proto._matches = function _matches(str) { + if (this.index + str.length > this.len) { + return null; + } + + var m = this.str.slice(this.index, this.index + str.length); + return m === str; + }; + + _proto._extractString = function _extractString(str) { + if (this._matches(str)) { + this.forwardN(str.length); + return str; + } + + return null; + }; + + _proto._extractUntil = function _extractUntil(charString) { + // Extract all non-matching chars, with the default matching set + // to everything + return this._extractMatching(true, charString || ''); + }; + + _proto._extract = function _extract(charString) { + // Extract all matching chars (no default, so charString must be + // explicit) + return this._extractMatching(false, charString); + }; + + _proto._extractMatching = function _extractMatching(breakOnMatch, charString) { + // Pull out characters until a breaking char is hit. + // If breakOnMatch is false, a non-matching char stops it. + // If breakOnMatch is true, a matching char stops it. + if (this.isFinished()) { + return null; + } + + var first = charString.indexOf(this.current()); // Only proceed if the first character doesn't meet our condition + + if (breakOnMatch && first === -1 || !breakOnMatch && first !== -1) { + var t = this.current(); + this.forward(); // And pull out all the chars one at a time until we hit a + // breaking char + + var idx = charString.indexOf(this.current()); + + while ((breakOnMatch && idx === -1 || !breakOnMatch && idx !== -1) && !this.isFinished()) { + t += this.current(); + this.forward(); + idx = charString.indexOf(this.current()); + } + + return t; + } + + return ''; + }; + + _proto._extractRegex = function _extractRegex(regex) { + var matches = this.currentStr().match(regex); + + if (!matches) { + return null; + } // Move forward whatever was matched + + + this.forwardN(matches[0].length); + return matches; + }; + + _proto.isFinished = function isFinished() { + return this.index >= this.len; + }; + + _proto.forwardN = function forwardN(n) { + for (var i = 0; i < n; i++) { + this.forward(); + } + }; + + _proto.forward = function forward() { + this.index++; + + if (this.previous() === '\n') { + this.lineno++; + this.colno = 0; + } else { + this.colno++; + } + }; + + _proto.backN = function backN(n) { + for (var i = 0; i < n; i++) { + this.back(); + } + }; + + _proto.back = function back() { + this.index--; + + if (this.current() === '\n') { + this.lineno--; + var idx = this.src.lastIndexOf('\n', this.index - 1); + + if (idx === -1) { + this.colno = this.index; + } else { + this.colno = this.index - idx; + } + } else { + this.colno--; + } + } // current returns current character + ; + + _proto.current = function current() { + if (!this.isFinished()) { + return this.str.charAt(this.index); + } + + return ''; + } // currentStr returns what's left of the unparsed string + ; + + _proto.currentStr = function currentStr() { + if (!this.isFinished()) { + return this.str.substr(this.index); + } + + return ''; + }; + + _proto.previous = function previous() { + return this.str.charAt(this.index - 1); + }; + + return Tokenizer; +}(); + +module.exports = { + lex: function lex(src, opts) { + return new Tokenizer(src, opts); + }, + TOKEN_STRING: TOKEN_STRING, + TOKEN_WHITESPACE: TOKEN_WHITESPACE, + TOKEN_DATA: TOKEN_DATA, + TOKEN_BLOCK_START: TOKEN_BLOCK_START, + TOKEN_BLOCK_END: TOKEN_BLOCK_END, + TOKEN_VARIABLE_START: TOKEN_VARIABLE_START, + TOKEN_VARIABLE_END: TOKEN_VARIABLE_END, + TOKEN_COMMENT: TOKEN_COMMENT, + TOKEN_LEFT_PAREN: TOKEN_LEFT_PAREN, + TOKEN_RIGHT_PAREN: TOKEN_RIGHT_PAREN, + TOKEN_LEFT_BRACKET: TOKEN_LEFT_BRACKET, + TOKEN_RIGHT_BRACKET: TOKEN_RIGHT_BRACKET, + TOKEN_LEFT_CURLY: TOKEN_LEFT_CURLY, + TOKEN_RIGHT_CURLY: TOKEN_RIGHT_CURLY, + TOKEN_OPERATOR: TOKEN_OPERATOR, + TOKEN_COMMA: TOKEN_COMMA, + TOKEN_COLON: TOKEN_COLON, + TOKEN_TILDE: TOKEN_TILDE, + TOKEN_PIPE: TOKEN_PIPE, + TOKEN_INT: TOKEN_INT, + TOKEN_FLOAT: TOKEN_FLOAT, + TOKEN_BOOLEAN: TOKEN_BOOLEAN, + TOKEN_NONE: TOKEN_NONE, + TOKEN_SYMBOL: TOKEN_SYMBOL, + TOKEN_SPECIAL: TOKEN_SPECIAL, + TOKEN_REGEX: TOKEN_REGEX +}; + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Loader = __webpack_require__(6); + +var _require = __webpack_require__(19), + PrecompiledLoader = _require.PrecompiledLoader; + +var WebLoader = /*#__PURE__*/function (_Loader) { + _inheritsLoose(WebLoader, _Loader); + + function WebLoader(baseURL, opts) { + var _this; + + _this = _Loader.call(this) || this; + _this.baseURL = baseURL || '.'; + opts = opts || {}; // By default, the cache is turned off because there's no way + // to "watch" templates over HTTP, so they are re-downloaded + // and compiled each time. (Remember, PRECOMPILE YOUR + // TEMPLATES in production!) + + _this.useCache = !!opts.useCache; // We default `async` to false so that the simple synchronous + // API can be used when you aren't doing anything async in + // your templates (which is most of the time). This performs a + // sync ajax request, but that's ok because it should *only* + // happen in development. PRECOMPILE YOUR TEMPLATES. + + _this.async = !!opts.async; + return _this; + } + + var _proto = WebLoader.prototype; + + _proto.resolve = function resolve(from, to) { + throw new Error('relative templates not support in the browser yet'); + }; + + _proto.getSource = function getSource(name, cb) { + var _this2 = this; + + var useCache = this.useCache; + var result; + this.fetch(this.baseURL + '/' + name, function (err, src) { + if (err) { + if (cb) { + cb(err.content); + } else if (err.status === 404) { + result = null; + } else { + throw err.content; + } + } else { + result = { + src: src, + path: name, + noCache: !useCache + }; + + _this2.emit('load', name, result); + + if (cb) { + cb(null, result); + } + } + }); // if this WebLoader isn't running asynchronously, the + // fetch above would actually run sync and we'll have a + // result here + + return result; + }; + + _proto.fetch = function fetch(url, cb) { + // Only in the browser please + if (typeof window === 'undefined') { + throw new Error('WebLoader can only by used in a browser'); + } + + var ajax = new XMLHttpRequest(); + var loading = true; + + ajax.onreadystatechange = function () { + if (ajax.readyState === 4 && loading) { + loading = false; + + if (ajax.status === 0 || ajax.status === 200) { + cb(null, ajax.responseText); + } else { + cb({ + status: ajax.status, + content: ajax.responseText + }); + } + } + }; + + url += (url.indexOf('?') === -1 ? '?' : '&') + 's=' + new Date().getTime(); + ajax.open('GET', url, this.async); + ajax.send(); + }; + + return WebLoader; +}(Loader); + +module.exports = { + WebLoader: WebLoader, + PrecompiledLoader: PrecompiledLoader +}; + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + + +var lib = __webpack_require__(0); + +var _require = __webpack_require__(7), + Environment = _require.Environment, + Template = _require.Template; + +var Loader = __webpack_require__(6); + +var loaders = __webpack_require__(10); + +var precompile = __webpack_require__(23); + +var compiler = __webpack_require__(5); + +var parser = __webpack_require__(8); + +var lexer = __webpack_require__(9); + +var runtime = __webpack_require__(2); + +var nodes = __webpack_require__(3); + +var installJinjaCompat = __webpack_require__(25); // A single instance of an environment, since this is so commonly used + + +var e; + +function configure(templatesPath, opts) { + opts = opts || {}; + + if (lib.isObject(templatesPath)) { + opts = templatesPath; + templatesPath = null; + } + + var TemplateLoader; + + if (loaders.FileSystemLoader) { + TemplateLoader = new loaders.FileSystemLoader(templatesPath, { + watch: opts.watch, + noCache: opts.noCache + }); + } else if (loaders.WebLoader) { + TemplateLoader = new loaders.WebLoader(templatesPath, { + useCache: opts.web && opts.web.useCache, + async: opts.web && opts.web.async + }); + } + + e = new Environment(TemplateLoader, opts); + + if (opts && opts.express) { + e.express(opts.express); + } + + return e; +} + +module.exports = { + Environment: Environment, + Template: Template, + Loader: Loader, + FileSystemLoader: loaders.FileSystemLoader, + NodeResolveLoader: loaders.NodeResolveLoader, + PrecompiledLoader: loaders.PrecompiledLoader, + WebLoader: loaders.WebLoader, + compiler: compiler, + parser: parser, + lexer: lexer, + runtime: runtime, + lib: lib, + nodes: nodes, + installJinjaCompat: installJinjaCompat, + configure: configure, + reset: function reset() { + e = undefined; + }, + compile: function compile(src, env, path, eagerCompile) { + if (!e) { + configure(); + } + + return new Template(src, env, path, eagerCompile); + }, + render: function render(name, ctx, cb) { + if (!e) { + configure(); + } + + return e.render(name, ctx, cb); + }, + renderString: function renderString(src, ctx, cb) { + if (!e) { + configure(); + } + + return e.renderString(src, ctx, cb); + }, + precompile: precompile ? precompile.precompile : undefined, + precompileString: precompile ? precompile.precompileString : undefined +}; + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + + +// rawAsap provides everything we need except exception management. +var rawAsap = __webpack_require__(13); +// RawTasks are recycled to reduce GC churn. +var freeTasks = []; +// We queue errors to ensure they are thrown in right order (FIFO). +// Array-as-queue is good enough here, since we are just dealing with exceptions. +var pendingErrors = []; +var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); + +function throwFirstError() { + if (pendingErrors.length) { + throw pendingErrors.shift(); + } +} + +/** + * Calls a task as soon as possible after returning, in its own event, with priority + * over other events like animation, reflow, and repaint. An error thrown from an + * event will not interrupt, nor even substantially slow down the processing of + * other events, but will be rather postponed to a lower priority event. + * @param {{call}} task A callable object, typically a function that takes no + * arguments. + */ +module.exports = asap; +function asap(task) { + var rawTask; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); + } + rawTask.task = task; + rawAsap(rawTask); +} + +// We wrap tasks with recyclable task objects. A task object implements +// `call`, just like a function. +function RawTask() { + this.task = null; +} + +// The sole purpose of wrapping the task is to catch the exception and recycle +// the task object after its single use. +RawTask.prototype.call = function () { + try { + this.task.call(); + } catch (error) { + if (asap.onerror) { + // This hook exists purely for testing purposes. + // Its name will be periodically randomized to break any code that + // depends on its existence. + asap.onerror(error); + } else { + // In a web browser, exceptions are not fatal. However, to avoid + // slowing down the queue of pending tasks, we rethrow the error in a + // lower priority turn. + pendingErrors.push(error); + requestErrorThrow(); + } + } finally { + this.task = null; + freeTasks[freeTasks.length] = this; + } +}; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { +/* WEBPACK VAR INJECTION */(function(global) { + +// Use the fastest means possible to execute a task in its own turn, with +// priority over other events including IO, animation, reflow, and redraw +// events in browsers. +// +// An exception thrown by a task will permanently interrupt the processing of +// subsequent tasks. The higher level `asap` function ensures that if an +// exception is thrown by a task, that the task queue will continue flushing as +// soon as possible, but if you use `rawAsap` directly, you are responsible to +// either ensure that no exceptions are thrown from your task, or to manually +// call `rawAsap.requestFlush` if an exception is thrown. +module.exports = rawAsap; +function rawAsap(task) { + if (!queue.length) { + requestFlush(); + } + // Equivalent to push, but avoids a function call. + queue[queue.length] = task; +} + +var queue = []; +// `requestFlush` is an implementation-specific method that attempts to kick +// off a `flush` event as quickly as possible. `flush` will attempt to exhaust +// the event queue before yielding to the browser's own event loop. +var requestFlush; +// The position of the next task to execute in the task queue. This is +// preserved between calls to `flush` so that it can be resumed if +// a task throws an exception. +var index = 0; +// If a task schedules additional tasks recursively, the task queue can grow +// unbounded. To prevent memory exhaustion, the task queue will periodically +// truncate already-completed tasks. +var capacity = 1024; + +// The flush function processes all tasks that have been scheduled with +// `rawAsap` unless and until one of those tasks throws an exception. +// If a task throws an exception, `flush` ensures that its state will remain +// consistent and will resume where it left off when called again. +// However, `flush` does not make any arrangements to be called again if an +// exception is thrown. +function flush() { + while (index < queue.length) { + var currentIndex = index; + // Advance the index before calling the task. This ensures that we will + // begin flushing on the next task the task throws an error. + index = index + 1; + queue[currentIndex].call(); + // Prevent leaking memory for long chains of recursive calls to `asap`. + // If we call `asap` within tasks scheduled by `asap`, the queue will + // grow, but to avoid an O(n) walk for every task we execute, we don't + // shift tasks off the queue after they have been executed. + // Instead, we periodically shift 1024 tasks off the queue. + if (index > capacity) { + // Manually shift all values starting at the index back to the + // beginning of the queue. + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; +} + +// `requestFlush` is implemented using a strategy based on data collected from +// every available SauceLabs Selenium web driver worker at time of writing. +// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 + +// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that +// have WebKitMutationObserver but not un-prefixed MutationObserver. +// Must use `global` or `self` instead of `window` to work in both frames and web +// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. + +/* globals self */ +var scope = typeof global !== "undefined" ? global : self; +var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; + +// MutationObservers are desirable because they have high priority and work +// reliably everywhere they are implemented. +// They are implemented in all modern browsers. +// +// - Android 4-4.3 +// - Chrome 26-34 +// - Firefox 14-29 +// - Internet Explorer 11 +// - iPad Safari 6-7.1 +// - iPhone Safari 7-7.1 +// - Safari 6-7 +if (typeof BrowserMutationObserver === "function") { + requestFlush = makeRequestCallFromMutationObserver(flush); + +// MessageChannels are desirable because they give direct access to the HTML +// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera +// 11-12, and in web workers in many engines. +// Although message channels yield to any queued rendering and IO tasks, they +// would be better than imposing the 4ms delay of timers. +// However, they do not work reliably in Internet Explorer or Safari. + +// Internet Explorer 10 is the only browser that has setImmediate but does +// not have MutationObservers. +// Although setImmediate yields to the browser's renderer, it would be +// preferrable to falling back to setTimeout since it does not have +// the minimum 4ms penalty. +// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and +// Desktop to a lesser extent) that renders both setImmediate and +// MessageChannel useless for the purposes of ASAP. +// https://github.com/kriskowal/q/issues/396 + +// Timers are implemented universally. +// We fall back to timers in workers in most engines, and in foreground +// contexts in the following browsers. +// However, note that even this simple case requires nuances to operate in a +// broad spectrum of browsers. +// +// - Firefox 3-13 +// - Internet Explorer 6-9 +// - iPad Safari 4.3 +// - Lynx 2.8.7 +} else { + requestFlush = makeRequestCallFromTimer(flush); +} + +// `requestFlush` requests that the high priority event queue be flushed as +// soon as possible. +// This is useful to prevent an error thrown in a task from stalling the event +// queue if the exception handled by Node.js’s +// `process.on("uncaughtException")` or by a domain. +rawAsap.requestFlush = requestFlush; + +// To request a high priority event, we induce a mutation observer by toggling +// the text of a text node between "1" and "-1". +function makeRequestCallFromMutationObserver(callback) { + var toggle = 1; + var observer = new BrowserMutationObserver(callback); + var node = document.createTextNode(""); + observer.observe(node, {characterData: true}); + return function requestCall() { + toggle = -toggle; + node.data = toggle; + }; +} + +// The message channel technique was discovered by Malte Ubl and was the +// original foundation for this library. +// http://www.nonblocking.io/2011/06/windownexttick.html + +// Safari 6.0.5 (at least) intermittently fails to create message ports on a +// page's first load. Thankfully, this version of Safari supports +// MutationObservers, so we don't need to fall back in that case. + +// function makeRequestCallFromMessageChannel(callback) { +// var channel = new MessageChannel(); +// channel.port1.onmessage = callback; +// return function requestCall() { +// channel.port2.postMessage(0); +// }; +// } + +// For reasons explained above, we are also unable to use `setImmediate` +// under any circumstances. +// Even if we were, there is another bug in Internet Explorer 10. +// It is not sufficient to assign `setImmediate` to `requestFlush` because +// `setImmediate` must be called *by name* and therefore must be wrapped in a +// closure. +// Never forget. + +// function makeRequestCallFromSetImmediate(callback) { +// return function requestCall() { +// setImmediate(callback); +// }; +// } + +// Safari 6.0 has a problem where timers will get lost while the user is +// scrolling. This problem does not impact ASAP because Safari 6.0 supports +// mutation observers, so that implementation is used instead. +// However, if we ever elect to use timers in Safari, the prevalent work-around +// is to add a scroll event listener that calls for a flush. + +// `setTimeout` does not call the passed callback if the delay is less than +// approximately 7 in web workers in Firefox 8 through 18, and sometimes not +// even then. + +function makeRequestCallFromTimer(callback) { + return function requestCall() { + // We dispatch a timeout with a specified delay of 0 for engines that + // can reliably accommodate that request. This will usually be snapped + // to a 4 milisecond delay, but once we're flushing, there's no delay + // between events. + var timeoutHandle = setTimeout(handleTimer, 0); + // However, since this timer gets frequently dropped in Firefox + // workers, we enlist an interval handle that will try to fire + // an event 20 times per second until it succeeds. + var intervalHandle = setInterval(handleTimer, 50); + + function handleTimer() { + // Whichever timer succeeds will cancel both timers and + // execute the callback. + clearTimeout(timeoutHandle); + clearInterval(intervalHandle); + callback(); + } + }; +} + +// This is for `asap.js` only. +// Its name will be periodically randomized to break any code that depends on +// its existence. +rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; + +// ASAP was originally a nextTick shim included in Q. This was factored out +// into this ASAP package. It was later adapted to RSVP which made further +// amendments. These decisions, particularly to marginalize MessageChannel and +// to capture the MutationObserver implementation in a closure, were integrated +// back into ASAP proper. +// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(14))); + +/***/ }), +/* 14 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// MIT license (by Elan Shanker). +(function(globals) { + + var executeSync = function(){ + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'function'){ + args[0].apply(null, args.splice(1)); + } + }; + + var executeAsync = function(fn){ + if (typeof setImmediate === 'function') { + setImmediate(fn); + } else if (typeof process !== 'undefined' && process.nextTick) { + process.nextTick(fn); + } else { + setTimeout(fn, 0); + } + }; + + var makeIterator = function (tasks) { + var makeCallback = function (index) { + var fn = function () { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + }; + return makeCallback(0); + }; + + var _isArray = Array.isArray || function(maybeArray){ + return Object.prototype.toString.call(maybeArray) === '[object Array]'; + }; + + var waterfall = function (tasks, callback, forceAsync) { + var nextTick = forceAsync ? executeAsync : executeSync; + callback = callback || function () {}; + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + callback = function () {}; + } else { + var args = Array.prototype.slice.call(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } else { + args.push(callback); + } + nextTick(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(makeIterator(tasks))(); + }; + + { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return waterfall; + }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // RequireJS + } +})(); + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null; +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + }; + +var ReflectOwnKeys; +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys; +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +}; + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function eventListener() { + if (errorListener !== undefined) { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + } var errorListener; + + // Adding an error listener is not optional because + // if an error is thrown on an event emitter we cannot + // guarantee that the actual event we are waiting will + // be fired. The result could be a silent way to create + // memory or file descriptor leaks, which is something + // we should avoid. + if (name !== 'error') { + errorListener = function errorListener(err) { + emitter.removeListener(name, eventListener); + reject(err); + }; + + emitter.once('error', errorListener); + } + + emitter.once(name, eventListener); + }); +} + + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + + +var nodes = __webpack_require__(3); + +var lib = __webpack_require__(0); + +var sym = 0; + +function gensym() { + return 'hole_' + sym++; +} // copy-on-write version of map + + +function mapCOW(arr, func) { + var res = null; + + for (var i = 0; i < arr.length; i++) { + var item = func(arr[i]); + + if (item !== arr[i]) { + if (!res) { + res = arr.slice(); + } + + res[i] = item; + } + } + + return res || arr; +} + +function walk(ast, func, depthFirst) { + if (!(ast instanceof nodes.Node)) { + return ast; + } + + if (!depthFirst) { + var astT = func(ast); + + if (astT && astT !== ast) { + return astT; + } + } + + if (ast instanceof nodes.NodeList) { + var children = mapCOW(ast.children, function (node) { + return walk(node, func, depthFirst); + }); + + if (children !== ast.children) { + ast = new nodes[ast.typename](ast.lineno, ast.colno, children); + } + } else if (ast instanceof nodes.CallExtension) { + var args = walk(ast.args, func, depthFirst); + var contentArgs = mapCOW(ast.contentArgs, function (node) { + return walk(node, func, depthFirst); + }); + + if (args !== ast.args || contentArgs !== ast.contentArgs) { + ast = new nodes[ast.typename](ast.extName, ast.prop, args, contentArgs); + } + } else { + var props = ast.fields.map(function (field) { + return ast[field]; + }); + var propsT = mapCOW(props, function (prop) { + return walk(prop, func, depthFirst); + }); + + if (propsT !== props) { + ast = new nodes[ast.typename](ast.lineno, ast.colno); + propsT.forEach(function (prop, i) { + ast[ast.fields[i]] = prop; + }); + } + } + + return depthFirst ? func(ast) || ast : ast; +} + +function depthWalk(ast, func) { + return walk(ast, func, true); +} + +function _liftFilters(node, asyncFilters, prop) { + var children = []; + var walked = depthWalk(prop ? node[prop] : node, function (descNode) { + var symbol; + + if (descNode instanceof nodes.Block) { + return descNode; + } else if (descNode instanceof nodes.Filter && lib.indexOf(asyncFilters, descNode.name.value) !== -1 || descNode instanceof nodes.CallExtensionAsync) { + symbol = new nodes.Symbol(descNode.lineno, descNode.colno, gensym()); + children.push(new nodes.FilterAsync(descNode.lineno, descNode.colno, descNode.name, descNode.args, symbol)); + } + + return symbol; + }); + + if (prop) { + node[prop] = walked; + } else { + node = walked; + } + + if (children.length) { + children.push(node); + return new nodes.NodeList(node.lineno, node.colno, children); + } else { + return node; + } +} + +function liftFilters(ast, asyncFilters) { + return depthWalk(ast, function (node) { + if (node instanceof nodes.Output) { + return _liftFilters(node, asyncFilters); + } else if (node instanceof nodes.Set) { + return _liftFilters(node, asyncFilters, 'value'); + } else if (node instanceof nodes.For) { + return _liftFilters(node, asyncFilters, 'arr'); + } else if (node instanceof nodes.If) { + return _liftFilters(node, asyncFilters, 'cond'); + } else if (node instanceof nodes.CallExtension) { + return _liftFilters(node, asyncFilters, 'args'); + } else { + return undefined; + } + }); +} + +function liftSuper(ast) { + return walk(ast, function (blockNode) { + if (!(blockNode instanceof nodes.Block)) { + return; + } + + var hasSuper = false; + var symbol = gensym(); + blockNode.body = walk(blockNode.body, function (node) { + // eslint-disable-line consistent-return + if (node instanceof nodes.FunCall && node.name.value === 'super') { + hasSuper = true; + return new nodes.Symbol(node.lineno, node.colno, symbol); + } + }); + + if (hasSuper) { + blockNode.body.children.unshift(new nodes.Super(0, 0, blockNode.name, new nodes.Symbol(0, 0, symbol))); + } + }); +} + +function convertStatements(ast) { + return depthWalk(ast, function (node) { + if (!(node instanceof nodes.If) && !(node instanceof nodes.For)) { + return undefined; + } + + var async = false; + walk(node, function (child) { + if (child instanceof nodes.FilterAsync || child instanceof nodes.IfAsync || child instanceof nodes.AsyncEach || child instanceof nodes.AsyncAll || child instanceof nodes.CallExtensionAsync) { + async = true; // Stop iterating by returning the node + + return child; + } + + return undefined; + }); + + if (async) { + if (node instanceof nodes.If) { + return new nodes.IfAsync(node.lineno, node.colno, node.cond, node.body, node.else_); + } else if (node instanceof nodes.For && !(node instanceof nodes.AsyncAll)) { + return new nodes.AsyncEach(node.lineno, node.colno, node.arr, node.name, node.body, node.else_); + } + } + + return undefined; + }); +} + +function cps(ast, asyncFilters) { + return convertStatements(liftSuper(liftFilters(ast, asyncFilters))); +} + +function transform(ast, asyncFilters) { + return cps(ast, asyncFilters || []); +} // var parser = require('./parser'); +// var src = 'hello {% foo %}{% endfoo %} end'; +// var ast = transform(parser.parse(src, [new FooExtension()]), ['bar']); +// nodes.printNodes(ast); + + +module.exports = { + transform: transform +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + + +var lib = __webpack_require__(0); + +var r = __webpack_require__(2); + +var exports = module.exports = {}; + +function normalize(value, defaultValue) { + if (value === null || value === undefined || value === false) { + return defaultValue; + } + + return value; +} + +exports.abs = Math.abs; + +function isNaN(num) { + return num !== num; // eslint-disable-line no-self-compare +} + +function batch(arr, linecount, fillWith) { + var i; + var res = []; + var tmp = []; + + for (i = 0; i < arr.length; i++) { + if (i % linecount === 0 && tmp.length) { + res.push(tmp); + tmp = []; + } + + tmp.push(arr[i]); + } + + if (tmp.length) { + if (fillWith) { + for (i = tmp.length; i < linecount; i++) { + tmp.push(fillWith); + } + } + + res.push(tmp); + } + + return res; +} + +exports.batch = batch; + +function capitalize(str) { + str = normalize(str, ''); + var ret = str.toLowerCase(); + return r.copySafeness(str, ret.charAt(0).toUpperCase() + ret.slice(1)); +} + +exports.capitalize = capitalize; + +function center(str, width) { + str = normalize(str, ''); + width = width || 80; + + if (str.length >= width) { + return str; + } + + var spaces = width - str.length; + var pre = lib.repeat(' ', spaces / 2 - spaces % 2); + var post = lib.repeat(' ', spaces / 2); + return r.copySafeness(str, pre + str + post); +} + +exports.center = center; + +function default_(val, def, bool) { + if (bool) { + return val || def; + } else { + return val !== undefined ? val : def; + } +} // TODO: it is confusing to export something called 'default' + + +exports['default'] = default_; // eslint-disable-line dot-notation + +function dictsort(val, caseSensitive, by) { + if (!lib.isObject(val)) { + throw new lib.TemplateError('dictsort filter: val must be an object'); + } + + var array = []; // deliberately include properties from the object's prototype + + for (var k in val) { + // eslint-disable-line guard-for-in, no-restricted-syntax + array.push([k, val[k]]); + } + + var si; + + if (by === undefined || by === 'key') { + si = 0; + } else if (by === 'value') { + si = 1; + } else { + throw new lib.TemplateError('dictsort filter: You can only sort by either key or value'); + } + + array.sort(function (t1, t2) { + var a = t1[si]; + var b = t2[si]; + + if (!caseSensitive) { + if (lib.isString(a)) { + a = a.toUpperCase(); + } + + if (lib.isString(b)) { + b = b.toUpperCase(); + } + } + + return a > b ? 1 : a === b ? 0 : -1; // eslint-disable-line no-nested-ternary + }); + return array; +} + +exports.dictsort = dictsort; + +function dump(obj, spaces) { + return JSON.stringify(obj, null, spaces); +} + +exports.dump = dump; + +function escape(str) { + if (str instanceof r.SafeString) { + return str; + } + + str = str === null || str === undefined ? '' : str; + return r.markSafe(lib.escape(str.toString())); +} + +exports.escape = escape; + +function safe(str) { + if (str instanceof r.SafeString) { + return str; + } + + str = str === null || str === undefined ? '' : str; + return r.markSafe(str.toString()); +} + +exports.safe = safe; + +function first(arr) { + return arr[0]; +} + +exports.first = first; + +function forceescape(str) { + str = str === null || str === undefined ? '' : str; + return r.markSafe(lib.escape(str.toString())); +} + +exports.forceescape = forceescape; + +function groupby(arr, attr) { + return lib.groupBy(arr, attr, this.env.opts.throwOnUndefined); +} + +exports.groupby = groupby; + +function indent(str, width, indentfirst) { + str = normalize(str, ''); + + if (str === '') { + return ''; + } + + width = width || 4; // let res = ''; + + var lines = str.split('\n'); + var sp = lib.repeat(' ', width); + var res = lines.map(function (l, i) { + return i === 0 && !indentfirst ? l : "" + sp + l; + }).join('\n'); + return r.copySafeness(str, res); +} + +exports.indent = indent; + +function join(arr, del, attr) { + del = del || ''; + + if (attr) { + arr = lib.map(arr, function (v) { + return v[attr]; + }); + } + + return arr.join(del); +} + +exports.join = join; + +function last(arr) { + return arr[arr.length - 1]; +} + +exports.last = last; + +function lengthFilter(val) { + var value = normalize(val, ''); + + if (value !== undefined) { + if (typeof Map === 'function' && value instanceof Map || typeof Set === 'function' && value instanceof Set) { + // ECMAScript 2015 Maps and Sets + return value.size; + } + + if (lib.isObject(value) && !(value instanceof r.SafeString)) { + // Objects (besides SafeStrings), non-primative Arrays + return lib.keys(value).length; + } + + return value.length; + } + + return 0; +} + +exports.length = lengthFilter; + +function list(val) { + if (lib.isString(val)) { + return val.split(''); + } else if (lib.isObject(val)) { + return lib._entries(val || {}).map(function (_ref) { + var key = _ref[0], + value = _ref[1]; + return { + key: key, + value: value + }; + }); + } else if (lib.isArray(val)) { + return val; + } else { + throw new lib.TemplateError('list filter: type not iterable'); + } +} + +exports.list = list; + +function lower(str) { + str = normalize(str, ''); + return str.toLowerCase(); +} + +exports.lower = lower; + +function nl2br(str) { + if (str === null || str === undefined) { + return ''; + } + + return r.copySafeness(str, str.replace(/\r\n|\n/g, '
    \n')); +} + +exports.nl2br = nl2br; + +function random(arr) { + return arr[Math.floor(Math.random() * arr.length)]; +} + +exports.random = random; +/** + * Construct select or reject filter + * + * @param {boolean} expectedTestResult + * @returns {function(array, string, *): array} + */ + +function getSelectOrReject(expectedTestResult) { + function filter(arr, testName, secondArg) { + if (testName === void 0) { + testName = 'truthy'; + } + + var context = this; + var test = context.env.getTest(testName); + return lib.toArray(arr).filter(function examineTestResult(item) { + return test.call(context, item, secondArg) === expectedTestResult; + }); + } + + return filter; +} + +exports.reject = getSelectOrReject(false); + +function rejectattr(arr, attr) { + return arr.filter(function (item) { + return !item[attr]; + }); +} + +exports.rejectattr = rejectattr; +exports.select = getSelectOrReject(true); + +function selectattr(arr, attr) { + return arr.filter(function (item) { + return !!item[attr]; + }); +} + +exports.selectattr = selectattr; + +function replace(str, old, new_, maxCount) { + var originalStr = str; + + if (old instanceof RegExp) { + return str.replace(old, new_); + } + + if (typeof maxCount === 'undefined') { + maxCount = -1; + } + + var res = ''; // Output + // Cast Numbers in the search term to string + + if (typeof old === 'number') { + old = '' + old; + } else if (typeof old !== 'string') { + // If it is something other than number or string, + // return the original string + return str; + } // Cast numbers in the replacement to string + + + if (typeof str === 'number') { + str = '' + str; + } // If by now, we don't have a string, throw it back + + + if (typeof str !== 'string' && !(str instanceof r.SafeString)) { + return str; + } // ShortCircuits + + + if (old === '') { + // Mimic the python behaviour: empty string is replaced + // by replacement e.g. "abc"|replace("", ".") -> .a.b.c. + res = new_ + str.split('').join(new_) + new_; + return r.copySafeness(str, res); + } + + var nextIndex = str.indexOf(old); // if # of replacements to perform is 0, or the string to does + // not contain the old value, return the string + + if (maxCount === 0 || nextIndex === -1) { + return str; + } + + var pos = 0; + var count = 0; // # of replacements made + + while (nextIndex > -1 && (maxCount === -1 || count < maxCount)) { + // Grab the next chunk of src string and add it with the + // replacement, to the result + res += str.substring(pos, nextIndex) + new_; // Increment our pointer in the src string + + pos = nextIndex + old.length; + count++; // See if there are any more replacements to be made + + nextIndex = str.indexOf(old, pos); + } // We've either reached the end, or done the max # of + // replacements, tack on any remaining string + + + if (pos < str.length) { + res += str.substring(pos); + } + + return r.copySafeness(originalStr, res); +} + +exports.replace = replace; + +function reverse(val) { + var arr; + + if (lib.isString(val)) { + arr = list(val); + } else { + // Copy it + arr = lib.map(val, function (v) { + return v; + }); + } + + arr.reverse(); + + if (lib.isString(val)) { + return r.copySafeness(val, arr.join('')); + } + + return arr; +} + +exports.reverse = reverse; + +function round(val, precision, method) { + precision = precision || 0; + var factor = Math.pow(10, precision); + var rounder; + + if (method === 'ceil') { + rounder = Math.ceil; + } else if (method === 'floor') { + rounder = Math.floor; + } else { + rounder = Math.round; + } + + return rounder(val * factor) / factor; +} + +exports.round = round; + +function slice(arr, slices, fillWith) { + var sliceLength = Math.floor(arr.length / slices); + var extra = arr.length % slices; + var res = []; + var offset = 0; + + for (var i = 0; i < slices; i++) { + var start = offset + i * sliceLength; + + if (i < extra) { + offset++; + } + + var end = offset + (i + 1) * sliceLength; + var currSlice = arr.slice(start, end); + + if (fillWith && i >= extra) { + currSlice.push(fillWith); + } + + res.push(currSlice); + } + + return res; +} + +exports.slice = slice; + +function sum(arr, attr, start) { + if (start === void 0) { + start = 0; + } + + if (attr) { + arr = lib.map(arr, function (v) { + return v[attr]; + }); + } + + return start + arr.reduce(function (a, b) { + return a + b; + }, 0); +} + +exports.sum = sum; +exports.sort = r.makeMacro(['value', 'reverse', 'case_sensitive', 'attribute'], [], function sortFilter(arr, reversed, caseSens, attr) { + var _this = this; + + // Copy it + var array = lib.map(arr, function (v) { + return v; + }); + var getAttribute = lib.getAttrGetter(attr); + array.sort(function (a, b) { + var x = attr ? getAttribute(a) : a; + var y = attr ? getAttribute(b) : b; + + if (_this.env.opts.throwOnUndefined && attr && (x === undefined || y === undefined)) { + throw new TypeError("sort: attribute \"" + attr + "\" resolved to undefined"); + } + + if (!caseSens && lib.isString(x) && lib.isString(y)) { + x = x.toLowerCase(); + y = y.toLowerCase(); + } + + if (x < y) { + return reversed ? 1 : -1; + } else if (x > y) { + return reversed ? -1 : 1; + } else { + return 0; + } + }); + return array; +}); + +function string(obj) { + return r.copySafeness(obj, obj); +} + +exports.string = string; + +function striptags(input, preserveLinebreaks) { + input = normalize(input, ''); + var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|/gi; + var trimmedInput = trim(input.replace(tags, '')); + var res = ''; + + if (preserveLinebreaks) { + res = trimmedInput.replace(/^ +| +$/gm, '') // remove leading and trailing spaces + .replace(/ +/g, ' ') // squash adjacent spaces + .replace(/(\r\n)/g, '\n') // normalize linebreaks (CRLF -> LF) + .replace(/\n\n\n+/g, '\n\n'); // squash abnormal adjacent linebreaks + } else { + res = trimmedInput.replace(/\s+/gi, ' '); + } + + return r.copySafeness(input, res); +} + +exports.striptags = striptags; + +function title(str) { + str = normalize(str, ''); + var words = str.split(' ').map(function (word) { + return capitalize(word); + }); + return r.copySafeness(str, words.join(' ')); +} + +exports.title = title; + +function trim(str) { + return r.copySafeness(str, str.replace(/^\s*|\s*$/g, '')); +} + +exports.trim = trim; + +function truncate(input, length, killwords, end) { + var orig = input; + input = normalize(input, ''); + length = length || 255; + + if (input.length <= length) { + return input; + } + + if (killwords) { + input = input.substring(0, length); + } else { + var idx = input.lastIndexOf(' ', length); + + if (idx === -1) { + idx = length; + } + + input = input.substring(0, idx); + } + + input += end !== undefined && end !== null ? end : '...'; + return r.copySafeness(orig, input); +} + +exports.truncate = truncate; + +function upper(str) { + str = normalize(str, ''); + return str.toUpperCase(); +} + +exports.upper = upper; + +function urlencode(obj) { + var enc = encodeURIComponent; + + if (lib.isString(obj)) { + return enc(obj); + } else { + var keyvals = lib.isArray(obj) ? obj : lib._entries(obj); + return keyvals.map(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; + return enc(k) + "=" + enc(v); + }).join('&'); + } +} + +exports.urlencode = urlencode; // For the jinja regexp, see +// https://github.com/mitsuhiko/jinja2/blob/f15b814dcba6aa12bc74d1f7d0c881d55f7126be/jinja2/utils.py#L20-L23 + +var puncRe = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; // from http://blog.gerv.net/2011/05/html5_email_address_regexp/ + +var emailRe = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i; +var httpHttpsRe = /^https?:\/\/.*$/; +var wwwRe = /^www\./; +var tldRe = /\.(?:org|net|com)(?:\:|\/|$)/; + +function urlize(str, length, nofollow) { + if (isNaN(length)) { + length = Infinity; + } + + var noFollowAttr = nofollow === true ? ' rel="nofollow"' : ''; + var words = str.split(/(\s+)/).filter(function (word) { + // If the word has no length, bail. This can happen for str with + // trailing whitespace. + return word && word.length; + }).map(function (word) { + var matches = word.match(puncRe); + var possibleUrl = matches ? matches[1] : word; + var shortUrl = possibleUrl.substr(0, length); // url that starts with http or https + + if (httpHttpsRe.test(possibleUrl)) { + return "" + shortUrl + ""; + } // url that starts with www. + + + if (wwwRe.test(possibleUrl)) { + return "" + shortUrl + ""; + } // an email address of the form username@domain.tld + + + if (emailRe.test(possibleUrl)) { + return "" + possibleUrl + ""; + } // url that ends in .com, .org or .net that is not an email address + + + if (tldRe.test(possibleUrl)) { + return "" + shortUrl + ""; + } + + return word; + }); + return words.join(''); +} + +exports.urlize = urlize; + +function wordcount(str) { + str = normalize(str, ''); + var words = str ? str.match(/\w+/g) : null; + return words ? words.length : null; +} + +exports.wordcount = wordcount; + +function float(val, def) { + var res = parseFloat(val); + return isNaN(res) ? def : res; +} + +exports.float = float; +var intFilter = r.makeMacro(['value', 'default', 'base'], [], function doInt(value, defaultValue, base) { + if (base === void 0) { + base = 10; + } + + var res = parseInt(value, base); + return isNaN(res) ? defaultValue : res; +}); +exports.int = intFilter; // Aliases + +exports.d = exports.default; +exports.e = exports.escape; + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Loader = __webpack_require__(6); + +var PrecompiledLoader = /*#__PURE__*/function (_Loader) { + _inheritsLoose(PrecompiledLoader, _Loader); + + function PrecompiledLoader(compiledTemplates) { + var _this; + + _this = _Loader.call(this) || this; + _this.precompiled = compiledTemplates || {}; + return _this; + } + + var _proto = PrecompiledLoader.prototype; + + _proto.getSource = function getSource(name) { + if (this.precompiled[name]) { + return { + src: { + type: 'code', + obj: this.precompiled[name] + }, + path: name + }; + } + + return null; + }; + + return PrecompiledLoader; +}(Loader); + +module.exports = { + PrecompiledLoader: PrecompiledLoader +}; + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + + +var SafeString = __webpack_require__(2).SafeString; +/** + * Returns `true` if the object is a function, otherwise `false`. + * @param { any } value + * @returns { boolean } + */ + + +function callable(value) { + return typeof value === 'function'; +} + +exports.callable = callable; +/** + * Returns `true` if the object is strictly not `undefined`. + * @param { any } value + * @returns { boolean } + */ + +function defined(value) { + return value !== undefined; +} + +exports.defined = defined; +/** + * Returns `true` if the operand (one) is divisble by the test's argument + * (two). + * @param { number } one + * @param { number } two + * @returns { boolean } + */ + +function divisibleby(one, two) { + return one % two === 0; +} + +exports.divisibleby = divisibleby; +/** + * Returns true if the string has been escaped (i.e., is a SafeString). + * @param { any } value + * @returns { boolean } + */ + +function escaped(value) { + return value instanceof SafeString; +} + +exports.escaped = escaped; +/** + * Returns `true` if the arguments are strictly equal. + * @param { any } one + * @param { any } two + */ + +function equalto(one, two) { + return one === two; +} + +exports.equalto = equalto; // Aliases + +exports.eq = exports.equalto; +exports.sameas = exports.equalto; +/** + * Returns `true` if the value is evenly divisible by 2. + * @param { number } value + * @returns { boolean } + */ + +function even(value) { + return value % 2 === 0; +} + +exports.even = even; +/** + * Returns `true` if the value is falsy - if I recall correctly, '', 0, false, + * undefined, NaN or null. I don't know if we should stick to the default JS + * behavior or attempt to replicate what Python believes should be falsy (i.e., + * empty arrays, empty dicts, not 0...). + * @param { any } value + * @returns { boolean } + */ + +function falsy(value) { + return !value; +} + +exports.falsy = falsy; +/** + * Returns `true` if the operand (one) is greater or equal to the test's + * argument (two). + * @param { number } one + * @param { number } two + * @returns { boolean } + */ + +function ge(one, two) { + return one >= two; +} + +exports.ge = ge; +/** + * Returns `true` if the operand (one) is greater than the test's argument + * (two). + * @param { number } one + * @param { number } two + * @returns { boolean } + */ + +function greaterthan(one, two) { + return one > two; +} + +exports.greaterthan = greaterthan; // alias + +exports.gt = exports.greaterthan; +/** + * Returns `true` if the operand (one) is less than or equal to the test's + * argument (two). + * @param { number } one + * @param { number } two + * @returns { boolean } + */ + +function le(one, two) { + return one <= two; +} + +exports.le = le; +/** + * Returns `true` if the operand (one) is less than the test's passed argument + * (two). + * @param { number } one + * @param { number } two + * @returns { boolean } + */ + +function lessthan(one, two) { + return one < two; +} + +exports.lessthan = lessthan; // alias + +exports.lt = exports.lessthan; +/** + * Returns `true` if the string is lowercased. + * @param { string } value + * @returns { boolean } + */ + +function lower(value) { + return value.toLowerCase() === value; +} + +exports.lower = lower; +/** + * Returns `true` if the operand (one) is less than or equal to the test's + * argument (two). + * @param { number } one + * @param { number } two + * @returns { boolean } + */ + +function ne(one, two) { + return one !== two; +} + +exports.ne = ne; +/** + * Returns true if the value is strictly equal to `null`. + * @param { any } + * @returns { boolean } + */ + +function nullTest(value) { + return value === null; +} + +exports.null = nullTest; +/** + * Returns true if value is a number. + * @param { any } + * @returns { boolean } + */ + +function number(value) { + return typeof value === 'number'; +} + +exports.number = number; +/** + * Returns `true` if the value is *not* evenly divisible by 2. + * @param { number } value + * @returns { boolean } + */ + +function odd(value) { + return value % 2 === 1; +} + +exports.odd = odd; +/** + * Returns `true` if the value is a string, `false` if not. + * @param { any } value + * @returns { boolean } + */ + +function string(value) { + return typeof value === 'string'; +} + +exports.string = string; +/** + * Returns `true` if the value is not in the list of things considered falsy: + * '', null, undefined, 0, NaN and false. + * @param { any } value + * @returns { boolean } + */ + +function truthy(value) { + return !!value; +} + +exports.truthy = truthy; +/** + * Returns `true` if the value is undefined. + * @param { any } value + * @returns { boolean } + */ + +function undefinedTest(value) { + return value === undefined; +} + +exports.undefined = undefinedTest; +/** + * Returns `true` if the string is uppercased. + * @param { string } value + * @returns { boolean } + */ + +function upper(value) { + return value.toUpperCase() === value; +} + +exports.upper = upper; +/** + * If ES6 features are available, returns `true` if the value implements the + * `Symbol.iterator` method. If not, it's a string or Array. + * + * Could potentially cause issues if a browser exists that has Set and Map but + * not Symbol. + * + * @param { any } value + * @returns { boolean } + */ + +function iterable(value) { + if (typeof Symbol !== 'undefined') { + return !!value[Symbol.iterator]; + } else { + return Array.isArray(value) || typeof value === 'string'; + } +} + +exports.iterable = iterable; +/** + * If ES6 features are available, returns `true` if the value is an object hash + * or an ES6 Map. Otherwise just return if it's an object hash. + * @param { any } value + * @returns { boolean } + */ + +function mapping(value) { + // only maps and object hashes + var bool = value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value); + + if (Set) { + return bool && !(value instanceof Set); + } else { + return bool; + } +} + +exports.mapping = mapping; + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + + +function _cycler(items) { + var index = -1; + return { + current: null, + reset: function reset() { + index = -1; + this.current = null; + }, + next: function next() { + index++; + + if (index >= items.length) { + index = 0; + } + + this.current = items[index]; + return this.current; + } + }; +} + +function _joiner(sep) { + sep = sep || ','; + var first = true; + return function () { + var val = first ? '' : sep; + first = false; + return val; + }; +} // Making this a function instead so it returns a new object +// each time it's called. That way, if something like an environment +// uses it, they will each have their own copy. + + +function globals() { + return { + range: function range(start, stop, step) { + if (typeof stop === 'undefined') { + stop = start; + start = 0; + step = 1; + } else if (!step) { + step = 1; + } + + var arr = []; + + if (step > 0) { + for (var i = start; i < stop; i += step) { + arr.push(i); + } + } else { + for (var _i = start; _i > stop; _i += step) { + // eslint-disable-line for-direction + arr.push(_i); + } + } + + return arr; + }, + cycler: function cycler() { + return _cycler(Array.prototype.slice.call(arguments)); + }, + joiner: function joiner(sep) { + return _joiner(sep); + } + }; +} + +module.exports = globals; + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +var path = __webpack_require__(4); + +module.exports = function express(env, app) { + function NunjucksView(name, opts) { + this.name = name; + this.path = name; + this.defaultEngine = opts.defaultEngine; + this.ext = path.extname(name); + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + if (!this.ext) { + this.name += this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine; + } + } + + NunjucksView.prototype.render = function render(opts, cb) { + env.render(this.name, opts, cb); + }; + + app.set('view', NunjucksView); + app.set('nunjucksEnv', env); + return env; +}; + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + + +var fs = __webpack_require__(4); + +var path = __webpack_require__(4); + +var _require = __webpack_require__(0), + _prettifyError = _require._prettifyError; + +var compiler = __webpack_require__(5); + +var _require2 = __webpack_require__(7), + Environment = _require2.Environment; + +var precompileGlobal = __webpack_require__(24); + +function match(filename, patterns) { + if (!Array.isArray(patterns)) { + return false; + } + + return patterns.some(function (pattern) { + return filename.match(pattern); + }); +} + +function precompileString(str, opts) { + opts = opts || {}; + opts.isString = true; + var env = opts.env || new Environment([]); + var wrapper = opts.wrapper || precompileGlobal; + + if (!opts.name) { + throw new Error('the "name" option is required when compiling a string'); + } + + return wrapper([_precompile(str, opts.name, env)], opts); +} + +function precompile(input, opts) { + // The following options are available: + // + // * name: name of the template (auto-generated when compiling a directory) + // * isString: input is a string, not a file path + // * asFunction: generate a callable function + // * force: keep compiling on error + // * env: the Environment to use (gets extensions and async filters from it) + // * include: which file/folders to include (folders are auto-included, files are auto-excluded) + // * exclude: which file/folders to exclude (folders are auto-included, files are auto-excluded) + // * wrapper: function(templates, opts) {...} + // Customize the output format to store the compiled template. + // By default, templates are stored in a global variable used by the runtime. + // A custom loader will be necessary to load your custom wrapper. + opts = opts || {}; + var env = opts.env || new Environment([]); + var wrapper = opts.wrapper || precompileGlobal; + + if (opts.isString) { + return precompileString(input, opts); + } + + var pathStats = fs.existsSync(input) && fs.statSync(input); + var precompiled = []; + var templates = []; + + function addTemplates(dir) { + fs.readdirSync(dir).forEach(function (file) { + var filepath = path.join(dir, file); + var subpath = filepath.substr(path.join(input, '/').length); + var stat = fs.statSync(filepath); + + if (stat && stat.isDirectory()) { + subpath += '/'; + + if (!match(subpath, opts.exclude)) { + addTemplates(filepath); + } + } else if (match(subpath, opts.include)) { + templates.push(filepath); + } + }); + } + + if (pathStats.isFile()) { + precompiled.push(_precompile(fs.readFileSync(input, 'utf-8'), opts.name || input, env)); + } else if (pathStats.isDirectory()) { + addTemplates(input); + + for (var i = 0; i < templates.length; i++) { + var name = templates[i].replace(path.join(input, '/'), ''); + + try { + precompiled.push(_precompile(fs.readFileSync(templates[i], 'utf-8'), name, env)); + } catch (e) { + if (opts.force) { + // Don't stop generating the output if we're + // forcing compilation. + console.error(e); // eslint-disable-line no-console + } else { + throw e; + } + } + } + } + + return wrapper(precompiled, opts); +} + +function _precompile(str, name, env) { + env = env || new Environment([]); + var asyncFilters = env.asyncFilters; + var extensions = env.extensionsList; + var template; + name = name.replace(/\\/g, '/'); + + try { + template = compiler.compile(str, asyncFilters, extensions, name, env.opts); + } catch (err) { + throw _prettifyError(name, false, err); + } + + return { + name: name, + template: template + }; +} + +module.exports = { + precompile: precompile, + precompileString: precompileString +}; + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + + +function precompileGlobal(templates, opts) { + var out = ''; + opts = opts || {}; + + for (var i = 0; i < templates.length; i++) { + var name = JSON.stringify(templates[i].name); + var template = templates[i].template; + out += '(function() {' + '(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' + '[' + name + '] = (function() {\n' + template + '\n})();\n'; + + if (opts.asFunction) { + out += 'return function(ctx, cb) { return nunjucks.render(' + name + ', ctx, cb); }\n'; + } + + out += '})();\n'; + } + + return out; +} + +module.exports = precompileGlobal; + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +function installCompat() { + /* eslint-disable camelcase */ + // This must be called like `nunjucks.installCompat` so that `this` + // references the nunjucks instance + + var runtime = this.runtime; + var lib = this.lib; // Handle slim case where these 'modules' are excluded from the built source + + var Compiler = this.compiler.Compiler; + var Parser = this.parser.Parser; + var nodes = this.nodes; + var lexer = this.lexer; + var orig_contextOrFrameLookup = runtime.contextOrFrameLookup; + var orig_memberLookup = runtime.memberLookup; + var orig_Compiler_assertType; + var orig_Parser_parseAggregate; + + if (Compiler) { + orig_Compiler_assertType = Compiler.prototype.assertType; + } + + if (Parser) { + orig_Parser_parseAggregate = Parser.prototype.parseAggregate; + } + + function uninstall() { + runtime.contextOrFrameLookup = orig_contextOrFrameLookup; + runtime.memberLookup = orig_memberLookup; + + if (Compiler) { + Compiler.prototype.assertType = orig_Compiler_assertType; + } + + if (Parser) { + Parser.prototype.parseAggregate = orig_Parser_parseAggregate; + } + } + + runtime.contextOrFrameLookup = function contextOrFrameLookup(context, frame, key) { + var val = orig_contextOrFrameLookup.apply(this, arguments); + + if (val !== undefined) { + return val; + } + + switch (key) { + case 'True': + return true; + + case 'False': + return false; + + case 'None': + return null; + + default: + return undefined; + } + }; + + function getTokensState(tokens) { + return { + index: tokens.index, + lineno: tokens.lineno, + colno: tokens.colno + }; + } + + if (nodes && Compiler && Parser) { + // i.e., not slim mode + var Slice = nodes.Node.extend('Slice', { + fields: ['start', 'stop', 'step'], + init: function init(lineno, colno, start, stop, step) { + start = start || new nodes.Literal(lineno, colno, null); + stop = stop || new nodes.Literal(lineno, colno, null); + step = step || new nodes.Literal(lineno, colno, 1); + this.parent(lineno, colno, start, stop, step); + } + }); + + Compiler.prototype.assertType = function assertType(node) { + if (node instanceof Slice) { + return; + } + + orig_Compiler_assertType.apply(this, arguments); + }; + + Compiler.prototype.compileSlice = function compileSlice(node, frame) { + this._emit('('); + + this._compileExpression(node.start, frame); + + this._emit('),('); + + this._compileExpression(node.stop, frame); + + this._emit('),('); + + this._compileExpression(node.step, frame); + + this._emit(')'); + }; + + Parser.prototype.parseAggregate = function parseAggregate() { + var _this = this; + + var origState = getTokensState(this.tokens); // Set back one accounting for opening bracket/parens + + origState.colno--; + origState.index--; + + try { + return orig_Parser_parseAggregate.apply(this); + } catch (e) { + var errState = getTokensState(this.tokens); + + var rethrow = function rethrow() { + lib._assign(_this.tokens, errState); + + return e; + }; // Reset to state before original parseAggregate called + + + lib._assign(this.tokens, origState); + + this.peeked = false; + var tok = this.peekToken(); + + if (tok.type !== lexer.TOKEN_LEFT_BRACKET) { + throw rethrow(); + } else { + this.nextToken(); + } + + var node = new Slice(tok.lineno, tok.colno); // If we don't encounter a colon while parsing, this is not a slice, + // so re-raise the original exception. + + var isSlice = false; + + for (var i = 0; i <= node.fields.length; i++) { + if (this.skip(lexer.TOKEN_RIGHT_BRACKET)) { + break; + } + + if (i === node.fields.length) { + if (isSlice) { + this.fail('parseSlice: too many slice components', tok.lineno, tok.colno); + } else { + break; + } + } + + if (this.skip(lexer.TOKEN_COLON)) { + isSlice = true; + } else { + var field = node.fields[i]; + node[field] = this.parseExpression(); + isSlice = this.skip(lexer.TOKEN_COLON) || isSlice; + } + } + + if (!isSlice) { + throw rethrow(); + } + + return new nodes.Array(tok.lineno, tok.colno, [node]); + } + }; + } + + function sliceLookup(obj, start, stop, step) { + obj = obj || []; + + if (start === null) { + start = step < 0 ? obj.length - 1 : 0; + } + + if (stop === null) { + stop = step < 0 ? -1 : obj.length; + } else if (stop < 0) { + stop += obj.length; + } + + if (start < 0) { + start += obj.length; + } + + var results = []; + + for (var i = start;; i += step) { + if (i < 0 || i > obj.length) { + break; + } + + if (step > 0 && i >= stop) { + break; + } + + if (step < 0 && i <= stop) { + break; + } + + results.push(runtime.memberLookup(obj, i)); + } + + return results; + } + + function hasOwnProp(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + } + + var ARRAY_MEMBERS = { + pop: function pop(index) { + if (index === undefined) { + return this.pop(); + } + + if (index >= this.length || index < 0) { + throw new Error('KeyError'); + } + + return this.splice(index, 1); + }, + append: function append(element) { + return this.push(element); + }, + remove: function remove(element) { + for (var i = 0; i < this.length; i++) { + if (this[i] === element) { + return this.splice(i, 1); + } + } + + throw new Error('ValueError'); + }, + count: function count(element) { + var count = 0; + + for (var i = 0; i < this.length; i++) { + if (this[i] === element) { + count++; + } + } + + return count; + }, + index: function index(element) { + var i; + + if ((i = this.indexOf(element)) === -1) { + throw new Error('ValueError'); + } + + return i; + }, + find: function find(element) { + return this.indexOf(element); + }, + insert: function insert(index, elem) { + return this.splice(index, 0, elem); + } + }; + var OBJECT_MEMBERS = { + items: function items() { + return lib._entries(this); + }, + values: function values() { + return lib._values(this); + }, + keys: function keys() { + return lib.keys(this); + }, + get: function get(key, def) { + var output = this[key]; + + if (output === undefined) { + output = def; + } + + return output; + }, + has_key: function has_key(key) { + return hasOwnProp(this, key); + }, + pop: function pop(key, def) { + var output = this[key]; + + if (output === undefined && def !== undefined) { + output = def; + } else if (output === undefined) { + throw new Error('KeyError'); + } else { + delete this[key]; + } + + return output; + }, + popitem: function popitem() { + var keys = lib.keys(this); + + if (!keys.length) { + throw new Error('KeyError'); + } + + var k = keys[0]; + var val = this[k]; + delete this[k]; + return [k, val]; + }, + setdefault: function setdefault(key, def) { + if (def === void 0) { + def = null; + } + + if (!(key in this)) { + this[key] = def; + } + + return this[key]; + }, + update: function update(kwargs) { + lib._assign(this, kwargs); + + return null; // Always returns None + } + }; + OBJECT_MEMBERS.iteritems = OBJECT_MEMBERS.items; + OBJECT_MEMBERS.itervalues = OBJECT_MEMBERS.values; + OBJECT_MEMBERS.iterkeys = OBJECT_MEMBERS.keys; + + runtime.memberLookup = function memberLookup(obj, val, autoescape) { + if (arguments.length === 4) { + return sliceLookup.apply(this, arguments); + } + + obj = obj || {}; // If the object is an object, return any of the methods that Python would + // otherwise provide. + + if (lib.isArray(obj) && hasOwnProp(ARRAY_MEMBERS, val)) { + return ARRAY_MEMBERS[val].bind(obj); + } + + if (lib.isObject(obj) && hasOwnProp(OBJECT_MEMBERS, val)) { + return OBJECT_MEMBERS[val].bind(obj); + } + + return orig_memberLookup.apply(this, arguments); + }; + + return uninstall; +} + +module.exports = installCompat; + +/***/ }) +/******/ ]); +}); + +}); + +var nunjucks$1 = /*@__PURE__*/getDefaultExportFromCjs(nunjucks); + +class TemplateLoader { + constructor(path, fsHandler, templateType) { + this.path = path; + this.fsHandler = fsHandler; + this.templateType = templateType; + } + load() { + return __awaiter(this, void 0, void 0, function* () { + let content = yield this.selectTemplate(); + let env = nunjucks$1.configure({ autoescape: false }); + return nunjucks$1.compile(content, env); + }); + } + selectTemplate() { + return __awaiter(this, void 0, void 0, function* () { + let content = this.templateType.defaultTemplate(); + if (this.path !== null && this.path !== "") { + if (!this.path.endsWith(".md")) { + this.path += ".md"; + } + Log.debug(`Loading template content from ${this.path}`); + content = yield this.fsHandler.read(this.path); + } + else { + Log.debug(`Using default ${this.templateType.type()}`); + } + return content; + }); + } +} + +class HeaderTemplateType { + type() { + return "header template"; + } + defaultTemplate() { + return `- **URL:** {{ source_url }} +- **Author:** {{ author }} +- **Tags:** #{{ category }} +- **Date:** [[{{ updated }}]] +--- +`; + } +} +class HighlightTemplateType { + type() { + return "highlight template"; + } + defaultTemplate() { + return `{{ text }} %% highlight_id: {{ id }} %% +{%- if note %} +Note: {{ note }} +{%- endif %} +`; + } +} + +class BaseTemplateRenderer { + constructor(template, handler) { + this.template = template; + this.fsHandler = handler; + } +} +class HeaderTemplateRenderer extends BaseTemplateRenderer { + constructor(template, handler) { + super(template, handler); + } + render(doc) { + return this.template.render(doc); + } + static create(path, handler) { + return __awaiter(this, void 0, void 0, function* () { + let template = yield new TemplateLoader(path, handler, new HeaderTemplateType()).load(); + return new HeaderTemplateRenderer(template, handler); + }); + } +} +class HighlightTemplateRenderer extends BaseTemplateRenderer { + constructor(template, handler) { + super(template, handler); + } + render(highlight) { + let renderedContent = this.template.render(highlight); + if (!renderedContent.includes(`highlight_id: ${highlight.id}`)) { + renderedContent += `%% highlight_id: ${highlight.id} %%\n`; + } + return renderedContent; + } + static create(path, handler) { + return __awaiter(this, void 0, void 0, function* () { + let template = yield new TemplateLoader(path, handler, new HighlightTemplateType()).load(); + return new HighlightTemplateRenderer(template, handler); + }); + } +} + +class FileDoc { + constructor(doc, header, highlight, handler) { + this.doc = doc; + this.headerRenderer = header; + this.highlightRenderer = highlight; + this.fsHandler = handler; + } + createOrUpdate(storagePath) { + return __awaiter(this, void 0, void 0, function* () { + const file = this.fsHandler.normalizePath(this.preparePath(storagePath)); + var content = ''; + if (!(yield this.fsHandler.exists(file))) { + Log.debug(`Document ${file} not found. Will be created`); + content = yield this.headerRenderer.render(this.doc); + } + else { + Log.debug(`Document ${file} found. Loading content and updating highlights`); + content = yield this.fsHandler.read(file); + } + this.doc.highlights.forEach(hl => { + if (!content.includes(`highlight_id: ${hl.id}`)) { + content += `\n${this.highlightRenderer.render(hl)}\n`; + } + }); + yield this.fsHandler.write(file, content); + }); + } + preparePath(storagePath = '') { + if (storagePath.length > 0 && storagePath.slice(-1) !== '/') { + storagePath = storagePath + '/'; + } + return `${storagePath}${this.sanitizeName()}.md`; + } + sanitizeName() { + console.log(`Sanitizing ${this.doc.title}`); + return this.doc.title + .replace(/(http[s]?\:\/\/)/, '') + .replace(/(\?.*)/, '') // Remove query params + .replace(/\./g, '_') + .replace(/[\/\\\:\|]/g, '-'); + } +} + +class TokenManager { + constructor(localStorage) { + this.localStorage = localStorage || window.localStorage; + } + get() { + const token = this.localStorage.getItem('readwise_token'); + if (token === null || token.length == 0) { + return null; + } + return token; + } + upsert(token) { + this.localStorage.setItem('readwise_token', token); + } +} + +class FileSystemHandler { + constructor(vault) { + this.vault = vault; + this.adapter = vault.adapter; + } + normalizePath(path) { + return obsidian.normalizePath(path); + } + read(path) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.adapter.read(path); + }); + } + write(path, data) { + return __awaiter(this, void 0, void 0, function* () { + yield this.adapter.write(path, data); + }); + } + exists(path) { + return __awaiter(this, void 0, void 0, function* () { + return yield this.adapter.exists(path); + }); + } + pluginsDir() { + return this.normalizePath(`${this.vault.configDir}/plugins`); + } +} + +class DateHandler { + constructor(date) { + this.moment = window.moment; + this.date = date; + } + fromNow() { + return this.moment(this.date).fromNow(); + } + format(format) { + return this.moment(this.date).format(format); + } + utc() { + return new DateHandler(this.moment(this.date).utc()); + } +} +class DateFactory { + createHandler(date) { + return new DateHandler(date); + } +} + +class PromiseQueue { + constructor() { + this.tasks = []; + } + addTask(task) { + this.tasks.push(task); + if (this.tasks.length === 1) { + this.handleTask(); + } + } + handleTask() { + return __awaiter(this, void 0, void 0, function* () { + if (this.tasks.length > 0) { + this.tasks[0]().finally(() => { + this.tasks.shift(); + this.handleTask(); + }); + } + }); + } +} + +class AuthorsMapping { + constructor(filename, fsHandler) { + this.filename = filename; + this.fsHandler = fsHandler; + } + initialize() { + return __awaiter(this, void 0, void 0, function* () { + this.path = this.fsHandler.normalizePath(`${this.fsHandler.pluginsDir()}/obsidian-readwise/${this.filename}`); + if (!(yield this.fsHandler.exists(this.path))) { + Log.debug(`Creating authors mapping at ${this.path}`); + yield this.fsHandler.write(this.path, "{}"); + } + }); + } + load() { + return __awaiter(this, void 0, void 0, function* () { + let content = JSON.parse(yield (this.fsHandler.read(this.path))); + return new Map(Object.entries(content)); + }); + } +} + +class ObsidianReadwisePlugin extends obsidian.Plugin { + constructor() { + super(...arguments); + this.state = PluginState.idle; + } + setState(state) { + this.state = state; + this.mode.display(); + } + getState() { + return this.state; + } + onload() { + return __awaiter(this, void 0, void 0, function* () { + this.tokenManager = new TokenManager(); + this.mode = this.app.isMobile ? new MobileMode(this) : new DesktopMode(this); + this.mode.onload(); + this.promiseQueue = new PromiseQueue(); + yield this.loadSettings(); + this.setState(PluginState.idle); + this.addSettingTab(new ObsidianReadwiseSettingsTab(this.app, this)); + this.addCommand({ + id: "sync", + name: "Sync highlights", + callback: () => this.promiseQueue.addTask(() => this.syncReadwise(this.settings.lastUpdate)), + }); + this.authorsMapping = new AuthorsMapping(this.settings.authorsMappingFilename, new FileSystemHandler(this.app.vault)); + yield this.authorsMapping.initialize(); + if (this.settings.syncOnBoot) { + yield this.syncReadwise(this.settings.lastUpdate); + } + if (this.settings.autoSyncInterval > 0) { + const now = new Date(); + const diff = this.settings.autoSyncInterval - (Math.round(((now.getTime() - this.settings.lastUpdate) / 1000) / 3600)); + this.startAutoSync(diff <= 0 && !this.settings.syncOnBoot ? 0 : diff); + } + }); + } + onunload() { + return __awaiter(this, void 0, void 0, function* () { + window.clearTimeout(this.timeoutIdSync); + yield this.saveSettings(); + }); + } + loadSettings() { + return __awaiter(this, void 0, void 0, function* () { + this.settings = ObsidianReadwiseSettingsGenerator.withData(yield this.loadData()); + }); + } + saveSettings() { + return __awaiter(this, void 0, void 0, function* () { + yield this.saveData(this.settings); + }); + } + syncReadwise(since, to) { + return __awaiter(this, void 0, void 0, function* () { + if (!(yield this.initializeApi())) { + return; + } + const documentsResults = yield this.getNewHighlightsInDocuments(since, to); + if (documentsResults.isErr()) { + const error = documentsResults.unwrapErr(); + Log.error({ message: error.message, context: error }); + this.mode.displayError(`Unexpected error: ${error.message}`); + return 0; + } + const documents = documentsResults.unwrap(); + if (documents.length > 0) { + yield this.updateNotes(documents); + } + this.settings.lastUpdate = Date.now(); + yield this.saveSettings(); + this.setState(PluginState.idle); + let message = documents.length > 0 + ? `Readwise: Synced new changes. ${documents.length} files synced` + : `Readwise: Everything up-to-date`; + this.mode.displayMessage(message); + }); + } + getNewHighlightsInDocuments(since, to) { + return __awaiter(this, void 0, void 0, function* () { + this.setState(PluginState.checking); + return yield this.api.getDocumentsWithHighlights(since, to); + }); + } + updateNotes(documents) { + return __awaiter(this, void 0, void 0, function* () { + this.setState(PluginState.syncing); + const handler = new FileSystemHandler(this.app.vault); + const header = yield HeaderTemplateRenderer.create(this.settings.headerTemplatePath, handler); + const highlight = yield HighlightTemplateRenderer.create(this.settings.highlightTemplatePath, handler); + const mapping = yield this.authorsMapping.load(); + documents.forEach(doc => { + if (mapping.has(doc.author)) { + doc.author = mapping.get(doc.author); + } + const fileDoc = new FileDoc(doc, header, highlight, handler); + fileDoc.createOrUpdate(this.settings.highlightStoragePath); + }); + }); + } + initializeApi() { + return __awaiter(this, void 0, void 0, function* () { + let token = this.tokenManager.get(); + if (token === null) { + Log.debug("Starting Modal to ask for token"); + const tokenModal = new ReadwiseApiTokenModal(this.app, this.tokenManager); + yield tokenModal.waitForClose; + token = this.tokenManager.get(); + if (token === null) { + alert("Token was empty or was not provided, please configure it in the settings to sync with Readwise"); + return false; + } + } + this.api = new ReadwiseApi(token, new DateFactory()); + return true; + }); + } + startAutoSync(hours) { + this.timeoutIdSync = window.setTimeout(() => { + this.promiseQueue.addTask(() => this.syncReadwise(this.settings.lastUpdate)); + this.startAutoSync(); + }, (hours !== null && hours !== void 0 ? hours : this.settings.autoSyncInterval) * 3600000); + } + clearAutoSync() { + if (this.timeoutIdSync) { + window.clearTimeout(this.timeoutIdSync); + return true; + } + return false; + } +} +class DesktopMode { + constructor(plugin) { + this.plugin = plugin; + } + onload() { + this.statusBar = new StatusBar(this.plugin.addStatusBarItem(), this.plugin, new DateFactory()); + this.plugin.registerInterval(window.setInterval(() => this.statusBar.display(), 1000)); + } + display() { + this.statusBar.display(); + } + displayMessage(message) { + if (!this.plugin.settings.disableNotifications) { + new obsidian.Notice(message); + } + this.statusBar.displayMessage(message.toLowerCase(), 4 * 1000); + Log.debug(message); + } + displayError(message) { + new obsidian.Notice(message); + this.statusBar.displayMessage(message.toLowerCase(), 0); + Log.debug(message); + } +} +class MobileMode { + constructor(plugin) { + this.plugin = plugin; + } + onload() { + return; + } + display() { + return; + } + displayMessage(message) { + if (!this.plugin.settings.disableNotifications) { + new obsidian.Notice(message); + } + Log.debug(message); + } + displayError(message) { + new obsidian.Notice(message); + Log.debug(message); + } +} + +module.exports = ObsidianReadwisePlugin; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-readwise/manifest.json b/.obsidian/plugins/obsidian-readwise/manifest.json new file mode 100644 index 00000000..a4c869a7 --- /dev/null +++ b/.obsidian/plugins/obsidian-readwise/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "obsidian-readwise", + "name": "Readwise Community", + "version": "0.0.9", + "minAppVersion": "0.11.9", + "description": "Sync Readwise highlights into your notes", + "author": "Rene Hernandez", + "authorUrl": "https://renehernandez.io", + "isDesktopOnly": false +} diff --git a/.obsidian/plugins/readwise-official/main.js b/.obsidian/plugins/readwise-official/main.js new file mode 100644 index 00000000..3ffec8c3 --- /dev/null +++ b/.obsidian/plugins/readwise-official/main.js @@ -0,0 +1,10770 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ROLLUP +if you want to view the source visit the plugins github repository +*/ + +'use strict'; + +var obsidian = require('obsidian'); + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc. + * JZlib is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) + * and contributors of zlib. + */ + +// deno-lint-ignore-file no-this-alias prefer-const + +// Global + +const MAX_BITS$1 = 15; +const D_CODES = 30; +const BL_CODES = 19; + +const LENGTH_CODES = 29; +const LITERALS = 256; +const L_CODES = (LITERALS + 1 + LENGTH_CODES); +const HEAP_SIZE = (2 * L_CODES + 1); + +const END_BLOCK = 256; + +// Bit length codes must not exceed MAX_BL_BITS bits +const MAX_BL_BITS = 7; + +// repeat previous bit length 3-6 times (2 bits of repeat count) +const REP_3_6 = 16; + +// repeat a zero length 3-10 times (3 bits of repeat count) +const REPZ_3_10 = 17; + +// repeat a zero length 11-138 times (7 bits of repeat count) +const REPZ_11_138 = 18; + +// The lengths of the bit length codes are sent in order of decreasing +// probability, to avoid transmitting the lengths for unused bit +// length codes. + +const Buf_size = 8 * 2; + +// JZlib version : "1.0.2" +const Z_DEFAULT_COMPRESSION = -1; + +// compression strategy +const Z_FILTERED = 1; +const Z_HUFFMAN_ONLY = 2; +const Z_DEFAULT_STRATEGY = 0; + +const Z_NO_FLUSH$1 = 0; +const Z_PARTIAL_FLUSH = 1; +const Z_FULL_FLUSH = 3; +const Z_FINISH$1 = 4; + +const Z_OK$1 = 0; +const Z_STREAM_END$1 = 1; +const Z_NEED_DICT$1 = 2; +const Z_STREAM_ERROR$1 = -2; +const Z_DATA_ERROR$1 = -3; +const Z_BUF_ERROR$1 = -5; + +// Tree + +function extractArray(array) { + return flatArray(array.map(([length, value]) => (new Array(length)).fill(value, 0, length))); +} + +function flatArray(array) { + return array.reduce((a, b) => a.concat(Array.isArray(b) ? flatArray(b) : b), []); +} + +// see definition of array dist_code below +const _dist_code = [0, 1, 2, 3].concat(...extractArray([ + [2, 4], [2, 5], [4, 6], [4, 7], [8, 8], [8, 9], [16, 10], [16, 11], [32, 12], [32, 13], [64, 14], [64, 15], [2, 0], [1, 16], + [1, 17], [2, 18], [2, 19], [4, 20], [4, 21], [8, 22], [8, 23], [16, 24], [16, 25], [32, 26], [32, 27], [64, 28], [64, 29] +])); + +function Tree() { + const that = this; + + // dyn_tree; // the dynamic tree + // max_code; // largest code with non zero frequency + // stat_desc; // the corresponding static tree + + // Compute the optimal bit lengths for a tree and update the total bit + // length + // for the current block. + // IN assertion: the fields freq and dad are set, heap[heap_max] and + // above are the tree nodes sorted by increasing frequency. + // OUT assertions: the field len is set to the optimal bit length, the + // array bl_count contains the frequencies for each bit length. + // The length opt_len is updated; static_len is also updated if stree is + // not null. + function gen_bitlen(s) { + const tree = that.dyn_tree; + const stree = that.stat_desc.static_tree; + const extra = that.stat_desc.extra_bits; + const base = that.stat_desc.extra_base; + const max_length = that.stat_desc.max_length; + let h; // heap index + let n, m; // iterate over the tree elements + let bits; // bit length + let xbits; // extra bits + let f; // frequency + let overflow = 0; // number of elements with bit length too large + + for (bits = 0; bits <= MAX_BITS$1; bits++) + s.bl_count[bits] = 0; + + // In a first pass, compute the optimal bit lengths (which may + // overflow in the case of the bit length tree). + tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + // We overwrite tree[n*2+1] which is no longer needed + + if (n > that.max_code) + continue; // not a leaf node + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) + xbits = extra[n - base]; + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (stree) + s.static_len += f * (stree[n * 2 + 1] + xbits); + } + if (overflow === 0) + return; + + // This happens for example on obj2 and pic of the Calgary corpus + // Find the first bit length which could increase: + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) + bits--; + s.bl_count[bits]--; // move one leaf down the tree + s.bl_count[bits + 1] += 2; // move one overflow item as its brother + s.bl_count[max_length]--; + // The brother of the overflow item also moves one step up, + // but this does not affect bl_count[max_length] + overflow -= 2; + } while (overflow > 0); + + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > that.max_code) + continue; + if (tree[m * 2 + 1] != bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + + // Reverse the first len bits of a code, using straightforward code (a + // faster + // method would use a table) + // IN assertion: 1 <= len <= 15 + function bi_reverse(code, // the value to invert + len // its bit length + ) { + let res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + + // Generate the codes for a given tree and bit counts (which need not be + // optimal). + // IN assertion: the array bl_count contains the bit length statistics for + // the given tree and the field len is set for all tree elements. + // OUT assertion: the field code is set for all tree elements of non + // zero code length. + function gen_codes(tree, // the tree to decorate + max_code, // largest code with non zero frequency + bl_count // number of codes at each bit length + ) { + const next_code = []; // next code value for each + // bit length + let code = 0; // running code value + let bits; // bit index + let n; // code index + let len; + + // The distribution counts are first used to generate the code values + // without bit reversal. + for (bits = 1; bits <= MAX_BITS$1; bits++) { + next_code[bits] = code = ((code + bl_count[bits - 1]) << 1); + } + + // Check that the bit counts in bl_count are consistent. The last code + // must be all ones. + // Assert (code + bl_count[MAX_BITS]-1 == (1<= 1; n--) + s.pqdownheap(tree, n); + + // Construct the Huffman tree by repeatedly combining the least two + // frequent nodes. + + node = elems; // next internal node of the tree + do { + // n = node of least frequency + n = s.heap[1]; + s.heap[1] = s.heap[s.heap_len--]; + s.pqdownheap(tree, 1); + m = s.heap[1]; // m = node of next least frequency + + s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency + s.heap[--s.heap_max] = m; + + // Create a new node father of n and m + tree[node * 2] = (tree[n * 2] + tree[m * 2]); + s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node; + + // and insert the new node in the heap + s.heap[1] = node++; + s.pqdownheap(tree, 1); + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1]; + + // At this point, the fields freq and dad are set. We can now + // generate the bit lengths. + + gen_bitlen(s); + + // The field len is now set, we can generate the bit codes + gen_codes(tree, that.max_code, s.bl_count); + }; + +} + +Tree._length_code = [0, 1, 2, 3, 4, 5, 6, 7].concat(...extractArray([ + [2, 8], [2, 9], [2, 10], [2, 11], [4, 12], [4, 13], [4, 14], [4, 15], [8, 16], [8, 17], [8, 18], [8, 19], + [16, 20], [16, 21], [16, 22], [16, 23], [32, 24], [32, 25], [32, 26], [31, 27], [1, 28]])); + +Tree.base_length = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0]; + +Tree.base_dist = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, + 24576]; + +// Mapping from a distance to a distance code. dist is the distance - 1 and +// must not have side effects. _dist_code[256] and _dist_code[257] are never +// used. +Tree.d_code = function (dist) { + return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]); +}; + +// extra bits for each length code +Tree.extra_lbits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]; + +// extra bits for each distance code +Tree.extra_dbits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]; + +// extra bits for each bit length code +Tree.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; + +Tree.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + +// StaticTree + +function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) { + const that = this; + that.static_tree = static_tree; + that.extra_bits = extra_bits; + that.extra_base = extra_base; + that.elems = elems; + that.max_length = max_length; +} + +const static_ltree2_first_part = [12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, + 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, + 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81, + 209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85, + 213, 53, 181, 117, 245, 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 19, 275, 147, 403, 83, 339, 211, 467, 51, 307, + 179, 435, 115, 371, 243, 499, 11, 267, 139, 395, 75, 331, 203, 459, 43, 299, 171, 427, 107, 363, 235, 491, 27, 283, 155, 411, 91, 347, 219, 475, + 59, 315, 187, 443, 123, 379, 251, 507, 7, 263, 135, 391, 71, 327, 199, 455, 39, 295, 167, 423, 103, 359, 231, 487, 23, 279, 151, 407, 87, 343, 215, + 471, 55, 311, 183, 439, 119, 375, 247, 503, 15, 271, 143, 399, 79, 335, 207, 463, 47, 303, 175, 431, 111, 367, 239, 495, 31, 287, 159, 415, 95, + 351, 223, 479, 63, 319, 191, 447, 127, 383, 255, 511, 0, 64, 32, 96, 16, 80, 48, 112, 8, 72, 40, 104, 24, 88, 56, 120, 4, 68, 36, 100, 20, 84, 52, + 116, 3, 131, 67, 195, 35, 163, 99, 227]; +const static_ltree2_second_part = extractArray([[144, 8], [112, 9], [24, 7], [8, 8]]); +StaticTree.static_ltree = flatArray(static_ltree2_first_part.map((value, index) => [value, static_ltree2_second_part[index]])); + +const static_dtree_first_part = [0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, 1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23]; +const static_dtree_second_part = extractArray([[30, 5]]); +StaticTree.static_dtree = flatArray(static_dtree_first_part.map((value, index) => [value, static_dtree_second_part[index]])); + +StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS$1); + +StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS$1); + +StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS); + +// Deflate + +const MAX_MEM_LEVEL = 9; +const DEF_MEM_LEVEL = 8; + +function Config(good_length, max_lazy, nice_length, max_chain, func) { + const that = this; + that.good_length = good_length; + that.max_lazy = max_lazy; + that.nice_length = nice_length; + that.max_chain = max_chain; + that.func = func; +} + +const STORED$1 = 0; +const FAST = 1; +const SLOW = 2; +const config_table = [ + new Config(0, 0, 0, 0, STORED$1), + new Config(4, 4, 8, 4, FAST), + new Config(4, 5, 16, 8, FAST), + new Config(4, 6, 32, 32, FAST), + new Config(4, 4, 16, 16, SLOW), + new Config(8, 16, 32, 32, SLOW), + new Config(8, 16, 128, 128, SLOW), + new Config(8, 32, 128, 256, SLOW), + new Config(32, 128, 258, 1024, SLOW), + new Config(32, 258, 258, 4096, SLOW) +]; + +const z_errmsg = ["need dictionary", // Z_NEED_DICT + // 2 + "stream end", // Z_STREAM_END 1 + "", // Z_OK 0 + "", // Z_ERRNO (-1) + "stream error", // Z_STREAM_ERROR (-2) + "data error", // Z_DATA_ERROR (-3) + "", // Z_MEM_ERROR (-4) + "buffer error", // Z_BUF_ERROR (-5) + "",// Z_VERSION_ERROR (-6) + ""]; + +// block not completed, need more input or more output +const NeedMore = 0; + +// block flush performed +const BlockDone = 1; + +// finish started, need only more output at next deflate +const FinishStarted = 2; + +// finish done, accept no more input or output +const FinishDone = 3; + +// preset dictionary flag in zlib header +const PRESET_DICT$1 = 0x20; + +const INIT_STATE = 42; +const BUSY_STATE = 113; +const FINISH_STATE = 666; + +// The deflate compression method +const Z_DEFLATED$1 = 8; + +const STORED_BLOCK = 0; +const STATIC_TREES = 1; +const DYN_TREES = 2; + +const MIN_MATCH = 3; +const MAX_MATCH = 258; +const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +function smaller(tree, n, m, depth) { + const tn2 = tree[n * 2]; + const tm2 = tree[m * 2]; + return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m])); +} + +function Deflate() { + + const that = this; + let strm; // pointer back to this zlib stream + let status; // as the name implies + // pending_buf; // output still pending + let pending_buf_size; // size of pending_buf + // pending_out; // next pending byte to output to the stream + // pending; // nb of bytes in the pending buffer + + // dist_buf; // buffer for distances + // lc_buf; // buffer for literals or lengths + // To simplify the code, dist_buf and lc_buf have the same number of elements. + // To use different lengths, an extra flag array would be necessary. + + let last_flush; // value of flush param for previous deflate call + + let w_size; // LZ77 win size (32K by default) + let w_bits; // log2(w_size) (8..16) + let w_mask; // w_size - 1 + + let win; + // Sliding win. Input bytes are read into the second half of the win, + // and move to the first half later to keep a dictionary of at least wSize + // bytes. With this organization, matches are limited to a distance of + // wSize-MAX_MATCH bytes, but this ensures that IO is always + // performed with a length multiple of the block size. Also, it limits + // the win size to 64K, which is quite useful on MSDOS. + // To do: use the user input buffer as sliding win. + + let window_size; + // Actual size of win: 2*wSize, except when the user input buffer + // is directly used as sliding win. + + let prev; + // Link to older string with same hash index. To limit the size of this + // array to 64K, this link is maintained only for the last 32K strings. + // An index in this array is thus a win index modulo 32K. + + let head; // Heads of the hash chains or NIL. + + let ins_h; // hash index of string to be inserted + let hash_size; // number of elements in hash table + let hash_bits; // log2(hash_size) + let hash_mask; // hash_size-1 + + // Number of bits by which ins_h must be shifted at each input + // step. It must be such that after MIN_MATCH steps, the oldest + // byte no longer takes part in the hash key, that is: + // hash_shift * MIN_MATCH >= hash_bits + let hash_shift; + + // Window position at the beginning of the current output block. Gets + // negative when the win is moved backwards. + + let block_start; + + let match_length; // length of best match + let prev_match; // previous match + let match_available; // set if previous match exists + let strstart; // start of string to insert + let match_start; // start of matching string + let lookahead; // number of valid bytes ahead in win + + // Length of the best match at previous step. Matches not greater than this + // are discarded. This is used in the lazy match evaluation. + let prev_length; + + // To speed up deflation, hash chains are never searched beyond this + // length. A higher limit improves compression ratio but degrades the speed. + let max_chain_length; + + // Attempt to find a better match only when the current match is strictly + // smaller than this value. This mechanism is used only for compression + // levels >= 4. + let max_lazy_match; + + // Insert new strings in the hash table only if the match length is not + // greater than this length. This saves time but degrades compression. + // max_insert_length is used only for compression levels <= 3. + + let level; // compression level (1..9) + let strategy; // favor or force Huffman coding + + // Use a faster search when the previous match is longer than this + let good_match; + + // Stop searching when current match exceeds this + let nice_match; + + let dyn_ltree; // literal and length tree + let dyn_dtree; // distance tree + let bl_tree; // Huffman tree for bit lengths + + const l_desc = new Tree(); // desc for literal tree + const d_desc = new Tree(); // desc for distance tree + const bl_desc = new Tree(); // desc for bit length tree + + // that.heap_len; // number of elements in the heap + // that.heap_max; // element of largest frequency + // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + // The same heap array is used to build all trees. + + // Depth of each subtree used as tie breaker for trees of equal frequency + that.depth = []; + + // Size of match buffer for literals/lengths. There are 4 reasons for + // limiting lit_bufsize to 64K: + // - frequencies can be kept in 16 bit counters + // - if compression is not successful for the first block, all input + // data is still in the win so we can still emit a stored block even + // when input comes from standard input. (This can also be done for + // all blocks if lit_bufsize is not greater than 32K.) + // - if compression is not successful for a file smaller than 64K, we can + // even emit a stored file instead of a stored block (saving 5 bytes). + // This is applicable only for zip (not gzip or zlib). + // - creating new Huffman trees less frequently may not provide fast + // adaptation to changes in the input data statistics. (Take for + // example a binary file with poorly compressible code followed by + // a highly compressible string table.) Smaller buffer sizes give + // fast adaptation but have of course the overhead of transmitting + // trees more frequently. + // - I can't count above 4 + let lit_bufsize; + + let last_lit; // running index in dist_buf and lc_buf + + // that.opt_len; // bit length of current block with optimal trees + // that.static_len; // bit length of current block with static trees + let matches; // number of string matches in current block + let last_eob_len; // bit length of EOB code for last block + + // Output buffer. bits are inserted starting at the bottom (least + // significant bits). + let bi_buf; + + // Number of valid bits in bi_buf. All bits above the last valid bit + // are always zero. + let bi_valid; + + // number of codes at each bit length for an optimal tree + that.bl_count = []; + + // heap used to build the Huffman trees + that.heap = []; + + dyn_ltree = []; + dyn_dtree = []; + bl_tree = []; + + function lm_init() { + window_size = 2 * w_size; + + head[hash_size - 1] = 0; + for (let i = 0; i < hash_size - 1; i++) { + head[i] = 0; + } + + // Set the default configuration parameters: + max_lazy_match = config_table[level].max_lazy; + good_match = config_table[level].good_length; + nice_match = config_table[level].nice_length; + max_chain_length = config_table[level].max_chain; + + strstart = 0; + block_start = 0; + lookahead = 0; + match_length = prev_length = MIN_MATCH - 1; + match_available = 0; + ins_h = 0; + } + + function init_block() { + let i; + // Initialize the trees. + for (i = 0; i < L_CODES; i++) + dyn_ltree[i * 2] = 0; + for (i = 0; i < D_CODES; i++) + dyn_dtree[i * 2] = 0; + for (i = 0; i < BL_CODES; i++) + bl_tree[i * 2] = 0; + + dyn_ltree[END_BLOCK * 2] = 1; + that.opt_len = that.static_len = 0; + last_lit = matches = 0; + } + + // Initialize the tree data structures for a new zlib stream. + function tr_init() { + + l_desc.dyn_tree = dyn_ltree; + l_desc.stat_desc = StaticTree.static_l_desc; + + d_desc.dyn_tree = dyn_dtree; + d_desc.stat_desc = StaticTree.static_d_desc; + + bl_desc.dyn_tree = bl_tree; + bl_desc.stat_desc = StaticTree.static_bl_desc; + + bi_buf = 0; + bi_valid = 0; + last_eob_len = 8; // enough lookahead for inflate + + // Initialize the first block of the first file: + init_block(); + } + + // Restore the heap property by moving down the tree starting at node k, + // exchanging a node with the smallest of its two sons if necessary, + // stopping + // when the heap property is re-established (each father smaller than its + // two sons). + that.pqdownheap = function (tree, // the tree to restore + k // node to move down + ) { + const heap = that.heap; + const v = heap[k]; + let j = k << 1; // left son of k + while (j <= that.heap_len) { + // Set j to the smallest of the two sons: + if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) { + j++; + } + // Exit if v is smaller than both sons + if (smaller(tree, v, heap[j], that.depth)) + break; + + // Exchange v with the smallest son + heap[k] = heap[j]; + k = j; + // And continue down the tree, setting j to the left son of k + j <<= 1; + } + heap[k] = v; + }; + + // Scan a literal or distance tree to determine the frequencies of the codes + // in the bit length tree. + function scan_tree(tree,// the tree to be scanned + max_code // and its largest code of non zero frequency + ) { + let prevlen = -1; // last emitted length + let curlen; // length of current code + let nextlen = tree[0 * 2 + 1]; // length of next code + let count = 0; // repeat count of the current code + let max_count = 7; // max repeat count + let min_count = 4; // min repeat count + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 0xffff; // guard + + for (let n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + bl_tree[curlen * 2] += count; + } else if (curlen !== 0) { + if (curlen != prevlen) + bl_tree[curlen * 2]++; + bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) { + bl_tree[REPZ_3_10 * 2]++; + } else { + bl_tree[REPZ_11_138 * 2]++; + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen == nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + + // Construct the Huffman tree for the bit lengths and return the index in + // bl_order of the last bit length code to send. + function build_bl_tree() { + let max_blindex; // index of last bit length code of non zero freq + + // Determine the bit length frequencies for literal and distance trees + scan_tree(dyn_ltree, l_desc.max_code); + scan_tree(dyn_dtree, d_desc.max_code); + + // Build the bit length tree: + bl_desc.build_tree(that); + // opt_len now includes the length of the tree representations, except + // the lengths of the bit lengths codes and the 5+5+4 bits for the + // counts. + + // Determine the number of bit length codes to send. The pkzip format + // requires that at least 4 bit length codes be sent. (appnote.txt says + // 3 but the actual value used is 4.) + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0) + break; + } + // Update opt_len to include the bit length tree and counts + that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + + return max_blindex; + } + + // Output a byte on the stream. + // IN assertion: there is enough room in pending_buf. + function put_byte(p) { + that.pending_buf[that.pending++] = p; + } + + function put_short(w) { + put_byte(w & 0xff); + put_byte((w >>> 8) & 0xff); + } + + function putShortMSB(b) { + put_byte((b >> 8) & 0xff); + put_byte((b & 0xff) & 0xff); + } + + function send_bits(value, length) { + let val; + const len = length; + if (bi_valid > Buf_size - len) { + val = value; + // bi_buf |= (val << bi_valid); + bi_buf |= ((val << bi_valid) & 0xffff); + put_short(bi_buf); + bi_buf = val >>> (Buf_size - bi_valid); + bi_valid += len - Buf_size; + } else { + // bi_buf |= (value) << bi_valid; + bi_buf |= (((value) << bi_valid) & 0xffff); + bi_valid += len; + } + } + + function send_code(c, tree) { + const c2 = c * 2; + send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff); + } + + // Send a literal or distance tree in compressed form, using the codes in + // bl_tree. + function send_tree(tree,// the tree to be sent + max_code // and its largest code of non zero frequency + ) { + let n; // iterates over all tree elements + let prevlen = -1; // last emitted length + let curlen; // length of current code + let nextlen = tree[0 * 2 + 1]; // length of next code + let count = 0; // repeat count of the current code + let max_count = 7; // max repeat count + let min_count = 4; // min repeat count + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(curlen, bl_tree); + } while (--count !== 0); + } else if (curlen !== 0) { + if (curlen != prevlen) { + send_code(curlen, bl_tree); + count--; + } + send_code(REP_3_6, bl_tree); + send_bits(count - 3, 2); + } else if (count <= 10) { + send_code(REPZ_3_10, bl_tree); + send_bits(count - 3, 3); + } else { + send_code(REPZ_11_138, bl_tree); + send_bits(count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen == nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + + // Send the header for a block using dynamic Huffman trees: the counts, the + // lengths of the bit length codes, the literal tree and the distance tree. + // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + function send_all_trees(lcodes, dcodes, blcodes) { + let rank; // index in bl_order + + send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt + send_bits(dcodes - 1, 5); + send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt + for (rank = 0; rank < blcodes; rank++) { + send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3); + } + send_tree(dyn_ltree, lcodes - 1); // literal tree + send_tree(dyn_dtree, dcodes - 1); // distance tree + } + + // Flush the bit buffer, keeping at most 7 bits in it. + function bi_flush() { + if (bi_valid == 16) { + put_short(bi_buf); + bi_buf = 0; + bi_valid = 0; + } else if (bi_valid >= 8) { + put_byte(bi_buf & 0xff); + bi_buf >>>= 8; + bi_valid -= 8; + } + } + + // Send one empty static block to give enough lookahead for inflate. + // This takes 10 bits, of which 7 may remain in the bit buffer. + // The current inflate code requires 9 bits of lookahead. If the + // last two codes for the previous block (real code plus EOB) were coded + // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode + // the last real code. In this case we send two empty static blocks instead + // of one. (There are no problems if the previous block is stored or fixed.) + // To simplify the code, we assume the worst case of last real code encoded + // on one bit only. + function _tr_align() { + send_bits(STATIC_TREES << 1, 3); + send_code(END_BLOCK, StaticTree.static_ltree); + + bi_flush(); + + // Of the 10 bits for the empty block, we have already sent + // (10 - bi_valid) bits. The lookahead for the last real code (before + // the EOB of the previous block) was thus at least one plus the length + // of the EOB plus what we have just sent of the empty static block. + if (1 + last_eob_len + 10 - bi_valid < 9) { + send_bits(STATIC_TREES << 1, 3); + send_code(END_BLOCK, StaticTree.static_ltree); + bi_flush(); + } + last_eob_len = 7; + } + + // Save the match info and tally the frequency counts. Return true if + // the current block must be flushed. + function _tr_tally(dist, // distance of matched string + lc // match length-MIN_MATCH or unmatched char (if dist==0) + ) { + let out_length, in_length, dcode; + that.dist_buf[last_lit] = dist; + that.lc_buf[last_lit] = lc & 0xff; + last_lit++; + + if (dist === 0) { + // lc is the unmatched char + dyn_ltree[lc * 2]++; + } else { + matches++; + // Here, lc is the match length - MIN_MATCH + dist--; // dist = match distance - 1 + dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++; + dyn_dtree[Tree.d_code(dist) * 2]++; + } + + if ((last_lit & 0x1fff) === 0 && level > 2) { + // Compute an upper bound for the compressed length + out_length = last_lit * 8; + in_length = strstart - block_start; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]); + } + out_length >>>= 3; + if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2)) + return true; + } + + return (last_lit == lit_bufsize - 1); + // We avoid equality with lit_bufsize because of wraparound at 64K + // on 16 bit machines and because stored blocks are restricted to + // 64K-1 bytes. + } + + // Send the block data compressed using the given Huffman trees + function compress_block(ltree, dtree) { + let dist; // distance of matched string + let lc; // match length or unmatched char (if dist === 0) + let lx = 0; // running index in dist_buf and lc_buf + let code; // the code to send + let extra; // number of extra bits to send + + if (last_lit !== 0) { + do { + dist = that.dist_buf[lx]; + lc = that.lc_buf[lx]; + lx++; + + if (dist === 0) { + send_code(lc, ltree); // send a literal byte + } else { + // Here, lc is the match length - MIN_MATCH + code = Tree._length_code[lc]; + + send_code(code + LITERALS + 1, ltree); // send the length + // code + extra = Tree.extra_lbits[code]; + if (extra !== 0) { + lc -= Tree.base_length[code]; + send_bits(lc, extra); // send the extra length bits + } + dist--; // dist is now the match distance - 1 + code = Tree.d_code(dist); + + send_code(code, dtree); // send the distance code + extra = Tree.extra_dbits[code]; + if (extra !== 0) { + dist -= Tree.base_dist[code]; + send_bits(dist, extra); // send the extra distance bits + } + } // literal or match pair ? + } while (lx < last_lit); + } + + send_code(END_BLOCK, ltree); + last_eob_len = ltree[END_BLOCK * 2 + 1]; + } + + // Flush the bit buffer and align the output on a byte boundary + function bi_windup() { + if (bi_valid > 8) { + put_short(bi_buf); + } else if (bi_valid > 0) { + put_byte(bi_buf & 0xff); + } + bi_buf = 0; + bi_valid = 0; + } + + // Copy a stored block, storing first the length and its + // one's complement if requested. + function copy_block(buf, // the input data + len, // its length + header // true if block header must be written + ) { + bi_windup(); // align on byte boundary + last_eob_len = 8; // enough lookahead for inflate + + if (header) { + put_short(len); + put_short(~len); + } + + that.pending_buf.set(win.subarray(buf, buf + len), that.pending); + that.pending += len; + } + + // Send a stored block + function _tr_stored_block(buf, // input block + stored_len, // length of input block + eof // true if this is the last block for a file + ) { + send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type + copy_block(buf, stored_len, true); // with header + } + + // Determine the best encoding for the current block: dynamic trees, static + // trees or store, and output the encoded block to the zip file. + function _tr_flush_block(buf, // input block, or NULL if too old + stored_len, // length of input block + eof // true if this is the last block for a file + ) { + let opt_lenb, static_lenb;// opt_len and static_len in bytes + let max_blindex = 0; // index of last bit length code of non zero freq + + // Build the Huffman trees unless a stored block is forced + if (level > 0) { + // Construct the literal and distance trees + l_desc.build_tree(that); + + d_desc.build_tree(that); + + // At this point, opt_len and static_len are the total bit lengths + // of + // the compressed block data, excluding the tree representations. + + // Build the bit length tree for the above two trees, and get the + // index + // in bl_order of the last bit length code to send. + max_blindex = build_bl_tree(); + + // Determine the best encoding. Compute first the block length in + // bytes + opt_lenb = (that.opt_len + 3 + 7) >>> 3; + static_lenb = (that.static_len + 3 + 7) >>> 3; + + if (static_lenb <= opt_lenb) + opt_lenb = static_lenb; + } else { + opt_lenb = static_lenb = stored_len + 5; // force a stored block + } + + if ((stored_len + 4 <= opt_lenb) && buf != -1) { + // 4: two words for the lengths + // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + // Otherwise we can't have processed more than WSIZE input bytes + // since + // the last block flush, because compression would have been + // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + // transform a block into a stored block. + _tr_stored_block(buf, stored_len, eof); + } else if (static_lenb == opt_lenb) { + send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3); + compress_block(StaticTree.static_ltree, StaticTree.static_dtree); + } else { + send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3); + send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1); + compress_block(dyn_ltree, dyn_dtree); + } + + // The above check is made mod 2^32, for files larger than 512 MB + // and uLong implemented on 32 bits. + + init_block(); + + if (eof) { + bi_windup(); + } + } + + function flush_block_only(eof) { + _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof); + block_start = strstart; + strm.flush_pending(); + } + + // Fill the win when the lookahead becomes insufficient. + // Updates strstart and lookahead. + // + // IN assertion: lookahead < MIN_LOOKAHEAD + // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + // At least one byte has been read, or avail_in === 0; reads are + // performed for at least two bytes (required for the zip translate_eol + // option -- not supported here). + function fill_window() { + let n, m; + let p; + let more; // Amount of free space at the end of the win. + + do { + more = (window_size - lookahead - strstart); + + // Deal with !@#$% 64K limit: + if (more === 0 && strstart === 0 && lookahead === 0) { + more = w_size; + } else if (more == -1) { + // Very unlikely, but possible on 16 bit machine if strstart == + // 0 + // and lookahead == 1 (input done one byte at time) + more--; + + // If the win is almost full and there is insufficient + // lookahead, + // move the upper half to the lower one to make room in the + // upper half. + } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) { + win.set(win.subarray(w_size, w_size + w_size), 0); + + match_start -= w_size; + strstart -= w_size; // we now have strstart >= MAX_DIST + block_start -= w_size; + + // Slide the hash table (could be avoided with 32 bit values + // at the expense of memory usage). We slide even when level == + // 0 + // to keep the hash table consistent if we switch back to level + // > 0 + // later. (Using level 0 permanently is not an optimal usage of + // zlib, so we don't care about this pathological case.) + + n = hash_size; + p = n; + do { + m = (head[--p] & 0xffff); + head[p] = (m >= w_size ? m - w_size : 0); + } while (--n !== 0); + + n = w_size; + p = n; + do { + m = (prev[--p] & 0xffff); + prev[p] = (m >= w_size ? m - w_size : 0); + // If n is not on any hash chain, prev[n] is garbage but + // its value will never be used. + } while (--n !== 0); + more += w_size; + } + + if (strm.avail_in === 0) + return; + + // If there was no sliding: + // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + // more == window_size - lookahead - strstart + // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + // => more >= window_size - 2*WSIZE + 2 + // In the BIG_MEM or MMAP case (not yet supported), + // window_size == input_size + MIN_LOOKAHEAD && + // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + // Otherwise, window_size == 2*WSIZE so more >= 2. + // If there was sliding, more >= WSIZE. So in all cases, more >= 2. + + n = strm.read_buf(win, strstart + lookahead, more); + lookahead += n; + + // Initialize the hash value now that we have some input: + if (lookahead >= MIN_MATCH) { + ins_h = win[strstart] & 0xff; + ins_h = (((ins_h) << hash_shift) ^ (win[strstart + 1] & 0xff)) & hash_mask; + } + // If the whole input has less than MIN_MATCH bytes, ins_h is + // garbage, + // but this is not important since only literal bytes will be + // emitted. + } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0); + } + + // Copy without compression as much as possible from the input stream, + // return + // the current block state. + // This function does not insert new strings in the dictionary since + // uncompressible data is probably not useful. This function is used + // only for the level=0 compression option. + // NOTE: this function should be optimized to avoid extra copying from + // win to pending_buf. + function deflate_stored(flush) { + // Stored blocks are limited to 0xffff bytes, pending_buf is limited + // to pending_buf_size, and each stored block has a 5 byte header: + + let max_block_size = 0xffff; + let max_start; + + if (max_block_size > pending_buf_size - 5) { + max_block_size = pending_buf_size - 5; + } + + // Copy as much as possible from input to output: + // eslint-disable-next-line no-constant-condition + while (true) { + // Fill the win as much as possible: + if (lookahead <= 1) { + fill_window(); + if (lookahead === 0 && flush == Z_NO_FLUSH$1) + return NeedMore; + if (lookahead === 0) + break; // flush the current block + } + + strstart += lookahead; + lookahead = 0; + + // Emit a stored block if pending_buf will be full: + max_start = block_start + max_block_size; + if (strstart === 0 || strstart >= max_start) { + // strstart === 0 is possible when wraparound on 16-bit machine + lookahead = (strstart - max_start); + strstart = max_start; + + flush_block_only(false); + if (strm.avail_out === 0) + return NeedMore; + + } + + // Flush if we may have to slide, otherwise block_start may become + // negative and the data will be gone: + if (strstart - block_start >= w_size - MIN_LOOKAHEAD) { + flush_block_only(false); + if (strm.avail_out === 0) + return NeedMore; + } + } + + flush_block_only(flush == Z_FINISH$1); + if (strm.avail_out === 0) + return (flush == Z_FINISH$1) ? FinishStarted : NeedMore; + + return flush == Z_FINISH$1 ? FinishDone : BlockDone; + } + + function longest_match(cur_match) { + let chain_length = max_chain_length; // max hash chain length + let scan = strstart; // current string + let match; // matched string + let len; // length of current match + let best_len = prev_length; // best match length so far + const limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0; + let _nice_match = nice_match; + + // Stop when cur_match becomes <= limit. To simplify the code, + // we prevent matches with the string of win index 0. + + const wmask = w_mask; + + const strend = strstart + MAX_MATCH; + let scan_end1 = win[scan + best_len - 1]; + let scan_end = win[scan + best_len]; + + // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of + // 16. + // It is easy to get rid of this optimization if necessary. + + // Do not waste too much time if we already have a good match: + if (prev_length >= good_match) { + chain_length >>= 2; + } + + // Do not look for matches beyond the end of the input. This is + // necessary + // to make deflate deterministic. + if (_nice_match > lookahead) + _nice_match = lookahead; + + do { + match = cur_match; + + // Skip to next match if the match length cannot increase + // or if the match length is less than 2: + if (win[match + best_len] != scan_end || win[match + best_len - 1] != scan_end1 || win[match] != win[scan] + || win[++match] != win[scan + 1]) + continue; + + // The check at best_len-1 can be removed because it will be made + // again later. (This heuristic is not always a win.) + // It is not necessary to compare scan[2] and match[2] since they + // are always equal when the other bytes match, given that + // the hash keys are equal and that HASH_BITS >= 8. + scan += 2; + match++; + + // We check for insufficient lookahead only every 8th comparison; + // the 256th check will be made at strstart+258. + // eslint-disable-next-line no-empty + do { + // empty block + } while (win[++scan] == win[++match] && win[++scan] == win[++match] && win[++scan] == win[++match] + && win[++scan] == win[++match] && win[++scan] == win[++match] && win[++scan] == win[++match] + && win[++scan] == win[++match] && win[++scan] == win[++match] && scan < strend); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + match_start = cur_match; + best_len = len; + if (len >= _nice_match) + break; + scan_end1 = win[scan + best_len - 1]; + scan_end = win[scan + best_len]; + } + + } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0); + + if (best_len <= lookahead) + return best_len; + return lookahead; + } + + // Compress as much as possible from the input stream, return the current + // block state. + // This function does not perform lazy evaluation of matches and inserts + // new strings in the dictionary only for unmatched strings or for short + // matches. It is used only for the fast compression options. + function deflate_fast(flush) { + // short hash_head = 0; // head of the hash chain + let hash_head = 0; // head of the hash chain + let bflush; // set if current block must be flushed + + // eslint-disable-next-line no-constant-condition + while (true) { + // Make sure that we always have enough lookahead, except + // at the end of the input file. We need MAX_MATCH bytes + // for the next match, plus MIN_MATCH bytes to insert the + // string following the next match. + if (lookahead < MIN_LOOKAHEAD) { + fill_window(); + if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH$1) { + return NeedMore; + } + if (lookahead === 0) + break; // flush the current block + } + + // Insert the string win[strstart .. strstart+2] in the + // dictionary, and set hash_head to the head of the hash chain: + if (lookahead >= MIN_MATCH) { + ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; + + // prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head = (head[ins_h] & 0xffff); + prev[strstart & w_mask] = head[ins_h]; + head[ins_h] = strstart; + } + + // Find the longest match, discarding those <= prev_length. + // At this point we have always match_length < MIN_MATCH + + if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) { + // To simplify the code, we prevent matches with the string + // of win index 0 (in particular we have to avoid a match + // of the string with itself at the start of the input file). + if (strategy != Z_HUFFMAN_ONLY) { + match_length = longest_match(hash_head); + } + // longest_match() sets match_start + } + if (match_length >= MIN_MATCH) { + // check_match(strstart, match_start, match_length); + + bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH); + + lookahead -= match_length; + + // Insert new strings in the hash table only if the match length + // is not too large. This saves time but degrades compression. + if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) { + match_length--; // string at strstart already in hash table + do { + strstart++; + + ins_h = ((ins_h << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; + // prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head = (head[ins_h] & 0xffff); + prev[strstart & w_mask] = head[ins_h]; + head[ins_h] = strstart; + + // strstart never exceeds WSIZE-MAX_MATCH, so there are + // always MIN_MATCH bytes ahead. + } while (--match_length !== 0); + strstart++; + } else { + strstart += match_length; + match_length = 0; + ins_h = win[strstart] & 0xff; + + ins_h = (((ins_h) << hash_shift) ^ (win[strstart + 1] & 0xff)) & hash_mask; + // If lookahead < MIN_MATCH, ins_h is garbage, but it does + // not + // matter since it will be recomputed at next deflate call. + } + } else { + // No match, output a literal byte + + bflush = _tr_tally(0, win[strstart] & 0xff); + lookahead--; + strstart++; + } + if (bflush) { + + flush_block_only(false); + if (strm.avail_out === 0) + return NeedMore; + } + } + + flush_block_only(flush == Z_FINISH$1); + if (strm.avail_out === 0) { + if (flush == Z_FINISH$1) + return FinishStarted; + else + return NeedMore; + } + return flush == Z_FINISH$1 ? FinishDone : BlockDone; + } + + // Same as above, but achieves better compression. We use a lazy + // evaluation for matches: a match is finally adopted only if there is + // no better match at the next win position. + function deflate_slow(flush) { + // short hash_head = 0; // head of hash chain + let hash_head = 0; // head of hash chain + let bflush; // set if current block must be flushed + let max_insert; + + // Process the input block. + // eslint-disable-next-line no-constant-condition + while (true) { + // Make sure that we always have enough lookahead, except + // at the end of the input file. We need MAX_MATCH bytes + // for the next match, plus MIN_MATCH bytes to insert the + // string following the next match. + + if (lookahead < MIN_LOOKAHEAD) { + fill_window(); + if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH$1) { + return NeedMore; + } + if (lookahead === 0) + break; // flush the current block + } + + // Insert the string win[strstart .. strstart+2] in the + // dictionary, and set hash_head to the head of the hash chain: + + if (lookahead >= MIN_MATCH) { + ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; + // prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head = (head[ins_h] & 0xffff); + prev[strstart & w_mask] = head[ins_h]; + head[ins_h] = strstart; + } + + // Find the longest match, discarding those <= prev_length. + prev_length = match_length; + prev_match = match_start; + match_length = MIN_MATCH - 1; + + if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) { + // To simplify the code, we prevent matches with the string + // of win index 0 (in particular we have to avoid a match + // of the string with itself at the start of the input file). + + if (strategy != Z_HUFFMAN_ONLY) { + match_length = longest_match(hash_head); + } + // longest_match() sets match_start + + if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) { + + // If prev_match is also MIN_MATCH, match_start is garbage + // but we will ignore the current match anyway. + match_length = MIN_MATCH - 1; + } + } + + // If there was a match at the previous step and the current + // match is not better, output the previous match: + if (prev_length >= MIN_MATCH && match_length <= prev_length) { + max_insert = strstart + lookahead - MIN_MATCH; + // Do not insert strings in hash table beyond this. + + // check_match(strstart-1, prev_match, prev_length); + + bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH); + + // Insert in hash table all strings up to the end of the match. + // strstart-1 and strstart are already inserted. If there is not + // enough lookahead, the last two strings are not inserted in + // the hash table. + lookahead -= prev_length - 1; + prev_length -= 2; + do { + if (++strstart <= max_insert) { + ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; + // prev[strstart&w_mask]=hash_head=head[ins_h]; + hash_head = (head[ins_h] & 0xffff); + prev[strstart & w_mask] = head[ins_h]; + head[ins_h] = strstart; + } + } while (--prev_length !== 0); + match_available = 0; + match_length = MIN_MATCH - 1; + strstart++; + + if (bflush) { + flush_block_only(false); + if (strm.avail_out === 0) + return NeedMore; + } + } else if (match_available !== 0) { + + // If there was no match at the previous position, output a + // single literal. If there was a match but the current match + // is longer, truncate the previous match to a single literal. + + bflush = _tr_tally(0, win[strstart - 1] & 0xff); + + if (bflush) { + flush_block_only(false); + } + strstart++; + lookahead--; + if (strm.avail_out === 0) + return NeedMore; + } else { + // There is no previous match to compare with, wait for + // the next step to decide. + + match_available = 1; + strstart++; + lookahead--; + } + } + + if (match_available !== 0) { + bflush = _tr_tally(0, win[strstart - 1] & 0xff); + match_available = 0; + } + flush_block_only(flush == Z_FINISH$1); + + if (strm.avail_out === 0) { + if (flush == Z_FINISH$1) + return FinishStarted; + else + return NeedMore; + } + + return flush == Z_FINISH$1 ? FinishDone : BlockDone; + } + + function deflateReset(strm) { + strm.total_in = strm.total_out = 0; + strm.msg = null; // + + that.pending = 0; + that.pending_out = 0; + + status = BUSY_STATE; + + last_flush = Z_NO_FLUSH$1; + + tr_init(); + lm_init(); + return Z_OK$1; + } + + that.deflateInit = function (strm, _level, bits, _method, memLevel, _strategy) { + if (!_method) + _method = Z_DEFLATED$1; + if (!memLevel) + memLevel = DEF_MEM_LEVEL; + if (!_strategy) + _strategy = Z_DEFAULT_STRATEGY; + + // byte[] my_version=ZLIB_VERSION; + + // + // if (!version || version[0] != my_version[0] + // || stream_size != sizeof(z_stream)) { + // return Z_VERSION_ERROR; + // } + + strm.msg = null; + + if (_level == Z_DEFAULT_COMPRESSION) + _level = 6; + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED$1 || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0 + || _strategy > Z_HUFFMAN_ONLY) { + return Z_STREAM_ERROR$1; + } + + strm.dstate = that; + + w_bits = bits; + w_size = 1 << w_bits; + w_mask = w_size - 1; + + hash_bits = memLevel + 7; + hash_size = 1 << hash_bits; + hash_mask = hash_size - 1; + hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + win = new Uint8Array(w_size * 2); + prev = []; + head = []; + + lit_bufsize = 1 << (memLevel + 6); // 16K elements by default + + that.pending_buf = new Uint8Array(lit_bufsize * 4); + pending_buf_size = lit_bufsize * 4; + + that.dist_buf = new Uint16Array(lit_bufsize); + that.lc_buf = new Uint8Array(lit_bufsize); + + level = _level; + + strategy = _strategy; + + return deflateReset(strm); + }; + + that.deflateEnd = function () { + if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) { + return Z_STREAM_ERROR$1; + } + // Deallocate in reverse order of allocations: + that.lc_buf = null; + that.dist_buf = null; + that.pending_buf = null; + head = null; + prev = null; + win = null; + // free + that.dstate = null; + return status == BUSY_STATE ? Z_DATA_ERROR$1 : Z_OK$1; + }; + + that.deflateParams = function (strm, _level, _strategy) { + let err = Z_OK$1; + + if (_level == Z_DEFAULT_COMPRESSION) { + _level = 6; + } + if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) { + return Z_STREAM_ERROR$1; + } + + if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) { + // Flush the last buffer: + err = strm.deflate(Z_PARTIAL_FLUSH); + } + + if (level != _level) { + level = _level; + max_lazy_match = config_table[level].max_lazy; + good_match = config_table[level].good_length; + nice_match = config_table[level].nice_length; + max_chain_length = config_table[level].max_chain; + } + strategy = _strategy; + return err; + }; + + that.deflateSetDictionary = function (_strm, dictionary, dictLength) { + let length = dictLength; + let n, index = 0; + + if (!dictionary || status != INIT_STATE) + return Z_STREAM_ERROR$1; + + if (length < MIN_MATCH) + return Z_OK$1; + if (length > w_size - MIN_LOOKAHEAD) { + length = w_size - MIN_LOOKAHEAD; + index = dictLength - length; // use the tail of the dictionary + } + win.set(dictionary.subarray(index, index + length), 0); + + strstart = length; + block_start = length; + + // Insert all strings in the hash table (except for the last two bytes). + // s->lookahead stays null, so s->ins_h will be recomputed at the next + // call of fill_window. + + ins_h = win[0] & 0xff; + ins_h = (((ins_h) << hash_shift) ^ (win[1] & 0xff)) & hash_mask; + + for (n = 0; n <= length - MIN_MATCH; n++) { + ins_h = (((ins_h) << hash_shift) ^ (win[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; + prev[n & w_mask] = head[ins_h]; + head[ins_h] = n; + } + return Z_OK$1; + }; + + that.deflate = function (_strm, flush) { + let i, header, level_flags, old_flush, bstate; + + if (flush > Z_FINISH$1 || flush < 0) { + return Z_STREAM_ERROR$1; + } + + if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH$1)) { + _strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_STREAM_ERROR$1)]; + return Z_STREAM_ERROR$1; + } + if (_strm.avail_out === 0) { + _strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)]; + return Z_BUF_ERROR$1; + } + + strm = _strm; // just in case + old_flush = last_flush; + last_flush = flush; + + // Write the zlib header + if (status == INIT_STATE) { + header = (Z_DEFLATED$1 + ((w_bits - 8) << 4)) << 8; + level_flags = ((level - 1) & 0xff) >> 1; + + if (level_flags > 3) + level_flags = 3; + header |= (level_flags << 6); + if (strstart !== 0) + header |= PRESET_DICT$1; + header += 31 - (header % 31); + + status = BUSY_STATE; + putShortMSB(header); + } + + // Flush as much pending output as possible + if (that.pending !== 0) { + strm.flush_pending(); + if (strm.avail_out === 0) { + // console.log(" avail_out==0"); + // Since avail_out is 0, deflate will be called again with + // more output space, but possibly with both pending and + // avail_in equal to zero. There won't be anything to do, + // but this is not an error situation so make sure we + // return OK instead of BUF_ERROR at next call of deflate: + last_flush = -1; + return Z_OK$1; + } + + // Make sure there is something to do and avoid duplicate + // consecutive + // flushes. For repeated and useless calls with Z_FINISH, we keep + // returning Z_STREAM_END instead of Z_BUFF_ERROR. + } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH$1) { + strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)]; + return Z_BUF_ERROR$1; + } + + // User must not provide more input after the first FINISH: + if (status == FINISH_STATE && strm.avail_in !== 0) { + _strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)]; + return Z_BUF_ERROR$1; + } + + // Start a new block or continue the current one. + if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH$1 && status != FINISH_STATE)) { + bstate = -1; + switch (config_table[level].func) { + case STORED$1: + bstate = deflate_stored(flush); + break; + case FAST: + bstate = deflate_fast(flush); + break; + case SLOW: + bstate = deflate_slow(flush); + break; + } + + if (bstate == FinishStarted || bstate == FinishDone) { + status = FINISH_STATE; + } + if (bstate == NeedMore || bstate == FinishStarted) { + if (strm.avail_out === 0) { + last_flush = -1; // avoid BUF_ERROR next call, see above + } + return Z_OK$1; + // If flush != Z_NO_FLUSH && avail_out === 0, the next call + // of deflate should use the same flush parameter to make sure + // that the flush is complete. So we don't have to output an + // empty block here, this will be done at next call. This also + // ensures that for a very small output buffer, we emit at most + // one empty block. + } + + if (bstate == BlockDone) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(); + } else { // FULL_FLUSH or SYNC_FLUSH + _tr_stored_block(0, 0, false); + // For a full flush, this empty block will be recognized + // as a special marker by inflate_sync(). + if (flush == Z_FULL_FLUSH) { + // state.head[s.hash_size-1]=0; + for (i = 0; i < hash_size/*-1*/; i++) + // forget history + head[i] = 0; + } + } + strm.flush_pending(); + if (strm.avail_out === 0) { + last_flush = -1; // avoid BUF_ERROR at next call, see above + return Z_OK$1; + } + } + } + + if (flush != Z_FINISH$1) + return Z_OK$1; + return Z_STREAM_END$1; + }; +} + +// ZStream + +function ZStream$1() { + const that = this; + that.next_in_index = 0; + that.next_out_index = 0; + // that.next_in; // next input byte + that.avail_in = 0; // number of bytes available at next_in + that.total_in = 0; // total nb of input bytes read so far + // that.next_out; // next output byte should be put there + that.avail_out = 0; // remaining free space at next_out + that.total_out = 0; // total nb of bytes output so far + // that.msg; + // that.dstate; +} + +ZStream$1.prototype = { + deflateInit(level, bits) { + const that = this; + that.dstate = new Deflate(); + if (!bits) + bits = MAX_BITS$1; + return that.dstate.deflateInit(that, level, bits); + }, + + deflate(flush) { + const that = this; + if (!that.dstate) { + return Z_STREAM_ERROR$1; + } + return that.dstate.deflate(that, flush); + }, + + deflateEnd() { + const that = this; + if (!that.dstate) + return Z_STREAM_ERROR$1; + const ret = that.dstate.deflateEnd(); + that.dstate = null; + return ret; + }, + + deflateParams(level, strategy) { + const that = this; + if (!that.dstate) + return Z_STREAM_ERROR$1; + return that.dstate.deflateParams(that, level, strategy); + }, + + deflateSetDictionary(dictionary, dictLength) { + const that = this; + if (!that.dstate) + return Z_STREAM_ERROR$1; + return that.dstate.deflateSetDictionary(that, dictionary, dictLength); + }, + + // Read a new buffer from the current input stream, update the + // total number of bytes read. All deflate() input goes through + // this function so some applications may wish to modify it to avoid + // allocating a large strm->next_in buffer and copying from it. + // (See also flush_pending()). + read_buf(buf, start, size) { + const that = this; + let len = that.avail_in; + if (len > size) + len = size; + if (len === 0) + return 0; + that.avail_in -= len; + buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start); + that.next_in_index += len; + that.total_in += len; + return len; + }, + + // Flush as much pending output as possible. All deflate() output goes + // through this function so some applications may wish to modify it + // to avoid allocating a large strm->next_out buffer and copying into it. + // (See also read_buf()). + flush_pending() { + const that = this; + let len = that.dstate.pending; + + if (len > that.avail_out) + len = that.avail_out; + if (len === 0) + return; + + // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index + // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index + + // len)) { + // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " + + // that.next_out_index + ", " + len); + // console.log("avail_out=" + that.avail_out); + // } + + that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index); + + that.next_out_index += len; + that.dstate.pending_out += len; + that.total_out += len; + that.avail_out -= len; + that.dstate.pending -= len; + if (that.dstate.pending === 0) { + that.dstate.pending_out = 0; + } + } +}; + +// Deflate + +function ZipDeflate(options) { + const that = this; + const z = new ZStream$1(); + const bufsize = getMaximumCompressedSize(options && options.chunkSize ? options.chunkSize : 64 * 1024); + const flush = Z_NO_FLUSH$1; + const buf = new Uint8Array(bufsize); + let level = options ? options.level : Z_DEFAULT_COMPRESSION; + if (typeof level == "undefined") + level = Z_DEFAULT_COMPRESSION; + z.deflateInit(level); + z.next_out = buf; + + that.append = function (data, onprogress) { + let err, array, lastIndex = 0, bufferIndex = 0, bufferSize = 0; + const buffers = []; + if (!data.length) + return; + z.next_in_index = 0; + z.next_in = data; + z.avail_in = data.length; + do { + z.next_out_index = 0; + z.avail_out = bufsize; + err = z.deflate(flush); + if (err != Z_OK$1) + throw new Error("deflating: " + z.msg); + if (z.next_out_index) + if (z.next_out_index == bufsize) + buffers.push(new Uint8Array(buf)); + else + buffers.push(buf.subarray(0, z.next_out_index)); + bufferSize += z.next_out_index; + if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) { + onprogress(z.next_in_index); + lastIndex = z.next_in_index; + } + } while (z.avail_in > 0 || z.avail_out === 0); + if (buffers.length > 1) { + array = new Uint8Array(bufferSize); + buffers.forEach(function (chunk) { + array.set(chunk, bufferIndex); + bufferIndex += chunk.length; + }); + } else { + array = buffers[0] ? new Uint8Array(buffers[0]) : new Uint8Array(); + } + return array; + }; + that.flush = function () { + let err, array, bufferIndex = 0, bufferSize = 0; + const buffers = []; + do { + z.next_out_index = 0; + z.avail_out = bufsize; + err = z.deflate(Z_FINISH$1); + if (err != Z_STREAM_END$1 && err != Z_OK$1) + throw new Error("deflating: " + z.msg); + if (bufsize - z.avail_out > 0) + buffers.push(buf.slice(0, z.next_out_index)); + bufferSize += z.next_out_index; + } while (z.avail_in > 0 || z.avail_out === 0); + z.deflateEnd(); + array = new Uint8Array(bufferSize); + buffers.forEach(function (chunk) { + array.set(chunk, bufferIndex); + bufferIndex += chunk.length; + }); + return array; + }; +} + +function getMaximumCompressedSize(uncompressedSize) { + return uncompressedSize + (5 * (Math.floor(uncompressedSize / 16383) + 1)); +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc. + * JZlib is based on zlib-1.1.3, so all credit should go authors + * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) + * and contributors of zlib. + */ + +// deno-lint-ignore-file no-this-alias prefer-const + +// Global + +const MAX_BITS = 15; + +const Z_OK = 0; +const Z_STREAM_END = 1; +const Z_NEED_DICT = 2; +const Z_STREAM_ERROR = -2; +const Z_DATA_ERROR = -3; +const Z_MEM_ERROR = -4; +const Z_BUF_ERROR = -5; + +const inflate_mask = [0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, + 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff]; + +const MANY = 1440; + +// JZlib version : "1.0.2" +const Z_NO_FLUSH = 0; +const Z_FINISH = 4; + +// InfTree +const fixed_bl = 9; +const fixed_bd = 5; + +const fixed_tl = [96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, + 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, + 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, + 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, + 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, + 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, + 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, + 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, + 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, + 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, + 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, + 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, + 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, + 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, + 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, + 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, + 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, + 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, + 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, + 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, + 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, + 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, + 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, + 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, + 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, + 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, + 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, + 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, + 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, + 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, + 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, + 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, + 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, + 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, + 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, + 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, + 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255]; +const fixed_td = [80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5, + 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5, + 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577]; + +// Tables for deflate from PKZIP's appnote.txt. +const cplens = [ // Copy lengths for literal codes 257..285 + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0]; + +// see note #13 above about 258 +const cplext = [ // Extra bits for literal codes 257..285 + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid +]; + +const cpdist = [ // Copy offsets for distance codes 0..29 + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577]; + +const cpdext = [ // Extra bits for distance codes + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]; + +// If BMAX needs to be larger than 16, then h and x[] should be uLong. +const BMAX = 15; // maximum bit length of any code + +function InfTree() { + const that = this; + + let hn; // hufts used in space + let v; // work area for huft_build + let c; // bit length count table + let r; // table entry for structure assignment + let u; // table stack + let x; // bit offsets, then code stack + + function huft_build(b, // code lengths in bits (all assumed <= + // BMAX) + bindex, n, // number of codes (assumed <= 288) + s, // number of simple-valued codes (0..s-1) + d, // list of base values for non-simple codes + e, // list of extra bits for non-simple codes + t, // result: starting table + m, // maximum lookup bits, returns actual + hp,// space for trees + hn,// hufts used in space + v // working area: values in order of bit length + ) { + // Given a list of code lengths and a maximum table size, make a set of + // tables to decode that set of codes. Return Z_OK on success, + // Z_BUF_ERROR + // if the given code set is incomplete (the tables are still built in + // this + // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set + // of + // lengths), or Z_MEM_ERROR if not enough memory. + + let a; // counter for codes of length k + let f; // i repeats in table every f entries + let g; // maximum code length + let h; // table level + let i; // counter, current code + let j; // counter + let k; // number of bits in current code + let l; // bits per table (returned in m) + let mask; // (1 << w) - 1, to avoid cc -O bug on HP + let p; // pointer into c[], b[], or v[] + let q; // points to current table + let w; // bits before this table == (l * h) + let xp; // pointer into x + let y; // number of dummy codes added + let z; // number of entries in current table + + // Generate counts for each bit length + + p = 0; + i = n; + do { + c[b[bindex + p]]++; + p++; + i--; // assume all entries <= BMAX + } while (i !== 0); + + if (c[0] == n) { // null input--all zero length codes + t[0] = -1; + m[0] = 0; + return Z_OK; + } + + // Find minimum and maximum length, bound *m by those + l = m[0]; + for (j = 1; j <= BMAX; j++) + if (c[j] !== 0) + break; + k = j; // minimum code length + if (l < j) { + l = j; + } + for (i = BMAX; i !== 0; i--) { + if (c[i] !== 0) + break; + } + g = i; // maximum code length + if (l > i) { + l = i; + } + m[0] = l; + + // Adjust last length count to fill out codes, if needed + for (y = 1 << j; j < i; j++, y <<= 1) { + if ((y -= c[j]) < 0) { + return Z_DATA_ERROR; + } + } + if ((y -= c[i]) < 0) { + return Z_DATA_ERROR; + } + c[i] += y; + + // Generate starting offsets into the value table for each length + x[1] = j = 0; + p = 1; + xp = 2; + while (--i !== 0) { // note that i == g from above + x[xp] = (j += c[p]); + xp++; + p++; + } + + // Make a table of values in order of bit lengths + i = 0; + p = 0; + do { + if ((j = b[bindex + p]) !== 0) { + v[x[j]++] = i; + } + p++; + } while (++i < n); + n = x[g]; // set n to length of v + + // Generate the Huffman codes and for each, make the table entries + x[0] = i = 0; // first Huffman code is zero + p = 0; // grab values in bit order + h = -1; // no tables yet--level -1 + w = -l; // bits decoded == (l * h) + u[0] = 0; // just to keep compilers happy + q = 0; // ditto + z = 0; // ditto + + // go through the bit lengths (k already is bits in shortest code) + for (; k <= g; k++) { + a = c[k]; + while (a-- !== 0) { + // here i is the Huffman code of length k bits for value *p + // make tables up to required level + while (k > w + l) { + h++; + w += l; // previous table always l bits + // compute minimum size table less than or equal to l bits + z = g - w; + z = (z > l) ? l : z; // table size upper limit + if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table + // too few codes for + // k-w bit table + f -= a + 1; // deduct codes from patterns left + xp = k; + if (j < z) { + while (++j < z) { // try smaller tables up to z bits + if ((f <<= 1) <= c[++xp]) + break; // enough codes to use up j bits + f -= c[xp]; // else deduct codes from patterns + } + } + } + z = 1 << j; // table entries for j-bit table + + // allocate new table + if (hn[0] + z > MANY) { // (note: doesn't matter for fixed) + return Z_DATA_ERROR; // overflow of MANY + } + u[h] = q = /* hp+ */hn[0]; // DEBUG + hn[0] += z; + + // connect to last table, if there is one + if (h !== 0) { + x[h] = i; // save pattern for backing up + r[0] = /* (byte) */j; // bits in this table + r[1] = /* (byte) */l; // bits to dump before this table + j = i >>> (w - l); + r[2] = /* (int) */(q - u[h - 1] - j); // offset to this table + hp.set(r, (u[h - 1] + j) * 3); + // to + // last + // table + } else { + t[0] = q; // first table is returned result + } + } + + // set up table entry in r + r[1] = /* (byte) */(k - w); + if (p >= n) { + r[0] = 128 + 64; // out of values--invalid code + } else if (v[p] < s) { + r[0] = /* (byte) */(v[p] < 256 ? 0 : 32 + 64); // 256 is + // end-of-block + r[2] = v[p++]; // simple code is just the value + } else { + r[0] = /* (byte) */(e[v[p] - s] + 16 + 64); // non-simple--look + // up in lists + r[2] = d[v[p++] - s]; + } + + // fill code-like entries with r + f = 1 << (k - w); + for (j = i >>> w; j < z; j += f) { + hp.set(r, (q + j) * 3); + } + + // backwards increment the k-bit code i + for (j = 1 << (k - 1); (i & j) !== 0; j >>>= 1) { + i ^= j; + } + i ^= j; + + // backup over finished tables + mask = (1 << w) - 1; // needed on HP, cc -O bug + while ((i & mask) != x[h]) { + h--; // don't need to update q + w -= l; + mask = (1 << w) - 1; + } + } + } + // Return Z_BUF_ERROR if we were given an incomplete table + return y !== 0 && g != 1 ? Z_BUF_ERROR : Z_OK; + } + + function initWorkArea(vsize) { + let i; + if (!hn) { + hn = []; // []; //new Array(1); + v = []; // new Array(vsize); + c = new Int32Array(BMAX + 1); // new Array(BMAX + 1); + r = []; // new Array(3); + u = new Int32Array(BMAX); // new Array(BMAX); + x = new Int32Array(BMAX + 1); // new Array(BMAX + 1); + } + if (v.length < vsize) { + v = []; // new Array(vsize); + } + for (i = 0; i < vsize; i++) { + v[i] = 0; + } + for (i = 0; i < BMAX + 1; i++) { + c[i] = 0; + } + for (i = 0; i < 3; i++) { + r[i] = 0; + } + // for(int i=0; i 257)) { + if (result == Z_DATA_ERROR) { + z.msg = "oversubscribed distance tree"; + } else if (result == Z_BUF_ERROR) { + z.msg = "incomplete distance tree"; + result = Z_DATA_ERROR; + } else if (result != Z_MEM_ERROR) { + z.msg = "empty distance tree with lengths"; + result = Z_DATA_ERROR; + } + return result; + } + + return Z_OK; + }; + +} + +InfTree.inflate_trees_fixed = function (bl, // literal desired/actual bit depth + bd, // distance desired/actual bit depth + tl,// literal/length tree result + td// distance tree result +) { + bl[0] = fixed_bl; + bd[0] = fixed_bd; + tl[0] = fixed_tl; + td[0] = fixed_td; + return Z_OK; +}; + +// InfCodes + +// waiting for "i:"=input, +// "o:"=output, +// "x:"=nothing +const START = 0; // x: set up for LEN +const LEN = 1; // i: get length/literal/eob next +const LENEXT = 2; // i: getting length extra (have base) +const DIST = 3; // i: get distance next +const DISTEXT = 4;// i: getting distance extra +const COPY = 5; // o: copying bytes in win, waiting +// for space +const LIT = 6; // o: got literal, waiting for output +// space +const WASH = 7; // o: got eob, possibly still output +// waiting +const END = 8; // x: got eob and all data flushed +const BADCODE = 9;// x: got error + +function InfCodes() { + const that = this; + + let mode; // current inflate_codes mode + + // mode dependent information + let len = 0; + + let tree; // pointer into tree + let tree_index = 0; + let need = 0; // bits needed + + let lit = 0; + + // if EXT or COPY, where and how much + let get = 0; // bits to get for extra + let dist = 0; // distance back to copy from + + let lbits = 0; // ltree bits decoded per branch + let dbits = 0; // dtree bits decoder per branch + let ltree; // literal/length/eob tree + let ltree_index = 0; // literal/length/eob tree + let dtree; // distance tree + let dtree_index = 0; // distance tree + + // Called with number of bytes left to write in win at least 258 + // (the maximum string length) and number of input bytes available + // at least ten. The ten bytes are six bytes for the longest length/ + // distance pair plus four bytes for overloading the bit buffer. + + function inflate_fast(bl, bd, tl, tl_index, td, td_index, s, z) { + let t; // temporary pointer + let tp; // temporary pointer + let tp_index; // temporary pointer + let e; // extra bits or operation + let b; // bit buffer + let k; // bits in bit buffer + let p; // input data pointer + let n; // bytes available there + let q; // output win write pointer + let m; // bytes to end of win or read pointer + let ml; // mask for literal/length tree + let md; // mask for distance tree + let c; // bytes to copy + let d; // distance back to copy from + let r; // copy source pointer + + let tp_index_t_3; // (tp_index+t)*3 + + // load input, output, bit values + p = z.next_in_index; + n = z.avail_in; + b = s.bitb; + k = s.bitk; + q = s.write; + m = q < s.read ? s.read - q - 1 : s.end - q; + + // initialize masks + ml = inflate_mask[bl]; + md = inflate_mask[bd]; + + // do until not enough input or output space for fast loop + do { // assume called with m >= 258 && n >= 10 + // get literal/length code + while (k < (20)) { // max bits for literal/length code + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + t = b & ml; + tp = tl; + tp_index = tl_index; + tp_index_t_3 = (tp_index + t) * 3; + if ((e = tp[tp_index_t_3]) === 0) { + b >>= (tp[tp_index_t_3 + 1]); + k -= (tp[tp_index_t_3 + 1]); + + s.win[q++] = /* (byte) */tp[tp_index_t_3 + 2]; + m--; + continue; + } + do { + + b >>= (tp[tp_index_t_3 + 1]); + k -= (tp[tp_index_t_3 + 1]); + + if ((e & 16) !== 0) { + e &= 15; + c = tp[tp_index_t_3 + 2] + (/* (int) */b & inflate_mask[e]); + + b >>= e; + k -= e; + + // decode distance base of block to copy + while (k < (15)) { // max bits for distance code + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + t = b & md; + tp = td; + tp_index = td_index; + tp_index_t_3 = (tp_index + t) * 3; + e = tp[tp_index_t_3]; + + do { + + b >>= (tp[tp_index_t_3 + 1]); + k -= (tp[tp_index_t_3 + 1]); + + if ((e & 16) !== 0) { + // get extra bits to add to distance base + e &= 15; + while (k < (e)) { // get extra bits (up to 13) + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]); + + b >>= (e); + k -= (e); + + // do the copy + m -= c; + if (q >= d) { // offset before dest + // just copy + r = q - d; + if (q - r > 0 && 2 > (q - r)) { + s.win[q++] = s.win[r++]; // minimum + // count is + // three, + s.win[q++] = s.win[r++]; // so unroll + // loop a + // little + c -= 2; + } else { + s.win.set(s.win.subarray(r, r + 2), q); + q += 2; + r += 2; + c -= 2; + } + } else { // else offset after destination + r = q - d; + do { + r += s.end; // force pointer in win + } while (r < 0); // covers invalid distances + e = s.end - r; + if (c > e) { // if source crosses, + c -= e; // wrapped copy + if (q - r > 0 && e > (q - r)) { + do { + s.win[q++] = s.win[r++]; + } while (--e !== 0); + } else { + s.win.set(s.win.subarray(r, r + e), q); + q += e; + r += e; + e = 0; + } + r = 0; // copy rest from start of win + } + + } + + // copy all or what's left + if (q - r > 0 && c > (q - r)) { + do { + s.win[q++] = s.win[r++]; + } while (--c !== 0); + } else { + s.win.set(s.win.subarray(r, r + c), q); + q += c; + r += c; + c = 0; + } + break; + } else if ((e & 64) === 0) { + t += tp[tp_index_t_3 + 2]; + t += (b & inflate_mask[e]); + tp_index_t_3 = (tp_index + t) * 3; + e = tp[tp_index_t_3]; + } else { + z.msg = "invalid distance code"; + + c = z.avail_in - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= c << 3; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + + return Z_DATA_ERROR; + } + // eslint-disable-next-line no-constant-condition + } while (true); + break; + } + + if ((e & 64) === 0) { + t += tp[tp_index_t_3 + 2]; + t += (b & inflate_mask[e]); + tp_index_t_3 = (tp_index + t) * 3; + if ((e = tp[tp_index_t_3]) === 0) { + + b >>= (tp[tp_index_t_3 + 1]); + k -= (tp[tp_index_t_3 + 1]); + + s.win[q++] = /* (byte) */tp[tp_index_t_3 + 2]; + m--; + break; + } + } else if ((e & 32) !== 0) { + + c = z.avail_in - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= c << 3; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + + return Z_STREAM_END; + } else { + z.msg = "invalid literal/length code"; + + c = z.avail_in - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= c << 3; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + + return Z_DATA_ERROR; + } + // eslint-disable-next-line no-constant-condition + } while (true); + } while (m >= 258 && n >= 10); + + // not enough input or output--restore pointers and return + c = z.avail_in - n; + c = (k >> 3) < c ? k >> 3 : c; + n += c; + p -= c; + k -= c << 3; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + + return Z_OK; + } + + that.init = function (bl, bd, tl, tl_index, td, td_index) { + mode = START; + lbits = /* (byte) */bl; + dbits = /* (byte) */bd; + ltree = tl; + ltree_index = tl_index; + dtree = td; + dtree_index = td_index; + tree = null; + }; + + that.proc = function (s, z, r) { + let j; // temporary storage + let tindex; // temporary pointer + let e; // extra bits or operation + let b = 0; // bit buffer + let k = 0; // bits in bit buffer + let p = 0; // input data pointer + let n; // bytes available there + let q; // output win write pointer + let m; // bytes to end of win or read pointer + let f; // pointer to copy strings from + + // copy input/output information to locals (UPDATE macro restores) + p = z.next_in_index; + n = z.avail_in; + b = s.bitb; + k = s.bitk; + q = s.write; + m = q < s.read ? s.read - q - 1 : s.end - q; + + // process input and output based on current state + // eslint-disable-next-line no-constant-condition + while (true) { + switch (mode) { + // waiting for "i:"=input, "o:"=output, "x:"=nothing + case START: // x: set up for LEN + if (m >= 258 && n >= 10) { + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z); + + p = z.next_in_index; + n = z.avail_in; + b = s.bitb; + k = s.bitk; + q = s.write; + m = q < s.read ? s.read - q - 1 : s.end - q; + + if (r != Z_OK) { + mode = r == Z_STREAM_END ? WASH : BADCODE; + break; + } + } + need = lbits; + tree = ltree; + tree_index = ltree_index; + + mode = LEN; + /* falls through */ + case LEN: // i: get length/literal/eob next + j = need; + + while (k < (j)) { + if (n !== 0) + r = Z_OK; + else { + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + tindex = (tree_index + (b & inflate_mask[j])) * 3; + + b >>>= (tree[tindex + 1]); + k -= (tree[tindex + 1]); + + e = tree[tindex]; + + if (e === 0) { // literal + lit = tree[tindex + 2]; + mode = LIT; + break; + } + if ((e & 16) !== 0) { // length + get = e & 15; + len = tree[tindex + 2]; + mode = LENEXT; + break; + } + if ((e & 64) === 0) { // next table + need = e; + tree_index = tindex / 3 + tree[tindex + 2]; + break; + } + if ((e & 32) !== 0) { // end of block + mode = WASH; + break; + } + mode = BADCODE; // invalid code + z.msg = "invalid literal/length code"; + r = Z_DATA_ERROR; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + + case LENEXT: // i: getting length extra (have base) + j = get; + + while (k < (j)) { + if (n !== 0) + r = Z_OK; + else { + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + len += (b & inflate_mask[j]); + + b >>= j; + k -= j; + + need = dbits; + tree = dtree; + tree_index = dtree_index; + mode = DIST; + /* falls through */ + case DIST: // i: get distance next + j = need; + + while (k < (j)) { + if (n !== 0) + r = Z_OK; + else { + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + tindex = (tree_index + (b & inflate_mask[j])) * 3; + + b >>= tree[tindex + 1]; + k -= tree[tindex + 1]; + + e = (tree[tindex]); + if ((e & 16) !== 0) { // distance + get = e & 15; + dist = tree[tindex + 2]; + mode = DISTEXT; + break; + } + if ((e & 64) === 0) { // next table + need = e; + tree_index = tindex / 3 + tree[tindex + 2]; + break; + } + mode = BADCODE; // invalid code + z.msg = "invalid distance code"; + r = Z_DATA_ERROR; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + + case DISTEXT: // i: getting distance extra + j = get; + + while (k < (j)) { + if (n !== 0) + r = Z_OK; + else { + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + dist += (b & inflate_mask[j]); + + b >>= j; + k -= j; + + mode = COPY; + /* falls through */ + case COPY: // o: copying bytes in win, waiting for space + f = q - dist; + while (f < 0) { // modulo win size-"while" instead + f += s.end; // of "if" handles invalid distances + } + while (len !== 0) { + + if (m === 0) { + if (q == s.end && s.read !== 0) { + q = 0; + m = q < s.read ? s.read - q - 1 : s.end - q; + } + if (m === 0) { + s.write = q; + r = s.inflate_flush(z, r); + q = s.write; + m = q < s.read ? s.read - q - 1 : s.end - q; + + if (q == s.end && s.read !== 0) { + q = 0; + m = q < s.read ? s.read - q - 1 : s.end - q; + } + + if (m === 0) { + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + } + } + + s.win[q++] = s.win[f++]; + m--; + + if (f == s.end) + f = 0; + len--; + } + mode = START; + break; + case LIT: // o: got literal, waiting for output space + if (m === 0) { + if (q == s.end && s.read !== 0) { + q = 0; + m = q < s.read ? s.read - q - 1 : s.end - q; + } + if (m === 0) { + s.write = q; + r = s.inflate_flush(z, r); + q = s.write; + m = q < s.read ? s.read - q - 1 : s.end - q; + + if (q == s.end && s.read !== 0) { + q = 0; + m = q < s.read ? s.read - q - 1 : s.end - q; + } + if (m === 0) { + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + } + } + r = Z_OK; + + s.win[q++] = /* (byte) */lit; + m--; + + mode = START; + break; + case WASH: // o: got eob, possibly more output + if (k > 7) { // return unused byte, if any + k -= 8; + n++; + p--; // can always return one + } + + s.write = q; + r = s.inflate_flush(z, r); + q = s.write; + m = q < s.read ? s.read - q - 1 : s.end - q; + + if (s.read != s.write) { + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + mode = END; + /* falls through */ + case END: + r = Z_STREAM_END; + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + + case BADCODE: // x: got error + + r = Z_DATA_ERROR; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + + default: + r = Z_STREAM_ERROR; + + s.bitb = b; + s.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + s.write = q; + return s.inflate_flush(z, r); + } + } + }; + + that.free = function () { + // ZFREE(z, c); + }; + +} + +// InfBlocks + +// Table for deflate from PKZIP's appnote.txt. +const border = [ // Order of the bit length code lengths + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + +const TYPE = 0; // get type bits (3, including end bit) +const LENS = 1; // get lengths for stored +const STORED = 2;// processing stored block +const TABLE = 3; // get table lengths +const BTREE = 4; // get bit lengths tree for a dynamic +// block +const DTREE = 5; // get length, distance trees for a +// dynamic block +const CODES = 6; // processing fixed or dynamic block +const DRY = 7; // output remaining win bytes +const DONELOCKS = 8; // finished last block, done +const BADBLOCKS = 9; // ot a data error--stuck here + +function InfBlocks(z, w) { + const that = this; + + let mode = TYPE; // current inflate_block mode + + let left = 0; // if STORED, bytes left to copy + + let table = 0; // table lengths (14 bits) + let index = 0; // index into blens (or border) + let blens; // bit lengths of codes + const bb = [0]; // bit length tree depth + const tb = [0]; // bit length decoding tree + + const codes = new InfCodes(); // if CODES, current state + + let last = 0; // true if this block is the last block + + let hufts = new Int32Array(MANY * 3); // single malloc for tree space + const check = 0; // check on output + const inftree = new InfTree(); + + that.bitk = 0; // bits in bit buffer + that.bitb = 0; // bit buffer + that.win = new Uint8Array(w); // sliding win + that.end = w; // one byte after sliding win + that.read = 0; // win read pointer + that.write = 0; // win write pointer + + that.reset = function (z, c) { + if (c) + c[0] = check; + // if (mode == BTREE || mode == DTREE) { + // } + if (mode == CODES) { + codes.free(z); + } + mode = TYPE; + that.bitk = 0; + that.bitb = 0; + that.read = that.write = 0; + }; + + that.reset(z, null); + + // copy as much as possible from the sliding win to the output area + that.inflate_flush = function (z, r) { + let n; + let p; + let q; + + // local copies of source and destination pointers + p = z.next_out_index; + q = that.read; + + // compute number of bytes to copy as far as end of win + n = /* (int) */((q <= that.write ? that.write : that.end) - q); + if (n > z.avail_out) + n = z.avail_out; + if (n !== 0 && r == Z_BUF_ERROR) + r = Z_OK; + + // update counters + z.avail_out -= n; + z.total_out += n; + + // copy as far as end of win + z.next_out.set(that.win.subarray(q, q + n), p); + p += n; + q += n; + + // see if more to copy at beginning of win + if (q == that.end) { + // wrap pointers + q = 0; + if (that.write == that.end) + that.write = 0; + + // compute bytes to copy + n = that.write - q; + if (n > z.avail_out) + n = z.avail_out; + if (n !== 0 && r == Z_BUF_ERROR) + r = Z_OK; + + // update counters + z.avail_out -= n; + z.total_out += n; + + // copy + z.next_out.set(that.win.subarray(q, q + n), p); + p += n; + q += n; + } + + // update pointers + z.next_out_index = p; + that.read = q; + + // done + return r; + }; + + that.proc = function (z, r) { + let t; // temporary storage + let b; // bit buffer + let k; // bits in bit buffer + let p; // input data pointer + let n; // bytes available there + let q; // output win write pointer + let m; // bytes to end of win or read pointer + + let i; + + // copy input/output information to locals (UPDATE macro restores) + // { + p = z.next_in_index; + n = z.avail_in; + b = that.bitb; + k = that.bitk; + // } + // { + q = that.write; + m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); + // } + + // process input based on current state + // DEBUG dtree + // eslint-disable-next-line no-constant-condition + while (true) { + let bl, bd, tl, td, bl_, bd_, tl_, td_; + switch (mode) { + case TYPE: + + while (k < (3)) { + if (n !== 0) { + r = Z_OK; + } else { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + t = /* (int) */(b & 7); + last = t & 1; + + switch (t >>> 1) { + case 0: // stored + // { + b >>>= (3); + k -= (3); + // } + t = k & 7; // go to byte boundary + + // { + b >>>= (t); + k -= (t); + // } + mode = LENS; // get length of stored block + break; + case 1: // fixed + // { + bl = []; // new Array(1); + bd = []; // new Array(1); + tl = [[]]; // new Array(1); + td = [[]]; // new Array(1); + + InfTree.inflate_trees_fixed(bl, bd, tl, td); + codes.init(bl[0], bd[0], tl[0], 0, td[0], 0); + // } + + // { + b >>>= (3); + k -= (3); + // } + + mode = CODES; + break; + case 2: // dynamic + + // { + b >>>= (3); + k -= (3); + // } + + mode = TABLE; + break; + case 3: // illegal + + // { + b >>>= (3); + k -= (3); + // } + mode = BADBLOCKS; + z.msg = "invalid block type"; + r = Z_DATA_ERROR; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + break; + case LENS: + + while (k < (32)) { + if (n !== 0) { + r = Z_OK; + } else { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)) { + mode = BADBLOCKS; + z.msg = "invalid stored block lengths"; + r = Z_DATA_ERROR; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + left = (b & 0xffff); + b = k = 0; // dump bits + mode = left !== 0 ? STORED : (last !== 0 ? DRY : TYPE); + break; + case STORED: + if (n === 0) { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + + if (m === 0) { + if (q == that.end && that.read !== 0) { + q = 0; + m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); + } + if (m === 0) { + that.write = q; + r = that.inflate_flush(z, r); + q = that.write; + m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); + if (q == that.end && that.read !== 0) { + q = 0; + m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); + } + if (m === 0) { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + } + } + r = Z_OK; + + t = left; + if (t > n) + t = n; + if (t > m) + t = m; + that.win.set(z.read_buf(p, t), q); + p += t; + n -= t; + q += t; + m -= t; + if ((left -= t) !== 0) + break; + mode = last !== 0 ? DRY : TYPE; + break; + case TABLE: + + while (k < (14)) { + if (n !== 0) { + r = Z_OK; + } else { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + table = t = (b & 0x3fff); + if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { + mode = BADBLOCKS; + z.msg = "too many length or distance symbols"; + r = Z_DATA_ERROR; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); + if (!blens || blens.length < t) { + blens = []; // new Array(t); + } else { + for (i = 0; i < t; i++) { + blens[i] = 0; + } + } + + // { + b >>>= (14); + k -= (14); + // } + + index = 0; + mode = BTREE; + /* falls through */ + case BTREE: + while (index < 4 + (table >>> 10)) { + while (k < (3)) { + if (n !== 0) { + r = Z_OK; + } else { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + blens[border[index++]] = b & 7; + + // { + b >>>= (3); + k -= (3); + // } + } + + while (index < 19) { + blens[border[index++]] = 0; + } + + bb[0] = 7; + t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z); + if (t != Z_OK) { + r = t; + if (r == Z_DATA_ERROR) { + blens = null; + mode = BADBLOCKS; + } + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + + index = 0; + mode = DTREE; + /* falls through */ + case DTREE: + // eslint-disable-next-line no-constant-condition + while (true) { + t = table; + if (index >= 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) { + break; + } + + let j, c; + + t = bb[0]; + + while (k < (t)) { + if (n !== 0) { + r = Z_OK; + } else { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + // if (tb[0] == -1) { + // System.err.println("null..."); + // } + + t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1]; + c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2]; + + if (c < 16) { + b >>>= (t); + k -= (t); + blens[index++] = c; + } else { // c == 16..18 + i = c == 18 ? 7 : c - 14; + j = c == 18 ? 11 : 3; + + while (k < (t + i)) { + if (n !== 0) { + r = Z_OK; + } else { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + n--; + b |= (z.read_byte(p++) & 0xff) << k; + k += 8; + } + + b >>>= (t); + k -= (t); + + j += (b & inflate_mask[i]); + + b >>>= (i); + k -= (i); + + i = index; + t = table; + if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { + blens = null; + mode = BADBLOCKS; + z.msg = "invalid bit length repeat"; + r = Z_DATA_ERROR; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + + c = c == 16 ? blens[i - 1] : 0; + do { + blens[i++] = c; + } while (--j !== 0); + index = i; + } + } + + tb[0] = -1; + // { + bl_ = []; // new Array(1); + bd_ = []; // new Array(1); + tl_ = []; // new Array(1); + td_ = []; // new Array(1); + bl_[0] = 9; // must be <= 9 for lookahead assumptions + bd_[0] = 6; // must be <= 9 for lookahead assumptions + + t = table; + t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl_, bd_, tl_, td_, hufts, z); + + if (t != Z_OK) { + if (t == Z_DATA_ERROR) { + blens = null; + mode = BADBLOCKS; + } + r = t; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + codes.init(bl_[0], bd_[0], hufts, tl_[0], hufts, td_[0]); + // } + mode = CODES; + /* falls through */ + case CODES: + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + + if ((r = codes.proc(that, z, r)) != Z_STREAM_END) { + return that.inflate_flush(z, r); + } + r = Z_OK; + codes.free(z); + + p = z.next_in_index; + n = z.avail_in; + b = that.bitb; + k = that.bitk; + q = that.write; + m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); + + if (last === 0) { + mode = TYPE; + break; + } + mode = DRY; + /* falls through */ + case DRY: + that.write = q; + r = that.inflate_flush(z, r); + q = that.write; + m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q); + if (that.read != that.write) { + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + mode = DONELOCKS; + /* falls through */ + case DONELOCKS: + r = Z_STREAM_END; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + case BADBLOCKS: + r = Z_DATA_ERROR; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + + default: + r = Z_STREAM_ERROR; + + that.bitb = b; + that.bitk = k; + z.avail_in = n; + z.total_in += p - z.next_in_index; + z.next_in_index = p; + that.write = q; + return that.inflate_flush(z, r); + } + } + }; + + that.free = function (z) { + that.reset(z, null); + that.win = null; + hufts = null; + // ZFREE(z, s); + }; + + that.set_dictionary = function (d, start, n) { + that.win.set(d.subarray(start, start + n), 0); + that.read = that.write = n; + }; + + // Returns true if inflate is currently at the end of a block generated + // by Z_SYNC_FLUSH or Z_FULL_FLUSH. + that.sync_point = function () { + return mode == LENS ? 1 : 0; + }; + +} + +// Inflate + +// preset dictionary flag in zlib header +const PRESET_DICT = 0x20; + +const Z_DEFLATED = 8; + +const METHOD = 0; // waiting for method byte +const FLAG = 1; // waiting for flag byte +const DICT4 = 2; // four dictionary check bytes to go +const DICT3 = 3; // three dictionary check bytes to go +const DICT2 = 4; // two dictionary check bytes to go +const DICT1 = 5; // one dictionary check byte to go +const DICT0 = 6; // waiting for inflateSetDictionary +const BLOCKS = 7; // decompressing blocks +const DONE = 12; // finished check, done +const BAD = 13; // got an error--stay here + +const mark = [0, 0, 0xff, 0xff]; + +function Inflate() { + const that = this; + + that.mode = 0; // current inflate mode + + // mode dependent information + that.method = 0; // if FLAGS, method byte + + // if CHECK, check values to compare + that.was = [0]; // new Array(1); // computed check value + that.need = 0; // stream check value + + // if BAD, inflateSync's marker bytes count + that.marker = 0; + + // mode independent information + that.wbits = 0; // log2(win size) (8..15, defaults to 15) + + // this.blocks; // current inflate_blocks state + + function inflateReset(z) { + if (!z || !z.istate) + return Z_STREAM_ERROR; + + z.total_in = z.total_out = 0; + z.msg = null; + z.istate.mode = BLOCKS; + z.istate.blocks.reset(z, null); + return Z_OK; + } + + that.inflateEnd = function (z) { + if (that.blocks) + that.blocks.free(z); + that.blocks = null; + // ZFREE(z, z->state); + return Z_OK; + }; + + that.inflateInit = function (z, w) { + z.msg = null; + that.blocks = null; + + // set win size + if (w < 8 || w > 15) { + that.inflateEnd(z); + return Z_STREAM_ERROR; + } + that.wbits = w; + + z.istate.blocks = new InfBlocks(z, 1 << w); + + // reset state + inflateReset(z); + return Z_OK; + }; + + that.inflate = function (z, f) { + let r; + let b; + + if (!z || !z.istate || !z.next_in) + return Z_STREAM_ERROR; + const istate = z.istate; + f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; + r = Z_BUF_ERROR; + // eslint-disable-next-line no-constant-condition + while (true) { + switch (istate.mode) { + case METHOD: + + if (z.avail_in === 0) + return r; + r = f; + + z.avail_in--; + z.total_in++; + if (((istate.method = z.read_byte(z.next_in_index++)) & 0xf) != Z_DEFLATED) { + istate.mode = BAD; + z.msg = "unknown compression method"; + istate.marker = 5; // can't try inflateSync + break; + } + if ((istate.method >> 4) + 8 > istate.wbits) { + istate.mode = BAD; + z.msg = "invalid win size"; + istate.marker = 5; // can't try inflateSync + break; + } + istate.mode = FLAG; + /* falls through */ + case FLAG: + + if (z.avail_in === 0) + return r; + r = f; + + z.avail_in--; + z.total_in++; + b = (z.read_byte(z.next_in_index++)) & 0xff; + + if ((((istate.method << 8) + b) % 31) !== 0) { + istate.mode = BAD; + z.msg = "incorrect header check"; + istate.marker = 5; // can't try inflateSync + break; + } + + if ((b & PRESET_DICT) === 0) { + istate.mode = BLOCKS; + break; + } + istate.mode = DICT4; + /* falls through */ + case DICT4: + + if (z.avail_in === 0) + return r; + r = f; + + z.avail_in--; + z.total_in++; + istate.need = ((z.read_byte(z.next_in_index++) & 0xff) << 24) & 0xff000000; + istate.mode = DICT3; + /* falls through */ + case DICT3: + + if (z.avail_in === 0) + return r; + r = f; + + z.avail_in--; + z.total_in++; + istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 16) & 0xff0000; + istate.mode = DICT2; + /* falls through */ + case DICT2: + + if (z.avail_in === 0) + return r; + r = f; + + z.avail_in--; + z.total_in++; + istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 8) & 0xff00; + istate.mode = DICT1; + /* falls through */ + case DICT1: + + if (z.avail_in === 0) + return r; + r = f; + + z.avail_in--; + z.total_in++; + istate.need += (z.read_byte(z.next_in_index++) & 0xff); + istate.mode = DICT0; + return Z_NEED_DICT; + case DICT0: + istate.mode = BAD; + z.msg = "need dictionary"; + istate.marker = 0; // can try inflateSync + return Z_STREAM_ERROR; + case BLOCKS: + + r = istate.blocks.proc(z, r); + if (r == Z_DATA_ERROR) { + istate.mode = BAD; + istate.marker = 0; // can try inflateSync + break; + } + if (r == Z_OK) { + r = f; + } + if (r != Z_STREAM_END) { + return r; + } + r = f; + istate.blocks.reset(z, istate.was); + istate.mode = DONE; + /* falls through */ + case DONE: + z.avail_in = 0; + return Z_STREAM_END; + case BAD: + return Z_DATA_ERROR; + default: + return Z_STREAM_ERROR; + } + } + }; + + that.inflateSetDictionary = function (z, dictionary, dictLength) { + let index = 0, length = dictLength; + if (!z || !z.istate || z.istate.mode != DICT0) + return Z_STREAM_ERROR; + const istate = z.istate; + if (length >= (1 << istate.wbits)) { + length = (1 << istate.wbits) - 1; + index = dictLength - length; + } + istate.blocks.set_dictionary(dictionary, index, length); + istate.mode = BLOCKS; + return Z_OK; + }; + + that.inflateSync = function (z) { + let n; // number of bytes to look at + let p; // pointer to bytes + let m; // number of marker bytes found in a row + let r, w; // temporaries to save total_in and total_out + + // set up + if (!z || !z.istate) + return Z_STREAM_ERROR; + const istate = z.istate; + if (istate.mode != BAD) { + istate.mode = BAD; + istate.marker = 0; + } + if ((n = z.avail_in) === 0) + return Z_BUF_ERROR; + p = z.next_in_index; + m = istate.marker; + + // search + while (n !== 0 && m < 4) { + if (z.read_byte(p) == mark[m]) { + m++; + } else if (z.read_byte(p) !== 0) { + m = 0; + } else { + m = 4 - m; + } + p++; + n--; + } + + // restore + z.total_in += p - z.next_in_index; + z.next_in_index = p; + z.avail_in = n; + istate.marker = m; + + // return no joy or set up to restart on a new block + if (m != 4) { + return Z_DATA_ERROR; + } + r = z.total_in; + w = z.total_out; + inflateReset(z); + z.total_in = r; + z.total_out = w; + istate.mode = BLOCKS; + return Z_OK; + }; + + // Returns true if inflate is currently at the end of a block generated + // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + // implementation to provide an additional safety check. PPP uses + // Z_SYNC_FLUSH + // but removes the length bytes of the resulting empty stored block. When + // decompressing, PPP checks that at the end of input packet, inflate is + // waiting for these length bytes. + that.inflateSyncPoint = function (z) { + if (!z || !z.istate || !z.istate.blocks) + return Z_STREAM_ERROR; + return z.istate.blocks.sync_point(); + }; +} + +// ZStream + +function ZStream() { +} + +ZStream.prototype = { + inflateInit(bits) { + const that = this; + that.istate = new Inflate(); + if (!bits) + bits = MAX_BITS; + return that.istate.inflateInit(that, bits); + }, + + inflate(f) { + const that = this; + if (!that.istate) + return Z_STREAM_ERROR; + return that.istate.inflate(that, f); + }, + + inflateEnd() { + const that = this; + if (!that.istate) + return Z_STREAM_ERROR; + const ret = that.istate.inflateEnd(that); + that.istate = null; + return ret; + }, + + inflateSync() { + const that = this; + if (!that.istate) + return Z_STREAM_ERROR; + return that.istate.inflateSync(that); + }, + inflateSetDictionary(dictionary, dictLength) { + const that = this; + if (!that.istate) + return Z_STREAM_ERROR; + return that.istate.inflateSetDictionary(that, dictionary, dictLength); + }, + read_byte(start) { + const that = this; + return that.next_in[start]; + }, + read_buf(start, size) { + const that = this; + return that.next_in.subarray(start, start + size); + } +}; + +// Inflater + +function ZipInflate(options) { + const that = this; + const z = new ZStream(); + const bufsize = options && options.chunkSize ? Math.floor(options.chunkSize * 2) : 128 * 1024; + const flush = Z_NO_FLUSH; + const buf = new Uint8Array(bufsize); + let nomoreinput = false; + + z.inflateInit(); + z.next_out = buf; + + that.append = function (data, onprogress) { + const buffers = []; + let err, array, lastIndex = 0, bufferIndex = 0, bufferSize = 0; + if (data.length === 0) + return; + z.next_in_index = 0; + z.next_in = data; + z.avail_in = data.length; + do { + z.next_out_index = 0; + z.avail_out = bufsize; + if ((z.avail_in === 0) && (!nomoreinput)) { // if buffer is empty and more input is available, refill it + z.next_in_index = 0; + nomoreinput = true; + } + err = z.inflate(flush); + if (nomoreinput && (err === Z_BUF_ERROR)) { + if (z.avail_in !== 0) + throw new Error("inflating: bad input"); + } else if (err !== Z_OK && err !== Z_STREAM_END) + throw new Error("inflating: " + z.msg); + if ((nomoreinput || err === Z_STREAM_END) && (z.avail_in === data.length)) + throw new Error("inflating: bad input"); + if (z.next_out_index) + if (z.next_out_index === bufsize) + buffers.push(new Uint8Array(buf)); + else + buffers.push(buf.subarray(0, z.next_out_index)); + bufferSize += z.next_out_index; + if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) { + onprogress(z.next_in_index); + lastIndex = z.next_in_index; + } + } while (z.avail_in > 0 || z.avail_out === 0); + if (buffers.length > 1) { + array = new Uint8Array(bufferSize); + buffers.forEach(function (chunk) { + array.set(chunk, bufferIndex); + bufferIndex += chunk.length; + }); + } else { + array = buffers[0] ? new Uint8Array(buffers[0]) : new Uint8Array(); + } + return array; + }; + that.flush = function () { + z.inflateEnd(); + }; +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const MAX_32_BITS = 0xffffffff; +const MAX_16_BITS = 0xffff; +const COMPRESSION_METHOD_DEFLATE = 0x08; +const COMPRESSION_METHOD_STORE = 0x00; +const COMPRESSION_METHOD_AES = 0x63; + +const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50; +const SPLIT_ZIP_FILE_SIGNATURE = 0x08074b50; +const CENTRAL_FILE_HEADER_SIGNATURE = 0x02014b50; +const END_OF_CENTRAL_DIR_SIGNATURE = 0x06054b50; +const ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = 0x06064b50; +const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = 0x07064b50; +const END_OF_CENTRAL_DIR_LENGTH = 22; +const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH = 20; +const ZIP64_END_OF_CENTRAL_DIR_LENGTH = 56; + +const EXTRAFIELD_TYPE_ZIP64 = 0x0001; +const EXTRAFIELD_TYPE_AES = 0x9901; +const EXTRAFIELD_TYPE_NTFS = 0x000a; +const EXTRAFIELD_TYPE_NTFS_TAG1 = 0x0001; +const EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP = 0x5455; +const EXTRAFIELD_TYPE_UNICODE_PATH = 0x7075; +const EXTRAFIELD_TYPE_UNICODE_COMMENT = 0x6375; +const EXTRAFIELD_TYPE_USDZ = 0x1986; + +const BITFLAG_ENCRYPTED = 0x01; +const BITFLAG_LEVEL = 0x06; +const BITFLAG_DATA_DESCRIPTOR = 0x0008; +const BITFLAG_LANG_ENCODING_FLAG = 0x0800; +const FILE_ATTR_MSDOS_DIR_MASK = 0x10; + +const DIRECTORY_SIGNATURE = "/"; + +const UNDEFINED_VALUE = undefined; +const UNDEFINED_TYPE = "undefined"; +const FUNCTION_TYPE = "function"; + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +class StreamAdapter { + + constructor(Codec) { + return class extends TransformStream { + constructor(_format, options) { + const codec = new Codec(options); + super({ + transform(chunk, controller) { + controller.enqueue(codec.append(chunk)); + }, + flush(controller) { + const chunk = codec.flush(); + if (chunk) { + controller.enqueue(chunk); + } + } + }); + } + }; + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const MINIMUM_CHUNK_SIZE = 64; +let maxWorkers = 2; +try { + if (typeof navigator != UNDEFINED_TYPE && navigator.hardwareConcurrency) { + maxWorkers = navigator.hardwareConcurrency; + } +} catch (_error) { + // ignored +} +const DEFAULT_CONFIGURATION = { + chunkSize: 512 * 1024, + maxWorkers, + terminateWorkerTimeout: 5000, + useWebWorkers: true, + useCompressionStream: true, + workerScripts: UNDEFINED_VALUE, + CompressionStreamNative: typeof CompressionStream != UNDEFINED_TYPE && CompressionStream, + DecompressionStreamNative: typeof DecompressionStream != UNDEFINED_TYPE && DecompressionStream +}; + +const config = Object.assign({}, DEFAULT_CONFIGURATION); + +function getConfiguration() { + return config; +} + +function getChunkSize(config) { + return Math.max(config.chunkSize, MINIMUM_CHUNK_SIZE); +} + +function configure(configuration) { + const { + baseURL, + chunkSize, + maxWorkers, + terminateWorkerTimeout, + useCompressionStream, + useWebWorkers, + Deflate, + Inflate, + CompressionStream, + DecompressionStream, + workerScripts + } = configuration; + setIfDefined("baseURL", baseURL); + setIfDefined("chunkSize", chunkSize); + setIfDefined("maxWorkers", maxWorkers); + setIfDefined("terminateWorkerTimeout", terminateWorkerTimeout); + setIfDefined("useCompressionStream", useCompressionStream); + setIfDefined("useWebWorkers", useWebWorkers); + if (Deflate) { + config.CompressionStream = new StreamAdapter(Deflate); + } + if (Inflate) { + config.DecompressionStream = new StreamAdapter(Inflate); + } + setIfDefined("CompressionStream", CompressionStream); + setIfDefined("DecompressionStream", DecompressionStream); + if (workerScripts !== UNDEFINED_VALUE) { + const { deflate, inflate } = workerScripts; + if (deflate || inflate) { + if (!config.workerScripts) { + config.workerScripts = {}; + } + } + if (deflate) { + if (!Array.isArray(deflate)) { + throw new Error("workerScripts.deflate must be an array"); + } + config.workerScripts.deflate = deflate; + } + if (inflate) { + if (!Array.isArray(inflate)) { + throw new Error("workerScripts.inflate must be an array"); + } + config.workerScripts.inflate = inflate; + } + } +} + +function setIfDefined(propertyName, propertyValue) { + if (propertyValue !== UNDEFINED_VALUE) { + config[propertyName] = propertyValue; + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const table$1 = { + "application": { + "andrew-inset": "ez", + "annodex": "anx", + "atom+xml": "atom", + "atomcat+xml": "atomcat", + "atomserv+xml": "atomsrv", + "bbolin": "lin", + "cu-seeme": "cu", + "davmount+xml": "davmount", + "dsptype": "tsp", + "ecmascript": [ + "es", + "ecma" + ], + "futuresplash": "spl", + "hta": "hta", + "java-archive": "jar", + "java-serialized-object": "ser", + "java-vm": "class", + "m3g": "m3g", + "mac-binhex40": "hqx", + "mathematica": [ + "nb", + "ma", + "mb" + ], + "msaccess": "mdb", + "msword": [ + "doc", + "dot", + "wiz" + ], + "mxf": "mxf", + "oda": "oda", + "ogg": "ogx", + "pdf": "pdf", + "pgp-keys": "key", + "pgp-signature": [ + "asc", + "sig" + ], + "pics-rules": "prf", + "postscript": [ + "ps", + "ai", + "eps", + "epsi", + "epsf", + "eps2", + "eps3" + ], + "rar": "rar", + "rdf+xml": "rdf", + "rss+xml": "rss", + "rtf": "rtf", + "xhtml+xml": [ + "xhtml", + "xht" + ], + "xml": [ + "xml", + "xsl", + "xsd", + "xpdl" + ], + "xspf+xml": "xspf", + "zip": "zip", + "vnd.android.package-archive": "apk", + "vnd.cinderella": "cdy", + "vnd.google-earth.kml+xml": "kml", + "vnd.google-earth.kmz": "kmz", + "vnd.mozilla.xul+xml": "xul", + "vnd.ms-excel": [ + "xls", + "xlb", + "xlt", + "xlm", + "xla", + "xlc", + "xlw" + ], + "vnd.ms-pki.seccat": "cat", + "vnd.ms-pki.stl": "stl", + "vnd.ms-powerpoint": [ + "ppt", + "pps", + "pot", + "ppa", + "pwz" + ], + "vnd.oasis.opendocument.chart": "odc", + "vnd.oasis.opendocument.database": "odb", + "vnd.oasis.opendocument.formula": "odf", + "vnd.oasis.opendocument.graphics": "odg", + "vnd.oasis.opendocument.graphics-template": "otg", + "vnd.oasis.opendocument.image": "odi", + "vnd.oasis.opendocument.presentation": "odp", + "vnd.oasis.opendocument.presentation-template": "otp", + "vnd.oasis.opendocument.spreadsheet": "ods", + "vnd.oasis.opendocument.spreadsheet-template": "ots", + "vnd.oasis.opendocument.text": "odt", + "vnd.oasis.opendocument.text-master": [ + "odm", + "otm" + ], + "vnd.oasis.opendocument.text-template": "ott", + "vnd.oasis.opendocument.text-web": "oth", + "vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx", + "vnd.openxmlformats-officedocument.spreadsheetml.template": "xltx", + "vnd.openxmlformats-officedocument.presentationml.presentation": "pptx", + "vnd.openxmlformats-officedocument.presentationml.slideshow": "ppsx", + "vnd.openxmlformats-officedocument.presentationml.template": "potx", + "vnd.openxmlformats-officedocument.wordprocessingml.document": "docx", + "vnd.openxmlformats-officedocument.wordprocessingml.template": "dotx", + "vnd.smaf": "mmf", + "vnd.stardivision.calc": "sdc", + "vnd.stardivision.chart": "sds", + "vnd.stardivision.draw": "sda", + "vnd.stardivision.impress": "sdd", + "vnd.stardivision.math": [ + "sdf", + "smf" + ], + "vnd.stardivision.writer": [ + "sdw", + "vor" + ], + "vnd.stardivision.writer-global": "sgl", + "vnd.sun.xml.calc": "sxc", + "vnd.sun.xml.calc.template": "stc", + "vnd.sun.xml.draw": "sxd", + "vnd.sun.xml.draw.template": "std", + "vnd.sun.xml.impress": "sxi", + "vnd.sun.xml.impress.template": "sti", + "vnd.sun.xml.math": "sxm", + "vnd.sun.xml.writer": "sxw", + "vnd.sun.xml.writer.global": "sxg", + "vnd.sun.xml.writer.template": "stw", + "vnd.symbian.install": [ + "sis", + "sisx" + ], + "vnd.visio": [ + "vsd", + "vst", + "vss", + "vsw", + "vsdx", + "vssx", + "vstx", + "vssm", + "vstm" + ], + "vnd.wap.wbxml": "wbxml", + "vnd.wap.wmlc": "wmlc", + "vnd.wap.wmlscriptc": "wmlsc", + "vnd.wordperfect": "wpd", + "vnd.wordperfect5.1": "wp5", + "x-123": "wk", + "x-7z-compressed": "7z", + "x-abiword": "abw", + "x-apple-diskimage": "dmg", + "x-bcpio": "bcpio", + "x-bittorrent": "torrent", + "x-cbr": [ + "cbr", + "cba", + "cbt", + "cb7" + ], + "x-cbz": "cbz", + "x-cdf": [ + "cdf", + "cda" + ], + "x-cdlink": "vcd", + "x-chess-pgn": "pgn", + "x-cpio": "cpio", + "x-csh": "csh", + "x-director": [ + "dir", + "dxr", + "cst", + "cct", + "cxt", + "w3d", + "fgd", + "swa" + ], + "x-dms": "dms", + "x-doom": "wad", + "x-dvi": "dvi", + "x-httpd-eruby": "rhtml", + "x-font": "pcf.Z", + "x-freemind": "mm", + "x-gnumeric": "gnumeric", + "x-go-sgf": "sgf", + "x-graphing-calculator": "gcf", + "x-gtar": [ + "gtar", + "taz" + ], + "x-hdf": "hdf", + "x-httpd-php": [ + "phtml", + "pht", + "php" + ], + "x-httpd-php-source": "phps", + "x-httpd-php3": "php3", + "x-httpd-php3-preprocessed": "php3p", + "x-httpd-php4": "php4", + "x-httpd-php5": "php5", + "x-ica": "ica", + "x-info": "info", + "x-internet-signup": [ + "ins", + "isp" + ], + "x-iphone": "iii", + "x-iso9660-image": "iso", + "x-java-jnlp-file": "jnlp", + "x-jmol": "jmz", + "x-killustrator": "kil", + "x-latex": "latex", + "x-lyx": "lyx", + "x-lzx": "lzx", + "x-maker": [ + "frm", + "fb", + "fbdoc" + ], + "x-ms-wmd": "wmd", + "x-msdos-program": [ + "com", + "exe", + "bat", + "dll" + ], + "x-netcdf": [ + "nc" + ], + "x-ns-proxy-autoconfig": [ + "pac", + "dat" + ], + "x-nwc": "nwc", + "x-object": "o", + "x-oz-application": "oza", + "x-pkcs7-certreqresp": "p7r", + "x-python-code": [ + "pyc", + "pyo" + ], + "x-qgis": [ + "qgs", + "shp", + "shx" + ], + "x-quicktimeplayer": "qtl", + "x-redhat-package-manager": [ + "rpm", + "rpa" + ], + "x-ruby": "rb", + "x-sh": "sh", + "x-shar": "shar", + "x-shockwave-flash": [ + "swf", + "swfl" + ], + "x-silverlight": "scr", + "x-stuffit": "sit", + "x-sv4cpio": "sv4cpio", + "x-sv4crc": "sv4crc", + "x-tar": "tar", + "x-tex-gf": "gf", + "x-tex-pk": "pk", + "x-texinfo": [ + "texinfo", + "texi" + ], + "x-trash": [ + "~", + "%", + "bak", + "old", + "sik" + ], + "x-ustar": "ustar", + "x-wais-source": "src", + "x-wingz": "wz", + "x-x509-ca-cert": [ + "crt", + "der", + "cer" + ], + "x-xcf": "xcf", + "x-xfig": "fig", + "x-xpinstall": "xpi", + "applixware": "aw", + "atomsvc+xml": "atomsvc", + "ccxml+xml": "ccxml", + "cdmi-capability": "cdmia", + "cdmi-container": "cdmic", + "cdmi-domain": "cdmid", + "cdmi-object": "cdmio", + "cdmi-queue": "cdmiq", + "docbook+xml": "dbk", + "dssc+der": "dssc", + "dssc+xml": "xdssc", + "emma+xml": "emma", + "epub+zip": "epub", + "exi": "exi", + "font-tdpfr": "pfr", + "gml+xml": "gml", + "gpx+xml": "gpx", + "gxf": "gxf", + "hyperstudio": "stk", + "inkml+xml": [ + "ink", + "inkml" + ], + "ipfix": "ipfix", + "jsonml+json": "jsonml", + "lost+xml": "lostxml", + "mads+xml": "mads", + "marc": "mrc", + "marcxml+xml": "mrcx", + "mathml+xml": [ + "mathml", + "mml" + ], + "mbox": "mbox", + "mediaservercontrol+xml": "mscml", + "metalink+xml": "metalink", + "metalink4+xml": "meta4", + "mets+xml": "mets", + "mods+xml": "mods", + "mp21": [ + "m21", + "mp21" + ], + "mp4": "mp4s", + "oebps-package+xml": "opf", + "omdoc+xml": "omdoc", + "onenote": [ + "onetoc", + "onetoc2", + "onetmp", + "onepkg" + ], + "oxps": "oxps", + "patch-ops-error+xml": "xer", + "pgp-encrypted": "pgp", + "pkcs10": "p10", + "pkcs7-mime": [ + "p7m", + "p7c" + ], + "pkcs7-signature": "p7s", + "pkcs8": "p8", + "pkix-attr-cert": "ac", + "pkix-crl": "crl", + "pkix-pkipath": "pkipath", + "pkixcmp": "pki", + "pls+xml": "pls", + "prs.cww": "cww", + "pskc+xml": "pskcxml", + "reginfo+xml": "rif", + "relax-ng-compact-syntax": "rnc", + "resource-lists+xml": "rl", + "resource-lists-diff+xml": "rld", + "rls-services+xml": "rs", + "rpki-ghostbusters": "gbr", + "rpki-manifest": "mft", + "rpki-roa": "roa", + "rsd+xml": "rsd", + "sbml+xml": "sbml", + "scvp-cv-request": "scq", + "scvp-cv-response": "scs", + "scvp-vp-request": "spq", + "scvp-vp-response": "spp", + "sdp": "sdp", + "set-payment-initiation": "setpay", + "set-registration-initiation": "setreg", + "shf+xml": "shf", + "sparql-query": "rq", + "sparql-results+xml": "srx", + "srgs": "gram", + "srgs+xml": "grxml", + "sru+xml": "sru", + "ssdl+xml": "ssdl", + "ssml+xml": "ssml", + "tei+xml": [ + "tei", + "teicorpus" + ], + "thraud+xml": "tfi", + "timestamped-data": "tsd", + "vnd.3gpp.pic-bw-large": "plb", + "vnd.3gpp.pic-bw-small": "psb", + "vnd.3gpp.pic-bw-var": "pvb", + "vnd.3gpp2.tcap": "tcap", + "vnd.3m.post-it-notes": "pwn", + "vnd.accpac.simply.aso": "aso", + "vnd.accpac.simply.imp": "imp", + "vnd.acucobol": "acu", + "vnd.acucorp": [ + "atc", + "acutc" + ], + "vnd.adobe.air-application-installer-package+zip": "air", + "vnd.adobe.formscentral.fcdt": "fcdt", + "vnd.adobe.fxp": [ + "fxp", + "fxpl" + ], + "vnd.adobe.xdp+xml": "xdp", + "vnd.adobe.xfdf": "xfdf", + "vnd.ahead.space": "ahead", + "vnd.airzip.filesecure.azf": "azf", + "vnd.airzip.filesecure.azs": "azs", + "vnd.amazon.ebook": "azw", + "vnd.americandynamics.acc": "acc", + "vnd.amiga.ami": "ami", + "vnd.anser-web-certificate-issue-initiation": "cii", + "vnd.anser-web-funds-transfer-initiation": "fti", + "vnd.antix.game-component": "atx", + "vnd.apple.installer+xml": "mpkg", + "vnd.apple.mpegurl": "m3u8", + "vnd.aristanetworks.swi": "swi", + "vnd.astraea-software.iota": "iota", + "vnd.audiograph": "aep", + "vnd.blueice.multipass": "mpm", + "vnd.bmi": "bmi", + "vnd.businessobjects": "rep", + "vnd.chemdraw+xml": "cdxml", + "vnd.chipnuts.karaoke-mmd": "mmd", + "vnd.claymore": "cla", + "vnd.cloanto.rp9": "rp9", + "vnd.clonk.c4group": [ + "c4g", + "c4d", + "c4f", + "c4p", + "c4u" + ], + "vnd.cluetrust.cartomobile-config": "c11amc", + "vnd.cluetrust.cartomobile-config-pkg": "c11amz", + "vnd.commonspace": "csp", + "vnd.contact.cmsg": "cdbcmsg", + "vnd.cosmocaller": "cmc", + "vnd.crick.clicker": "clkx", + "vnd.crick.clicker.keyboard": "clkk", + "vnd.crick.clicker.palette": "clkp", + "vnd.crick.clicker.template": "clkt", + "vnd.crick.clicker.wordbank": "clkw", + "vnd.criticaltools.wbs+xml": "wbs", + "vnd.ctc-posml": "pml", + "vnd.cups-ppd": "ppd", + "vnd.curl.car": "car", + "vnd.curl.pcurl": "pcurl", + "vnd.dart": "dart", + "vnd.data-vision.rdz": "rdz", + "vnd.dece.data": [ + "uvf", + "uvvf", + "uvd", + "uvvd" + ], + "vnd.dece.ttml+xml": [ + "uvt", + "uvvt" + ], + "vnd.dece.unspecified": [ + "uvx", + "uvvx" + ], + "vnd.dece.zip": [ + "uvz", + "uvvz" + ], + "vnd.denovo.fcselayout-link": "fe_launch", + "vnd.dna": "dna", + "vnd.dolby.mlp": "mlp", + "vnd.dpgraph": "dpg", + "vnd.dreamfactory": "dfac", + "vnd.ds-keypoint": "kpxx", + "vnd.dvb.ait": "ait", + "vnd.dvb.service": "svc", + "vnd.dynageo": "geo", + "vnd.ecowin.chart": "mag", + "vnd.enliven": "nml", + "vnd.epson.esf": "esf", + "vnd.epson.msf": "msf", + "vnd.epson.quickanime": "qam", + "vnd.epson.salt": "slt", + "vnd.epson.ssf": "ssf", + "vnd.eszigno3+xml": [ + "es3", + "et3" + ], + "vnd.ezpix-album": "ez2", + "vnd.ezpix-package": "ez3", + "vnd.fdf": "fdf", + "vnd.fdsn.mseed": "mseed", + "vnd.fdsn.seed": [ + "seed", + "dataless" + ], + "vnd.flographit": "gph", + "vnd.fluxtime.clip": "ftc", + "vnd.framemaker": [ + "fm", + "frame", + "maker", + "book" + ], + "vnd.frogans.fnc": "fnc", + "vnd.frogans.ltf": "ltf", + "vnd.fsc.weblaunch": "fsc", + "vnd.fujitsu.oasys": "oas", + "vnd.fujitsu.oasys2": "oa2", + "vnd.fujitsu.oasys3": "oa3", + "vnd.fujitsu.oasysgp": "fg5", + "vnd.fujitsu.oasysprs": "bh2", + "vnd.fujixerox.ddd": "ddd", + "vnd.fujixerox.docuworks": "xdw", + "vnd.fujixerox.docuworks.binder": "xbd", + "vnd.fuzzysheet": "fzs", + "vnd.genomatix.tuxedo": "txd", + "vnd.geogebra.file": "ggb", + "vnd.geogebra.tool": "ggt", + "vnd.geometry-explorer": [ + "gex", + "gre" + ], + "vnd.geonext": "gxt", + "vnd.geoplan": "g2w", + "vnd.geospace": "g3w", + "vnd.gmx": "gmx", + "vnd.grafeq": [ + "gqf", + "gqs" + ], + "vnd.groove-account": "gac", + "vnd.groove-help": "ghf", + "vnd.groove-identity-message": "gim", + "vnd.groove-injector": "grv", + "vnd.groove-tool-message": "gtm", + "vnd.groove-tool-template": "tpl", + "vnd.groove-vcard": "vcg", + "vnd.hal+xml": "hal", + "vnd.handheld-entertainment+xml": "zmm", + "vnd.hbci": "hbci", + "vnd.hhe.lesson-player": "les", + "vnd.hp-hpgl": "hpgl", + "vnd.hp-hpid": "hpid", + "vnd.hp-hps": "hps", + "vnd.hp-jlyt": "jlt", + "vnd.hp-pcl": "pcl", + "vnd.hp-pclxl": "pclxl", + "vnd.hydrostatix.sof-data": "sfd-hdstx", + "vnd.ibm.minipay": "mpy", + "vnd.ibm.modcap": [ + "afp", + "listafp", + "list3820" + ], + "vnd.ibm.rights-management": "irm", + "vnd.ibm.secure-container": "sc", + "vnd.iccprofile": [ + "icc", + "icm" + ], + "vnd.igloader": "igl", + "vnd.immervision-ivp": "ivp", + "vnd.immervision-ivu": "ivu", + "vnd.insors.igm": "igm", + "vnd.intercon.formnet": [ + "xpw", + "xpx" + ], + "vnd.intergeo": "i2g", + "vnd.intu.qbo": "qbo", + "vnd.intu.qfx": "qfx", + "vnd.ipunplugged.rcprofile": "rcprofile", + "vnd.irepository.package+xml": "irp", + "vnd.is-xpr": "xpr", + "vnd.isac.fcs": "fcs", + "vnd.jam": "jam", + "vnd.jcp.javame.midlet-rms": "rms", + "vnd.jisp": "jisp", + "vnd.joost.joda-archive": "joda", + "vnd.kahootz": [ + "ktz", + "ktr" + ], + "vnd.kde.karbon": "karbon", + "vnd.kde.kchart": "chrt", + "vnd.kde.kformula": "kfo", + "vnd.kde.kivio": "flw", + "vnd.kde.kontour": "kon", + "vnd.kde.kpresenter": [ + "kpr", + "kpt" + ], + "vnd.kde.kspread": "ksp", + "vnd.kde.kword": [ + "kwd", + "kwt" + ], + "vnd.kenameaapp": "htke", + "vnd.kidspiration": "kia", + "vnd.kinar": [ + "kne", + "knp" + ], + "vnd.koan": [ + "skp", + "skd", + "skt", + "skm" + ], + "vnd.kodak-descriptor": "sse", + "vnd.las.las+xml": "lasxml", + "vnd.llamagraphics.life-balance.desktop": "lbd", + "vnd.llamagraphics.life-balance.exchange+xml": "lbe", + "vnd.lotus-1-2-3": "123", + "vnd.lotus-approach": "apr", + "vnd.lotus-freelance": "pre", + "vnd.lotus-notes": "nsf", + "vnd.lotus-organizer": "org", + "vnd.lotus-screencam": "scm", + "vnd.lotus-wordpro": "lwp", + "vnd.macports.portpkg": "portpkg", + "vnd.mcd": "mcd", + "vnd.medcalcdata": "mc1", + "vnd.mediastation.cdkey": "cdkey", + "vnd.mfer": "mwf", + "vnd.mfmp": "mfm", + "vnd.micrografx.flo": "flo", + "vnd.micrografx.igx": "igx", + "vnd.mif": "mif", + "vnd.mobius.daf": "daf", + "vnd.mobius.dis": "dis", + "vnd.mobius.mbk": "mbk", + "vnd.mobius.mqy": "mqy", + "vnd.mobius.msl": "msl", + "vnd.mobius.plc": "plc", + "vnd.mobius.txf": "txf", + "vnd.mophun.application": "mpn", + "vnd.mophun.certificate": "mpc", + "vnd.ms-artgalry": "cil", + "vnd.ms-cab-compressed": "cab", + "vnd.ms-excel.addin.macroenabled.12": "xlam", + "vnd.ms-excel.sheet.binary.macroenabled.12": "xlsb", + "vnd.ms-excel.sheet.macroenabled.12": "xlsm", + "vnd.ms-excel.template.macroenabled.12": "xltm", + "vnd.ms-fontobject": "eot", + "vnd.ms-htmlhelp": "chm", + "vnd.ms-ims": "ims", + "vnd.ms-lrm": "lrm", + "vnd.ms-officetheme": "thmx", + "vnd.ms-powerpoint.addin.macroenabled.12": "ppam", + "vnd.ms-powerpoint.presentation.macroenabled.12": "pptm", + "vnd.ms-powerpoint.slide.macroenabled.12": "sldm", + "vnd.ms-powerpoint.slideshow.macroenabled.12": "ppsm", + "vnd.ms-powerpoint.template.macroenabled.12": "potm", + "vnd.ms-project": [ + "mpp", + "mpt" + ], + "vnd.ms-word.document.macroenabled.12": "docm", + "vnd.ms-word.template.macroenabled.12": "dotm", + "vnd.ms-works": [ + "wps", + "wks", + "wcm", + "wdb" + ], + "vnd.ms-wpl": "wpl", + "vnd.ms-xpsdocument": "xps", + "vnd.mseq": "mseq", + "vnd.musician": "mus", + "vnd.muvee.style": "msty", + "vnd.mynfc": "taglet", + "vnd.neurolanguage.nlu": "nlu", + "vnd.nitf": [ + "ntf", + "nitf" + ], + "vnd.noblenet-directory": "nnd", + "vnd.noblenet-sealer": "nns", + "vnd.noblenet-web": "nnw", + "vnd.nokia.n-gage.data": "ngdat", + "vnd.nokia.n-gage.symbian.install": "n-gage", + "vnd.nokia.radio-preset": "rpst", + "vnd.nokia.radio-presets": "rpss", + "vnd.novadigm.edm": "edm", + "vnd.novadigm.edx": "edx", + "vnd.novadigm.ext": "ext", + "vnd.oasis.opendocument.chart-template": "otc", + "vnd.oasis.opendocument.formula-template": "odft", + "vnd.oasis.opendocument.image-template": "oti", + "vnd.olpc-sugar": "xo", + "vnd.oma.dd2+xml": "dd2", + "vnd.openofficeorg.extension": "oxt", + "vnd.openxmlformats-officedocument.presentationml.slide": "sldx", + "vnd.osgeo.mapguide.package": "mgp", + "vnd.osgi.dp": "dp", + "vnd.osgi.subsystem": "esa", + "vnd.palm": [ + "pdb", + "pqa", + "oprc" + ], + "vnd.pawaafile": "paw", + "vnd.pg.format": "str", + "vnd.pg.osasli": "ei6", + "vnd.picsel": "efif", + "vnd.pmi.widget": "wg", + "vnd.pocketlearn": "plf", + "vnd.powerbuilder6": "pbd", + "vnd.previewsystems.box": "box", + "vnd.proteus.magazine": "mgz", + "vnd.publishare-delta-tree": "qps", + "vnd.pvi.ptid1": "ptid", + "vnd.quark.quarkxpress": [ + "qxd", + "qxt", + "qwd", + "qwt", + "qxl", + "qxb" + ], + "vnd.realvnc.bed": "bed", + "vnd.recordare.musicxml": "mxl", + "vnd.recordare.musicxml+xml": "musicxml", + "vnd.rig.cryptonote": "cryptonote", + "vnd.rn-realmedia": "rm", + "vnd.rn-realmedia-vbr": "rmvb", + "vnd.route66.link66+xml": "link66", + "vnd.sailingtracker.track": "st", + "vnd.seemail": "see", + "vnd.sema": "sema", + "vnd.semd": "semd", + "vnd.semf": "semf", + "vnd.shana.informed.formdata": "ifm", + "vnd.shana.informed.formtemplate": "itp", + "vnd.shana.informed.interchange": "iif", + "vnd.shana.informed.package": "ipk", + "vnd.simtech-mindmapper": [ + "twd", + "twds" + ], + "vnd.smart.teacher": "teacher", + "vnd.solent.sdkm+xml": [ + "sdkm", + "sdkd" + ], + "vnd.spotfire.dxp": "dxp", + "vnd.spotfire.sfs": "sfs", + "vnd.stepmania.package": "smzip", + "vnd.stepmania.stepchart": "sm", + "vnd.sus-calendar": [ + "sus", + "susp" + ], + "vnd.svd": "svd", + "vnd.syncml+xml": "xsm", + "vnd.syncml.dm+wbxml": "bdm", + "vnd.syncml.dm+xml": "xdm", + "vnd.tao.intent-module-archive": "tao", + "vnd.tcpdump.pcap": [ + "pcap", + "cap", + "dmp" + ], + "vnd.tmobile-livetv": "tmo", + "vnd.trid.tpt": "tpt", + "vnd.triscape.mxs": "mxs", + "vnd.trueapp": "tra", + "vnd.ufdl": [ + "ufd", + "ufdl" + ], + "vnd.uiq.theme": "utz", + "vnd.umajin": "umj", + "vnd.unity": "unityweb", + "vnd.uoml+xml": "uoml", + "vnd.vcx": "vcx", + "vnd.visionary": "vis", + "vnd.vsf": "vsf", + "vnd.webturbo": "wtb", + "vnd.wolfram.player": "nbp", + "vnd.wqd": "wqd", + "vnd.wt.stf": "stf", + "vnd.xara": "xar", + "vnd.xfdl": "xfdl", + "vnd.yamaha.hv-dic": "hvd", + "vnd.yamaha.hv-script": "hvs", + "vnd.yamaha.hv-voice": "hvp", + "vnd.yamaha.openscoreformat": "osf", + "vnd.yamaha.openscoreformat.osfpvg+xml": "osfpvg", + "vnd.yamaha.smaf-audio": "saf", + "vnd.yamaha.smaf-phrase": "spf", + "vnd.yellowriver-custom-menu": "cmp", + "vnd.zul": [ + "zir", + "zirz" + ], + "vnd.zzazz.deck+xml": "zaz", + "voicexml+xml": "vxml", + "widget": "wgt", + "winhlp": "hlp", + "wsdl+xml": "wsdl", + "wspolicy+xml": "wspolicy", + "x-ace-compressed": "ace", + "x-authorware-bin": [ + "aab", + "x32", + "u32", + "vox" + ], + "x-authorware-map": "aam", + "x-authorware-seg": "aas", + "x-blorb": [ + "blb", + "blorb" + ], + "x-bzip": "bz", + "x-bzip2": [ + "bz2", + "boz" + ], + "x-cfs-compressed": "cfs", + "x-chat": "chat", + "x-conference": "nsc", + "x-dgc-compressed": "dgc", + "x-dtbncx+xml": "ncx", + "x-dtbook+xml": "dtb", + "x-dtbresource+xml": "res", + "x-eva": "eva", + "x-font-bdf": "bdf", + "x-font-ghostscript": "gsf", + "x-font-linux-psf": "psf", + "x-font-pcf": "pcf", + "x-font-snf": "snf", + "x-font-ttf": [ + "ttf", + "ttc" + ], + "x-font-type1": [ + "pfa", + "pfb", + "pfm", + "afm" + ], + "x-freearc": "arc", + "x-gca-compressed": "gca", + "x-glulx": "ulx", + "x-gramps-xml": "gramps", + "x-install-instructions": "install", + "x-lzh-compressed": [ + "lzh", + "lha" + ], + "x-mie": "mie", + "x-mobipocket-ebook": [ + "prc", + "mobi" + ], + "x-ms-application": "application", + "x-ms-shortcut": "lnk", + "x-ms-xbap": "xbap", + "x-msbinder": "obd", + "x-mscardfile": "crd", + "x-msclip": "clp", + "application/x-ms-installer": "msi", + "x-msmediaview": [ + "mvb", + "m13", + "m14" + ], + "x-msmetafile": [ + "wmf", + "wmz", + "emf", + "emz" + ], + "x-msmoney": "mny", + "x-mspublisher": "pub", + "x-msschedule": "scd", + "x-msterminal": "trm", + "x-mswrite": "wri", + "x-nzb": "nzb", + "x-pkcs12": [ + "p12", + "pfx" + ], + "x-pkcs7-certificates": [ + "p7b", + "spc" + ], + "x-research-info-systems": "ris", + "x-silverlight-app": "xap", + "x-sql": "sql", + "x-stuffitx": "sitx", + "x-subrip": "srt", + "x-t3vm-image": "t3", + "x-tex-tfm": "tfm", + "x-tgif": "obj", + "x-xliff+xml": "xlf", + "x-xz": "xz", + "x-zmachine": [ + "z1", + "z2", + "z3", + "z4", + "z5", + "z6", + "z7", + "z8" + ], + "xaml+xml": "xaml", + "xcap-diff+xml": "xdf", + "xenc+xml": "xenc", + "xml-dtd": "dtd", + "xop+xml": "xop", + "xproc+xml": "xpl", + "xslt+xml": "xslt", + "xv+xml": [ + "mxml", + "xhvml", + "xvml", + "xvm" + ], + "yang": "yang", + "yin+xml": "yin", + "envoy": "evy", + "fractals": "fif", + "internet-property-stream": "acx", + "olescript": "axs", + "vnd.ms-outlook": "msg", + "vnd.ms-pkicertstore": "sst", + "x-compress": "z", + "x-perfmon": [ + "pma", + "pmc", + "pmr", + "pmw" + ], + "ynd.ms-pkipko": "pko", + "gzip": [ + "gz", + "tgz" + ], + "smil+xml": [ + "smi", + "smil" + ], + "vnd.debian.binary-package": [ + "deb", + "udeb" + ], + "vnd.hzn-3d-crossword": "x3d", + "vnd.sqlite3": [ + "db", + "sqlite", + "sqlite3", + "db-wal", + "sqlite-wal", + "db-shm", + "sqlite-shm" + ], + "vnd.wap.sic": "sic", + "vnd.wap.slc": "slc", + "x-krita": [ + "kra", + "krz" + ], + "x-perl": [ + "pm", + "pl" + ], + "yaml": [ + "yaml", + "yml" + ] + }, + "audio": { + "amr": "amr", + "amr-wb": "awb", + "annodex": "axa", + "basic": [ + "au", + "snd" + ], + "flac": "flac", + "midi": [ + "mid", + "midi", + "kar", + "rmi" + ], + "mpeg": [ + "mpga", + "mpega", + "mp3", + "m4a", + "mp2a", + "m2a", + "m3a" + ], + "mpegurl": "m3u", + "ogg": [ + "oga", + "ogg", + "spx" + ], + "prs.sid": "sid", + "x-aiff": "aifc", + "x-gsm": "gsm", + "x-ms-wma": "wma", + "x-ms-wax": "wax", + "x-pn-realaudio": "ram", + "x-realaudio": "ra", + "x-sd2": "sd2", + "adpcm": "adp", + "mp4": "mp4a", + "s3m": "s3m", + "silk": "sil", + "vnd.dece.audio": [ + "uva", + "uvva" + ], + "vnd.digital-winds": "eol", + "vnd.dra": "dra", + "vnd.dts": "dts", + "vnd.dts.hd": "dtshd", + "vnd.lucent.voice": "lvp", + "vnd.ms-playready.media.pya": "pya", + "vnd.nuera.ecelp4800": "ecelp4800", + "vnd.nuera.ecelp7470": "ecelp7470", + "vnd.nuera.ecelp9600": "ecelp9600", + "vnd.rip": "rip", + "webm": "weba", + "x-caf": "caf", + "x-matroska": "mka", + "x-pn-realaudio-plugin": "rmp", + "xm": "xm", + "aac": "aac", + "aiff": [ + "aiff", + "aif", + "aff" + ], + "opus": "opus", + "wav": "wav" + }, + "chemical": { + "x-alchemy": "alc", + "x-cache": [ + "cac", + "cache" + ], + "x-cache-csf": "csf", + "x-cactvs-binary": [ + "cbin", + "cascii", + "ctab" + ], + "x-cdx": "cdx", + "x-chem3d": "c3d", + "x-cif": "cif", + "x-cmdf": "cmdf", + "x-cml": "cml", + "x-compass": "cpa", + "x-crossfire": "bsd", + "x-csml": [ + "csml", + "csm" + ], + "x-ctx": "ctx", + "x-cxf": [ + "cxf", + "cef" + ], + "x-embl-dl-nucleotide": [ + "emb", + "embl" + ], + "x-gamess-input": [ + "inp", + "gam", + "gamin" + ], + "x-gaussian-checkpoint": [ + "fch", + "fchk" + ], + "x-gaussian-cube": "cub", + "x-gaussian-input": [ + "gau", + "gjc", + "gjf" + ], + "x-gaussian-log": "gal", + "x-gcg8-sequence": "gcg", + "x-genbank": "gen", + "x-hin": "hin", + "x-isostar": [ + "istr", + "ist" + ], + "x-jcamp-dx": [ + "jdx", + "dx" + ], + "x-kinemage": "kin", + "x-macmolecule": "mcm", + "x-macromodel-input": "mmod", + "x-mdl-molfile": "mol", + "x-mdl-rdfile": "rd", + "x-mdl-rxnfile": "rxn", + "x-mdl-sdfile": "sd", + "x-mdl-tgf": "tgf", + "x-mmcif": "mcif", + "x-mol2": "mol2", + "x-molconn-Z": "b", + "x-mopac-graph": "gpt", + "x-mopac-input": [ + "mop", + "mopcrt", + "zmt" + ], + "x-mopac-out": "moo", + "x-ncbi-asn1": "asn", + "x-ncbi-asn1-ascii": [ + "prt", + "ent" + ], + "x-ncbi-asn1-binary": "val", + "x-rosdal": "ros", + "x-swissprot": "sw", + "x-vamas-iso14976": "vms", + "x-vmd": "vmd", + "x-xtel": "xtel", + "x-xyz": "xyz" + }, + "font": { + "otf": "otf", + "woff": "woff", + "woff2": "woff2" + }, + "image": { + "gif": "gif", + "ief": "ief", + "jpeg": [ + "jpeg", + "jpg", + "jpe", + "jfif", + "jfif-tbnl", + "jif" + ], + "pcx": "pcx", + "png": "png", + "svg+xml": [ + "svg", + "svgz" + ], + "tiff": [ + "tiff", + "tif" + ], + "vnd.djvu": [ + "djvu", + "djv" + ], + "vnd.wap.wbmp": "wbmp", + "x-canon-cr2": "cr2", + "x-canon-crw": "crw", + "x-cmu-raster": "ras", + "x-coreldraw": "cdr", + "x-coreldrawpattern": "pat", + "x-coreldrawtemplate": "cdt", + "x-corelphotopaint": "cpt", + "x-epson-erf": "erf", + "x-icon": "ico", + "x-jg": "art", + "x-jng": "jng", + "x-nikon-nef": "nef", + "x-olympus-orf": "orf", + "x-portable-anymap": "pnm", + "x-portable-bitmap": "pbm", + "x-portable-graymap": "pgm", + "x-portable-pixmap": "ppm", + "x-rgb": "rgb", + "x-xbitmap": "xbm", + "x-xpixmap": "xpm", + "x-xwindowdump": "xwd", + "bmp": "bmp", + "cgm": "cgm", + "g3fax": "g3", + "ktx": "ktx", + "prs.btif": "btif", + "sgi": "sgi", + "vnd.dece.graphic": [ + "uvi", + "uvvi", + "uvg", + "uvvg" + ], + "vnd.dwg": "dwg", + "vnd.dxf": "dxf", + "vnd.fastbidsheet": "fbs", + "vnd.fpx": "fpx", + "vnd.fst": "fst", + "vnd.fujixerox.edmics-mmr": "mmr", + "vnd.fujixerox.edmics-rlc": "rlc", + "vnd.ms-modi": "mdi", + "vnd.ms-photo": "wdp", + "vnd.net-fpx": "npx", + "vnd.xiff": "xif", + "webp": "webp", + "x-3ds": "3ds", + "x-cmx": "cmx", + "x-freehand": [ + "fh", + "fhc", + "fh4", + "fh5", + "fh7" + ], + "x-pict": [ + "pic", + "pct" + ], + "x-tga": "tga", + "cis-cod": "cod", + "avif": "avifs", + "heic": [ + "heif", + "heic" + ], + "pjpeg": [ + "pjpg" + ], + "vnd.adobe.photoshop": "psd", + "x-adobe-dng": "dng", + "x-fuji-raf": "raf", + "x-icns": "icns", + "x-kodak-dcr": "dcr", + "x-kodak-k25": "k25", + "x-kodak-kdc": "kdc", + "x-minolta-mrw": "mrw", + "x-panasonic-raw": [ + "raw", + "rw2", + "rwl" + ], + "x-pentax-pef": [ + "pef", + "ptx" + ], + "x-sigma-x3f": "x3f", + "x-sony-arw": "arw", + "x-sony-sr2": "sr2", + "x-sony-srf": "srf" + }, + "message": { + "rfc822": [ + "eml", + "mime", + "mht", + "mhtml", + "nws" + ] + }, + "model": { + "iges": [ + "igs", + "iges" + ], + "mesh": [ + "msh", + "mesh", + "silo" + ], + "vrml": [ + "wrl", + "vrml" + ], + "x3d+vrml": [ + "x3dv", + "x3dvz" + ], + "x3d+xml": "x3dz", + "x3d+binary": [ + "x3db", + "x3dbz" + ], + "vnd.collada+xml": "dae", + "vnd.dwf": "dwf", + "vnd.gdl": "gdl", + "vnd.gtw": "gtw", + "vnd.mts": "mts", + "vnd.usdz+zip": "usdz", + "vnd.vtu": "vtu" + }, + "text": { + "cache-manifest": [ + "manifest", + "appcache" + ], + "calendar": [ + "ics", + "icz", + "ifb" + ], + "css": "css", + "csv": "csv", + "h323": "323", + "html": [ + "html", + "htm", + "shtml", + "stm" + ], + "iuls": "uls", + "plain": [ + "txt", + "text", + "brf", + "conf", + "def", + "list", + "log", + "in", + "bas", + "diff", + "ksh" + ], + "richtext": "rtx", + "scriptlet": [ + "sct", + "wsc" + ], + "texmacs": "tm", + "tab-separated-values": "tsv", + "vnd.sun.j2me.app-descriptor": "jad", + "vnd.wap.wml": "wml", + "vnd.wap.wmlscript": "wmls", + "x-bibtex": "bib", + "x-boo": "boo", + "x-c++hdr": [ + "h++", + "hpp", + "hxx", + "hh" + ], + "x-c++src": [ + "c++", + "cpp", + "cxx", + "cc" + ], + "x-component": "htc", + "x-dsrc": "d", + "x-diff": "patch", + "x-haskell": "hs", + "x-java": "java", + "x-literate-haskell": "lhs", + "x-moc": "moc", + "x-pascal": [ + "p", + "pas", + "pp", + "inc" + ], + "x-pcs-gcd": "gcd", + "x-python": "py", + "x-scala": "scala", + "x-setext": "etx", + "x-tcl": [ + "tcl", + "tk" + ], + "x-tex": [ + "tex", + "ltx", + "sty", + "cls" + ], + "x-vcalendar": "vcs", + "x-vcard": "vcf", + "n3": "n3", + "prs.lines.tag": "dsc", + "sgml": [ + "sgml", + "sgm" + ], + "troff": [ + "t", + "tr", + "roff", + "man", + "me", + "ms" + ], + "turtle": "ttl", + "uri-list": [ + "uri", + "uris", + "urls" + ], + "vcard": "vcard", + "vnd.curl": "curl", + "vnd.curl.dcurl": "dcurl", + "vnd.curl.scurl": "scurl", + "vnd.curl.mcurl": "mcurl", + "vnd.dvb.subtitle": "sub", + "vnd.fly": "fly", + "vnd.fmi.flexstor": "flx", + "vnd.graphviz": "gv", + "vnd.in3d.3dml": "3dml", + "vnd.in3d.spot": "spot", + "x-asm": [ + "s", + "asm" + ], + "x-c": [ + "c", + "h", + "dic" + ], + "x-fortran": [ + "f", + "for", + "f77", + "f90" + ], + "x-opml": "opml", + "x-nfo": "nfo", + "x-sfv": "sfv", + "x-uuencode": "uu", + "webviewhtml": "htt", + "javascript": "js", + "json": "json", + "markdown": [ + "md", + "markdown", + "mdown", + "markdn" + ], + "vnd.wap.si": "si", + "vnd.wap.sl": "sl" + }, + "video": { + "avif": "avif", + "3gpp": "3gp", + "annodex": "axv", + "dl": "dl", + "dv": [ + "dif", + "dv" + ], + "fli": "fli", + "gl": "gl", + "mpeg": [ + "mpeg", + "mpg", + "mpe", + "m1v", + "m2v", + "mp2", + "mpa", + "mpv2" + ], + "mp4": [ + "mp4", + "mp4v", + "mpg4" + ], + "quicktime": [ + "qt", + "mov" + ], + "ogg": "ogv", + "vnd.mpegurl": [ + "mxu", + "m4u" + ], + "x-flv": "flv", + "x-la-asf": [ + "lsf", + "lsx" + ], + "x-mng": "mng", + "x-ms-asf": [ + "asf", + "asx", + "asr" + ], + "x-ms-wm": "wm", + "x-ms-wmv": "wmv", + "x-ms-wmx": "wmx", + "x-ms-wvx": "wvx", + "x-msvideo": "avi", + "x-sgi-movie": "movie", + "x-matroska": [ + "mpv", + "mkv", + "mk3d", + "mks" + ], + "3gpp2": "3g2", + "h261": "h261", + "h263": "h263", + "h264": "h264", + "jpeg": "jpgv", + "jpm": [ + "jpm", + "jpgm" + ], + "mj2": [ + "mj2", + "mjp2" + ], + "vnd.dece.hd": [ + "uvh", + "uvvh" + ], + "vnd.dece.mobile": [ + "uvm", + "uvvm" + ], + "vnd.dece.pd": [ + "uvp", + "uvvp" + ], + "vnd.dece.sd": [ + "uvs", + "uvvs" + ], + "vnd.dece.video": [ + "uvv", + "uvvv" + ], + "vnd.dvb.file": "dvb", + "vnd.fvt": "fvt", + "vnd.ms-playready.media.pyv": "pyv", + "vnd.uvvu.mp4": [ + "uvu", + "uvvu" + ], + "vnd.vivo": "viv", + "webm": "webm", + "x-f4v": "f4v", + "x-m4v": "m4v", + "x-ms-vob": "vob", + "x-smv": "smv", + "mp2t": "ts" + }, + "x-conference": { + "x-cooltalk": "ice" + }, + "x-world": { + "x-vrml": [ + "vrm", + "flr", + "wrz", + "xaf", + "xof" + ] + } +}; + +(() => { + const mimeTypes = {}; + for (const type of Object.keys(table$1)) { + for (const subtype of Object.keys(table$1[type])) { + const value = table$1[type][subtype]; + if (typeof value == "string") { + mimeTypes[value] = type + "/" + subtype; + } else { + for (let indexMimeType = 0; indexMimeType < value.length; indexMimeType++) { + mimeTypes[value[indexMimeType]] = type + "/" + subtype; + } + } + } + } + return mimeTypes; +})(); + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const table = []; +for (let i = 0; i < 256; i++) { + let t = i; + for (let j = 0; j < 8; j++) { + if (t & 1) { + t = (t >>> 1) ^ 0xEDB88320; + } else { + t = t >>> 1; + } + } + table[i] = t; +} + +class Crc32 { + + constructor(crc) { + this.crc = crc || -1; + } + + append(data) { + let crc = this.crc | 0; + for (let offset = 0, length = data.length | 0; offset < length; offset++) { + crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF]; + } + this.crc = crc; + } + + get() { + return ~this.crc; + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +class Crc32Stream extends TransformStream { + + constructor() { + // deno-lint-ignore prefer-const + let stream; + const crc32 = new Crc32(); + super({ + transform(chunk, controller) { + crc32.append(chunk); + controller.enqueue(chunk); + }, + flush() { + const value = new Uint8Array(4); + const dataView = new DataView(value.buffer); + dataView.setUint32(0, crc32.get()); + stream.value = value; + } + }); + stream = this; + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +function encodeText(value) { + // deno-lint-ignore valid-typeof + if (typeof TextEncoder == UNDEFINED_TYPE) { + value = unescape(encodeURIComponent(value)); + const result = new Uint8Array(value.length); + for (let i = 0; i < result.length; i++) { + result[i] = value.charCodeAt(i); + } + return result; + } else { + return new TextEncoder().encode(value); + } +} + +// Derived from https://github.com/xqdoo00o/jszip/blob/master/lib/sjcl.js and https://github.com/bitwiseshiftleft/sjcl + +// deno-lint-ignore-file no-this-alias + +/* + * SJCL is open. You can use, modify and redistribute it under a BSD + * license or under the GNU GPL, version 2.0. + */ + +/** @fileOverview Javascript cryptography implementation. + * + * Crush to remove comments, shorten variable names and + * generally reduce transmission size. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */ + +/** @fileOverview Arrays of bits, encoded as arrays of Numbers. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** + * Arrays of bits, encoded as arrays of Numbers. + * @namespace + * @description + *

    + * These objects are the currency accepted by SJCL's crypto functions. + *

    + * + *

    + * Most of our crypto primitives operate on arrays of 4-byte words internally, + * but many of them can take arguments that are not a multiple of 4 bytes. + * This library encodes arrays of bits (whose size need not be a multiple of 8 + * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an + * array of words, 32 bits at a time. Since the words are double-precision + * floating point numbers, they fit some extra data. We use this (in a private, + * possibly-changing manner) to encode the number of bits actually present + * in the last word of the array. + *

    + * + *

    + * Because bitwise ops clear this out-of-band data, these arrays can be passed + * to ciphers like AES which want arrays of words. + *

    + */ +const bitArray = { + /** + * Concatenate two bit arrays. + * @param {bitArray} a1 The first array. + * @param {bitArray} a2 The second array. + * @return {bitArray} The concatenation of a1 and a2. + */ + concat(a1, a2) { + if (a1.length === 0 || a2.length === 0) { + return a1.concat(a2); + } + + const last = a1[a1.length - 1], shift = bitArray.getPartial(last); + if (shift === 32) { + return a1.concat(a2); + } else { + return bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1)); + } + }, + + /** + * Find the length of an array of bits. + * @param {bitArray} a The array. + * @return {Number} The length of a, in bits. + */ + bitLength(a) { + const l = a.length; + if (l === 0) { + return 0; + } + const x = a[l - 1]; + return (l - 1) * 32 + bitArray.getPartial(x); + }, + + /** + * Truncate an array. + * @param {bitArray} a The array. + * @param {Number} len The length to truncate to, in bits. + * @return {bitArray} A new array, truncated to len bits. + */ + clamp(a, len) { + if (a.length * 32 < len) { + return a; + } + a = a.slice(0, Math.ceil(len / 32)); + const l = a.length; + len = len & 31; + if (l > 0 && len) { + a[l - 1] = bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1); + } + return a; + }, + + /** + * Make a partial word for a bit array. + * @param {Number} len The number of bits in the word. + * @param {Number} x The bits. + * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side. + * @return {Number} The partial word. + */ + partial(len, x, _end) { + if (len === 32) { + return x; + } + return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000; + }, + + /** + * Get the number of bits used by a partial word. + * @param {Number} x The partial word. + * @return {Number} The number of bits used by the partial word. + */ + getPartial(x) { + return Math.round(x / 0x10000000000) || 32; + }, + + /** Shift an array right. + * @param {bitArray} a The array to shift. + * @param {Number} shift The number of bits to shift. + * @param {Number} [carry=0] A byte to carry in + * @param {bitArray} [out=[]] An array to prepend to the output. + * @private + */ + _shiftRight(a, shift, carry, out) { + if (out === undefined) { + out = []; + } + + for (; shift >= 32; shift -= 32) { + out.push(carry); + carry = 0; + } + if (shift === 0) { + return out.concat(a); + } + + for (let i = 0; i < a.length; i++) { + out.push(carry | a[i] >>> shift); + carry = a[i] << (32 - shift); + } + const last2 = a.length ? a[a.length - 1] : 0; + const shift2 = bitArray.getPartial(last2); + out.push(bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1)); + return out; + } +}; + +/** @fileOverview Bit array codec implementations. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** + * Arrays of bytes + * @namespace + */ +const codec = { + bytes: { + /** Convert from a bitArray to an array of bytes. */ + fromBits(arr) { + const bl = bitArray.bitLength(arr); + const byteLength = bl / 8; + const out = new Uint8Array(byteLength); + let tmp; + for (let i = 0; i < byteLength; i++) { + if ((i & 3) === 0) { + tmp = arr[i / 4]; + } + out[i] = tmp >>> 24; + tmp <<= 8; + } + return out; + }, + /** Convert from an array of bytes to a bitArray. */ + toBits(bytes) { + const out = []; + let i; + let tmp = 0; + for (i = 0; i < bytes.length; i++) { + tmp = tmp << 8 | bytes[i]; + if ((i & 3) === 3) { + out.push(tmp); + tmp = 0; + } + } + if (i & 3) { + out.push(bitArray.partial(8 * (i & 3), tmp)); + } + return out; + } + } +}; + +const hash = {}; + +/** + * Context for a SHA-1 operation in progress. + * @constructor + */ +hash.sha1 = class { + constructor(hash) { + const sha1 = this; + /** + * The hash's block size, in bits. + * @constant + */ + sha1.blockSize = 512; + /** + * The SHA-1 initialization vector. + * @private + */ + sha1._init = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; + /** + * The SHA-1 hash key. + * @private + */ + sha1._key = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6]; + if (hash) { + sha1._h = hash._h.slice(0); + sha1._buffer = hash._buffer.slice(0); + sha1._length = hash._length; + } else { + sha1.reset(); + } + } + + /** + * Reset the hash state. + * @return this + */ + reset() { + const sha1 = this; + sha1._h = sha1._init.slice(0); + sha1._buffer = []; + sha1._length = 0; + return sha1; + } + + /** + * Input several words to the hash. + * @param {bitArray|String} data the data to hash. + * @return this + */ + update(data) { + const sha1 = this; + if (typeof data === "string") { + data = codec.utf8String.toBits(data); + } + const b = sha1._buffer = bitArray.concat(sha1._buffer, data); + const ol = sha1._length; + const nl = sha1._length = ol + bitArray.bitLength(data); + if (nl > 9007199254740991) { + throw new Error("Cannot hash more than 2^53 - 1 bits"); + } + const c = new Uint32Array(b); + let j = 0; + for (let i = sha1.blockSize + ol - ((sha1.blockSize + ol) & (sha1.blockSize - 1)); i <= nl; + i += sha1.blockSize) { + sha1._block(c.subarray(16 * j, 16 * (j + 1))); + j += 1; + } + b.splice(0, 16 * j); + return sha1; + } + + /** + * Complete hashing and output the hash value. + * @return {bitArray} The hash value, an array of 5 big-endian words. TODO + */ + finalize() { + const sha1 = this; + let b = sha1._buffer; + const h = sha1._h; + + // Round out and push the buffer + b = bitArray.concat(b, [bitArray.partial(1, 1)]); + // Round out the buffer to a multiple of 16 words, less the 2 length words. + for (let i = b.length + 2; i & 15; i++) { + b.push(0); + } + + // append the length + b.push(Math.floor(sha1._length / 0x100000000)); + b.push(sha1._length | 0); + + while (b.length) { + sha1._block(b.splice(0, 16)); + } + + sha1.reset(); + return h; + } + + /** + * The SHA-1 logical functions f(0), f(1), ..., f(79). + * @private + */ + _f(t, b, c, d) { + if (t <= 19) { + return (b & c) | (~b & d); + } else if (t <= 39) { + return b ^ c ^ d; + } else if (t <= 59) { + return (b & c) | (b & d) | (c & d); + } else if (t <= 79) { + return b ^ c ^ d; + } + } + + /** + * Circular left-shift operator. + * @private + */ + _S(n, x) { + return (x << n) | (x >>> 32 - n); + } + + /** + * Perform one cycle of SHA-1. + * @param {Uint32Array|bitArray} words one block of words. + * @private + */ + _block(words) { + const sha1 = this; + const h = sha1._h; + // When words is passed to _block, it has 16 elements. SHA1 _block + // function extends words with new elements (at the end there are 80 elements). + // The problem is that if we use Uint32Array instead of Array, + // the length of Uint32Array cannot be changed. Thus, we replace words with a + // normal Array here. + const w = Array(80); // do not use Uint32Array here as the instantiation is slower + for (let j = 0; j < 16; j++) { + w[j] = words[j]; + } + + let a = h[0]; + let b = h[1]; + let c = h[2]; + let d = h[3]; + let e = h[4]; + + for (let t = 0; t <= 79; t++) { + if (t >= 16) { + w[t] = sha1._S(1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]); + } + const tmp = (sha1._S(5, a) + sha1._f(t, b, c, d) + e + w[t] + + sha1._key[Math.floor(t / 20)]) | 0; + e = d; + d = c; + c = sha1._S(30, b); + b = a; + a = tmp; + } + + h[0] = (h[0] + a) | 0; + h[1] = (h[1] + b) | 0; + h[2] = (h[2] + c) | 0; + h[3] = (h[3] + d) | 0; + h[4] = (h[4] + e) | 0; + } +}; + +/** @fileOverview Low-level AES implementation. + * + * This file contains a low-level implementation of AES, optimized for + * size and for efficiency on several browsers. It is based on + * OpenSSL's aes_core.c, a public-domain implementation by Vincent + * Rijmen, Antoon Bosselaers and Paulo Barreto. + * + * An older version of this implementation is available in the public + * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh, + * Stanford University 2008-2010 and BSD-licensed for liability + * reasons. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +const cipher = {}; + +/** + * Schedule out an AES key for both encryption and decryption. This + * is a low-level class. Use a cipher mode to do bulk encryption. + * + * @constructor + * @param {Array} key The key as an array of 4, 6 or 8 words. + */ +cipher.aes = class { + constructor(key) { + /** + * The expanded S-box and inverse S-box tables. These will be computed + * on the client so that we don't have to send them down the wire. + * + * There are two tables, _tables[0] is for encryption and + * _tables[1] is for decryption. + * + * The first 4 sub-tables are the expanded S-box with MixColumns. The + * last (_tables[01][4]) is the S-box itself. + * + * @private + */ + const aes = this; + aes._tables = [[[], [], [], [], []], [[], [], [], [], []]]; + + if (!aes._tables[0][0][0]) { + aes._precompute(); + } + + const sbox = aes._tables[0][4]; + const decTable = aes._tables[1]; + const keyLen = key.length; + + let i, encKey, decKey, rcon = 1; + + if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) { + throw new Error("invalid aes key size"); + } + + aes._key = [encKey = key.slice(0), decKey = []]; + + // schedule encryption keys + for (i = keyLen; i < 4 * keyLen + 28; i++) { + let tmp = encKey[i - 1]; + + // apply sbox + if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) { + tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; + + // shift rows and add rcon + if (i % keyLen === 0) { + tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24; + rcon = rcon << 1 ^ (rcon >> 7) * 283; + } + } + + encKey[i] = encKey[i - keyLen] ^ tmp; + } + + // schedule decryption keys + for (let j = 0; i; j++, i--) { + const tmp = encKey[j & 3 ? i : i - 4]; + if (i <= 4 || j < 4) { + decKey[j] = tmp; + } else { + decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ + decTable[1][sbox[tmp >> 16 & 255]] ^ + decTable[2][sbox[tmp >> 8 & 255]] ^ + decTable[3][sbox[tmp & 255]]; + } + } + } + // public + /* Something like this might appear here eventually + name: "AES", + blockSize: 4, + keySizes: [4,6,8], + */ + + /** + * Encrypt an array of 4 big-endian words. + * @param {Array} data The plaintext. + * @return {Array} The ciphertext. + */ + encrypt(data) { + return this._crypt(data, 0); + } + + /** + * Decrypt an array of 4 big-endian words. + * @param {Array} data The ciphertext. + * @return {Array} The plaintext. + */ + decrypt(data) { + return this._crypt(data, 1); + } + + /** + * Expand the S-box tables. + * + * @private + */ + _precompute() { + const encTable = this._tables[0]; + const decTable = this._tables[1]; + const sbox = encTable[4]; + const sboxInv = decTable[4]; + const d = []; + const th = []; + let xInv, x2, x4, x8; + + // Compute double and third tables + for (let i = 0; i < 256; i++) { + th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i; + } + + for (let x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) { + // Compute sbox + let s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4; + s = s >> 8 ^ s & 255 ^ 99; + sbox[x] = s; + sboxInv[s] = x; + + // Compute MixColumns + x8 = d[x4 = d[x2 = d[x]]]; + let tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100; + let tEnc = d[s] * 0x101 ^ s * 0x1010100; + + for (let i = 0; i < 4; i++) { + encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8; + decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8; + } + } + + // Compactify. Considerable speedup on Firefox. + for (let i = 0; i < 5; i++) { + encTable[i] = encTable[i].slice(0); + decTable[i] = decTable[i].slice(0); + } + } + + /** + * Encryption and decryption core. + * @param {Array} input Four words to be encrypted or decrypted. + * @param dir The direction, 0 for encrypt and 1 for decrypt. + * @return {Array} The four encrypted or decrypted words. + * @private + */ + _crypt(input, dir) { + if (input.length !== 4) { + throw new Error("invalid aes block size"); + } + + const key = this._key[dir]; + + const nInnerRounds = key.length / 4 - 2; + const out = [0, 0, 0, 0]; + const table = this._tables[dir]; + + // load up the tables + const t0 = table[0]; + const t1 = table[1]; + const t2 = table[2]; + const t3 = table[3]; + const sbox = table[4]; + + // state variables a,b,c,d are loaded with pre-whitened data + let a = input[0] ^ key[0]; + let b = input[dir ? 3 : 1] ^ key[1]; + let c = input[2] ^ key[2]; + let d = input[dir ? 1 : 3] ^ key[3]; + let kIndex = 4; + let a2, b2, c2; + + // Inner rounds. Cribbed from OpenSSL. + for (let i = 0; i < nInnerRounds; i++) { + a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex]; + b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1]; + c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2]; + d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3]; + kIndex += 4; + a = a2; b = b2; c = c2; + } + + // Last round. + for (let i = 0; i < 4; i++) { + out[dir ? 3 & -i : i] = + sbox[a >>> 24] << 24 ^ + sbox[b >> 16 & 255] << 16 ^ + sbox[c >> 8 & 255] << 8 ^ + sbox[d & 255] ^ + key[kIndex++]; + a2 = a; a = b; b = c; c = d; d = a2; + } + + return out; + } +}; + +/** + * Random values + * @namespace + */ +const random = { + /** + * Generate random words with pure js, cryptographically not as strong & safe as native implementation. + * @param {TypedArray} typedArray The array to fill. + * @return {TypedArray} The random values. + */ + getRandomValues(typedArray) { + const words = new Uint32Array(typedArray.buffer); + const r = (m_w) => { + let m_z = 0x3ade68b1; + const mask = 0xffffffff; + return function () { + m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; + m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; + const result = ((((m_z << 0x10) + m_w) & mask) / 0x100000000) + .5; + return result * (Math.random() > .5 ? 1 : -1); + }; + }; + for (let i = 0, rcache; i < typedArray.length; i += 4) { + const _r = r((rcache || Math.random()) * 0x100000000); + rcache = _r() * 0x3ade67b7; + words[i / 4] = (_r() * 0x100000000) | 0; + } + return typedArray; + } +}; + +/** @fileOverview CTR mode implementation. + * + * Special thanks to Roy Nicholson for pointing out a bug in our + * implementation. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** Brian Gladman's CTR Mode. +* @constructor +* @param {Object} _prf The aes instance to generate key. +* @param {bitArray} _iv The iv for ctr mode, it must be 128 bits. +*/ + +const mode = {}; + +/** + * Brian Gladman's CTR Mode. + * @namespace + */ +mode.ctrGladman = class { + constructor(prf, iv) { + this._prf = prf; + this._initIv = iv; + this._iv = iv; + } + + reset() { + this._iv = this._initIv; + } + + /** Input some data to calculate. + * @param {bitArray} data the data to process, it must be intergral multiple of 128 bits unless it's the last. + */ + update(data) { + return this.calculate(this._prf, data, this._iv); + } + + incWord(word) { + if (((word >> 24) & 0xff) === 0xff) { //overflow + let b1 = (word >> 16) & 0xff; + let b2 = (word >> 8) & 0xff; + let b3 = word & 0xff; + + if (b1 === 0xff) { // overflow b1 + b1 = 0; + if (b2 === 0xff) { + b2 = 0; + if (b3 === 0xff) { + b3 = 0; + } else { + ++b3; + } + } else { + ++b2; + } + } else { + ++b1; + } + + word = 0; + word += (b1 << 16); + word += (b2 << 8); + word += b3; + } else { + word += (0x01 << 24); + } + return word; + } + + incCounter(counter) { + if ((counter[0] = this.incWord(counter[0])) === 0) { + // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 + counter[1] = this.incWord(counter[1]); + } + } + + calculate(prf, data, iv) { + let l; + if (!(l = data.length)) { + return []; + } + const bl = bitArray.bitLength(data); + for (let i = 0; i < l; i += 4) { + this.incCounter(iv); + const e = prf.encrypt(iv); + data[i] ^= e[0]; + data[i + 1] ^= e[1]; + data[i + 2] ^= e[2]; + data[i + 3] ^= e[3]; + } + return bitArray.clamp(data, bl); + } +}; + +const misc = { + importKey(password) { + return new misc.hmacSha1(codec.bytes.toBits(password)); + }, + pbkdf2(prf, salt, count, length) { + count = count || 10000; + if (length < 0 || count < 0) { + throw new Error("invalid params to pbkdf2"); + } + const byteLength = ((length >> 5) + 1) << 2; + let u, ui, i, j, k; + const arrayBuffer = new ArrayBuffer(byteLength); + const out = new DataView(arrayBuffer); + let outLength = 0; + const b = bitArray; + salt = codec.bytes.toBits(salt); + for (k = 1; outLength < (byteLength || 1); k++) { + u = ui = prf.encrypt(b.concat(salt, [k])); + for (i = 1; i < count; i++) { + ui = prf.encrypt(ui); + for (j = 0; j < ui.length; j++) { + u[j] ^= ui[j]; + } + } + for (i = 0; outLength < (byteLength || 1) && i < u.length; i++) { + out.setInt32(outLength, u[i]); + outLength += 4; + } + } + return arrayBuffer.slice(0, length / 8); + } +}; + +/** @fileOverview HMAC implementation. + * + * @author Emily Stark + * @author Mike Hamburg + * @author Dan Boneh + */ + +/** HMAC with the specified hash function. + * @constructor + * @param {bitArray} key the key for HMAC. + * @param {Object} [Hash=hash.sha1] The hash function to use. + */ +misc.hmacSha1 = class { + + constructor(key) { + const hmac = this; + const Hash = hmac._hash = hash.sha1; + const exKey = [[], []]; + hmac._baseHash = [new Hash(), new Hash()]; + const bs = hmac._baseHash[0].blockSize / 32; + + if (key.length > bs) { + key = new Hash().update(key).finalize(); + } + + for (let i = 0; i < bs; i++) { + exKey[0][i] = key[i] ^ 0x36363636; + exKey[1][i] = key[i] ^ 0x5C5C5C5C; + } + + hmac._baseHash[0].update(exKey[0]); + hmac._baseHash[1].update(exKey[1]); + hmac._resultHash = new Hash(hmac._baseHash[0]); + } + reset() { + const hmac = this; + hmac._resultHash = new hmac._hash(hmac._baseHash[0]); + hmac._updated = false; + } + + update(data) { + const hmac = this; + hmac._updated = true; + hmac._resultHash.update(data); + } + + digest() { + const hmac = this; + const w = hmac._resultHash.finalize(); + const result = new (hmac._hash)(hmac._baseHash[1]).update(w).finalize(); + + hmac.reset(); + + return result; + } + + encrypt(data) { + if (!this._updated) { + this.update(data); + return this.digest(data); + } else { + throw new Error("encrypt on already updated hmac called!"); + } + } +}; + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const GET_RANDOM_VALUES_SUPPORTED = typeof crypto != UNDEFINED_TYPE && typeof crypto.getRandomValues == FUNCTION_TYPE; + +const ERR_INVALID_PASSWORD = "Invalid password"; +const ERR_INVALID_SIGNATURE = "Invalid signature"; +const ERR_ABORT_CHECK_PASSWORD = "zipjs-abort-check-password"; + +function getRandomValues(array) { + if (GET_RANDOM_VALUES_SUPPORTED) { + return crypto.getRandomValues(array); + } else { + return random.getRandomValues(array); + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const BLOCK_LENGTH = 16; +const RAW_FORMAT = "raw"; +const PBKDF2_ALGORITHM = { name: "PBKDF2" }; +const HASH_ALGORITHM = { name: "HMAC" }; +const HASH_FUNCTION = "SHA-1"; +const BASE_KEY_ALGORITHM = Object.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM); +const DERIVED_BITS_ALGORITHM = Object.assign({ iterations: 1000, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM); +const DERIVED_BITS_USAGE = ["deriveBits"]; +const SALT_LENGTH = [8, 12, 16]; +const KEY_LENGTH = [16, 24, 32]; +const SIGNATURE_LENGTH = 10; +const COUNTER_DEFAULT_VALUE = [0, 0, 0, 0]; +// deno-lint-ignore valid-typeof +const CRYPTO_API_SUPPORTED = typeof crypto != UNDEFINED_TYPE; +const subtle = CRYPTO_API_SUPPORTED && crypto.subtle; +const SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof subtle != UNDEFINED_TYPE; +const codecBytes = codec.bytes; +const Aes = cipher.aes; +const CtrGladman = mode.ctrGladman; +const HmacSha1 = misc.hmacSha1; + +let IMPORT_KEY_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.importKey == FUNCTION_TYPE; +let DERIVE_BITS_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.deriveBits == FUNCTION_TYPE; + +class AESDecryptionStream extends TransformStream { + + constructor({ password, rawPassword, signed, encryptionStrength, checkPasswordOnly }) { + super({ + start() { + Object.assign(this, { + ready: new Promise(resolve => this.resolveReady = resolve), + password: encodePassword(password, rawPassword), + signed, + strength: encryptionStrength - 1, + pending: new Uint8Array() + }); + }, + async transform(chunk, controller) { + const aesCrypto = this; + const { + password, + strength, + resolveReady, + ready + } = aesCrypto; + if (password) { + await createDecryptionKeys(aesCrypto, strength, password, subarray(chunk, 0, SALT_LENGTH[strength] + 2)); + chunk = subarray(chunk, SALT_LENGTH[strength] + 2); + if (checkPasswordOnly) { + controller.error(new Error(ERR_ABORT_CHECK_PASSWORD)); + } else { + resolveReady(); + } + } else { + await ready; + } + const output = new Uint8Array(chunk.length - SIGNATURE_LENGTH - ((chunk.length - SIGNATURE_LENGTH) % BLOCK_LENGTH)); + controller.enqueue(append(aesCrypto, chunk, output, 0, SIGNATURE_LENGTH, true)); + }, + async flush(controller) { + const { + signed, + ctr, + hmac, + pending, + ready + } = this; + if (hmac && ctr) { + await ready; + const chunkToDecrypt = subarray(pending, 0, pending.length - SIGNATURE_LENGTH); + const originalSignature = subarray(pending, pending.length - SIGNATURE_LENGTH); + let decryptedChunkArray = new Uint8Array(); + if (chunkToDecrypt.length) { + const encryptedChunk = toBits(codecBytes, chunkToDecrypt); + hmac.update(encryptedChunk); + const decryptedChunk = ctr.update(encryptedChunk); + decryptedChunkArray = fromBits(codecBytes, decryptedChunk); + } + if (signed) { + const signature = subarray(fromBits(codecBytes, hmac.digest()), 0, SIGNATURE_LENGTH); + for (let indexSignature = 0; indexSignature < SIGNATURE_LENGTH; indexSignature++) { + if (signature[indexSignature] != originalSignature[indexSignature]) { + throw new Error(ERR_INVALID_SIGNATURE); + } + } + } + controller.enqueue(decryptedChunkArray); + } + } + }); + } +} + +class AESEncryptionStream extends TransformStream { + + constructor({ password, rawPassword, encryptionStrength }) { + // deno-lint-ignore prefer-const + let stream; + super({ + start() { + Object.assign(this, { + ready: new Promise(resolve => this.resolveReady = resolve), + password: encodePassword(password, rawPassword), + strength: encryptionStrength - 1, + pending: new Uint8Array() + }); + }, + async transform(chunk, controller) { + const aesCrypto = this; + const { + password, + strength, + resolveReady, + ready + } = aesCrypto; + let preamble = new Uint8Array(); + if (password) { + preamble = await createEncryptionKeys(aesCrypto, strength, password); + resolveReady(); + } else { + await ready; + } + const output = new Uint8Array(preamble.length + chunk.length - (chunk.length % BLOCK_LENGTH)); + output.set(preamble, 0); + controller.enqueue(append(aesCrypto, chunk, output, preamble.length, 0)); + }, + async flush(controller) { + const { + ctr, + hmac, + pending, + ready + } = this; + if (hmac && ctr) { + await ready; + let encryptedChunkArray = new Uint8Array(); + if (pending.length) { + const encryptedChunk = ctr.update(toBits(codecBytes, pending)); + hmac.update(encryptedChunk); + encryptedChunkArray = fromBits(codecBytes, encryptedChunk); + } + stream.signature = fromBits(codecBytes, hmac.digest()).slice(0, SIGNATURE_LENGTH); + controller.enqueue(concat(encryptedChunkArray, stream.signature)); + } + } + }); + stream = this; + } +} + +function append(aesCrypto, input, output, paddingStart, paddingEnd, verifySignature) { + const { + ctr, + hmac, + pending + } = aesCrypto; + const inputLength = input.length - paddingEnd; + if (pending.length) { + input = concat(pending, input); + output = expand(output, inputLength - (inputLength % BLOCK_LENGTH)); + } + let offset; + for (offset = 0; offset <= inputLength - BLOCK_LENGTH; offset += BLOCK_LENGTH) { + const inputChunk = toBits(codecBytes, subarray(input, offset, offset + BLOCK_LENGTH)); + if (verifySignature) { + hmac.update(inputChunk); + } + const outputChunk = ctr.update(inputChunk); + if (!verifySignature) { + hmac.update(outputChunk); + } + output.set(fromBits(codecBytes, outputChunk), offset + paddingStart); + } + aesCrypto.pending = subarray(input, offset); + return output; +} + +async function createDecryptionKeys(decrypt, strength, password, preamble) { + const passwordVerificationKey = await createKeys$1(decrypt, strength, password, subarray(preamble, 0, SALT_LENGTH[strength])); + const passwordVerification = subarray(preamble, SALT_LENGTH[strength]); + if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) { + throw new Error(ERR_INVALID_PASSWORD); + } +} + +async function createEncryptionKeys(encrypt, strength, password) { + const salt = getRandomValues(new Uint8Array(SALT_LENGTH[strength])); + const passwordVerification = await createKeys$1(encrypt, strength, password, salt); + return concat(salt, passwordVerification); +} + +async function createKeys$1(aesCrypto, strength, password, salt) { + aesCrypto.password = null; + const baseKey = await importKey(RAW_FORMAT, password, BASE_KEY_ALGORITHM, false, DERIVED_BITS_USAGE); + const derivedBits = await deriveBits(Object.assign({ salt }, DERIVED_BITS_ALGORITHM), baseKey, 8 * ((KEY_LENGTH[strength] * 2) + 2)); + const compositeKey = new Uint8Array(derivedBits); + const key = toBits(codecBytes, subarray(compositeKey, 0, KEY_LENGTH[strength])); + const authentication = toBits(codecBytes, subarray(compositeKey, KEY_LENGTH[strength], KEY_LENGTH[strength] * 2)); + const passwordVerification = subarray(compositeKey, KEY_LENGTH[strength] * 2); + Object.assign(aesCrypto, { + keys: { + key, + authentication, + passwordVerification + }, + ctr: new CtrGladman(new Aes(key), Array.from(COUNTER_DEFAULT_VALUE)), + hmac: new HmacSha1(authentication) + }); + return passwordVerification; +} + +async function importKey(format, password, algorithm, extractable, keyUsages) { + if (IMPORT_KEY_SUPPORTED) { + try { + return await subtle.importKey(format, password, algorithm, extractable, keyUsages); + } catch (_error) { + IMPORT_KEY_SUPPORTED = false; + return misc.importKey(password); + } + } else { + return misc.importKey(password); + } +} + +async function deriveBits(algorithm, baseKey, length) { + if (DERIVE_BITS_SUPPORTED) { + try { + return await subtle.deriveBits(algorithm, baseKey, length); + } catch (_error) { + DERIVE_BITS_SUPPORTED = false; + return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length); + } + } else { + return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length); + } +} + +function encodePassword(password, rawPassword) { + if (rawPassword === UNDEFINED_VALUE) { + return encodeText(password); + } else { + return rawPassword; + } +} + +function concat(leftArray, rightArray) { + let array = leftArray; + if (leftArray.length + rightArray.length) { + array = new Uint8Array(leftArray.length + rightArray.length); + array.set(leftArray, 0); + array.set(rightArray, leftArray.length); + } + return array; +} + +function expand(inputArray, length) { + if (length && length > inputArray.length) { + const array = inputArray; + inputArray = new Uint8Array(length); + inputArray.set(array, 0); + } + return inputArray; +} + +function subarray(array, begin, end) { + return array.subarray(begin, end); +} + +function fromBits(codecBytes, chunk) { + return codecBytes.fromBits(chunk); +} +function toBits(codecBytes, chunk) { + return codecBytes.toBits(chunk); +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const HEADER_LENGTH = 12; + +class ZipCryptoDecryptionStream extends TransformStream { + + constructor({ password, passwordVerification, checkPasswordOnly }) { + super({ + start() { + Object.assign(this, { + password, + passwordVerification + }); + createKeys(this, password); + }, + transform(chunk, controller) { + const zipCrypto = this; + if (zipCrypto.password) { + const decryptedHeader = decrypt(zipCrypto, chunk.subarray(0, HEADER_LENGTH)); + zipCrypto.password = null; + if (decryptedHeader[HEADER_LENGTH - 1] != zipCrypto.passwordVerification) { + throw new Error(ERR_INVALID_PASSWORD); + } + chunk = chunk.subarray(HEADER_LENGTH); + } + if (checkPasswordOnly) { + controller.error(new Error(ERR_ABORT_CHECK_PASSWORD)); + } else { + controller.enqueue(decrypt(zipCrypto, chunk)); + } + } + }); + } +} + +class ZipCryptoEncryptionStream extends TransformStream { + + constructor({ password, passwordVerification }) { + super({ + start() { + Object.assign(this, { + password, + passwordVerification + }); + createKeys(this, password); + }, + transform(chunk, controller) { + const zipCrypto = this; + let output; + let offset; + if (zipCrypto.password) { + zipCrypto.password = null; + const header = getRandomValues(new Uint8Array(HEADER_LENGTH)); + header[HEADER_LENGTH - 1] = zipCrypto.passwordVerification; + output = new Uint8Array(chunk.length + header.length); + output.set(encrypt(zipCrypto, header), 0); + offset = HEADER_LENGTH; + } else { + output = new Uint8Array(chunk.length); + offset = 0; + } + output.set(encrypt(zipCrypto, chunk), offset); + controller.enqueue(output); + } + }); + } +} + +function decrypt(target, input) { + const output = new Uint8Array(input.length); + for (let index = 0; index < input.length; index++) { + output[index] = getByte(target) ^ input[index]; + updateKeys(target, output[index]); + } + return output; +} + +function encrypt(target, input) { + const output = new Uint8Array(input.length); + for (let index = 0; index < input.length; index++) { + output[index] = getByte(target) ^ input[index]; + updateKeys(target, input[index]); + } + return output; +} + +function createKeys(target, password) { + const keys = [0x12345678, 0x23456789, 0x34567890]; + Object.assign(target, { + keys, + crcKey0: new Crc32(keys[0]), + crcKey2: new Crc32(keys[2]), + }); + for (let index = 0; index < password.length; index++) { + updateKeys(target, password.charCodeAt(index)); + } +} + +function updateKeys(target, byte) { + let [key0, key1, key2] = target.keys; + target.crcKey0.append([byte]); + key0 = ~target.crcKey0.get(); + key1 = getInt32(Math.imul(getInt32(key1 + getInt8(key0)), 134775813) + 1); + target.crcKey2.append([key1 >>> 24]); + key2 = ~target.crcKey2.get(); + target.keys = [key0, key1, key2]; +} + +function getByte(target) { + const temp = target.keys[2] | 2; + return getInt8(Math.imul(temp, (temp ^ 1)) >>> 8); +} + +function getInt8(number) { + return number & 0xFF; +} + +function getInt32(number) { + return number & 0xFFFFFFFF; +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const COMPRESSION_FORMAT = "deflate-raw"; + +class DeflateStream extends TransformStream { + + constructor(options, { chunkSize, CompressionStream, CompressionStreamNative }) { + super({}); + const { compressed, encrypted, useCompressionStream, zipCrypto, signed, level } = options; + const stream = this; + let crc32Stream, encryptionStream; + let readable = filterEmptyChunks(super.readable); + if ((!encrypted || zipCrypto) && signed) { + crc32Stream = new Crc32Stream(); + readable = pipeThrough(readable, crc32Stream); + } + if (compressed) { + readable = pipeThroughCommpressionStream(readable, useCompressionStream, { level, chunkSize }, CompressionStreamNative, CompressionStream); + } + if (encrypted) { + if (zipCrypto) { + readable = pipeThrough(readable, new ZipCryptoEncryptionStream(options)); + } else { + encryptionStream = new AESEncryptionStream(options); + readable = pipeThrough(readable, encryptionStream); + } + } + setReadable(stream, readable, () => { + let signature; + if (encrypted && !zipCrypto) { + signature = encryptionStream.signature; + } + if ((!encrypted || zipCrypto) && signed) { + signature = new DataView(crc32Stream.value.buffer).getUint32(0); + } + stream.signature = signature; + }); + } +} + +class InflateStream extends TransformStream { + + constructor(options, { chunkSize, DecompressionStream, DecompressionStreamNative }) { + super({}); + const { zipCrypto, encrypted, signed, signature, compressed, useCompressionStream } = options; + let crc32Stream, decryptionStream; + let readable = filterEmptyChunks(super.readable); + if (encrypted) { + if (zipCrypto) { + readable = pipeThrough(readable, new ZipCryptoDecryptionStream(options)); + } else { + decryptionStream = new AESDecryptionStream(options); + readable = pipeThrough(readable, decryptionStream); + } + } + if (compressed) { + readable = pipeThroughCommpressionStream(readable, useCompressionStream, { chunkSize }, DecompressionStreamNative, DecompressionStream); + } + if ((!encrypted || zipCrypto) && signed) { + crc32Stream = new Crc32Stream(); + readable = pipeThrough(readable, crc32Stream); + } + setReadable(this, readable, () => { + if ((!encrypted || zipCrypto) && signed) { + const dataViewSignature = new DataView(crc32Stream.value.buffer); + if (signature != dataViewSignature.getUint32(0, false)) { + throw new Error(ERR_INVALID_SIGNATURE); + } + } + }); + } +} + +function filterEmptyChunks(readable) { + return pipeThrough(readable, new TransformStream({ + transform(chunk, controller) { + if (chunk && chunk.length) { + controller.enqueue(chunk); + } + } + })); +} + +function setReadable(stream, readable, flush) { + readable = pipeThrough(readable, new TransformStream({ flush })); + Object.defineProperty(stream, "readable", { + get() { + return readable; + } + }); +} + +function pipeThroughCommpressionStream(readable, useCompressionStream, options, CodecStreamNative, CodecStream) { + try { + const CompressionStream = useCompressionStream && CodecStreamNative ? CodecStreamNative : CodecStream; + readable = pipeThrough(readable, new CompressionStream(COMPRESSION_FORMAT, options)); + } catch (_error) { + if (useCompressionStream) { + try { + readable = pipeThrough(readable, new CodecStream(COMPRESSION_FORMAT, options)); + } catch (_error) { + return readable; + } + } else { + return readable; + } + } + return readable; +} + +function pipeThrough(readable, transformStream) { + return readable.pipeThrough(transformStream); +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const MESSAGE_EVENT_TYPE = "message"; +const MESSAGE_START = "start"; +const MESSAGE_PULL = "pull"; +const MESSAGE_DATA = "data"; +const MESSAGE_ACK_DATA = "ack"; +const MESSAGE_CLOSE = "close"; +const CODEC_DEFLATE = "deflate"; +const CODEC_INFLATE = "inflate"; + +class CodecStream extends TransformStream { + + constructor(options, config) { + super({}); + const codec = this; + const { codecType } = options; + let Stream; + if (codecType.startsWith(CODEC_DEFLATE)) { + Stream = DeflateStream; + } else if (codecType.startsWith(CODEC_INFLATE)) { + Stream = InflateStream; + } + let outputSize = 0; + let inputSize = 0; + const stream = new Stream(options, config); + const readable = super.readable; + const inputSizeStream = new TransformStream({ + transform(chunk, controller) { + if (chunk && chunk.length) { + inputSize += chunk.length; + controller.enqueue(chunk); + } + }, + flush() { + Object.assign(codec, { + inputSize + }); + } + }); + const outputSizeStream = new TransformStream({ + transform(chunk, controller) { + if (chunk && chunk.length) { + outputSize += chunk.length; + controller.enqueue(chunk); + } + }, + flush() { + const { signature } = stream; + Object.assign(codec, { + signature, + outputSize, + inputSize + }); + } + }); + Object.defineProperty(codec, "readable", { + get() { + return readable.pipeThrough(inputSizeStream).pipeThrough(stream).pipeThrough(outputSizeStream); + } + }); + } +} + +class ChunkStream extends TransformStream { + + constructor(chunkSize) { + let pendingChunk; + super({ + transform, + flush(controller) { + if (pendingChunk && pendingChunk.length) { + controller.enqueue(pendingChunk); + } + } + }); + + function transform(chunk, controller) { + if (pendingChunk) { + const newChunk = new Uint8Array(pendingChunk.length + chunk.length); + newChunk.set(pendingChunk); + newChunk.set(chunk, pendingChunk.length); + chunk = newChunk; + pendingChunk = null; + } + if (chunk.length > chunkSize) { + controller.enqueue(chunk.slice(0, chunkSize)); + transform(chunk.slice(chunkSize), controller); + } else { + pendingChunk = chunk; + } + } + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// deno-lint-ignore valid-typeof +let WEB_WORKERS_SUPPORTED = typeof Worker != UNDEFINED_TYPE; + +class CodecWorker { + + constructor(workerData, { readable, writable }, { options, config, streamOptions, useWebWorkers, transferStreams, scripts }, onTaskFinished) { + const { signal } = streamOptions; + Object.assign(workerData, { + busy: true, + readable: readable + .pipeThrough(new ChunkStream(config.chunkSize)) + .pipeThrough(new ProgressWatcherStream(readable, streamOptions), { signal }), + writable, + options: Object.assign({}, options), + scripts, + transferStreams, + terminate() { + return new Promise(resolve => { + const { worker, busy } = workerData; + if (worker) { + if (busy) { + workerData.resolveTerminated = resolve; + } else { + worker.terminate(); + resolve(); + } + workerData.interface = null; + } else { + resolve(); + } + }); + }, + onTaskFinished() { + const { resolveTerminated } = workerData; + if (resolveTerminated) { + workerData.resolveTerminated = null; + workerData.terminated = true; + workerData.worker.terminate(); + resolveTerminated(); + } + workerData.busy = false; + onTaskFinished(workerData); + } + }); + return (useWebWorkers && WEB_WORKERS_SUPPORTED ? createWebWorkerInterface : createWorkerInterface)(workerData, config); + } +} + +class ProgressWatcherStream extends TransformStream { + + constructor(readableSource, { onstart, onprogress, size, onend }) { + let chunkOffset = 0; + super({ + async start() { + if (onstart) { + await callHandler(onstart, size); + } + }, + async transform(chunk, controller) { + chunkOffset += chunk.length; + if (onprogress) { + await callHandler(onprogress, chunkOffset, size); + } + controller.enqueue(chunk); + }, + async flush() { + readableSource.size = chunkOffset; + if (onend) { + await callHandler(onend, chunkOffset); + } + } + }); + } +} + +async function callHandler(handler, ...parameters) { + try { + await handler(...parameters); + } catch (_error) { + // ignored + } +} + +function createWorkerInterface(workerData, config) { + return { + run: () => runWorker$1(workerData, config) + }; +} + +function createWebWorkerInterface(workerData, config) { + const { baseURL, chunkSize } = config; + if (!workerData.interface) { + let worker; + try { + worker = getWebWorker(workerData.scripts[0], baseURL, workerData); + } catch (_error) { + WEB_WORKERS_SUPPORTED = false; + return createWorkerInterface(workerData, config); + } + Object.assign(workerData, { + worker, + interface: { + run: () => runWebWorker(workerData, { chunkSize }) + } + }); + } + return workerData.interface; +} + +async function runWorker$1({ options, readable, writable, onTaskFinished }, config) { + try { + const codecStream = new CodecStream(options, config); + await readable.pipeThrough(codecStream).pipeTo(writable, { preventClose: true, preventAbort: true }); + const { + signature, + inputSize, + outputSize + } = codecStream; + return { + signature, + inputSize, + outputSize + }; + } finally { + onTaskFinished(); + } +} + +async function runWebWorker(workerData, config) { + let resolveResult, rejectResult; + const result = new Promise((resolve, reject) => { + resolveResult = resolve; + rejectResult = reject; + }); + Object.assign(workerData, { + reader: null, + writer: null, + resolveResult, + rejectResult, + result + }); + const { readable, options, scripts } = workerData; + const { writable, closed } = watchClosedStream(workerData.writable); + const streamsTransferred = sendMessage({ + type: MESSAGE_START, + scripts: scripts.slice(1), + options, + config, + readable, + writable + }, workerData); + if (!streamsTransferred) { + Object.assign(workerData, { + reader: readable.getReader(), + writer: writable.getWriter() + }); + } + const resultValue = await result; + if (!streamsTransferred) { + await writable.getWriter().close(); + } + await closed; + return resultValue; +} + +function watchClosedStream(writableSource) { + let resolveStreamClosed; + const closed = new Promise(resolve => resolveStreamClosed = resolve); + const writable = new WritableStream({ + async write(chunk) { + const writer = writableSource.getWriter(); + await writer.ready; + await writer.write(chunk); + writer.releaseLock(); + }, + close() { + resolveStreamClosed(); + }, + abort(reason) { + const writer = writableSource.getWriter(); + return writer.abort(reason); + } + }); + return { writable, closed }; +} + +let classicWorkersSupported = true; +let transferStreamsSupported = true; + +function getWebWorker(url, baseURL, workerData) { + const workerOptions = { type: "module" }; + let scriptUrl, worker; + // deno-lint-ignore valid-typeof + if (typeof url == FUNCTION_TYPE) { + url = url(); + } + try { + scriptUrl = new URL(url, baseURL); + } catch (_error) { + scriptUrl = url; + } + if (classicWorkersSupported) { + try { + worker = new Worker(scriptUrl); + } catch (_error) { + classicWorkersSupported = false; + worker = new Worker(scriptUrl, workerOptions); + } + } else { + worker = new Worker(scriptUrl, workerOptions); + } + worker.addEventListener(MESSAGE_EVENT_TYPE, event => onMessage(event, workerData)); + return worker; +} + +function sendMessage(message, { worker, writer, onTaskFinished, transferStreams }) { + try { + const { value, readable, writable } = message; + const transferables = []; + if (value) { + if (value.byteLength < value.buffer.byteLength) { + message.value = value.buffer.slice(0, value.byteLength); + } + else { + message.value = value.buffer; + } + transferables.push(message.value); + } + if (transferStreams && transferStreamsSupported) { + if (readable) { + transferables.push(readable); + } + if (writable) { + transferables.push(writable); + } + } else { + message.readable = message.writable = null; + } + if (transferables.length) { + try { + worker.postMessage(message, transferables); + return true; + } catch (_error) { + transferStreamsSupported = false; + message.readable = message.writable = null; + worker.postMessage(message); + } + } else { + worker.postMessage(message); + } + } catch (error) { + if (writer) { + writer.releaseLock(); + } + onTaskFinished(); + throw error; + } +} + +async function onMessage({ data }, workerData) { + const { type, value, messageId, result, error } = data; + const { reader, writer, resolveResult, rejectResult, onTaskFinished } = workerData; + try { + if (error) { + const { message, stack, code, name } = error; + const responseError = new Error(message); + Object.assign(responseError, { stack, code, name }); + close(responseError); + } else { + if (type == MESSAGE_PULL) { + const { value, done } = await reader.read(); + sendMessage({ type: MESSAGE_DATA, value, done, messageId }, workerData); + } + if (type == MESSAGE_DATA) { + await writer.ready; + await writer.write(new Uint8Array(value)); + sendMessage({ type: MESSAGE_ACK_DATA, messageId }, workerData); + } + if (type == MESSAGE_CLOSE) { + close(null, result); + } + } + } catch (error) { + sendMessage({ type: MESSAGE_CLOSE, messageId }, workerData); + close(error); + } + + function close(error, result) { + if (error) { + rejectResult(error); + } else { + resolveResult(result); + } + if (writer) { + writer.releaseLock(); + } + onTaskFinished(); + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +let pool = []; +const pendingRequests = []; + +let indexWorker = 0; + +async function runWorker(stream, workerOptions) { + const { options, config } = workerOptions; + const { transferStreams, useWebWorkers, useCompressionStream, codecType, compressed, signed, encrypted } = options; + const { workerScripts, maxWorkers } = config; + workerOptions.transferStreams = transferStreams || transferStreams === UNDEFINED_VALUE; + const streamCopy = !compressed && !signed && !encrypted && !workerOptions.transferStreams; + workerOptions.useWebWorkers = !streamCopy && (useWebWorkers || (useWebWorkers === UNDEFINED_VALUE && config.useWebWorkers)); + workerOptions.scripts = workerOptions.useWebWorkers && workerScripts ? workerScripts[codecType] : []; + options.useCompressionStream = useCompressionStream || (useCompressionStream === UNDEFINED_VALUE && config.useCompressionStream); + return (await getWorker()).run(); + + // deno-lint-ignore require-await + async function getWorker() { + const workerData = pool.find(workerData => !workerData.busy); + if (workerData) { + clearTerminateTimeout(workerData); + return new CodecWorker(workerData, stream, workerOptions, onTaskFinished); + } else if (pool.length < maxWorkers) { + const workerData = { indexWorker }; + indexWorker++; + pool.push(workerData); + return new CodecWorker(workerData, stream, workerOptions, onTaskFinished); + } else { + return new Promise(resolve => pendingRequests.push({ resolve, stream, workerOptions })); + } + } + + function onTaskFinished(workerData) { + if (pendingRequests.length) { + const [{ resolve, stream, workerOptions }] = pendingRequests.splice(0, 1); + resolve(new CodecWorker(workerData, stream, workerOptions, onTaskFinished)); + } else if (workerData.worker) { + clearTerminateTimeout(workerData); + terminateWorker(workerData, workerOptions); + } else { + pool = pool.filter(data => data != workerData); + } + } +} + +function terminateWorker(workerData, workerOptions) { + const { config } = workerOptions; + const { terminateWorkerTimeout } = config; + if (Number.isFinite(terminateWorkerTimeout) && terminateWorkerTimeout >= 0) { + if (workerData.terminated) { + workerData.terminated = false; + } else { + workerData.terminateTimeout = setTimeout(async () => { + pool = pool.filter(data => data != workerData); + try { + await workerData.terminate(); + } catch (_error) { + // ignored + } + }, terminateWorkerTimeout); + } + } +} + +function clearTerminateTimeout(workerData) { + const { terminateTimeout } = workerData; + if (terminateTimeout) { + clearTimeout(terminateTimeout); + workerData.terminateTimeout = null; + } +} + +function e(e,t={}){const n='const{Array:e,Object:t,Number:n,Math:r,Error:s,Uint8Array:i,Uint16Array:o,Uint32Array:c,Int32Array:f,Map:a,DataView:l,Promise:u,TextEncoder:w,crypto:h,postMessage:d,TransformStream:p,ReadableStream:y,WritableStream:m,CompressionStream:b,DecompressionStream:g}=self,k=void 0,v="undefined",S="function";class z{constructor(e){return class extends p{constructor(t,n){const r=new e(n);super({transform(e,t){t.enqueue(r.append(e))},flush(e){const t=r.flush();t&&e.enqueue(t)}})}}}}const C=[];for(let e=0;256>e;e++){let t=e;for(let e=0;8>e;e++)1&t?t=t>>>1^3988292384:t>>>=1;C[e]=t}class x{constructor(e){this.t=e||-1}append(e){let t=0|this.t;for(let n=0,r=0|e.length;r>n;n++)t=t>>>8^C[255&(t^e[n])];this.t=t}get(){return~this.t}}class A extends p{constructor(){let e;const t=new x;super({transform(e,n){t.append(e),n.enqueue(e)},flush(){const n=new i(4);new l(n.buffer).setUint32(0,t.get()),e.value=n}}),e=this}}const _={concat(e,t){if(0===e.length||0===t.length)return e.concat(t);const n=e[e.length-1],r=_.i(n);return 32===r?e.concat(t):_.o(t,r,0|n,e.slice(0,e.length-1))},l(e){const t=e.length;if(0===t)return 0;const n=e[t-1];return 32*(t-1)+_.i(n)},u(e,t){if(32*e.length0&&t&&(e[n-1]=_.h(t,e[n-1]&2147483648>>t-1,1)),e},h:(e,t,n)=>32===e?t:(n?0|t:t<<32-e)+1099511627776*e,i:e=>r.round(e/1099511627776)||32,o(e,t,n,r){for(void 0===r&&(r=[]);t>=32;t-=32)r.push(n),n=0;if(0===t)return r.concat(e);for(let s=0;s>>t),n=e[s]<<32-t;const s=e.length?e[e.length-1]:0,i=_.i(s);return r.push(_.h(t+i&31,t+i>32?n:r.pop(),1)),r}},I={bytes:{p(e){const t=_.l(e)/8,n=new i(t);let r;for(let s=0;t>s;s++)3&s||(r=e[s/4]),n[s]=r>>>24,r<<=8;return n},m(e){const t=[];let n,r=0;for(n=0;n9007199254740991)throw new s("Cannot hash more than 2^53 - 1 bits");const o=new c(n);let f=0;for(let e=t.blockSize+r-(t.blockSize+r&t.blockSize-1);i>=e;e+=t.blockSize)t.I(o.subarray(16*f,16*(f+1))),f+=1;return n.splice(0,16*f),t}P(){const e=this;let t=e.C;const n=e.S;t=_.concat(t,[_.h(1,1)]);for(let e=t.length+2;15&e;e++)t.push(0);for(t.push(r.floor(e.A/4294967296)),t.push(0|e.A);t.length;)e.I(t.splice(0,16));return e.reset(),n}D(e,t,n,r){return e>19?e>39?e>59?e>79?void 0:t^n^r:t&n|t&r|n&r:t^n^r:t&n|~t&r}V(e,t){return t<>>32-e}I(t){const n=this,s=n.S,i=e(80);for(let e=0;16>e;e++)i[e]=t[e];let o=s[0],c=s[1],f=s[2],a=s[3],l=s[4];for(let e=0;79>=e;e++){16>e||(i[e]=n.V(1,i[e-3]^i[e-8]^i[e-14]^i[e-16]));const t=n.V(5,o)+n.D(e,c,f,a)+l+i[e]+n.v[r.floor(e/20)]|0;l=a,a=f,f=n.V(30,c),c=o,o=t}s[0]=s[0]+o|0,s[1]=s[1]+c|0,s[2]=s[2]+f|0,s[3]=s[3]+a|0,s[4]=s[4]+l|0}},D={getRandomValues(e){const t=new c(e.buffer),n=e=>{let t=987654321;const n=4294967295;return()=>(t=36969*(65535&t)+(t>>16)&n,(((t<<16)+(e=18e3*(65535&e)+(e>>16)&n)&n)/4294967296+.5)*(r.random()>.5?1:-1))};for(let s,i=0;inew V.R(I.bytes.m(e)),B(e,t,n,r){if(n=n||1e4,0>r||0>n)throw new s("invalid params to pbkdf2");const i=1+(r>>5)<<2;let o,c,f,a,u;const w=new ArrayBuffer(i),h=new l(w);let d=0;const p=_;for(t=I.bytes.m(t),u=1;(i||1)>d;u++){for(o=c=e.encrypt(p.concat(t,[u])),f=1;n>f;f++)for(c=e.encrypt(c),a=0;ad&&fs&&(e=(new n).update(e).P());for(let t=0;s>t;t++)r[0][t]=909522486^e[t],r[1][t]=1549556828^e[t];t.U[0].update(r[0]),t.U[1].update(r[1]),t.K=new n(t.U[0])}reset(){const e=this;e.K=new e.M(e.U[0]),e.N=!1}update(e){this.N=!0,this.K.update(e)}digest(){const e=this,t=e.K.P(),n=new e.M(e.U[1]).update(t).P();return e.reset(),n}encrypt(e){if(this.N)throw new s("encrypt on already updated hmac called!");return this.update(e),this.digest(e)}}},R=typeof h!=v&&typeof h.getRandomValues==S,B="Invalid password",E="Invalid signature",M="zipjs-abort-check-password";function U(e){return R?h.getRandomValues(e):D.getRandomValues(e)}const K=16,N={name:"PBKDF2"},O=t.assign({hash:{name:"HMAC"}},N),T=t.assign({iterations:1e3,hash:{name:"SHA-1"}},N),W=["deriveBits"],j=[8,12,16],H=[16,24,32],L=10,F=[0,0,0,0],q=typeof h!=v,G=q&&h.subtle,J=q&&typeof G!=v,Q=I.bytes,X=class{constructor(e){const t=this;t.O=[[[],[],[],[],[]],[[],[],[],[],[]]],t.O[0][0][0]||t.T();const n=t.O[0][4],r=t.O[1],i=e.length;let o,c,f,a=1;if(4!==i&&6!==i&&8!==i)throw new s("invalid aes key size");for(t.v=[c=e.slice(0),f=[]],o=i;4*i+28>o;o++){let e=c[o-1];(o%i==0||8===i&&o%i==4)&&(e=n[e>>>24]<<24^n[e>>16&255]<<16^n[e>>8&255]<<8^n[255&e],o%i==0&&(e=e<<8^e>>>24^a<<24,a=a<<1^283*(a>>7))),c[o]=c[o-i]^e}for(let e=0;o;e++,o--){const t=c[3&e?o:o-4];f[e]=4>=o||4>e?t:r[0][n[t>>>24]]^r[1][n[t>>16&255]]^r[2][n[t>>8&255]]^r[3][n[255&t]]}}encrypt(e){return this.W(e,0)}decrypt(e){return this.W(e,1)}T(){const e=this.O[0],t=this.O[1],n=e[4],r=t[4],s=[],i=[];let o,c,f,a;for(let e=0;256>e;e++)i[(s[e]=e<<1^283*(e>>7))^e]=e;for(let l=o=0;!n[l];l^=c||1,o=i[o]||1){let i=o^o<<1^o<<2^o<<3^o<<4;i=i>>8^255&i^99,n[l]=i,r[i]=l,a=s[f=s[c=s[l]]];let u=16843009*a^65537*f^257*c^16843008*l,w=257*s[i]^16843008*i;for(let n=0;4>n;n++)e[n][l]=w=w<<24^w>>>8,t[n][i]=u=u<<24^u>>>8}for(let n=0;5>n;n++)e[n]=e[n].slice(0),t[n]=t[n].slice(0)}W(e,t){if(4!==e.length)throw new s("invalid aes block size");const n=this.v[t],r=n.length/4-2,i=[0,0,0,0],o=this.O[t],c=o[0],f=o[1],a=o[2],l=o[3],u=o[4];let w,h,d,p=e[0]^n[0],y=e[t?3:1]^n[1],m=e[2]^n[2],b=e[t?1:3]^n[3],g=4;for(let e=0;r>e;e++)w=c[p>>>24]^f[y>>16&255]^a[m>>8&255]^l[255&b]^n[g],h=c[y>>>24]^f[m>>16&255]^a[b>>8&255]^l[255&p]^n[g+1],d=c[m>>>24]^f[b>>16&255]^a[p>>8&255]^l[255&y]^n[g+2],b=c[b>>>24]^f[p>>16&255]^a[y>>8&255]^l[255&m]^n[g+3],g+=4,p=w,y=h,m=d;for(let e=0;4>e;e++)i[t?3&-e:e]=u[p>>>24]<<24^u[y>>16&255]<<16^u[m>>8&255]<<8^u[255&b]^n[g++],w=p,p=y,y=m,m=b,b=w;return i}},Y=class{constructor(e,t){this.j=e,this.H=t,this.L=t}reset(){this.L=this.H}update(e){return this.F(this.j,e,this.L)}q(e){if(255&~(e>>24))e+=1<<24;else{let t=e>>16&255,n=e>>8&255,r=255&e;255===t?(t=0,255===n?(n=0,255===r?r=0:++r):++n):++t,e=0,e+=t<<16,e+=n<<8,e+=r}return e}G(e){0===(e[0]=this.q(e[0]))&&(e[1]=this.q(e[1]))}F(e,t,n){let r;if(!(r=t.length))return[];const s=_.l(t);for(let s=0;r>s;s+=4){this.G(n);const r=e.encrypt(n);t[s]^=r[0],t[s+1]^=r[1],t[s+2]^=r[2],t[s+3]^=r[3]}return _.u(t,s)}},Z=V.R;let $=q&&J&&typeof G.importKey==S,ee=q&&J&&typeof G.deriveBits==S;class te extends p{constructor({password:e,rawPassword:n,signed:r,encryptionStrength:o,checkPasswordOnly:c}){super({start(){t.assign(this,{ready:new u((e=>this.J=e)),password:ie(e,n),signed:r,X:o-1,pending:new i})},async transform(e,t){const n=this,{password:r,X:o,J:f,ready:a}=n;r?(await(async(e,t,n,r)=>{const i=await se(e,t,n,ce(r,0,j[t])),o=ce(r,j[t]);if(i[0]!=o[0]||i[1]!=o[1])throw new s(B)})(n,o,r,ce(e,0,j[o]+2)),e=ce(e,j[o]+2),c?t.error(new s(M)):f()):await a;const l=new i(e.length-L-(e.length-L)%K);t.enqueue(re(n,e,l,0,L,!0))},async flush(e){const{signed:t,Y:n,Z:r,pending:o,ready:c}=this;if(r&&n){await c;const f=ce(o,0,o.length-L),a=ce(o,o.length-L);let l=new i;if(f.length){const e=ae(Q,f);r.update(e);const t=n.update(e);l=fe(Q,t)}if(t){const e=ce(fe(Q,r.digest()),0,L);for(let t=0;L>t;t++)if(e[t]!=a[t])throw new s(E)}e.enqueue(l)}}})}}class ne extends p{constructor({password:e,rawPassword:n,encryptionStrength:r}){let s;super({start(){t.assign(this,{ready:new u((e=>this.J=e)),password:ie(e,n),X:r-1,pending:new i})},async transform(e,t){const n=this,{password:r,X:s,J:o,ready:c}=n;let f=new i;r?(f=await(async(e,t,n)=>{const r=U(new i(j[t]));return oe(r,await se(e,t,n,r))})(n,s,r),o()):await c;const a=new i(f.length+e.length-e.length%K);a.set(f,0),t.enqueue(re(n,e,a,f.length,0))},async flush(e){const{Y:t,Z:n,pending:r,ready:o}=this;if(n&&t){await o;let c=new i;if(r.length){const e=t.update(ae(Q,r));n.update(e),c=fe(Q,e)}s.signature=fe(Q,n.digest()).slice(0,L),e.enqueue(oe(c,s.signature))}}}),s=this}}function re(e,t,n,r,s,o){const{Y:c,Z:f,pending:a}=e,l=t.length-s;let u;for(a.length&&(t=oe(a,t),n=((e,t)=>{if(t&&t>e.length){const n=e;(e=new i(t)).set(n,0)}return e})(n,l-l%K)),u=0;l-K>=u;u+=K){const e=ae(Q,ce(t,u,u+K));o&&f.update(e);const s=c.update(e);o||f.update(s),n.set(fe(Q,s),u+r)}return e.pending=ce(t,u),n}async function se(n,r,s,o){n.password=null;const c=await(async(e,t,n,r,s)=>{if(!$)return V.importKey(t);try{return await G.importKey("raw",t,n,!1,s)}catch(e){return $=!1,V.importKey(t)}})(0,s,O,0,W),f=await(async(e,t,n)=>{if(!ee)return V.B(t,e.salt,T.iterations,n);try{return await G.deriveBits(e,t,n)}catch(r){return ee=!1,V.B(t,e.salt,T.iterations,n)}})(t.assign({salt:o},T),c,8*(2*H[r]+2)),a=new i(f),l=ae(Q,ce(a,0,H[r])),u=ae(Q,ce(a,H[r],2*H[r])),w=ce(a,2*H[r]);return t.assign(n,{keys:{key:l,$:u,passwordVerification:w},Y:new Y(new X(l),e.from(F)),Z:new Z(u)}),w}function ie(e,t){return t===k?(e=>{if(typeof w==v){const t=new i((e=unescape(encodeURIComponent(e))).length);for(let n=0;n>>24]),i=~e.te.get(),e.keys=[n,s,i]}function ye(e){const t=2|e.keys[2];return me(r.imul(t,1^t)>>>8)}function me(e){return 255&e}function be(e){return 4294967295&e}const ge="deflate-raw";class ke extends p{constructor(e,{chunkSize:t,CompressionStream:n,CompressionStreamNative:r}){super({});const{compressed:s,encrypted:i,useCompressionStream:o,zipCrypto:c,signed:f,level:a}=e,u=this;let w,h,d=Se(super.readable);i&&!c||!f||(w=new A,d=xe(d,w)),s&&(d=Ce(d,o,{level:a,chunkSize:t},r,n)),i&&(c?d=xe(d,new ue(e)):(h=new ne(e),d=xe(d,h))),ze(u,d,(()=>{let e;i&&!c&&(e=h.signature),i&&!c||!f||(e=new l(w.value.buffer).getUint32(0)),u.signature=e}))}}class ve extends p{constructor(e,{chunkSize:t,DecompressionStream:n,DecompressionStreamNative:r}){super({});const{zipCrypto:i,encrypted:o,signed:c,signature:f,compressed:a,useCompressionStream:u}=e;let w,h,d=Se(super.readable);o&&(i?d=xe(d,new le(e)):(h=new te(e),d=xe(d,h))),a&&(d=Ce(d,u,{chunkSize:t},r,n)),o&&!i||!c||(w=new A,d=xe(d,w)),ze(this,d,(()=>{if((!o||i)&&c){const e=new l(w.value.buffer);if(f!=e.getUint32(0,!1))throw new s(E)}}))}}function Se(e){return xe(e,new p({transform(e,t){e&&e.length&&t.enqueue(e)}}))}function ze(e,n,r){n=xe(n,new p({flush:r})),t.defineProperty(e,"readable",{get:()=>n})}function Ce(e,t,n,r,s){try{e=xe(e,new(t&&r?r:s)(ge,n))}catch(r){if(!t)return e;try{e=xe(e,new s(ge,n))}catch(t){return e}}return e}function xe(e,t){return e.pipeThrough(t)}const Ae="data",_e="close";class Ie extends p{constructor(e,n){super({});const r=this,{codecType:s}=e;let i;s.startsWith("deflate")?i=ke:s.startsWith("inflate")&&(i=ve);let o=0,c=0;const f=new i(e,n),a=super.readable,l=new p({transform(e,t){e&&e.length&&(c+=e.length,t.enqueue(e))},flush(){t.assign(r,{inputSize:c})}}),u=new p({transform(e,t){e&&e.length&&(o+=e.length,t.enqueue(e))},flush(){const{signature:e}=f;t.assign(r,{signature:e,outputSize:o,inputSize:c})}});t.defineProperty(r,"readable",{get:()=>a.pipeThrough(l).pipeThrough(f).pipeThrough(u)})}}class Pe extends p{constructor(e){let t;super({transform:function n(r,s){if(t){const e=new i(t.length+r.length);e.set(t),e.set(r,t.length),r=e,t=null}r.length>e?(s.enqueue(r.slice(0,e)),n(r.slice(e),s)):t=r},flush(e){t&&t.length&&e.enqueue(t)}})}}const De=new a,Ve=new a;let Re,Be=0,Ee=!0;async function Me(e){try{const{options:t,scripts:r,config:s}=e;if(r&&r.length)try{Ee?importScripts.apply(k,r):await Ue(r)}catch(e){Ee=!1,await Ue(r)}self.initCodec&&self.initCodec(),s.CompressionStreamNative=self.CompressionStream,s.DecompressionStreamNative=self.DecompressionStream,self.Deflate&&(s.CompressionStream=new z(self.Deflate)),self.Inflate&&(s.DecompressionStream=new z(self.Inflate));const i={highWaterMark:1},o=e.readable||new y({async pull(e){const t=new u((e=>De.set(Be,e)));Ke({type:"pull",messageId:Be}),Be=(Be+1)%n.MAX_SAFE_INTEGER;const{value:r,done:s}=await t;e.enqueue(r),s&&e.close()}},i),c=e.writable||new m({async write(e){let t;const r=new u((e=>t=e));Ve.set(Be,t),Ke({type:Ae,value:e,messageId:Be}),Be=(Be+1)%n.MAX_SAFE_INTEGER,await r}},i),f=new Ie(t,s);Re=new AbortController;const{signal:a}=Re;await o.pipeThrough(f).pipeThrough(new Pe(s.chunkSize)).pipeTo(c,{signal:a,preventClose:!0,preventAbort:!0}),await c.getWriter().close();const{signature:l,inputSize:w,outputSize:h}=f;Ke({type:_e,result:{signature:l,inputSize:w,outputSize:h}})}catch(e){Ne(e)}}async function Ue(e){for(const t of e)await import(t)}function Ke(e){let{value:t}=e;if(t)if(t.length)try{t=new i(t),e.value=t.buffer,d(e,[e.value])}catch(t){d(e)}else d(e);else d(e)}function Ne(e=new s("Unknown error")){const{message:t,stack:n,code:r,name:i}=e;d({error:{message:t,stack:n,code:r,name:i}})}addEventListener("message",(({data:e})=>{const{type:t,messageId:n,value:r,done:s}=e;try{if("start"==t&&Me(e),t==Ae){const e=De.get(n);De.delete(n),e({value:new i(r),done:s})}if("ack"==t){const e=Ve.get(n);Ve.delete(n),e()}t==_e&&Re.abort()}catch(e){Ne(e)}}));const Oe=-2;function Te(t){return We(t.map((([t,n])=>new e(t).fill(n,0,t))))}function We(t){return t.reduce(((t,n)=>t.concat(e.isArray(n)?We(n):n)),[])}const je=[0,1,2,3].concat(...Te([[2,4],[2,5],[4,6],[4,7],[8,8],[8,9],[16,10],[16,11],[32,12],[32,13],[64,14],[64,15],[2,0],[1,16],[1,17],[2,18],[2,19],[4,20],[4,21],[8,22],[8,23],[16,24],[16,25],[32,26],[32,27],[64,28],[64,29]]));function He(){const e=this;function t(e,t){let n=0;do{n|=1&e,e>>>=1,n<<=1}while(--t>0);return n>>>1}e.ne=n=>{const s=e.re,i=e.ie.se,o=e.ie.oe;let c,f,a,l=-1;for(n.ce=0,n.fe=573,c=0;o>c;c++)0!==s[2*c]?(n.ae[++n.ce]=l=c,n.le[c]=0):s[2*c+1]=0;for(;2>n.ce;)a=n.ae[++n.ce]=2>l?++l:0,s[2*a]=1,n.le[a]=0,n.ue--,i&&(n.we-=i[2*a+1]);for(e.he=l,c=r.floor(n.ce/2);c>=1;c--)n.de(s,c);a=o;do{c=n.ae[1],n.ae[1]=n.ae[n.ce--],n.de(s,1),f=n.ae[1],n.ae[--n.fe]=c,n.ae[--n.fe]=f,s[2*a]=s[2*c]+s[2*f],n.le[a]=r.max(n.le[c],n.le[f])+1,s[2*c+1]=s[2*f+1]=a,n.ae[1]=a++,n.de(s,1)}while(n.ce>=2);n.ae[--n.fe]=n.ae[1],(t=>{const n=e.re,r=e.ie.se,s=e.ie.pe,i=e.ie.ye,o=e.ie.me;let c,f,a,l,u,w,h=0;for(l=0;15>=l;l++)t.be[l]=0;for(n[2*t.ae[t.fe]+1]=0,c=t.fe+1;573>c;c++)f=t.ae[c],l=n[2*n[2*f+1]+1]+1,l>o&&(l=o,h++),n[2*f+1]=l,f>e.he||(t.be[l]++,u=0,i>f||(u=s[f-i]),w=n[2*f],t.ue+=w*(l+u),r&&(t.we+=w*(r[2*f+1]+u)));if(0!==h){do{for(l=o-1;0===t.be[l];)l--;t.be[l]--,t.be[l+1]+=2,t.be[o]--,h-=2}while(h>0);for(l=o;0!==l;l--)for(f=t.be[l];0!==f;)a=t.ae[--c],a>e.he||(n[2*a+1]!=l&&(t.ue+=(l-n[2*a+1])*n[2*a],n[2*a+1]=l),f--)}})(n),((e,n,r)=>{const s=[];let i,o,c,f=0;for(i=1;15>=i;i++)s[i]=f=f+r[i-1]<<1;for(o=0;n>=o;o++)c=e[2*o+1],0!==c&&(e[2*o]=t(s[c]++,c))})(s,e.he,n.be)}}function Le(e,t,n,r,s){const i=this;i.se=e,i.pe=t,i.ye=n,i.oe=r,i.me=s}He.ge=[0,1,2,3,4,5,6,7].concat(...Te([[2,8],[2,9],[2,10],[2,11],[4,12],[4,13],[4,14],[4,15],[8,16],[8,17],[8,18],[8,19],[16,20],[16,21],[16,22],[16,23],[32,24],[32,25],[32,26],[31,27],[1,28]])),He.ke=[0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224,0],He.ve=[0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576],He.Se=e=>256>e?je[e]:je[256+(e>>>7)],He.ze=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],He.Ce=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],He.xe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],He.Ae=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];const Fe=Te([[144,8],[112,9],[24,7],[8,8]]);Le._e=We([12,140,76,204,44,172,108,236,28,156,92,220,60,188,124,252,2,130,66,194,34,162,98,226,18,146,82,210,50,178,114,242,10,138,74,202,42,170,106,234,26,154,90,218,58,186,122,250,6,134,70,198,38,166,102,230,22,150,86,214,54,182,118,246,14,142,78,206,46,174,110,238,30,158,94,222,62,190,126,254,1,129,65,193,33,161,97,225,17,145,81,209,49,177,113,241,9,137,73,201,41,169,105,233,25,153,89,217,57,185,121,249,5,133,69,197,37,165,101,229,21,149,85,213,53,181,117,245,13,141,77,205,45,173,109,237,29,157,93,221,61,189,125,253,19,275,147,403,83,339,211,467,51,307,179,435,115,371,243,499,11,267,139,395,75,331,203,459,43,299,171,427,107,363,235,491,27,283,155,411,91,347,219,475,59,315,187,443,123,379,251,507,7,263,135,391,71,327,199,455,39,295,167,423,103,359,231,487,23,279,151,407,87,343,215,471,55,311,183,439,119,375,247,503,15,271,143,399,79,335,207,463,47,303,175,431,111,367,239,495,31,287,159,415,95,351,223,479,63,319,191,447,127,383,255,511,0,64,32,96,16,80,48,112,8,72,40,104,24,88,56,120,4,68,36,100,20,84,52,116,3,131,67,195,35,163,99,227].map(((e,t)=>[e,Fe[t]])));const qe=Te([[30,5]]);function Ge(e,t,n,r,s){const i=this;i.Ie=e,i.Pe=t,i.De=n,i.Ve=r,i.Re=s}Le.Be=We([0,16,8,24,4,20,12,28,2,18,10,26,6,22,14,30,1,17,9,25,5,21,13,29,3,19,11,27,7,23].map(((e,t)=>[e,qe[t]]))),Le.Ee=new Le(Le._e,He.ze,257,286,15),Le.Me=new Le(Le.Be,He.Ce,0,30,15),Le.Ue=new Le(null,He.xe,0,19,7);const Je=[new Ge(0,0,0,0,0),new Ge(4,4,8,4,1),new Ge(4,5,16,8,1),new Ge(4,6,32,32,1),new Ge(4,4,16,16,2),new Ge(8,16,32,32,2),new Ge(8,16,128,128,2),new Ge(8,32,128,256,2),new Ge(32,128,258,1024,2),new Ge(32,258,258,4096,2)],Qe=["need dictionary","stream end","","","stream error","data error","","buffer error","",""],Xe=113,Ye=666,Ze=262;function $e(e,t,n,r){const s=e[2*t],i=e[2*n];return i>s||s==i&&r[t]<=r[n]}function et(){const e=this;let t,n,s,c,f,a,l,u,w,h,d,p,y,m,b,g,k,v,S,z,C,x,A,_,I,P,D,V,R,B,E,M,U;const K=new He,N=new He,O=new He;let T,W,j,H,L,F;function q(){let t;for(t=0;286>t;t++)E[2*t]=0;for(t=0;30>t;t++)M[2*t]=0;for(t=0;19>t;t++)U[2*t]=0;E[512]=1,e.ue=e.we=0,W=j=0}function G(e,t){let n,r=-1,s=e[1],i=0,o=7,c=4;0===s&&(o=138,c=3),e[2*(t+1)+1]=65535;for(let f=0;t>=f;f++)n=s,s=e[2*(f+1)+1],++ii?U[2*n]+=i:0!==n?(n!=r&&U[2*n]++,U[32]++):i>10?U[36]++:U[34]++,i=0,r=n,0===s?(o=138,c=3):n==s?(o=6,c=3):(o=7,c=4))}function J(t){e.Ke[e.pending++]=t}function Q(e){J(255&e),J(e>>>8&255)}function X(e,t){let n;const r=t;F>16-r?(n=e,L|=n<>>16-F,F+=r-16):(L|=e<=n;n++)if(r=i,i=e[2*(n+1)+1],++o>=c||r!=i){if(f>o)do{Y(r,U)}while(0!=--o);else 0!==r?(r!=s&&(Y(r,U),o--),Y(16,U),X(o-3,2)):o>10?(Y(18,U),X(o-11,7)):(Y(17,U),X(o-3,3));o=0,s=r,0===i?(c=138,f=3):r==i?(c=6,f=3):(c=7,f=4)}}function $(){16==F?(Q(L),L=0,F=0):8>F||(J(255&L),L>>>=8,F-=8)}function ee(t,n){let s,i,o;if(e.Ne[W]=t,e.Oe[W]=255&n,W++,0===t?E[2*n]++:(j++,t--,E[2*(He.ge[n]+256+1)]++,M[2*He.Se(t)]++),!(8191&W)&&D>2){for(s=8*W,i=C-k,o=0;30>o;o++)s+=M[2*o]*(5+He.Ce[o]);if(s>>>=3,jc);Y(256,t),H=t[513]}function ne(){F>8?Q(L):F>0&&J(255&L),L=0,F=0}function re(t,n,r){X(0+(r?1:0),3),((t,n)=>{ne(),H=8,Q(n),Q(~n),e.Ke.set(u.subarray(t,t+n),e.pending),e.pending+=n})(t,n)}function se(n){((t,n,r)=>{let s,i,o=0;D>0?(K.ne(e),N.ne(e),o=(()=>{let t;for(G(E,K.he),G(M,N.he),O.ne(e),t=18;t>=3&&0===U[2*He.Ae[t]+1];t--);return e.ue+=14+3*(t+1),t})(),s=e.ue+3+7>>>3,i=e.we+3+7>>>3,i>s||(s=i)):s=i=n+5,n+4>s||-1==t?i==s?(X(2+(r?1:0),3),te(Le._e,Le.Be)):(X(4+(r?1:0),3),((e,t,n)=>{let r;for(X(e-257,5),X(t-1,5),X(n-4,4),r=0;n>r;r++)X(U[2*He.Ae[r]+1],3);Z(E,e-1),Z(M,t-1)})(K.he+1,N.he+1,o+1),te(E,M)):re(t,n,r),q(),r&&ne()})(0>k?-1:k,C-k,n),k=C,t.Te()}function ie(){let e,n,r,s;do{if(s=w-A-C,0===s&&0===C&&0===A)s=f;else if(-1==s)s--;else if(C>=f+f-Ze){u.set(u.subarray(f,f+f),0),x-=f,C-=f,k-=f,e=y,r=e;do{n=65535&d[--r],d[r]=f>n?0:n-f}while(0!=--e);e=f,r=e;do{n=65535&h[--r],h[r]=f>n?0:n-f}while(0!=--e);s+=f}if(0===t.We)return;e=t.je(u,C+A,s),A+=e,3>A||(p=255&u[C],p=(p<A&&0!==t.We)}function oe(e){let t,n,r=I,s=C,i=_;const o=C>f-Ze?C-(f-Ze):0;let c=B;const a=l,w=C+258;let d=u[s+i-1],p=u[s+i];R>_||(r>>=2),c>A&&(c=A);do{if(t=e,u[t+i]==p&&u[t+i-1]==d&&u[t]==u[s]&&u[++t]==u[s+1]){s+=2,t++;do{}while(u[++s]==u[++t]&&u[++s]==u[++t]&&u[++s]==u[++t]&&u[++s]==u[++t]&&u[++s]==u[++t]&&u[++s]==u[++t]&&u[++s]==u[++t]&&u[++s]==u[++t]&&w>s);if(n=258-(w-s),s=w-258,n>i){if(x=e,i=n,n>=c)break;d=u[s+i-1],p=u[s+i]}}}while((e=65535&h[e&a])>o&&0!=--r);return i>A?A:i}e.le=[],e.be=[],e.ae=[],E=[],M=[],U=[],e.de=(t,n)=>{const r=e.ae,s=r[n];let i=n<<1;for(;i<=e.ce&&(i(W||(W=8),j||(j=8),G||(G=0),t.Le=null,-1==S&&(S=6),1>j||j>9||8!=W||9>x||x>15||0>S||S>9||0>G||G>2?Oe:(t.Fe=e,a=x,f=1<(t.qe=t.Ge=0,t.Le=null,e.pending=0,e.Je=0,n=Xe,c=0,K.re=E,K.ie=Le.Ee,N.re=M,N.ie=Le.Me,O.re=U,O.ie=Le.Ue,L=0,F=0,H=8,q(),(()=>{w=2*f,d[y-1]=0;for(let e=0;y-1>e;e++)d[e]=0;P=Je[D].Pe,R=Je[D].Ie,B=Je[D].De,I=Je[D].Ve,C=0,k=0,A=0,v=_=2,z=0,p=0})(),0))(t))),e.Qe=()=>42!=n&&n!=Xe&&n!=Ye?Oe:(e.Oe=null,e.Ne=null,e.Ke=null,d=null,h=null,u=null,e.Fe=null,n==Xe?-3:0),e.Xe=(e,t,n)=>{let r=0;return-1==t&&(t=6),0>t||t>9||0>n||n>2?Oe:(Je[D].Re!=Je[t].Re&&0!==e.qe&&(r=e.Ye(1)),D!=t&&(D=t,P=Je[D].Pe,R=Je[D].Ie,B=Je[D].De,I=Je[D].Ve),V=n,r)},e.Ze=(e,t,r)=>{let s,i=r,o=0;if(!t||42!=n)return Oe;if(3>i)return 0;for(i>f-Ze&&(i=f-Ze,o=r-i),u.set(t.subarray(o,o+i),0),C=i,k=i,p=255&u[0],p=(p<=s;s++)p=(p<{let o,w,m,I,R;if(i>4||0>i)return Oe;if(!r.$e||!r.et&&0!==r.We||n==Ye&&4!=i)return r.Le=Qe[4],Oe;if(0===r.tt)return r.Le=Qe[7],-5;var B;if(t=r,I=c,c=i,42==n&&(w=8+(a-8<<4)<<8,m=(D-1&255)>>1,m>3&&(m=3),w|=m<<6,0!==C&&(w|=32),w+=31-w%31,n=Xe,J((B=w)>>8&255),J(255&B)),0!==e.pending){if(t.Te(),0===t.tt)return c=-1,0}else if(0===t.We&&I>=i&&4!=i)return t.Le=Qe[7],-5;if(n==Ye&&0!==t.We)return r.Le=Qe[7],-5;if(0!==t.We||0!==A||0!=i&&n!=Ye){switch(R=-1,Je[D].Re){case 0:R=(e=>{let n,r=65535;for(r>s-5&&(r=s-5);;){if(1>=A){if(ie(),0===A&&0==e)return 0;if(0===A)break}if(C+=A,A=0,n=k+r,(0===C||C>=n)&&(A=C-n,C=n,se(!1),0===t.tt))return 0;if(C-k>=f-Ze&&(se(!1),0===t.tt))return 0}return se(4==e),0===t.tt?4==e?2:0:4==e?3:1})(i);break;case 1:R=(e=>{let n,r=0;for(;;){if(Ze>A){if(ie(),Ze>A&&0==e)return 0;if(0===A)break}if(3>A||(p=(p<f-Ze||2!=V&&(v=oe(r)),3>v)n=ee(0,255&u[C]),A--,C++;else if(n=ee(C-x,v-3),A-=v,v>P||3>A)C+=v,v=0,p=255&u[C],p=(p<{let n,r,s=0;for(;;){if(Ze>A){if(ie(),Ze>A&&0==e)return 0;if(0===A)break}if(3>A||(p=(p<_&&f-Ze>=(C-s&65535)&&(2!=V&&(v=oe(s)),5>=v&&(1==V||3==v&&C-x>4096)&&(v=2)),3>_||v>_)if(0!==z){if(n=ee(0,255&u[C-1]),n&&se(!1),C++,A--,0===t.tt)return 0}else z=1,C++,A--;else{r=C+A-3,n=ee(C-1-S,_-3),A-=_-1,_-=2;do{++C>r||(p=(p<1+H+10-F&&(X(2,3),Y(256,Le._e),$()),H=7;else if(re(0,0,!1),3==i)for(o=0;y>o;o++)d[o]=0;if(t.Te(),0===t.tt)return c=-1,0}}return 4!=i?0:1}}function tt(){const e=this;e.nt=0,e.rt=0,e.We=0,e.qe=0,e.tt=0,e.Ge=0}function nt(e){const t=new tt,n=(o=e&&e.chunkSize?e.chunkSize:65536)+5*(r.floor(o/16383)+1);var o;const c=new i(n);let f=e?e.level:-1;void 0===f&&(f=-1),t.He(f),t.$e=c,this.append=(e,r)=>{let o,f,a=0,l=0,u=0;const w=[];if(e.length){t.nt=0,t.et=e,t.We=e.length;do{if(t.rt=0,t.tt=n,o=t.Ye(0),0!=o)throw new s("deflating: "+t.Le);t.rt&&(t.rt==n?w.push(new i(c)):w.push(c.subarray(0,t.rt))),u+=t.rt,r&&t.nt>0&&t.nt!=a&&(r(t.nt),a=t.nt)}while(t.We>0||0===t.tt);return w.length>1?(f=new i(u),w.forEach((e=>{f.set(e,l),l+=e.length}))):f=w[0]?new i(w[0]):new i,f}},this.flush=()=>{let e,r,o=0,f=0;const a=[];do{if(t.rt=0,t.tt=n,e=t.Ye(4),1!=e&&0!=e)throw new s("deflating: "+t.Le);n-t.tt>0&&a.push(c.slice(0,t.rt)),f+=t.rt}while(t.We>0||0===t.tt);return t.Qe(),r=new i(f),a.forEach((e=>{r.set(e,o),o+=e.length})),r}}tt.prototype={He(e,t){const n=this;return n.Fe=new et,t||(t=15),n.Fe.He(n,e,t)},Ye(e){const t=this;return t.Fe?t.Fe.Ye(t,e):Oe},Qe(){const e=this;if(!e.Fe)return Oe;const t=e.Fe.Qe();return e.Fe=null,t},Xe(e,t){const n=this;return n.Fe?n.Fe.Xe(n,e,t):Oe},Ze(e,t){const n=this;return n.Fe?n.Fe.Ze(n,e,t):Oe},je(e,t,n){const r=this;let s=r.We;return s>n&&(s=n),0===s?0:(r.We-=s,e.set(r.et.subarray(r.nt,r.nt+s),t),r.nt+=s,r.qe+=s,s)},Te(){const e=this;let t=e.Fe.pending;t>e.tt&&(t=e.tt),0!==t&&(e.$e.set(e.Fe.Ke.subarray(e.Fe.Je,e.Fe.Je+t),e.rt),e.rt+=t,e.Fe.Je+=t,e.Ge+=t,e.tt-=t,e.Fe.pending-=t,0===e.Fe.pending&&(e.Fe.Je=0))}};const rt=-2,st=-3,it=-5,ot=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],ct=[96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,192,80,7,10,0,8,96,0,8,32,0,9,160,0,8,0,0,8,128,0,8,64,0,9,224,80,7,6,0,8,88,0,8,24,0,9,144,83,7,59,0,8,120,0,8,56,0,9,208,81,7,17,0,8,104,0,8,40,0,9,176,0,8,8,0,8,136,0,8,72,0,9,240,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,200,81,7,13,0,8,100,0,8,36,0,9,168,0,8,4,0,8,132,0,8,68,0,9,232,80,7,8,0,8,92,0,8,28,0,9,152,84,7,83,0,8,124,0,8,60,0,9,216,82,7,23,0,8,108,0,8,44,0,9,184,0,8,12,0,8,140,0,8,76,0,9,248,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,196,81,7,11,0,8,98,0,8,34,0,9,164,0,8,2,0,8,130,0,8,66,0,9,228,80,7,7,0,8,90,0,8,26,0,9,148,84,7,67,0,8,122,0,8,58,0,9,212,82,7,19,0,8,106,0,8,42,0,9,180,0,8,10,0,8,138,0,8,74,0,9,244,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,204,81,7,15,0,8,102,0,8,38,0,9,172,0,8,6,0,8,134,0,8,70,0,9,236,80,7,9,0,8,94,0,8,30,0,9,156,84,7,99,0,8,126,0,8,62,0,9,220,82,7,27,0,8,110,0,8,46,0,9,188,0,8,14,0,8,142,0,8,78,0,9,252,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,194,80,7,10,0,8,97,0,8,33,0,9,162,0,8,1,0,8,129,0,8,65,0,9,226,80,7,6,0,8,89,0,8,25,0,9,146,83,7,59,0,8,121,0,8,57,0,9,210,81,7,17,0,8,105,0,8,41,0,9,178,0,8,9,0,8,137,0,8,73,0,9,242,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,202,81,7,13,0,8,101,0,8,37,0,9,170,0,8,5,0,8,133,0,8,69,0,9,234,80,7,8,0,8,93,0,8,29,0,9,154,84,7,83,0,8,125,0,8,61,0,9,218,82,7,23,0,8,109,0,8,45,0,9,186,0,8,13,0,8,141,0,8,77,0,9,250,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,198,81,7,11,0,8,99,0,8,35,0,9,166,0,8,3,0,8,131,0,8,67,0,9,230,80,7,7,0,8,91,0,8,27,0,9,150,84,7,67,0,8,123,0,8,59,0,9,214,82,7,19,0,8,107,0,8,43,0,9,182,0,8,11,0,8,139,0,8,75,0,9,246,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,206,81,7,15,0,8,103,0,8,39,0,9,174,0,8,7,0,8,135,0,8,71,0,9,238,80,7,9,0,8,95,0,8,31,0,9,158,84,7,99,0,8,127,0,8,63,0,9,222,82,7,27,0,8,111,0,8,47,0,9,190,0,8,15,0,8,143,0,8,79,0,9,254,96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,193,80,7,10,0,8,96,0,8,32,0,9,161,0,8,0,0,8,128,0,8,64,0,9,225,80,7,6,0,8,88,0,8,24,0,9,145,83,7,59,0,8,120,0,8,56,0,9,209,81,7,17,0,8,104,0,8,40,0,9,177,0,8,8,0,8,136,0,8,72,0,9,241,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,201,81,7,13,0,8,100,0,8,36,0,9,169,0,8,4,0,8,132,0,8,68,0,9,233,80,7,8,0,8,92,0,8,28,0,9,153,84,7,83,0,8,124,0,8,60,0,9,217,82,7,23,0,8,108,0,8,44,0,9,185,0,8,12,0,8,140,0,8,76,0,9,249,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,197,81,7,11,0,8,98,0,8,34,0,9,165,0,8,2,0,8,130,0,8,66,0,9,229,80,7,7,0,8,90,0,8,26,0,9,149,84,7,67,0,8,122,0,8,58,0,9,213,82,7,19,0,8,106,0,8,42,0,9,181,0,8,10,0,8,138,0,8,74,0,9,245,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,205,81,7,15,0,8,102,0,8,38,0,9,173,0,8,6,0,8,134,0,8,70,0,9,237,80,7,9,0,8,94,0,8,30,0,9,157,84,7,99,0,8,126,0,8,62,0,9,221,82,7,27,0,8,110,0,8,46,0,9,189,0,8,14,0,8,142,0,8,78,0,9,253,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,195,80,7,10,0,8,97,0,8,33,0,9,163,0,8,1,0,8,129,0,8,65,0,9,227,80,7,6,0,8,89,0,8,25,0,9,147,83,7,59,0,8,121,0,8,57,0,9,211,81,7,17,0,8,105,0,8,41,0,9,179,0,8,9,0,8,137,0,8,73,0,9,243,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,203,81,7,13,0,8,101,0,8,37,0,9,171,0,8,5,0,8,133,0,8,69,0,9,235,80,7,8,0,8,93,0,8,29,0,9,155,84,7,83,0,8,125,0,8,61,0,9,219,82,7,23,0,8,109,0,8,45,0,9,187,0,8,13,0,8,141,0,8,77,0,9,251,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,199,81,7,11,0,8,99,0,8,35,0,9,167,0,8,3,0,8,131,0,8,67,0,9,231,80,7,7,0,8,91,0,8,27,0,9,151,84,7,67,0,8,123,0,8,59,0,9,215,82,7,19,0,8,107,0,8,43,0,9,183,0,8,11,0,8,139,0,8,75,0,9,247,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,207,81,7,15,0,8,103,0,8,39,0,9,175,0,8,7,0,8,135,0,8,71,0,9,239,80,7,9,0,8,95,0,8,31,0,9,159,84,7,99,0,8,127,0,8,63,0,9,223,82,7,27,0,8,111,0,8,47,0,9,191,0,8,15,0,8,143,0,8,79,0,9,255],ft=[80,5,1,87,5,257,83,5,17,91,5,4097,81,5,5,89,5,1025,85,5,65,93,5,16385,80,5,3,88,5,513,84,5,33,92,5,8193,82,5,9,90,5,2049,86,5,129,192,5,24577,80,5,2,87,5,385,83,5,25,91,5,6145,81,5,7,89,5,1537,85,5,97,93,5,24577,80,5,4,88,5,769,84,5,49,92,5,12289,82,5,13,90,5,3073,86,5,193,192,5,24577],at=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],lt=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,112,112],ut=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],wt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function ht(){let e,t,n,r,s,i;function o(e,t,o,c,f,a,l,u,w,h,d){let p,y,m,b,g,k,v,S,z,C,x,A,_,I,P;C=0,g=o;do{n[e[t+C]]++,C++,g--}while(0!==g);if(n[0]==o)return l[0]=-1,u[0]=0,0;for(S=u[0],k=1;15>=k&&0===n[k];k++);for(v=k,k>S&&(S=k),g=15;0!==g&&0===n[g];g--);for(m=g,S>g&&(S=g),u[0]=S,I=1<k;k++,I<<=1)if(0>(I-=n[k]))return st;if(0>(I-=n[g]))return st;for(n[g]+=I,i[1]=k=0,C=1,_=2;0!=--g;)i[_]=k+=n[C],_++,C++;g=0,C=0;do{0!==(k=e[t+C])&&(d[i[k]++]=g),C++}while(++g=v;v++)for(p=n[v];0!=p--;){for(;v>A+S;){if(b++,A+=S,P=m-A,P=P>S?S:P,(y=1<<(k=v-A))>p+1&&(y-=p+1,_=v,P>k))for(;++kn[++_];)y-=n[_];if(P=1<1440)return st;s[b]=x=h[0],h[0]+=P,0!==b?(i[b]=g,r[0]=k,r[1]=S,k=g>>>A-S,r[2]=x-s[b-1]-k,w.set(r,3*(s[b-1]+k))):l[0]=x}for(r[1]=v-A,o>C?d[C]d[C]?0:96,r[2]=d[C++]):(r[0]=a[d[C]-c]+16+64,r[2]=f[d[C++]-c]):r[0]=192,y=1<>>A;P>k;k+=y)w.set(r,3*(x+k));for(k=1<>>=1)g^=k;for(g^=k,z=(1<c;c++)t[c]=0;for(c=0;16>c;c++)n[c]=0;for(c=0;3>c;c++)r[c]=0;s.set(n.subarray(0,15),0),i.set(n.subarray(0,16),0)}this.st=(n,r,s,i,f)=>{let a;return c(19),e[0]=0,a=o(n,0,19,19,null,null,s,r,i,e,t),a==st?f.Le="oversubscribed dynamic bit lengths tree":a!=it&&0!==r[0]||(f.Le="incomplete dynamic bit lengths tree",a=st),a},this.it=(n,r,s,i,f,a,l,u,w)=>{let h;return c(288),e[0]=0,h=o(s,0,n,257,at,lt,a,i,u,e,t),0!=h||0===i[0]?(h==st?w.Le="oversubscribed literal/length tree":-4!=h&&(w.Le="incomplete literal/length tree",h=st),h):(c(288),h=o(s,n,r,0,ut,wt,l,f,u,e,t),0!=h||0===f[0]&&n>257?(h==st?w.Le="oversubscribed distance tree":h==it?(w.Le="incomplete distance tree",h=st):-4!=h&&(w.Le="empty distance tree with lengths",h=st),h):0)}}function dt(){const e=this;let t,n,r,s,i=0,o=0,c=0,f=0,a=0,l=0,u=0,w=0,h=0,d=0;function p(e,t,n,r,s,i,o,c){let f,a,l,u,w,h,d,p,y,m,b,g,k,v,S,z;d=c.nt,p=c.We,w=o.ot,h=o.ct,y=o.write,m=yh;)p--,w|=(255&c.ft(d++))<>=a[z+1],h-=a[z+1],16&u){for(u&=15,k=a[z+2]+(w&ot[u]),w>>=u,h-=u;15>h;)p--,w|=(255&c.ft(d++))<>=a[z+1],h-=a[z+1],16&u){for(u&=15;u>h;)p--,w|=(255&c.ft(d++))<>=u,h-=u,m-=k,v>y){S=y-v;do{S+=o.end}while(0>S);if(u=o.end-S,k>u){if(k-=u,y-S>0&&u>y-S)do{o.lt[y++]=o.lt[S++]}while(0!=--u);else o.lt.set(o.lt.subarray(S,S+u),y),y+=u,S+=u,u=0;S=0}}else S=y-v,y-S>0&&2>y-S?(o.lt[y++]=o.lt[S++],o.lt[y++]=o.lt[S++],k-=2):(o.lt.set(o.lt.subarray(S,S+2),y),y+=2,S+=2,k-=2);if(y-S>0&&k>y-S)do{o.lt[y++]=o.lt[S++]}while(0!=--k);else o.lt.set(o.lt.subarray(S,S+k),y),y+=k,S+=k,k=0;break}if(64&u)return c.Le="invalid distance code",k=c.We-p,k=k>h>>3?h>>3:k,p+=k,d-=k,h-=k<<3,o.ot=w,o.ct=h,c.We=p,c.qe+=d-c.nt,c.nt=d,o.write=y,st;f+=a[z+2],f+=w&ot[u],z=3*(l+f),u=a[z]}break}if(64&u)return 32&u?(k=c.We-p,k=k>h>>3?h>>3:k,p+=k,d-=k,h-=k<<3,o.ot=w,o.ct=h,c.We=p,c.qe+=d-c.nt,c.nt=d,o.write=y,1):(c.Le="invalid literal/length code",k=c.We-p,k=k>h>>3?h>>3:k,p+=k,d-=k,h-=k<<3,o.ot=w,o.ct=h,c.We=p,c.qe+=d-c.nt,c.nt=d,o.write=y,st);if(f+=a[z+2],f+=w&ot[u],z=3*(l+f),0===(u=a[z])){w>>=a[z+1],h-=a[z+1],o.lt[y++]=a[z+2],m--;break}}else w>>=a[z+1],h-=a[z+1],o.lt[y++]=a[z+2],m--}while(m>=258&&p>=10);return k=c.We-p,k=k>h>>3?h>>3:k,p+=k,d-=k,h-=k<<3,o.ot=w,o.ct=h,c.We=p,c.qe+=d-c.nt,c.nt=d,o.write=y,0}e.init=(e,i,o,c,f,a)=>{t=0,u=e,w=i,r=o,h=c,s=f,d=a,n=null},e.ut=(e,y,m)=>{let b,g,k,v,S,z,C,x=0,A=0,_=0;for(_=y.nt,v=y.We,x=e.ot,A=e.ct,S=e.write,z=S=258&&v>=10&&(e.ot=x,e.ct=A,y.We=v,y.qe+=_-y.nt,y.nt=_,e.write=S,m=p(u,w,r,h,s,d,e,y),_=y.nt,v=y.We,x=e.ot,A=e.ct,S=e.write,z=SA;){if(0===v)return e.ot=x,e.ct=A,y.We=v,y.qe+=_-y.nt,y.nt=_,e.write=S,e.wt(y,m);m=0,v--,x|=(255&y.ft(_++))<>>=n[g+1],A-=n[g+1],k=n[g],0===k){f=n[g+2],t=6;break}if(16&k){a=15&k,i=n[g+2],t=2;break}if(!(64&k)){c=k,o=g/3+n[g+2];break}if(32&k){t=7;break}return t=9,y.Le="invalid literal/length code",m=st,e.ot=x,e.ct=A,y.We=v,y.qe+=_-y.nt,y.nt=_,e.write=S,e.wt(y,m);case 2:for(b=a;b>A;){if(0===v)return e.ot=x,e.ct=A,y.We=v,y.qe+=_-y.nt,y.nt=_,e.write=S,e.wt(y,m);m=0,v--,x|=(255&y.ft(_++))<>=b,A-=b,c=w,n=s,o=d,t=3;case 3:for(b=c;b>A;){if(0===v)return e.ot=x,e.ct=A,y.We=v,y.qe+=_-y.nt,y.nt=_,e.write=S,e.wt(y,m);m=0,v--,x|=(255&y.ft(_++))<>=n[g+1],A-=n[g+1],k=n[g],16&k){a=15&k,l=n[g+2],t=4;break}if(!(64&k)){c=k,o=g/3+n[g+2];break}return t=9,y.Le="invalid distance code",m=st,e.ot=x,e.ct=A,y.We=v,y.qe+=_-y.nt,y.nt=_,e.write=S,e.wt(y,m);case 4:for(b=a;b>A;){if(0===v)return e.ot=x,e.ct=A,y.We=v,y.qe+=_-y.nt,y.nt=_,e.write=S,e.wt(y,m);m=0,v--,x|=(255&y.ft(_++))<>=b,A-=b,t=5;case 5:for(C=S-l;0>C;)C+=e.end;for(;0!==i;){if(0===z&&(S==e.end&&0!==e.read&&(S=0,z=S7&&(A-=8,v++,_--),e.write=S,m=e.wt(y,m),S=e.write,z=S{}}ht.dt=(e,t,n,r)=>(e[0]=9,t[0]=5,n[0]=ct,r[0]=ft,0);const pt=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function yt(e,t){const n=this;let r,s=0,o=0,c=0,a=0;const l=[0],u=[0],w=new dt;let h=0,d=new f(4320);const p=new ht;n.ct=0,n.ot=0,n.lt=new i(t),n.end=t,n.read=0,n.write=0,n.reset=(e,t)=>{t&&(t[0]=0),6==s&&w.ht(e),s=0,n.ct=0,n.ot=0,n.read=n.write=0},n.reset(e,null),n.wt=(e,t)=>{let r,s,i;return s=e.rt,i=n.read,r=(i>n.write?n.end:n.write)-i,r>e.tt&&(r=e.tt),0!==r&&t==it&&(t=0),e.tt-=r,e.Ge+=r,e.$e.set(n.lt.subarray(i,i+r),s),s+=r,i+=r,i==n.end&&(i=0,n.write==n.end&&(n.write=0),r=n.write-i,r>e.tt&&(r=e.tt),0!==r&&t==it&&(t=0),e.tt-=r,e.Ge+=r,e.$e.set(n.lt.subarray(i,i+r),s),s+=r,i+=r),e.rt=s,n.read=i,t},n.ut=(e,t)=>{let i,f,y,m,b,g,k,v;for(m=e.nt,b=e.We,f=n.ot,y=n.ct,g=n.write,k=gy;){if(0===b)return n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);t=0,b--,f|=(255&e.ft(m++))<>>1){case 0:f>>>=3,y-=3,i=7&y,f>>>=i,y-=i,s=1;break;case 1:S=[],z=[],C=[[]],x=[[]],ht.dt(S,z,C,x),w.init(S[0],z[0],C[0],0,x[0],0),f>>>=3,y-=3,s=6;break;case 2:f>>>=3,y-=3,s=3;break;case 3:return f>>>=3,y-=3,s=9,e.Le="invalid block type",t=st,n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t)}break;case 1:for(;32>y;){if(0===b)return n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);t=0,b--,f|=(255&e.ft(m++))<>>16&65535)!=(65535&f))return s=9,e.Le="invalid stored block lengths",t=st,n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);o=65535&f,f=y=0,s=0!==o?2:0!==h?7:0;break;case 2:if(0===b)return n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);if(0===k&&(g==n.end&&0!==n.read&&(g=0,k=gb&&(i=b),i>k&&(i=k),n.lt.set(e.je(m,i),g),m+=i,b-=i,g+=i,k-=i,0!=(o-=i))break;s=0!==h?7:0;break;case 3:for(;14>y;){if(0===b)return n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);t=0,b--,f|=(255&e.ft(m++))<29||(i>>5&31)>29)return s=9,e.Le="too many length or distance symbols",t=st,n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);if(i=258+(31&i)+(i>>5&31),!r||r.lengthv;v++)r[v]=0;f>>>=14,y-=14,a=0,s=4;case 4:for(;4+(c>>>10)>a;){for(;3>y;){if(0===b)return n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);t=0,b--,f|=(255&e.ft(m++))<>>=3,y-=3}for(;19>a;)r[pt[a++]]=0;if(l[0]=7,i=p.st(r,l,u,d,e),0!=i)return(t=i)==st&&(r=null,s=9),n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);a=0,s=5;case 5:for(;i=c,258+(31&i)+(i>>5&31)>a;){let o,w;for(i=l[0];i>y;){if(0===b)return n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);t=0,b--,f|=(255&e.ft(m++))<w)f>>>=i,y-=i,r[a++]=w;else{for(v=18==w?7:w-14,o=18==w?11:3;i+v>y;){if(0===b)return n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);t=0,b--,f|=(255&e.ft(m++))<>>=i,y-=i,o+=f&ot[v],f>>>=v,y-=v,v=a,i=c,v+o>258+(31&i)+(i>>5&31)||16==w&&1>v)return r=null,s=9,e.Le="invalid bit length repeat",t=st,n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);w=16==w?r[v-1]:0;do{r[v++]=w}while(0!=--o);a=v}}if(u[0]=-1,A=[],_=[],I=[],P=[],A[0]=9,_[0]=6,i=c,i=p.it(257+(31&i),1+(i>>5&31),r,A,_,I,P,d,e),0!=i)return i==st&&(r=null,s=9),t=i,n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,n.wt(e,t);w.init(A[0],_[0],d,I[0],d,P[0]),s=6;case 6:if(n.ot=f,n.ct=y,e.We=b,e.qe+=m-e.nt,e.nt=m,n.write=g,1!=(t=w.ut(n,e,t)))return n.wt(e,t);if(t=0,w.ht(e),m=e.nt,b=e.We,f=n.ot,y=n.ct,g=n.write,k=g{n.reset(e,null),n.lt=null,d=null},n.yt=(e,t,r)=>{n.lt.set(e.subarray(t,t+r),0),n.read=n.write=r},n.bt=()=>1==s?1:0}const mt=13,bt=[0,0,255,255];function gt(){const e=this;function t(e){return e&&e.gt?(e.qe=e.Ge=0,e.Le=null,e.gt.mode=7,e.gt.kt.reset(e,null),0):rt}e.mode=0,e.method=0,e.vt=[0],e.St=0,e.marker=0,e.zt=0,e.Ct=t=>(e.kt&&e.kt.ht(t),e.kt=null,0),e.xt=(n,r)=>(n.Le=null,e.kt=null,8>r||r>15?(e.Ct(n),rt):(e.zt=r,n.gt.kt=new yt(n,1<{let n,r;if(!e||!e.gt||!e.et)return rt;const s=e.gt;for(t=4==t?it:0,n=it;;)switch(s.mode){case 0:if(0===e.We)return n;if(n=t,e.We--,e.qe++,8!=(15&(s.method=e.ft(e.nt++)))){s.mode=mt,e.Le="unknown compression method",s.marker=5;break}if(8+(s.method>>4)>s.zt){s.mode=mt,e.Le="invalid win size",s.marker=5;break}s.mode=1;case 1:if(0===e.We)return n;if(n=t,e.We--,e.qe++,r=255&e.ft(e.nt++),((s.method<<8)+r)%31!=0){s.mode=mt,e.Le="incorrect header check",s.marker=5;break}if(!(32&r)){s.mode=7;break}s.mode=2;case 2:if(0===e.We)return n;n=t,e.We--,e.qe++,s.St=(255&e.ft(e.nt++))<<24&4278190080,s.mode=3;case 3:if(0===e.We)return n;n=t,e.We--,e.qe++,s.St+=(255&e.ft(e.nt++))<<16&16711680,s.mode=4;case 4:if(0===e.We)return n;n=t,e.We--,e.qe++,s.St+=(255&e.ft(e.nt++))<<8&65280,s.mode=5;case 5:return 0===e.We?n:(n=t,e.We--,e.qe++,s.St+=255&e.ft(e.nt++),s.mode=6,2);case 6:return s.mode=mt,e.Le="need dictionary",s.marker=0,rt;case 7:if(n=s.kt.ut(e,n),n==st){s.mode=mt,s.marker=0;break}if(0==n&&(n=t),1!=n)return n;n=t,s.kt.reset(e,s.vt),s.mode=12;case 12:return e.We=0,1;case mt:return st;default:return rt}},e._t=(e,t,n)=>{let r=0,s=n;if(!e||!e.gt||6!=e.gt.mode)return rt;const i=e.gt;return s<1<{let n,r,s,i,o;if(!e||!e.gt)return rt;const c=e.gt;if(c.mode!=mt&&(c.mode=mt,c.marker=0),0===(n=e.We))return it;for(r=e.nt,s=c.marker;0!==n&&4>s;)e.ft(r)==bt[s]?s++:s=0!==e.ft(r)?0:4-s,r++,n--;return e.qe+=r-e.nt,e.nt=r,e.We=n,c.marker=s,4!=s?st:(i=e.qe,o=e.Ge,t(e),e.qe=i,e.Ge=o,c.mode=7,0)},e.Pt=e=>e&&e.gt&&e.gt.kt?e.gt.kt.bt():rt}function kt(){}function vt(e){const t=new kt,n=e&&e.chunkSize?r.floor(2*e.chunkSize):131072,o=new i(n);let c=!1;t.xt(),t.$e=o,this.append=(e,r)=>{const f=[];let a,l,u=0,w=0,h=0;if(0!==e.length){t.nt=0,t.et=e,t.We=e.length;do{if(t.rt=0,t.tt=n,0!==t.We||c||(t.nt=0,c=!0),a=t.At(0),c&&a===it){if(0!==t.We)throw new s("inflating: bad input")}else if(0!==a&&1!==a)throw new s("inflating: "+t.Le);if((c||1===a)&&t.We===e.length)throw new s("inflating: bad input");t.rt&&(t.rt===n?f.push(new i(o)):f.push(o.subarray(0,t.rt))),h+=t.rt,r&&t.nt>0&&t.nt!=u&&(r(t.nt),u=t.nt)}while(t.We>0||0===t.tt);return f.length>1?(l=new i(h),f.forEach((e=>{l.set(e,w),w+=e.length}))):l=f[0]?new i(f[0]):new i,l}},this.flush=()=>{t.Ct()}}kt.prototype={xt(e){const t=this;return t.gt=new gt,e||(e=15),t.gt.xt(t,e)},At(e){const t=this;return t.gt?t.gt.At(t,e):rt},Ct(){const e=this;if(!e.gt)return rt;const t=e.gt.Ct(e);return e.gt=null,t},It(){const e=this;return e.gt?e.gt.It(e):rt},_t(e,t){const n=this;return n.gt?n.gt._t(n,e,t):rt},ft(e){return this.et[e]},je(e,t){return this.et.subarray(e,e+t)}},self.initCodec=()=>{self.Deflate=nt,self.Inflate=vt};\n',r=()=>t.useDataURI?"data:text/javascript,"+encodeURIComponent(n):URL.createObjectURL(new Blob([n],{type:"text/javascript"}));e({workerScripts:{inflate:[r],deflate:[r]}});} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +const ERR_ITERATOR_COMPLETED_TOO_SOON = "Writer iterator completed too soon"; +const HTTP_HEADER_CONTENT_TYPE = "Content-Type"; +const DEFAULT_CHUNK_SIZE = 64 * 1024; + +const PROPERTY_NAME_WRITABLE = "writable"; + +class Stream { + + constructor() { + this.size = 0; + } + + init() { + this.initialized = true; + } +} + +class Reader extends Stream { + + get readable() { + const reader = this; + const { chunkSize = DEFAULT_CHUNK_SIZE } = reader; + const readable = new ReadableStream({ + start() { + this.chunkOffset = 0; + }, + async pull(controller) { + const { offset = 0, size, diskNumberStart } = readable; + const { chunkOffset } = this; + controller.enqueue(await readUint8Array(reader, offset + chunkOffset, Math.min(chunkSize, size - chunkOffset), diskNumberStart)); + if (chunkOffset + chunkSize > size) { + controller.close(); + } else { + this.chunkOffset += chunkSize; + } + } + }); + return readable; + } +} + +class BlobReader extends Reader { + + constructor(blob) { + super(); + Object.assign(this, { + blob, + size: blob.size + }); + } + + async readUint8Array(offset, length) { + const reader = this; + const offsetEnd = offset + length; + const blob = offset || offsetEnd < reader.size ? reader.blob.slice(offset, offsetEnd) : reader.blob; + let arrayBuffer = await blob.arrayBuffer(); + if (arrayBuffer.byteLength > length) { + arrayBuffer = arrayBuffer.slice(offset, offsetEnd); + } + return new Uint8Array(arrayBuffer); + } +} + +class BlobWriter extends Stream { + + constructor(contentType) { + super(); + const writer = this; + const transformStream = new TransformStream(); + const headers = []; + if (contentType) { + headers.push([HTTP_HEADER_CONTENT_TYPE, contentType]); + } + Object.defineProperty(writer, PROPERTY_NAME_WRITABLE, { + get() { + return transformStream.writable; + } + }); + writer.blob = new Response(transformStream.readable, { headers }).blob(); + } + + getData() { + return this.blob; + } +} + +class TextWriter extends BlobWriter { + + constructor(encoding) { + super(encoding); + Object.assign(this, { + encoding, + utf8: !encoding || encoding.toLowerCase() == "utf-8" + }); + } + + async getData() { + const { + encoding, + utf8 + } = this; + const blob = await super.getData(); + if (blob.text && utf8) { + return blob.text(); + } else { + const reader = new FileReader(); + return new Promise((resolve, reject) => { + Object.assign(reader, { + onload: ({ target }) => resolve(target.result), + onerror: () => reject(reader.error) + }); + reader.readAsText(blob, encoding); + }); + } + } +} + +class SplitDataReader extends Reader { + + constructor(readers) { + super(); + this.readers = readers; + } + + async init() { + const reader = this; + const { readers } = reader; + reader.lastDiskNumber = 0; + reader.lastDiskOffset = 0; + await Promise.all(readers.map(async (diskReader, indexDiskReader) => { + await diskReader.init(); + if (indexDiskReader != readers.length - 1) { + reader.lastDiskOffset += diskReader.size; + } + reader.size += diskReader.size; + })); + super.init(); + } + + async readUint8Array(offset, length, diskNumber = 0) { + const reader = this; + const { readers } = this; + let result; + let currentDiskNumber = diskNumber; + if (currentDiskNumber == -1) { + currentDiskNumber = readers.length - 1; + } + let currentReaderOffset = offset; + while (currentReaderOffset >= readers[currentDiskNumber].size) { + currentReaderOffset -= readers[currentDiskNumber].size; + currentDiskNumber++; + } + const currentReader = readers[currentDiskNumber]; + const currentReaderSize = currentReader.size; + if (currentReaderOffset + length <= currentReaderSize) { + result = await readUint8Array(currentReader, currentReaderOffset, length); + } else { + const chunkLength = currentReaderSize - currentReaderOffset; + result = new Uint8Array(length); + result.set(await readUint8Array(currentReader, currentReaderOffset, chunkLength)); + result.set(await reader.readUint8Array(offset + chunkLength, length - chunkLength, diskNumber), chunkLength); + } + reader.lastDiskNumber = Math.max(currentDiskNumber, reader.lastDiskNumber); + return result; + } +} + +class SplitDataWriter extends Stream { + + constructor(writerGenerator, maxSize = 4294967295) { + super(); + const writer = this; + Object.assign(writer, { + diskNumber: 0, + diskOffset: 0, + size: 0, + maxSize, + availableSize: maxSize + }); + let diskSourceWriter, diskWritable, diskWriter; + const writable = new WritableStream({ + async write(chunk) { + const { availableSize } = writer; + if (!diskWriter) { + const { value, done } = await writerGenerator.next(); + if (done && !value) { + throw new Error(ERR_ITERATOR_COMPLETED_TOO_SOON); + } else { + diskSourceWriter = value; + diskSourceWriter.size = 0; + if (diskSourceWriter.maxSize) { + writer.maxSize = diskSourceWriter.maxSize; + } + writer.availableSize = writer.maxSize; + await initStream(diskSourceWriter); + diskWritable = value.writable; + diskWriter = diskWritable.getWriter(); + } + await this.write(chunk); + } else if (chunk.length >= availableSize) { + await writeChunk(chunk.slice(0, availableSize)); + await closeDisk(); + writer.diskOffset += diskSourceWriter.size; + writer.diskNumber++; + diskWriter = null; + await this.write(chunk.slice(availableSize)); + } else { + await writeChunk(chunk); + } + }, + async close() { + await diskWriter.ready; + await closeDisk(); + } + }); + Object.defineProperty(writer, PROPERTY_NAME_WRITABLE, { + get() { + return writable; + } + }); + + async function writeChunk(chunk) { + const chunkLength = chunk.length; + if (chunkLength) { + await diskWriter.ready; + await diskWriter.write(chunk); + diskSourceWriter.size += chunkLength; + writer.size += chunkLength; + writer.availableSize -= chunkLength; + } + } + + async function closeDisk() { + diskWritable.size = diskSourceWriter.size; + await diskWriter.close(); + } + } +} + +async function initStream(stream, initSize) { + if (stream.init && !stream.initialized) { + await stream.init(initSize); + } else { + return Promise.resolve(); + } +} + +function initReader(reader) { + if (Array.isArray(reader)) { + reader = new SplitDataReader(reader); + } + if (reader instanceof ReadableStream) { + reader = { + readable: reader + }; + } + return reader; +} + +function initWriter(writer) { + if (writer.writable === UNDEFINED_VALUE && typeof writer.next == FUNCTION_TYPE) { + writer = new SplitDataWriter(writer); + } + if (writer instanceof WritableStream) { + writer = { + writable: writer + }; + } + const { writable } = writer; + if (writable.size === UNDEFINED_VALUE) { + writable.size = 0; + } + if (!(writer instanceof SplitDataWriter)) { + Object.assign(writer, { + diskNumber: 0, + diskOffset: 0, + availableSize: Infinity, + maxSize: Infinity + }); + } + return writer; +} + +function readUint8Array(reader, offset, size, diskNumber) { + return reader.readUint8Array(offset, size, diskNumber); +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* global TextDecoder */ + +const CP437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ".split(""); +const VALID_CP437 = CP437.length == 256; + +function decodeCP437(stringValue) { + if (VALID_CP437) { + let result = ""; + for (let indexCharacter = 0; indexCharacter < stringValue.length; indexCharacter++) { + result += CP437[stringValue[indexCharacter]]; + } + return result; + } else { + return new TextDecoder().decode(stringValue); + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +function decodeText(value, encoding) { + if (encoding && encoding.trim().toLowerCase() == "cp437") { + return decodeCP437(value); + } else { + return new TextDecoder(encoding).decode(value); + } +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const PROPERTY_NAME_FILENAME = "filename"; +const PROPERTY_NAME_RAW_FILENAME = "rawFilename"; +const PROPERTY_NAME_COMMENT = "comment"; +const PROPERTY_NAME_RAW_COMMENT = "rawComment"; +const PROPERTY_NAME_UNCOMPPRESSED_SIZE = "uncompressedSize"; +const PROPERTY_NAME_COMPPRESSED_SIZE = "compressedSize"; +const PROPERTY_NAME_OFFSET = "offset"; +const PROPERTY_NAME_DISK_NUMBER_START = "diskNumberStart"; +const PROPERTY_NAME_LAST_MODIFICATION_DATE = "lastModDate"; +const PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE = "rawLastModDate"; +const PROPERTY_NAME_LAST_ACCESS_DATE = "lastAccessDate"; +const PROPERTY_NAME_RAW_LAST_ACCESS_DATE = "rawLastAccessDate"; +const PROPERTY_NAME_CREATION_DATE = "creationDate"; +const PROPERTY_NAME_RAW_CREATION_DATE = "rawCreationDate"; +const PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE = "internalFileAttribute"; +const PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE = "externalFileAttribute"; +const PROPERTY_NAME_MS_DOS_COMPATIBLE = "msDosCompatible"; +const PROPERTY_NAME_ZIP64 = "zip64"; +const PROPERTY_NAME_ENCRYPTED = "encrypted"; +const PROPERTY_NAME_VERSION = "version"; +const PROPERTY_NAME_VERSION_MADE_BY = "versionMadeBy"; +const PROPERTY_NAME_ZIPCRYPTO = "zipCrypto"; + +const PROPERTY_NAMES = [ + PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, PROPERTY_NAME_COMPPRESSED_SIZE, PROPERTY_NAME_UNCOMPPRESSED_SIZE, + PROPERTY_NAME_LAST_MODIFICATION_DATE, PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT, + PROPERTY_NAME_LAST_ACCESS_DATE, PROPERTY_NAME_CREATION_DATE, PROPERTY_NAME_OFFSET, PROPERTY_NAME_DISK_NUMBER_START, + PROPERTY_NAME_DISK_NUMBER_START, PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE, PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE, + PROPERTY_NAME_MS_DOS_COMPATIBLE, PROPERTY_NAME_ZIP64, PROPERTY_NAME_ENCRYPTED, PROPERTY_NAME_VERSION, PROPERTY_NAME_VERSION_MADE_BY, + PROPERTY_NAME_ZIPCRYPTO, "directory", "bitFlag", "signature", "filenameUTF8", "commentUTF8", "compressionMethod", "extraField", "rawExtraField", + "extraFieldZip64", "extraFieldUnicodePath", "extraFieldUnicodeComment", "extraFieldAES", "extraFieldNTFS", "extraFieldExtendedTimestamp"]; + +class Entry { + + constructor(data) { + PROPERTY_NAMES.forEach(name => this[name] = data[name]); + } + +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +const ERR_BAD_FORMAT = "File format is not recognized"; +const ERR_EOCDR_NOT_FOUND = "End of central directory not found"; +const ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND = "End of Zip64 central directory locator not found"; +const ERR_CENTRAL_DIRECTORY_NOT_FOUND = "Central directory header not found"; +const ERR_LOCAL_FILE_HEADER_NOT_FOUND = "Local file header not found"; +const ERR_EXTRAFIELD_ZIP64_NOT_FOUND = "Zip64 extra field not found"; +const ERR_ENCRYPTED = "File contains encrypted entry"; +const ERR_UNSUPPORTED_ENCRYPTION = "Encryption method not supported"; +const ERR_UNSUPPORTED_COMPRESSION = "Compression method not supported"; +const ERR_SPLIT_ZIP_FILE = "Split zip file"; +const CHARSET_UTF8 = "utf-8"; +const CHARSET_CP437 = "cp437"; +const ZIP64_PROPERTIES = [ + [PROPERTY_NAME_UNCOMPPRESSED_SIZE, MAX_32_BITS], + [PROPERTY_NAME_COMPPRESSED_SIZE, MAX_32_BITS], + [PROPERTY_NAME_OFFSET, MAX_32_BITS], + [PROPERTY_NAME_DISK_NUMBER_START, MAX_16_BITS] +]; +const ZIP64_EXTRACTION = { + [MAX_16_BITS]: { + getValue: getUint32, + bytes: 4 + }, + [MAX_32_BITS]: { + getValue: getBigUint64, + bytes: 8 + } +}; + +class ZipReader { + + constructor(reader, options = {}) { + Object.assign(this, { + reader: initReader(reader), + options, + config: getConfiguration() + }); + } + + async* getEntriesGenerator(options = {}) { + const zipReader = this; + let { reader } = zipReader; + const { config } = zipReader; + await initStream(reader); + if (reader.size === UNDEFINED_VALUE || !reader.readUint8Array) { + reader = new BlobReader(await new Response(reader.readable).blob()); + await initStream(reader); + } + if (reader.size < END_OF_CENTRAL_DIR_LENGTH) { + throw new Error(ERR_BAD_FORMAT); + } + reader.chunkSize = getChunkSize(config); + const endOfDirectoryInfo = await seekSignature(reader, END_OF_CENTRAL_DIR_SIGNATURE, reader.size, END_OF_CENTRAL_DIR_LENGTH, MAX_16_BITS * 16); + if (!endOfDirectoryInfo) { + const signatureArray = await readUint8Array(reader, 0, 4); + const signatureView = getDataView(signatureArray); + if (getUint32(signatureView) == SPLIT_ZIP_FILE_SIGNATURE) { + throw new Error(ERR_SPLIT_ZIP_FILE); + } else { + throw new Error(ERR_EOCDR_NOT_FOUND); + } + } + const endOfDirectoryView = getDataView(endOfDirectoryInfo); + let directoryDataLength = getUint32(endOfDirectoryView, 12); + let directoryDataOffset = getUint32(endOfDirectoryView, 16); + const commentOffset = endOfDirectoryInfo.offset; + const commentLength = getUint16(endOfDirectoryView, 20); + const appendedDataOffset = commentOffset + END_OF_CENTRAL_DIR_LENGTH + commentLength; + let lastDiskNumber = getUint16(endOfDirectoryView, 4); + const expectedLastDiskNumber = reader.lastDiskNumber || 0; + let diskNumber = getUint16(endOfDirectoryView, 6); + let filesLength = getUint16(endOfDirectoryView, 8); + let prependedDataLength = 0; + let startOffset = 0; + if (directoryDataOffset == MAX_32_BITS || directoryDataLength == MAX_32_BITS || filesLength == MAX_16_BITS || diskNumber == MAX_16_BITS) { + const endOfDirectoryLocatorArray = await readUint8Array(reader, endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH); + const endOfDirectoryLocatorView = getDataView(endOfDirectoryLocatorArray); + if (getUint32(endOfDirectoryLocatorView, 0) == ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE) { + directoryDataOffset = getBigUint64(endOfDirectoryLocatorView, 8); + let endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1); + let endOfDirectoryView = getDataView(endOfDirectoryArray); + const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH - ZIP64_END_OF_CENTRAL_DIR_LENGTH; + if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) { + const originalDirectoryDataOffset = directoryDataOffset; + directoryDataOffset = expectedDirectoryDataOffset; + prependedDataLength = directoryDataOffset - originalDirectoryDataOffset; + endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1); + endOfDirectoryView = getDataView(endOfDirectoryArray); + } + if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE) { + throw new Error(ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND); + } + if (lastDiskNumber == MAX_16_BITS) { + lastDiskNumber = getUint32(endOfDirectoryView, 16); + } + if (diskNumber == MAX_16_BITS) { + diskNumber = getUint32(endOfDirectoryView, 20); + } + if (filesLength == MAX_16_BITS) { + filesLength = getBigUint64(endOfDirectoryView, 32); + } + if (directoryDataLength == MAX_32_BITS) { + directoryDataLength = getBigUint64(endOfDirectoryView, 40); + } + directoryDataOffset -= directoryDataLength; + } + } + if (directoryDataOffset >= reader.size) { + prependedDataLength = reader.size - directoryDataOffset - directoryDataLength - END_OF_CENTRAL_DIR_LENGTH; + directoryDataOffset = reader.size - directoryDataLength - END_OF_CENTRAL_DIR_LENGTH; + } + if (expectedLastDiskNumber != lastDiskNumber) { + throw new Error(ERR_SPLIT_ZIP_FILE); + } + if (directoryDataOffset < 0) { + throw new Error(ERR_BAD_FORMAT); + } + let offset = 0; + let directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber); + let directoryView = getDataView(directoryArray); + if (directoryDataLength) { + const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - directoryDataLength; + if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) { + const originalDirectoryDataOffset = directoryDataOffset; + directoryDataOffset = expectedDirectoryDataOffset; + prependedDataLength += directoryDataOffset - originalDirectoryDataOffset; + directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber); + directoryView = getDataView(directoryArray); + } + } + const expectedDirectoryDataLength = endOfDirectoryInfo.offset - directoryDataOffset - (reader.lastDiskOffset || 0); + if (directoryDataLength != expectedDirectoryDataLength && expectedDirectoryDataLength >= 0) { + directoryDataLength = expectedDirectoryDataLength; + directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber); + directoryView = getDataView(directoryArray); + } + if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) { + throw new Error(ERR_BAD_FORMAT); + } + const filenameEncoding = getOptionValue(zipReader, options, "filenameEncoding"); + const commentEncoding = getOptionValue(zipReader, options, "commentEncoding"); + for (let indexFile = 0; indexFile < filesLength; indexFile++) { + const fileEntry = new ZipEntry(reader, config, zipReader.options); + if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE) { + throw new Error(ERR_CENTRAL_DIRECTORY_NOT_FOUND); + } + readCommonHeader(fileEntry, directoryView, offset + 6); + const languageEncodingFlag = Boolean(fileEntry.bitFlag.languageEncodingFlag); + const filenameOffset = offset + 46; + const extraFieldOffset = filenameOffset + fileEntry.filenameLength; + const commentOffset = extraFieldOffset + fileEntry.extraFieldLength; + const versionMadeBy = getUint16(directoryView, offset + 4); + const msDosCompatible = (versionMadeBy & 0) == 0; + const rawFilename = directoryArray.subarray(filenameOffset, extraFieldOffset); + const commentLength = getUint16(directoryView, offset + 32); + const endOffset = commentOffset + commentLength; + const rawComment = directoryArray.subarray(commentOffset, endOffset); + const filenameUTF8 = languageEncodingFlag; + const commentUTF8 = languageEncodingFlag; + const directory = msDosCompatible && ((getUint8(directoryView, offset + 38) & FILE_ATTR_MSDOS_DIR_MASK) == FILE_ATTR_MSDOS_DIR_MASK); + const offsetFileEntry = getUint32(directoryView, offset + 42) + prependedDataLength; + Object.assign(fileEntry, { + versionMadeBy, + msDosCompatible, + compressedSize: 0, + uncompressedSize: 0, + commentLength, + directory, + offset: offsetFileEntry, + diskNumberStart: getUint16(directoryView, offset + 34), + internalFileAttribute: getUint16(directoryView, offset + 36), + externalFileAttribute: getUint32(directoryView, offset + 38), + rawFilename, + filenameUTF8, + commentUTF8, + rawExtraField: directoryArray.subarray(extraFieldOffset, commentOffset) + }); + const decode = getOptionValue(zipReader, options, "decodeText") || decodeText; + const rawFilenameEncoding = filenameUTF8 ? CHARSET_UTF8 : filenameEncoding || CHARSET_CP437; + const rawCommentEncoding = commentUTF8 ? CHARSET_UTF8 : commentEncoding || CHARSET_CP437; + let filename = decode(rawFilename, rawFilenameEncoding); + if (filename === UNDEFINED_VALUE) { + filename = decodeText(rawFilename, rawFilenameEncoding); + } + let comment = decode(rawComment, rawCommentEncoding); + if (comment === UNDEFINED_VALUE) { + comment = decodeText(rawComment, rawCommentEncoding); + } + Object.assign(fileEntry, { + rawComment, + filename, + comment, + directory: directory || filename.endsWith(DIRECTORY_SIGNATURE) + }); + startOffset = Math.max(offsetFileEntry, startOffset); + readCommonFooter(fileEntry, fileEntry, directoryView, offset + 6); + fileEntry.zipCrypto = fileEntry.encrypted && !fileEntry.extraFieldAES; + const entry = new Entry(fileEntry); + entry.getData = (writer, options) => fileEntry.getData(writer, entry, options); + offset = endOffset; + const { onprogress } = options; + if (onprogress) { + try { + await onprogress(indexFile + 1, filesLength, new Entry(fileEntry)); + } catch (_error) { + // ignored + } + } + yield entry; + } + const extractPrependedData = getOptionValue(zipReader, options, "extractPrependedData"); + const extractAppendedData = getOptionValue(zipReader, options, "extractAppendedData"); + if (extractPrependedData) { + zipReader.prependedData = startOffset > 0 ? await readUint8Array(reader, 0, startOffset) : new Uint8Array(); + } + zipReader.comment = commentLength ? await readUint8Array(reader, commentOffset + END_OF_CENTRAL_DIR_LENGTH, commentLength) : new Uint8Array(); + if (extractAppendedData) { + zipReader.appendedData = appendedDataOffset < reader.size ? await readUint8Array(reader, appendedDataOffset, reader.size - appendedDataOffset) : new Uint8Array(); + } + return true; + } + + async getEntries(options = {}) { + const entries = []; + for await (const entry of this.getEntriesGenerator(options)) { + entries.push(entry); + } + return entries; + } + + async close() { + } +} + +class ZipEntry { + + constructor(reader, config, options) { + Object.assign(this, { + reader, + config, + options + }); + } + + async getData(writer, fileEntry, options = {}) { + const zipEntry = this; + const { + reader, + offset, + diskNumberStart, + extraFieldAES, + compressionMethod, + config, + bitFlag, + signature, + rawLastModDate, + uncompressedSize, + compressedSize + } = zipEntry; + const localDirectory = fileEntry.localDirectory = {}; + const dataArray = await readUint8Array(reader, offset, 30, diskNumberStart); + const dataView = getDataView(dataArray); + let password = getOptionValue(zipEntry, options, "password"); + let rawPassword = getOptionValue(zipEntry, options, "rawPassword"); + const passThrough = getOptionValue(zipEntry, options, "passThrough"); + password = password && password.length && password; + rawPassword = rawPassword && rawPassword.length && rawPassword; + if (extraFieldAES) { + if (extraFieldAES.originalCompressionMethod != COMPRESSION_METHOD_AES) { + throw new Error(ERR_UNSUPPORTED_COMPRESSION); + } + } + if ((compressionMethod != COMPRESSION_METHOD_STORE && compressionMethod != COMPRESSION_METHOD_DEFLATE) && !passThrough) { + throw new Error(ERR_UNSUPPORTED_COMPRESSION); + } + if (getUint32(dataView, 0) != LOCAL_FILE_HEADER_SIGNATURE) { + throw new Error(ERR_LOCAL_FILE_HEADER_NOT_FOUND); + } + readCommonHeader(localDirectory, dataView, 4); + localDirectory.rawExtraField = localDirectory.extraFieldLength ? + await readUint8Array(reader, offset + 30 + localDirectory.filenameLength, localDirectory.extraFieldLength, diskNumberStart) : + new Uint8Array(); + readCommonFooter(zipEntry, localDirectory, dataView, 4, true); + Object.assign(fileEntry, { + lastAccessDate: localDirectory.lastAccessDate, + creationDate: localDirectory.creationDate + }); + const encrypted = zipEntry.encrypted && localDirectory.encrypted && !passThrough; + const zipCrypto = encrypted && !extraFieldAES; + if (!passThrough) { + fileEntry.zipCrypto = zipCrypto; + } + if (encrypted) { + if (!zipCrypto && extraFieldAES.strength === UNDEFINED_VALUE) { + throw new Error(ERR_UNSUPPORTED_ENCRYPTION); + } else if (!password && !rawPassword) { + throw new Error(ERR_ENCRYPTED); + } + } + const dataOffset = offset + 30 + localDirectory.filenameLength + localDirectory.extraFieldLength; + const size = compressedSize; + const readable = reader.readable; + Object.assign(readable, { + diskNumberStart, + offset: dataOffset, + size + }); + const signal = getOptionValue(zipEntry, options, "signal"); + const checkPasswordOnly = getOptionValue(zipEntry, options, "checkPasswordOnly"); + if (checkPasswordOnly) { + writer = new WritableStream(); + } + writer = initWriter(writer); + await initStream(writer, passThrough ? compressedSize : uncompressedSize); + const { writable } = writer; + const { onstart, onprogress, onend } = options; + const workerOptions = { + options: { + codecType: CODEC_INFLATE, + password, + rawPassword, + zipCrypto, + encryptionStrength: extraFieldAES && extraFieldAES.strength, + signed: getOptionValue(zipEntry, options, "checkSignature") && !passThrough, + passwordVerification: zipCrypto && (bitFlag.dataDescriptor ? ((rawLastModDate >>> 8) & 0xFF) : ((signature >>> 24) & 0xFF)), + signature, + compressed: compressionMethod != 0 && !passThrough, + encrypted: zipEntry.encrypted && !passThrough, + useWebWorkers: getOptionValue(zipEntry, options, "useWebWorkers"), + useCompressionStream: getOptionValue(zipEntry, options, "useCompressionStream"), + transferStreams: getOptionValue(zipEntry, options, "transferStreams"), + checkPasswordOnly + }, + config, + streamOptions: { signal, size, onstart, onprogress, onend } + }; + let outputSize = 0; + try { + ({ outputSize } = (await runWorker({ readable, writable }, workerOptions))); + } catch (error) { + if (!checkPasswordOnly || error.message != ERR_ABORT_CHECK_PASSWORD) { + throw error; + } + } finally { + const preventClose = getOptionValue(zipEntry, options, "preventClose"); + writable.size += outputSize; + if (!preventClose && !writable.locked) { + await writable.getWriter().close(); + } + } + return checkPasswordOnly ? UNDEFINED_VALUE : writer.getData ? writer.getData() : writable; + } +} + +function readCommonHeader(directory, dataView, offset) { + const rawBitFlag = directory.rawBitFlag = getUint16(dataView, offset + 2); + const encrypted = (rawBitFlag & BITFLAG_ENCRYPTED) == BITFLAG_ENCRYPTED; + const rawLastModDate = getUint32(dataView, offset + 6); + Object.assign(directory, { + encrypted, + version: getUint16(dataView, offset), + bitFlag: { + level: (rawBitFlag & BITFLAG_LEVEL) >> 1, + dataDescriptor: (rawBitFlag & BITFLAG_DATA_DESCRIPTOR) == BITFLAG_DATA_DESCRIPTOR, + languageEncodingFlag: (rawBitFlag & BITFLAG_LANG_ENCODING_FLAG) == BITFLAG_LANG_ENCODING_FLAG + }, + rawLastModDate, + lastModDate: getDate(rawLastModDate), + filenameLength: getUint16(dataView, offset + 22), + extraFieldLength: getUint16(dataView, offset + 24) + }); +} + +function readCommonFooter(fileEntry, directory, dataView, offset, localDirectory) { + const { rawExtraField } = directory; + const extraField = directory.extraField = new Map(); + const rawExtraFieldView = getDataView(new Uint8Array(rawExtraField)); + let offsetExtraField = 0; + try { + while (offsetExtraField < rawExtraField.length) { + const type = getUint16(rawExtraFieldView, offsetExtraField); + const size = getUint16(rawExtraFieldView, offsetExtraField + 2); + extraField.set(type, { + type, + data: rawExtraField.slice(offsetExtraField + 4, offsetExtraField + 4 + size) + }); + offsetExtraField += 4 + size; + } + } catch (_error) { + // ignored + } + const compressionMethod = getUint16(dataView, offset + 4); + Object.assign(directory, { + signature: getUint32(dataView, offset + 10), + uncompressedSize: getUint32(dataView, offset + 18), + compressedSize: getUint32(dataView, offset + 14) + }); + const extraFieldZip64 = extraField.get(EXTRAFIELD_TYPE_ZIP64); + if (extraFieldZip64) { + readExtraFieldZip64(extraFieldZip64, directory); + directory.extraFieldZip64 = extraFieldZip64; + } + const extraFieldUnicodePath = extraField.get(EXTRAFIELD_TYPE_UNICODE_PATH); + if (extraFieldUnicodePath) { + readExtraFieldUnicode(extraFieldUnicodePath, PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, directory, fileEntry); + directory.extraFieldUnicodePath = extraFieldUnicodePath; + } + const extraFieldUnicodeComment = extraField.get(EXTRAFIELD_TYPE_UNICODE_COMMENT); + if (extraFieldUnicodeComment) { + readExtraFieldUnicode(extraFieldUnicodeComment, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT, directory, fileEntry); + directory.extraFieldUnicodeComment = extraFieldUnicodeComment; + } + const extraFieldAES = extraField.get(EXTRAFIELD_TYPE_AES); + if (extraFieldAES) { + readExtraFieldAES(extraFieldAES, directory, compressionMethod); + directory.extraFieldAES = extraFieldAES; + } else { + directory.compressionMethod = compressionMethod; + } + const extraFieldNTFS = extraField.get(EXTRAFIELD_TYPE_NTFS); + if (extraFieldNTFS) { + readExtraFieldNTFS(extraFieldNTFS, directory); + directory.extraFieldNTFS = extraFieldNTFS; + } + const extraFieldExtendedTimestamp = extraField.get(EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP); + if (extraFieldExtendedTimestamp) { + readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory); + directory.extraFieldExtendedTimestamp = extraFieldExtendedTimestamp; + } + const extraFieldUSDZ = extraField.get(EXTRAFIELD_TYPE_USDZ); + if (extraFieldUSDZ) { + directory.extraFieldUSDZ = extraFieldUSDZ; + } +} + +function readExtraFieldZip64(extraFieldZip64, directory) { + directory.zip64 = true; + const extraFieldView = getDataView(extraFieldZip64.data); + const missingProperties = ZIP64_PROPERTIES.filter(([propertyName, max]) => directory[propertyName] == max); + for (let indexMissingProperty = 0, offset = 0; indexMissingProperty < missingProperties.length; indexMissingProperty++) { + const [propertyName, max] = missingProperties[indexMissingProperty]; + if (directory[propertyName] == max) { + const extraction = ZIP64_EXTRACTION[max]; + directory[propertyName] = extraFieldZip64[propertyName] = extraction.getValue(extraFieldView, offset); + offset += extraction.bytes; + } else if (extraFieldZip64[propertyName]) { + throw new Error(ERR_EXTRAFIELD_ZIP64_NOT_FOUND); + } + } +} + +function readExtraFieldUnicode(extraFieldUnicode, propertyName, rawPropertyName, directory, fileEntry) { + const extraFieldView = getDataView(extraFieldUnicode.data); + const crc32 = new Crc32(); + crc32.append(fileEntry[rawPropertyName]); + const dataViewSignature = getDataView(new Uint8Array(4)); + dataViewSignature.setUint32(0, crc32.get(), true); + const signature = getUint32(extraFieldView, 1); + Object.assign(extraFieldUnicode, { + version: getUint8(extraFieldView, 0), + [propertyName]: decodeText(extraFieldUnicode.data.subarray(5)), + valid: !fileEntry.bitFlag.languageEncodingFlag && signature == getUint32(dataViewSignature, 0) + }); + if (extraFieldUnicode.valid) { + directory[propertyName] = extraFieldUnicode[propertyName]; + directory[propertyName + "UTF8"] = true; + } +} + +function readExtraFieldAES(extraFieldAES, directory, compressionMethod) { + const extraFieldView = getDataView(extraFieldAES.data); + const strength = getUint8(extraFieldView, 4); + Object.assign(extraFieldAES, { + vendorVersion: getUint8(extraFieldView, 0), + vendorId: getUint8(extraFieldView, 2), + strength, + originalCompressionMethod: compressionMethod, + compressionMethod: getUint16(extraFieldView, 5) + }); + directory.compressionMethod = extraFieldAES.compressionMethod; +} + +function readExtraFieldNTFS(extraFieldNTFS, directory) { + const extraFieldView = getDataView(extraFieldNTFS.data); + let offsetExtraField = 4; + let tag1Data; + try { + while (offsetExtraField < extraFieldNTFS.data.length && !tag1Data) { + const tagValue = getUint16(extraFieldView, offsetExtraField); + const attributeSize = getUint16(extraFieldView, offsetExtraField + 2); + if (tagValue == EXTRAFIELD_TYPE_NTFS_TAG1) { + tag1Data = extraFieldNTFS.data.slice(offsetExtraField + 4, offsetExtraField + 4 + attributeSize); + } + offsetExtraField += 4 + attributeSize; + } + } catch (_error) { + // ignored + } + try { + if (tag1Data && tag1Data.length == 24) { + const tag1View = getDataView(tag1Data); + const rawLastModDate = tag1View.getBigUint64(0, true); + const rawLastAccessDate = tag1View.getBigUint64(8, true); + const rawCreationDate = tag1View.getBigUint64(16, true); + Object.assign(extraFieldNTFS, { + rawLastModDate, + rawLastAccessDate, + rawCreationDate + }); + const lastModDate = getDateNTFS(rawLastModDate); + const lastAccessDate = getDateNTFS(rawLastAccessDate); + const creationDate = getDateNTFS(rawCreationDate); + const extraFieldData = { lastModDate, lastAccessDate, creationDate }; + Object.assign(extraFieldNTFS, extraFieldData); + Object.assign(directory, extraFieldData); + } + } catch (_error) { + // ignored + } +} + +function readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory) { + const extraFieldView = getDataView(extraFieldExtendedTimestamp.data); + const flags = getUint8(extraFieldView, 0); + const timeProperties = []; + const timeRawProperties = []; + if (localDirectory) { + if ((flags & 0x1) == 0x1) { + timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE); + timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE); + } + if ((flags & 0x2) == 0x2) { + timeProperties.push(PROPERTY_NAME_LAST_ACCESS_DATE); + timeRawProperties.push(PROPERTY_NAME_RAW_LAST_ACCESS_DATE); + } + if ((flags & 0x4) == 0x4) { + timeProperties.push(PROPERTY_NAME_CREATION_DATE); + timeRawProperties.push(PROPERTY_NAME_RAW_CREATION_DATE); + } + } else if (extraFieldExtendedTimestamp.data.length >= 5) { + timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE); + timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE); + } + let offset = 1; + timeProperties.forEach((propertyName, indexProperty) => { + if (extraFieldExtendedTimestamp.data.length >= offset + 4) { + const time = getUint32(extraFieldView, offset); + directory[propertyName] = extraFieldExtendedTimestamp[propertyName] = new Date(time * 1000); + const rawPropertyName = timeRawProperties[indexProperty]; + extraFieldExtendedTimestamp[rawPropertyName] = time; + } + offset += 4; + }); +} + +async function seekSignature(reader, signature, startOffset, minimumBytes, maximumLength) { + const signatureArray = new Uint8Array(4); + const signatureView = getDataView(signatureArray); + setUint32(signatureView, 0, signature); + const maximumBytes = minimumBytes + maximumLength; + return (await seek(minimumBytes)) || await seek(Math.min(maximumBytes, startOffset)); + + async function seek(length) { + const offset = startOffset - length; + const bytes = await readUint8Array(reader, offset, length); + for (let indexByte = bytes.length - minimumBytes; indexByte >= 0; indexByte--) { + if (bytes[indexByte] == signatureArray[0] && bytes[indexByte + 1] == signatureArray[1] && + bytes[indexByte + 2] == signatureArray[2] && bytes[indexByte + 3] == signatureArray[3]) { + return { + offset: offset + indexByte, + buffer: bytes.slice(indexByte, indexByte + minimumBytes).buffer + }; + } + } + } +} + +function getOptionValue(zipReader, options, name) { + return options[name] === UNDEFINED_VALUE ? zipReader.options[name] : options[name]; +} + +function getDate(timeRaw) { + const date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff; + try { + return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5, (time & 0x001F) * 2, 0); + } catch (_error) { + // ignored + } +} + +function getDateNTFS(timeRaw) { + return new Date((Number((timeRaw / BigInt(10000)) - BigInt(11644473600000)))); +} + +function getUint8(view, offset) { + return view.getUint8(offset); +} + +function getUint16(view, offset) { + return view.getUint16(offset, true); +} + +function getUint32(view, offset) { + return view.getUint32(offset, true); +} + +function getBigUint64(view, offset) { + return Number(view.getBigUint64(offset, true)); +} + +function setUint32(view, offset, value) { + view.setUint32(offset, value, true); +} + +function getDataView(array) { + return new DataView(array.buffer); +} + +/* + Copyright (c) 2022 Gildas Lormeau. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution. + + 3. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, + INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +let baseURL$1; +try { + baseURL$1 = (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || new URL('main.js', document.baseURI).href)); +} catch (_error) { + // ignored +} +configure({ baseURL: baseURL$1 }); +e(configure); + +/// + +configure({ Deflate: ZipDeflate, Inflate: ZipInflate }); + +/* + +TypeScript Md5 +============== + +Based on work by +* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html +* André Cruz: https://github.com/satazor/SparkMD5 +* Raymond Hill: https://github.com/gorhill/yamd5.js + +Effectively a TypeScrypt re-write of Raymond Hill JS Library + +The MIT License (MIT) + +Copyright (C) 2014 Raymond Hill + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + + + DO WHAT YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2015 André Cruz + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT YOU WANT TO. + + +*/ +class Md5 { + constructor() { + this._dataLength = 0; + this._bufferLength = 0; + this._state = new Int32Array(4); + this._buffer = new ArrayBuffer(68); + this._buffer8 = new Uint8Array(this._buffer, 0, 68); + this._buffer32 = new Uint32Array(this._buffer, 0, 17); + this.start(); + } + static hashStr(str, raw = false) { + return this.onePassHasher + .start() + .appendStr(str) + .end(raw); + } + static hashAsciiStr(str, raw = false) { + return this.onePassHasher + .start() + .appendAsciiStr(str) + .end(raw); + } + static _hex(x) { + const hc = Md5.hexChars; + const ho = Md5.hexOut; + let n; + let offset; + let j; + let i; + for (i = 0; i < 4; i += 1) { + offset = i * 8; + n = x[i]; + for (j = 0; j < 8; j += 2) { + ho[offset + 1 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + ho[offset + 0 + j] = hc.charAt(n & 0x0F); + n >>>= 4; + } + } + return ho.join(''); + } + static _md5cycle(x, k) { + let a = x[0]; + let b = x[1]; + let c = x[2]; + let d = x[3]; + // ff() + a += (b & c | ~b & d) + k[0] - 680876936 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[1] - 389564586 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[2] + 606105819 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[3] - 1044525330 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[4] - 176418897 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[5] + 1200080426 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[6] - 1473231341 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[7] - 45705983 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[8] + 1770035416 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[9] - 1958414417 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[10] - 42063 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[11] - 1990404162 | 0; + b = (b << 22 | b >>> 10) + c | 0; + a += (b & c | ~b & d) + k[12] + 1804603682 | 0; + a = (a << 7 | a >>> 25) + b | 0; + d += (a & b | ~a & c) + k[13] - 40341101 | 0; + d = (d << 12 | d >>> 20) + a | 0; + c += (d & a | ~d & b) + k[14] - 1502002290 | 0; + c = (c << 17 | c >>> 15) + d | 0; + b += (c & d | ~c & a) + k[15] + 1236535329 | 0; + b = (b << 22 | b >>> 10) + c | 0; + // gg() + a += (b & d | c & ~d) + k[1] - 165796510 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[6] - 1069501632 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[11] + 643717713 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[0] - 373897302 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[5] - 701558691 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[10] + 38016083 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[15] - 660478335 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[4] - 405537848 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[9] + 568446438 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[14] - 1019803690 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[3] - 187363961 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[8] + 1163531501 | 0; + b = (b << 20 | b >>> 12) + c | 0; + a += (b & d | c & ~d) + k[13] - 1444681467 | 0; + a = (a << 5 | a >>> 27) + b | 0; + d += (a & c | b & ~c) + k[2] - 51403784 | 0; + d = (d << 9 | d >>> 23) + a | 0; + c += (d & b | a & ~b) + k[7] + 1735328473 | 0; + c = (c << 14 | c >>> 18) + d | 0; + b += (c & a | d & ~a) + k[12] - 1926607734 | 0; + b = (b << 20 | b >>> 12) + c | 0; + // hh() + a += (b ^ c ^ d) + k[5] - 378558 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[8] - 2022574463 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[11] + 1839030562 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[14] - 35309556 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[1] - 1530992060 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[4] + 1272893353 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[7] - 155497632 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[10] - 1094730640 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[13] + 681279174 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[0] - 358537222 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[3] - 722521979 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[6] + 76029189 | 0; + b = (b << 23 | b >>> 9) + c | 0; + a += (b ^ c ^ d) + k[9] - 640364487 | 0; + a = (a << 4 | a >>> 28) + b | 0; + d += (a ^ b ^ c) + k[12] - 421815835 | 0; + d = (d << 11 | d >>> 21) + a | 0; + c += (d ^ a ^ b) + k[15] + 530742520 | 0; + c = (c << 16 | c >>> 16) + d | 0; + b += (c ^ d ^ a) + k[2] - 995338651 | 0; + b = (b << 23 | b >>> 9) + c | 0; + // ii() + a += (c ^ (b | ~d)) + k[0] - 198630844 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[5] - 57434055 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[10] - 1051523 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[15] - 30611744 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0; + b = (b << 21 | b >>> 11) + c | 0; + a += (c ^ (b | ~d)) + k[4] - 145523070 | 0; + a = (a << 6 | a >>> 26) + b | 0; + d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0; + d = (d << 10 | d >>> 22) + a | 0; + c += (a ^ (d | ~b)) + k[2] + 718787259 | 0; + c = (c << 15 | c >>> 17) + d | 0; + b += (d ^ (c | ~a)) + k[9] - 343485551 | 0; + b = (b << 21 | b >>> 11) + c | 0; + x[0] = a + x[0] | 0; + x[1] = b + x[1] | 0; + x[2] = c + x[2] | 0; + x[3] = d + x[3] | 0; + } + /** + * Initialise buffer to be hashed + */ + start() { + this._dataLength = 0; + this._bufferLength = 0; + this._state.set(Md5.stateIdentity); + return this; + } + // Char to code point to to array conversion: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt + // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown + /** + * Append a UTF-8 string to the hash buffer + * @param str String to append + */ + appendStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let code; + let i; + for (i = 0; i < str.length; i += 1) { + code = str.charCodeAt(i); + if (code < 128) { + buf8[bufLen++] = code; + } + else if (code < 0x800) { + buf8[bufLen++] = (code >>> 6) + 0xC0; + buf8[bufLen++] = code & 0x3F | 0x80; + } + else if (code < 0xD800 || code > 0xDBFF) { + buf8[bufLen++] = (code >>> 12) + 0xE0; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + else { + code = ((code - 0xD800) * 0x400) + (str.charCodeAt(++i) - 0xDC00) + 0x10000; + if (code > 0x10FFFF) { + throw new Error('Unicode standard supports code points up to U+10FFFF'); + } + buf8[bufLen++] = (code >>> 18) + 0xF0; + buf8[bufLen++] = (code >>> 12 & 0x3F) | 0x80; + buf8[bufLen++] = (code >>> 6 & 0x3F) | 0x80; + buf8[bufLen++] = (code & 0x3F) | 0x80; + } + if (bufLen >= 64) { + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen -= 64; + buf32[0] = buf32[16]; + } + } + this._bufferLength = bufLen; + return this; + } + /** + * Append an ASCII string to the hash buffer + * @param str String to append + */ + appendAsciiStr(str) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(str.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = str.charCodeAt(j++); + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + /** + * Append a byte array to the hash buffer + * @param input array to append + */ + appendByteArray(input) { + const buf8 = this._buffer8; + const buf32 = this._buffer32; + let bufLen = this._bufferLength; + let i; + let j = 0; + for (;;) { + i = Math.min(input.length - j, 64 - bufLen); + while (i--) { + buf8[bufLen++] = input[j++]; + } + if (bufLen < 64) { + break; + } + this._dataLength += 64; + Md5._md5cycle(this._state, buf32); + bufLen = 0; + } + this._bufferLength = bufLen; + return this; + } + /** + * Get the state of the hash buffer + */ + getState() { + const s = this._state; + return { + buffer: String.fromCharCode.apply(null, Array.from(this._buffer8)), + buflen: this._bufferLength, + length: this._dataLength, + state: [s[0], s[1], s[2], s[3]] + }; + } + /** + * Override the current state of the hash buffer + * @param state New hash buffer state + */ + setState(state) { + const buf = state.buffer; + const x = state.state; + const s = this._state; + let i; + this._dataLength = state.length; + this._bufferLength = state.buflen; + s[0] = x[0]; + s[1] = x[1]; + s[2] = x[2]; + s[3] = x[3]; + for (i = 0; i < buf.length; i += 1) { + this._buffer8[i] = buf.charCodeAt(i); + } + } + /** + * Hash the current state of the hash buffer and return the result + * @param raw Whether to return the value as an `Int32Array` + */ + end(raw = false) { + const bufLen = this._bufferLength; + const buf8 = this._buffer8; + const buf32 = this._buffer32; + const i = (bufLen >> 2) + 1; + this._dataLength += bufLen; + const dataBitsLen = this._dataLength * 8; + buf8[bufLen] = 0x80; + buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0; + buf32.set(Md5.buffer32Identity.subarray(i), i); + if (bufLen > 55) { + Md5._md5cycle(this._state, buf32); + buf32.set(Md5.buffer32Identity); + } + // Do the final computation based on the tail and length + // Beware that the final length may not fit in 32 bits so we take care of that + if (dataBitsLen <= 0xFFFFFFFF) { + buf32[14] = dataBitsLen; + } + else { + const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/); + if (matches === null) { + return; + } + const lo = parseInt(matches[2], 16); + const hi = parseInt(matches[1], 16) || 0; + buf32[14] = lo; + buf32[15] = hi; + } + Md5._md5cycle(this._state, buf32); + return raw ? this._state : Md5._hex(this._state); + } +} +// Private Static Variables +Md5.stateIdentity = new Int32Array([1732584193, -271733879, -1732584194, 271733878]); +Md5.buffer32Identity = new Int32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); +Md5.hexChars = '0123456789abcdef'; +Md5.hexOut = []; +// Permanent instance is to use for one-call hashing +Md5.onePassHasher = new Md5(); +if (Md5.hashStr('hello') !== '5d41402abc4b2a76b9719d911017c592') { + throw new Error('Md5 self test failed.'); +} + +// Inspired by +// https://github.com/renehernandez/obsidian-readwise/blob/eee5676524962ebfa7eaf1084e018dafe3c2f394/src/status.ts +class StatusBar { + constructor(statusBarEl) { + this.messages = []; + this.statusBarEl = statusBarEl; + } + displayMessage(message, timeout, forcing = false) { + if (this.messages[0] && this.messages[0].message === message) { + // don't show the same message twice + return; + } + this.messages.push({ + message: `readwise: ${message.slice(0, 100)}`, + timeout: timeout * 1000, + }); + if (forcing) { + this.currentMessage = null; + this.lastMessageTimestamp = null; + this.statusBarEl.setText(""); + } + this.display(); + } + display() { + if (this.currentMessage) { + let messageAge = Date.now() - this.lastMessageTimestamp; + if (messageAge >= this.currentMessage.timeout) { + this.currentMessage = null; + this.lastMessageTimestamp = null; + } + } + else if (this.messages.length) { + this.currentMessage = this.messages.shift(); + this.statusBarEl.setText(this.currentMessage.message); + this.lastMessageTimestamp = Date.now(); + return; + } + else { + this.statusBarEl.setText(""); + } + } +} + +// keep pluginVersion in sync with manifest.json +const pluginVersion = "3.0.1"; +// switch to local dev server for development +const baseURL = "https://readwise.io"; +// define our initial settings +// quoted keys for easy copying to data.json during development +const DEFAULT_SETTINGS = { + "token": "", + "readwiseDir": "Readwise", + "frequency": "0", + "triggerOnLoad": true, + "isSyncing": false, + "lastSyncFailed": false, + "lastSavedStatusID": 0, + "currentSyncStatusID": 0, + "refreshBooks": false, + "booksToRefresh": [], + "failedBooks": [], + "booksIDsMap": {}, + "reimportShowConfirmation": true +}; +/** The name of the Readwise Sync history file, without the extension. + * This is described as "Sync notification" in the Obsidian export settings + * on the Readwise website. */ +const READWISE_SYNC_FILENAME = "Readwise Syncs"; +class ReadwisePlugin extends obsidian.Plugin { + constructor() { + super(...arguments); + this.scheduleInterval = null; + } + getErrorMessageFromResponse(response) { + if (response && response.status === 409) { + return "Sync in progress initiated by different client"; + } + if (response && response.status === 417) { + return "Obsidian export is locked. Wait for an hour."; + } + return `${response ? response.statusText : "Can't connect to server"}`; + } + handleSyncError(buttonContext, msg) { + return __awaiter(this, void 0, void 0, function* () { + yield this.clearSettingsAfterRun(); + this.settings.lastSyncFailed = true; + yield this.saveSettings(); + if (buttonContext) { + this.showInfoStatus(buttonContext.buttonEl.parentElement, msg, "rw-error"); + buttonContext.buttonEl.setText("Run sync"); + } + else { + this.notice(msg, true, 4, true); + } + }); + } + clearSettingsAfterRun() { + return __awaiter(this, void 0, void 0, function* () { + this.settings.isSyncing = false; + this.settings.currentSyncStatusID = 0; + yield this.saveSettings(); + }); + } + handleSyncSuccess(buttonContext, msg = "Synced", exportID = null) { + return __awaiter(this, void 0, void 0, function* () { + yield this.clearSettingsAfterRun(); + this.settings.lastSyncFailed = false; + if (exportID) { + this.settings.lastSavedStatusID = exportID; + } + yield this.saveSettings(); + // if we have a button context, update the text on it + // this is the case if we fired on a "Run sync" click (the button) + if (buttonContext) { + this.showInfoStatus(buttonContext.buttonEl.parentNode.parentElement, msg, "rw-success"); + buttonContext.buttonEl.setText("Run sync"); + } + }); + } + /** Polls the Readwise API for the status of a given export; + * uses recursion for polling so that it can be awaited. */ + getExportStatus(statusID, buttonContext, _processedArtifactIds) { + return __awaiter(this, void 0, void 0, function* () { + if (statusID <= this.settings.lastSavedStatusID) { + console.log(`Readwise Official plugin: Already saved data from export ${statusID}`); + yield this.handleSyncSuccess(buttonContext); + this.notice("Readwise data is already up to date", false, 4); + return; + } + const processedArtifactIds = _processedArtifactIds !== null && _processedArtifactIds !== void 0 ? _processedArtifactIds : new Set(); + const downloadUnprocessedArtifacts = (allArtifactIds) => __awaiter(this, void 0, void 0, function* () { + for (const artifactId of allArtifactIds) { + if (!processedArtifactIds.has(artifactId)) { + yield this.downloadArtifact(artifactId, buttonContext); + processedArtifactIds.add(artifactId); + } + } + }); + try { + const response = yield fetch( + // status of archive build from this endpoint + `${baseURL}/api/get_export_status?exportStatusId=${statusID}`, { + headers: this.getAuthHeaders(), + }); + if (response && response.ok) { + const data = yield response.json(); + const WAITING_STATUSES = ['PENDING', 'RECEIVED', 'STARTED', 'RETRY']; + const SUCCESS_STATUSES = ['SUCCESS']; + if (WAITING_STATUSES.includes(data.taskStatus)) { + if (data.booksExported) { + const progressMsg = `Exporting Readwise data (${data.booksExported} / ${data.totalBooks}) ...`; + this.notice(progressMsg, false, 35, true); + } + else { + this.notice("Building export..."); + } + // process any artifacts available while the export is still being generated + yield downloadUnprocessedArtifacts(data.artifactIds); + // wait 1 second + yield new Promise(resolve => setTimeout(resolve, 1000)); + // then keep polling + yield this.getExportStatus(statusID, buttonContext, processedArtifactIds); + } + else if (SUCCESS_STATUSES.includes(data.taskStatus)) { + // make sure all artifacts are processed + yield downloadUnprocessedArtifacts(data.artifactIds); + yield this.acknowledgeSyncCompleted(buttonContext); + yield this.handleSyncSuccess(buttonContext, "Synced!", statusID); + this.notice("Readwise sync completed", true, 1, true); + console.log("Readwise Official plugin: completed sync"); + // @ts-ignore + if (this.app.isMobile) { + this.notice("If you don't see all of your Readwise files, please reload the Obsidian app", true); + } + } + else { + console.log("Readwise Official plugin: unknown status in getExportStatus: ", data); + yield this.handleSyncError(buttonContext, "Sync failed"); + return; + } + } + else { + console.log("Readwise Official plugin: bad response in getExportStatus: ", response); + yield this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response)); + } + } + catch (e) { + console.log("Readwise Official plugin: fetch failed in getExportStatus: ", e); + yield this.handleSyncError(buttonContext, "Sync failed"); + } + }); + } + /** Requests the archive from Readwise, polling until it's ready */ + queueExport(buttonContext, statusId, auto) { + return __awaiter(this, void 0, void 0, function* () { + if (this.settings.isSyncing) { + this.notice("Readwise sync already in progress", true); + return; + } + console.log('Readwise Official plugin: requesting archive...'); + this.settings.isSyncing = true; + yield this.saveSettings(); + const parentDeleted = !(yield this.app.vault.adapter.exists(this.settings.readwiseDir)); + // kickoff archive build form this endpoint + let url = `${baseURL}/api/obsidian/init?parentPageDeleted=${parentDeleted}`; + if (statusId) { + url += `&statusID=${statusId}`; + } + if (auto) { + url += `&auto=${auto}`; + } + let response, data; + try { + response = yield fetch(url, { + headers: this.getAuthHeaders() + }); + } + catch (e) { + console.log("Readwise Official plugin: fetch failed in queueExport: ", e); + } + if (response && response.ok) { + data = yield response.json(); + if (data.latest_id <= this.settings.lastSavedStatusID) { + yield this.handleSyncSuccess(buttonContext); + this.notice("Readwise data is already up to date", false, 4, true); + return; + } + // save the sync status ID so it can be polled until the archive is ready + this.settings.currentSyncStatusID = data.latest_id; + yield this.saveSettings(); + console.log("Readwise Official plugin: saved currentSyncStatusID", this.settings.currentSyncStatusID); + if (response.status === 201) { + this.notice("Syncing Readwise data"); + yield this.getExportStatus(this.settings.currentSyncStatusID, buttonContext); + console.log('Readwise Official plugin: queueExport done'); + } + else { + yield this.handleSyncSuccess(buttonContext, "Synced", data.latest_id); + this.notice("Latest Readwise sync already happened on your other device. Data should be up to date", false, 4, true); + } + } + else { + console.log("Readwise Official plugin: bad response in queueExport: ", response); + yield this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response)); + return; + } + }); + } + notice(msg, show = false, timeout = 0, forcing = false) { + if (show) { + new obsidian.Notice(msg); + } + // @ts-ignore + if (!this.app.isMobile) { + this.statusBar.displayMessage(msg.toLowerCase(), timeout, forcing); + } + else { + if (!show) { + new obsidian.Notice(msg); + } + } + } + showInfoStatus(container, msg, className = "") { + let info = container.find('.rw-info-container'); + info.setText(msg); + info.addClass(className); + } + clearInfoStatus(container) { + let info = container.find('.rw-info-container'); + info.empty(); + } + getAuthHeaders() { + return { + 'AUTHORIZATION': `Token ${this.settings.token}`, + 'Obsidian-Client': `${this.getObsidianClientID()}`, + 'Readwise-Client-Version': pluginVersion, + }; + } + downloadArtifact(artifactId, buttonContext) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + // download archive from this endpoint + let artifactURL = `${baseURL}/api/v2/download_artifact/${artifactId}`; + let response, blob; + try { + response = yield fetch(artifactURL, { headers: this.getAuthHeaders() }); + } + catch (e) { + console.log("Readwise Official plugin: fetch failed in downloadExport: ", e); + } + if (response && response.ok) { + blob = yield response.blob(); + } + else { + console.log("Readwise Official plugin: bad response in downloadExport: ", response); + yield this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response)); + throw new Error(`Readwise: error while fetching artifact ${artifactId}`); + } + this.fs = this.app.vault.adapter; + const blobReader = new BlobReader(blob); + const zipReader = new ZipReader(blobReader); + const entries = yield zipReader.getEntries(); + if (entries.length) { + for (const entry of entries) { + // will be extracted from JSON data + let bookID; + let data; + /** Combo of file `readwiseDir` and book name. + * Example: `Readwise/Books/Name of Book.json` */ + const processedFileName = obsidian.normalizePath(entry.filename + .replace(/^Readwise/, this.settings.readwiseDir) + .replace(/\.json$/, ".md")); + const isReadwiseSyncFile = processedFileName === `${this.settings.readwiseDir}/${READWISE_SYNC_FILENAME}.md`; + try { + const fileContent = yield entry.getData(new TextWriter()); + if (isReadwiseSyncFile) { + data = { + append_only_content: fileContent, + }; + } + else { + data = JSON.parse(fileContent); + } + bookID = this.encodeReadwiseBookId(data.book_id) || this.encodeReaderDocumentId(data.reader_document_id); + const undefinedBook = !bookID || !processedFileName; + if (undefinedBook && !isReadwiseSyncFile) { + console.error(`Error while processing entry: ${entry.filename}`); + } + // write the full document text file + if (data.full_document_text && data.full_document_text_path) { + const processedFullDocumentTextFileName = data.full_document_text_path.replace(/^Readwise/, this.settings.readwiseDir); + console.log("Writing full document text", processedFullDocumentTextFileName); + // track the book + this.settings.booksIDsMap[processedFullDocumentTextFileName] = bookID; + // ensure the directory exists + yield this.createDirForFile(processedFullDocumentTextFileName); + if (!(yield this.fs.exists(processedFullDocumentTextFileName))) { + // it's a new full document content file, just save it + yield this.fs.write(processedFullDocumentTextFileName, data.full_document_text); + } + else { + // full document content file already exists — overwrite it if it wasn't edited locally + const existingFullDocument = yield this.fs.read(processedFullDocumentTextFileName); + const existingFullDocumentHash = Md5.hashStr(existingFullDocument).toString(); + if (existingFullDocumentHash === data.last_full_document_hash) { + yield this.fs.write(processedFullDocumentTextFileName, data.full_document_text); + } + } + } + // write the actual files + let contentToSave = (_a = data.full_content) !== null && _a !== void 0 ? _a : data.append_only_content; + if (contentToSave) { + // track the book + this.settings.booksIDsMap[processedFileName] = bookID; + // ensure the directory exists + yield this.createDirForFile(processedFileName); + if (yield this.fs.exists(processedFileName)) { + // if the file already exists we need to append content to existing one + const existingContent = yield this.fs.read(processedFileName); + const existingContentHash = Md5.hashStr(existingContent).toString(); + if (existingContentHash !== data.last_content_hash) { + // content has been modified (it differs from the previously exported full document) + contentToSave = existingContent.trimEnd() + "\n" + data.append_only_content; + } + } + yield this.fs.write(processedFileName, contentToSave); + } + // save the entry in settings to ensure that it can be + // retried later when deleted files are re-synced if + // the user has `settings.refreshBooks` enabled + if (bookID) + yield this.saveSettings(); + } + catch (e) { + console.log(`Readwise Official plugin: error writing ${processedFileName}:`, e); + this.notice(`Readwise: error while writing ${processedFileName}: ${e}`, true, 4, true); + if (bookID) { + // handles case where user doesn't have `settings.refreshBooks` enabled + yield this.addToFailedBooks(bookID); + yield this.saveSettings(); + } + // communicate with readwise? + throw new Error(`Readwise: error while processing artifact ${artifactId}`); + } + if (data) { + yield this.removeBooksFromRefresh([this.encodeReadwiseBookId(data.book_id), this.encodeReaderDocumentId(data.reader_document_id)]); + yield this.removeBookFromFailedBooks([this.encodeReadwiseBookId(data.book_id), this.encodeReaderDocumentId(data.reader_document_id)]); + } + } + yield this.saveSettings(); + } + // close the ZipReader + yield zipReader.close(); + // wait for the metadata cache to process created/updated documents + yield new Promise((resolve) => { + const timeoutSeconds = 15; + console.log(`Readwise Official plugin: waiting for metadata cache processing for up to ${timeoutSeconds}s...`); + const timeout = setTimeout(() => { + this.app.metadataCache.offref(eventRef); + console.log("Readwise Official plugin: metadata cache processing timeout reached."); + resolve(); + }, timeoutSeconds * 1000); + const eventRef = this.app.metadataCache.on("resolved", () => { + this.app.metadataCache.offref(eventRef); + clearTimeout(timeout); + console.log("Readwise Official plugin: metadata cache processing has finished."); + resolve(); + }); + }); + }); + } + acknowledgeSyncCompleted(buttonContext) { + return __awaiter(this, void 0, void 0, function* () { + let response; + try { + response = yield fetch(`${baseURL}/api/obsidian/sync_ack`, { + headers: Object.assign(Object.assign({}, this.getAuthHeaders()), { 'Content-Type': 'application/json' }), + method: "POST", + }); + } + catch (e) { + console.log("Readwise Official plugin: fetch failed to acknowledged sync: ", e); + } + if (response && response.ok) { + return; + } + else { + console.log("Readwise Official plugin: bad response in acknowledge sync: ", response); + yield this.handleSyncError(buttonContext, this.getErrorMessageFromResponse(response)); + return; + } + }); + } + configureSchedule() { + return __awaiter(this, void 0, void 0, function* () { + const minutes = parseInt(this.settings.frequency); + let milliseconds = minutes * 60 * 1000; // minutes * seconds * milliseconds + console.log('Readwise Official plugin: setting interval to ', milliseconds, 'milliseconds'); + window.clearInterval(this.scheduleInterval); + this.scheduleInterval = null; + if (!milliseconds) { + // user set frequency to manual + return; + } + this.scheduleInterval = window.setInterval(() => this.syncBookHighlights(undefined, true), milliseconds); + this.registerInterval(this.scheduleInterval); + }); + } + /** Syncs provided book IDs, or uses the booksToRefresh list if none provided. + * ALL syncing starts with this function. */ + syncBookHighlights( + /** optional list of specific book IDs to sync */ + bookIds, + /** if true, was not initiated by user */ + auto) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.settings.token) + return; + let targetBookIds = [ + // try to sync provided bookIds + ...(bookIds || []), + // always try to sync failedBooks + ...this.settings.failedBooks, + ]; + // only sync `booksToRefresh` items if "resync deleted files" enabled + if (this.settings.refreshBooks) { + targetBookIds = [ + ...targetBookIds, + ...this.settings.booksToRefresh, + ]; + } + if (!targetBookIds.length) { + console.log('Readwise Official plugin: no targetBookIds, checking for new highlights'); + // no need to hit refresh_book_export; + // just check if there's new highlights from the server + yield this.queueExport(); + return; + } + console.log('Readwise Official plugin: refreshing books', { targetBookIds }); + let requestBookIds = []; + let requestReaderDocumentIds = []; + targetBookIds.map(id => { + const readerDocumentId = this.decodeReaderDocumentId(id); + if (readerDocumentId) { + requestReaderDocumentIds.push(readerDocumentId); + } + else { + requestBookIds.push(id); + } + }); + try { + const response = yield fetch( + // add books to next archive build from this endpoint + // NOTE: should only end up calling this endpoint when: + // 1. there are failedBooks + // 2. there are booksToRefresh + `${baseURL}/api/refresh_book_export`, { + headers: Object.assign(Object.assign({}, this.getAuthHeaders()), { 'Content-Type': 'application/json' }), + method: "POST", + body: JSON.stringify({ + exportTarget: 'obsidian', + userBookIds: requestBookIds, + readerDocumentIds: requestReaderDocumentIds, + }) + }); + if (response && response.ok) { + yield this.queueExport(); + return; + } + else { + console.log(`Readwise Official plugin: saving book id ${bookIds} to refresh later`); + const deduplicatedBookIds = new Set([...this.settings.booksToRefresh, ...bookIds]); + this.settings.booksToRefresh = Array.from(deduplicatedBookIds); + yield this.saveSettings(); + return; + } + } + catch (e) { + console.log("Readwise Official plugin: fetch failed in syncBookHighlights: ", e); + } + }); + } + addToFailedBooks(bookId) { + return __awaiter(this, void 0, void 0, function* () { + // NOTE: settings.failedBooks was added after initial settings schema, + // so not all users may have it, hence the fallback to DEFAULT_SETTINGS.failedBooks + let failedBooks = [...(this.settings.failedBooks || DEFAULT_SETTINGS.failedBooks)]; + failedBooks.push(bookId); + console.log(`Readwise Official plugin: added book id ${bookId} to failed books`); + this.settings.failedBooks = failedBooks; + // don't forget to save after! + // but don't do that here; this allows batching when removing multiple books. + }); + } + addBookToRefresh(bookId) { + return __awaiter(this, void 0, void 0, function* () { + let booksToRefresh = [...this.settings.booksToRefresh]; + booksToRefresh.push(bookId); + console.log(`Readwise Official plugin: added book id ${bookId} to refresh list`); + this.settings.booksToRefresh = booksToRefresh; + yield this.saveSettings(); + }); + } + removeBooksFromRefresh(bookIds = []) { + return __awaiter(this, void 0, void 0, function* () { + if (!bookIds.length) + return; + console.log(`Readwise Official plugin: removing book ids ${bookIds.join(', ')} from refresh list`); + this.settings.booksToRefresh = this.settings.booksToRefresh.filter(n => !bookIds.includes(n)); + // don't forget to save after! + // but don't do that here; this allows batching when removing multiple books. + }); + } + removeBookFromFailedBooks(bookIds = []) { + return __awaiter(this, void 0, void 0, function* () { + if (!bookIds.length) + return; + console.log(`Readwise Official plugin: removing book ids ${bookIds.join(', ')} from failed list`); + this.settings.failedBooks = this.settings.failedBooks.filter(n => !bookIds.includes(n)); + // don't forget to save after! + // but don't do that here; this allows batching when removing multiple books. + }); + } + reimportFile(vault, fileName) { + return __awaiter(this, void 0, void 0, function* () { + try { + this.notice("Deleting and reimporting file...", true); + yield vault.delete(vault.getAbstractFileByPath(fileName)); + const bookId = this.settings.booksIDsMap[fileName]; + yield this.addBookToRefresh(bookId); + // specifically re-sync this one file (not this.settings.booksToRefresh) + // because the user may have `settings.refreshBooks` disabled + yield this.syncBookHighlights([bookId]); + } + catch (e) { + console.log("Readwise Official plugin: fetch failed in Reimport current file: ", e); + } + }); + } + createDirForFile(filePath) { + return __awaiter(this, void 0, void 0, function* () { + const dirPath = filePath.replace(/\/*$/, '').replace(/^(.+)\/[^\/]*?$/, '$1'); + const exists = yield this.fs.exists(dirPath); + if (!exists) { + yield this.fs.mkdir(dirPath); + } + }); + } + onload() { + return __awaiter(this, void 0, void 0, function* () { + yield this.loadSettings(); + // @ts-expect-error - no type for isMobile + if (!this.app.isMobile) { + this.statusBar = new StatusBar(this.addStatusBarItem()); + this.registerInterval(window.setInterval(() => this.statusBar.display(), 1000)); + } + this.app.vault.on("rename", (file, oldPath) => __awaiter(this, void 0, void 0, function* () { + const bookId = this.settings.booksIDsMap[oldPath]; + if (!bookId) { + return; + } + delete this.settings.booksIDsMap[oldPath]; + this.settings.booksIDsMap[file.path] = bookId; + yield this.saveSettings(); + })); + this.addCommand({ + id: 'readwise-official-sync', + name: 'Sync your data now', + callback: () => { + this.syncBookHighlights(); + } + }); + this.addCommand({ + id: 'readwise-official-format', + name: 'Customize formatting', + callback: () => window.open(`${baseURL}/export/obsidian/preferences`) + }); + this.addCommand({ + id: 'readwise-official-reimport-file', + name: 'Delete and reimport this document', + checkCallback: (checking) => { + var _a; + const activeFilePath = (_a = this.app.workspace.getActiveFile()) === null || _a === void 0 ? void 0 : _a.path; + const isRWfile = activeFilePath && activeFilePath in this.settings.booksIDsMap; + if (checking) { + return isRWfile; + } + if (this.settings.reimportShowConfirmation) { + const modal = new obsidian.Modal(this.app); + modal.titleEl.setText("Delete and reimport this document?"); + modal.contentEl.createEl('p', { + text: 'Warning: Proceeding will delete this file entirely (including any changes you made) ' + + 'and then reimport a new copy of your highlights from Readwise.', + cls: 'rw-modal-warning-text', + }); + const buttonsContainer = modal.contentEl.createEl('div', { "cls": "rw-modal-btns" }); + const cancelBtn = buttonsContainer.createEl("button", { "text": "Cancel" }); + const confirmBtn = buttonsContainer.createEl("button", { "text": "Proceed", 'cls': 'mod-warning' }); + const showConfContainer = modal.contentEl.createEl('div', { 'cls': 'rw-modal-confirmation' }); + showConfContainer.createEl("label", { "attr": { "for": "rw-ask-nl" }, "text": "Don't ask me in the future" }); + const showConf = showConfContainer.createEl("input", { "type": "checkbox", "attr": { "name": "rw-ask-nl", "id": "rw-ask-nl" } }); + showConf.addEventListener('change', (ev) => __awaiter(this, void 0, void 0, function* () { + // @ts-expect-error - target.checked is not typed (TODO add type narrowing) + this.settings.reimportShowConfirmation = !ev.target.checked; + yield this.saveSettings(); + })); + cancelBtn.onClickEvent(() => { + modal.close(); + }); + confirmBtn.onClickEvent(() => { + this.reimportFile(this.app.vault, activeFilePath); + modal.close(); + }); + modal.open(); + } + else { + this.reimportFile(this.app.vault, activeFilePath); + } + } + }); + this.registerMarkdownPostProcessor((el, ctx) => { + if (!ctx.sourcePath.startsWith(this.settings.readwiseDir)) { + return; + } + let matches; + try { + // @ts-ignore + matches = [...ctx.getSectionInfo(el).text.matchAll(/__(.+)__/g)].map((a) => a[1]); + } + catch (TypeError) { + // failed interaction with a Dataview element + return; + } + const hypers = el.findAll("strong").filter(e => matches.contains(e.textContent)); + hypers.forEach(strongEl => { + const replacement = el.createEl('span'); + while (strongEl.firstChild) { + replacement.appendChild(strongEl.firstChild); + } + replacement.addClass("rw-hyper-highlight"); + strongEl.replaceWith(replacement); + }); + }); + this.addSettingTab(new ReadwiseSettingTab(this.app, this)); + // ensure workspace is settled; this ensures cache is loaded + this.app.workspace.onLayoutReady(() => __awaiter(this, void 0, void 0, function* () { + if (this.settings.isSyncing && this.settings.currentSyncStatusID) { + yield this.getExportStatus(this.settings.currentSyncStatusID); + } + else { + // we probably got some unhandled error... + this.settings.isSyncing = false; + yield this.saveSettings(); + } + if (this.settings.triggerOnLoad) { + yield this.syncBookHighlights(undefined, true); + } + yield this.configureSchedule(); + this.app.vault.on("delete", (file) => __awaiter(this, void 0, void 0, function* () { + const bookId = this.settings.booksIDsMap[file.path]; + if (bookId) { + // NOTE: because `on(delete)` also adds to `booksToRefresh`, + // the ID will be duplicated in `booksToRefresh`. + yield this.addBookToRefresh(bookId); + } + delete this.settings.booksIDsMap[file.path]; + // BUG: `on("delete")` events have no sequantial guarantees. + // meaning: if a user deletes many files at once, + // there is no guarantee that the event will be handled + // in any specific order. this can lead to reality + // drifting as book ID is deleted/saved as all the delete + // events compete to remove the book ID from the map and save. + yield this.saveSettings(); + })); + })); + }); + } + onunload() { + // we're not doing anything here for now... + return; + } + loadSettings() { + return __awaiter(this, void 0, void 0, function* () { + this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData()); + }); + } + saveSettings() { + return __awaiter(this, void 0, void 0, function* () { + yield this.saveData(this.settings); + }); + } + getObsidianClientID() { + let obsidianClientId = window.localStorage.getItem('rw-ObsidianClientId'); + if (obsidianClientId) { + return obsidianClientId; + } + else { + obsidianClientId = Math.random().toString(36).substring(2, 15); + window.localStorage.setItem('rw-ObsidianClientId', obsidianClientId); + return obsidianClientId; + } + } + getUserAuthToken(button, attempt = 0) { + return __awaiter(this, void 0, void 0, function* () { + let uuid = this.getObsidianClientID(); + if (attempt === 0) { + window.open(`${baseURL}/api_auth?token=${uuid}&service=obsidian`); + } + let response, data; + try { + response = yield fetch(`${baseURL}/api/auth?token=${uuid}`); + } + catch (e) { + console.log("Readwise Official plugin: fetch failed in getUserAuthToken: ", e); + } + if (response && response.ok) { + data = yield response.json(); + } + else { + console.log("Readwise Official plugin: bad response in getUserAuthToken: ", response); + this.showInfoStatus(button.parentElement, "Authorization failed. Try again", "rw-error"); + return; + } + if (data.userAccessToken) { + console.log("Readwise Official plugin: successfully authenticated with Readwise"); + this.settings.token = data.userAccessToken; + yield this.saveSettings(); + } + else { + if (attempt > 20) { + console.log('Readwise Official plugin: reached attempt limit in getUserAuthToken'); + return; + } + console.log(`Readwise Official plugin: didn't get token data, retrying (attempt ${attempt + 1})`); + yield new Promise(resolve => setTimeout(resolve, 1000)); + yield this.getUserAuthToken(button, attempt + 1); + } + yield this.saveSettings(); + return true; + }); + } + encodeReadwiseBookId(rawBookId) { + if (rawBookId) { + return rawBookId.toString(); + } + return undefined; + } + encodeReaderDocumentId(rawReaderDocumentId) { + if (rawReaderDocumentId) { + return `readerdocument:${rawReaderDocumentId}`; + } + return undefined; + } + decodeReaderDocumentId(readerDocumentId) { + if (!readerDocumentId || !readerDocumentId.startsWith("readerdocument:")) { + return undefined; + } + return readerDocumentId.replace(/^readerdocument:/, ""); + } +} +class ReadwiseSettingTab extends obsidian.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + let { containerEl } = this; + containerEl.empty(); + containerEl.createEl('h1', { text: 'Readwise Official' }); + containerEl.createEl('p', { text: 'Created by ' }).createEl('a', { text: 'Readwise', href: 'https://readwise.io' }); + containerEl.getElementsByTagName('p')[0].appendText(' 📚'); + containerEl.createEl('h2', { text: 'Settings' }); + if (this.plugin.settings.token) { + new obsidian.Setting(containerEl) + .setName("Sync your Readwise data with Obsidian") + .setDesc("On first sync, the Readwise plugin will create a new folder containing all your highlights") + .setClass('rw-setting-sync') + .addButton((button) => { + button.setCta().setTooltip("Once the sync begins, you can close this plugin page") + .setButtonText('Initiate Sync') + .onClick(() => __awaiter(this, void 0, void 0, function* () { + if (this.plugin.settings.isSyncing) { + // NOTE: This is used to prevent multiple syncs at the same time. However, if a previous sync fails, + // it can stop new syncs from happening. Make sure to set isSyncing to false + // if there's ever errors/failures in previous sync attempts, so that + // we don't block syncing subsequent times. + new obsidian.Notice("Readwise sync already in progress"); + } + else { + this.plugin.clearInfoStatus(containerEl); + yield this.plugin.syncBookHighlights(); + } + })); + }); + let el = containerEl.createEl("div", { cls: "rw-info-container" }); + containerEl.find(".rw-setting-sync > .setting-item-control ").prepend(el); + new obsidian.Setting(containerEl) + .setName("Customize formatting options") + .setDesc("You can customize which items export to Obsidian and how they appear from the Readwise website") + .addButton((button) => { + button.setButtonText("Customize").onClick(() => { + window.open(`${baseURL}/export/obsidian/preferences`); + }); + }); + new obsidian.Setting(containerEl) + .setName('Customize base folder') + .setDesc("By default, the plugin will save all your highlights into a folder named Readwise") + // TODO: change this to search filed when the API is exposed (https://github.com/obsidianmd/obsidian-api/issues/22) + .addText(text => text + .setPlaceholder('Defaults to: Readwise') + .setValue(this.plugin.settings.readwiseDir) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.readwiseDir = obsidian.normalizePath(value || "Readwise"); + yield this.plugin.saveSettings(); + }))); + new obsidian.Setting(containerEl) + .setName('Configure resync frequency') + .setDesc("If not set to Manual, Readwise will automatically resync with Obsidian when the app is open at the specified interval") + .addDropdown(dropdown => { + dropdown.addOption("0", "Manual"); + dropdown.addOption("60", "Every 1 hour"); + dropdown.addOption((12 * 60).toString(), "Every 12 hours"); + dropdown.addOption((24 * 60).toString(), "Every 24 hours"); + dropdown.addOption((7 * 24 * 60).toString(), "Every week"); + // select the currently-saved option + dropdown.setValue(this.plugin.settings.frequency); + dropdown.onChange((newValue) => __awaiter(this, void 0, void 0, function* () { + // update the plugin settings + this.plugin.settings.frequency = newValue; + yield this.plugin.saveSettings(); + // destroy & re-create the scheduled task + this.plugin.configureSchedule(); + })); + }); + new obsidian.Setting(containerEl) + .setName("Sync automatically when Obsidian opens") + .setDesc("If enabled, Readwise will automatically resync with Obsidian each time you open the app") + .addToggle((toggle) => { + toggle.setValue(this.plugin.settings.triggerOnLoad); + toggle.onChange((val) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.triggerOnLoad = val; + yield this.plugin.saveSettings(); + })); + }); + new obsidian.Setting(containerEl) + .setName("Resync deleted files") + .setDesc("If enabled, you can refresh individual items by deleting the file in Obsidian and initiating a resync") + .addToggle((toggle) => { + toggle.setValue(this.plugin.settings.refreshBooks); + toggle.onChange((val) => __awaiter(this, void 0, void 0, function* () { + this.plugin.settings.refreshBooks = val; + yield this.plugin.saveSettings(); + if (val) { + yield this.plugin.syncBookHighlights(); + } + })); + }); + if (this.plugin.settings.lastSyncFailed) { + this.plugin.showInfoStatus(containerEl.find(".rw-setting-sync .rw-info-container").parentElement, "Last sync failed", "rw-error"); + } + } + else { + new obsidian.Setting(containerEl) + .setName("Connect Obsidian to Readwise") + .setClass("rw-setting-connect") + .setDesc("The Readwise plugin enables automatic syncing of all your highlights from Kindle, Instapaper, Pocket, and more. Note: Requires Readwise account.") + .addButton((button) => { + button.setButtonText("Connect").setCta().onClick((evt) => __awaiter(this, void 0, void 0, function* () { + const success = yield this.plugin.getUserAuthToken(evt.target); + if (success) { + // re-render the settings + this.display(); + this.plugin.notice("Readwise connected", true); + } + })); + }); + let el = containerEl.createEl("div", { cls: "rw-info-container" }); + containerEl.find(".rw-setting-connect > .setting-item-control ").prepend(el); + } + const help = containerEl.createEl('p'); + help.innerHTML = "Question? Please see our Documentation or email us at hello@readwise.io 🙂"; + } +} + +module.exports = ReadwisePlugin; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/readwise-official/manifest.json b/.obsidian/plugins/readwise-official/manifest.json new file mode 100644 index 00000000..194897a2 --- /dev/null +++ b/.obsidian/plugins/readwise-official/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "readwise-official", + "name": "Readwise Official", + "version": "3.0.1", + "minAppVersion": "1.0.0", + "description": "Official Readwise <-> Obsidian integration", + "author": "Readwise", + "authorUrl": "https://readwise.io", + "isDesktopOnly": false +} diff --git a/.obsidian/plugins/readwise-official/styles.css b/.obsidian/plugins/readwise-official/styles.css new file mode 100644 index 00000000..2737cdf2 --- /dev/null +++ b/.obsidian/plugins/readwise-official/styles.css @@ -0,0 +1,58 @@ + +.theme-light { + --hyper-highlight: var(--text-highlight-bg, #FFF2AC); + --error-color: #DB5461; + --success-color: #8AAA79; + --info-color: var(--text-muted, #000); +} + +.theme-dark { + --hyper-highlight: var(--text-highlight-bg, #1C5998); + --error-color: #DB5461; + --success-color: #8AAA79; + --info-color: var(--text-muted, #fff); +} + +.rw-info-container { + margin-inline-end: 10px; +} + +.rw-info { + color: var(--info-color); + font-size: smaller; +} + +.rw-error { + color: var(--error-color); +} +.rw-success { + color: var(--success-color); +} + + +img[alt=rw-book-cover] { + max-height: 200px; +} + +.rw-hyper-highlight { + background-color: var(--hyper-highlight); +} + +.rw-modal-btns { + display: flex; + justify-content: flex-end; + gap: 0.5rem; +} + +.rw-modal-confirmation { + display: flex; + align-items: center; + gap: 0.5rem; + justify-content: flex-end; + margin-block-start: 1em; + font-size: smaller; +} + +.rw-modal-warning-text { + margin-block-start: 0; +} diff --git a/01-工作日记/2025-08-08.md b/01-工作日记/2025-08-08.md index 34cb7f13..11467701 100644 --- a/01-工作日记/2025-08-08.md +++ b/01-工作日记/2025-08-08.md @@ -15,7 +15,8 @@ excerpt: - [ ] ## 2 Tracking - +- 学习readwise:有readwise插件,可以自动同步你在各种平台上的阅读高亮,如Amazon Kindle、Apple Books、Google Play Books、Instapaper、Pocket、Medium、Twitter以及PDF等。它的主要功能是将这些高亮内容整合到Obsidian中,可惜是收费服务! +- ## 3 Tips - Unix与WIndows:在Mac下编辑的脚本不能直接在Windows使用,换行和字符集不一样,调试时才想起来! - Docker:Windows下安装到C盘以外安装脚本: